From 5ab15621a06e95a27e6945d4cfb49a01f662cf65 Mon Sep 17 00:00:00 2001 From: ZavaruKitsu Date: Sat, 8 Oct 2022 19:26:34 +0300 Subject: [PATCH] fix: reformat using C# rules --- Examples/AsyncFormUpdates/App.config | 794 ++++---- .../AsyncFormUpdates/AsyncFormUpdates.csproj | 144 +- Examples/AsyncFormUpdates/Program.cs | 16 +- .../Properties/AssemblyInfo.cs | 2 +- .../AsyncFormUpdates/forms/AsyncFormEdit.cs | 4 +- .../AsyncFormUpdates/forms/AsyncFormUpdate.cs | 4 +- Examples/AsyncFormUpdates/forms/Start.cs | 6 +- Examples/EFCoreBot/Database/BotDbContext.cs | 2 +- Examples/EFCoreBot/Database/User.cs | 2 +- Examples/EFCoreBot/EFCoreBot.csproj | 6 +- Examples/EFCoreBot/Program.cs | 19 +- Examples/EFCoreBot/StartForm.cs | 2 +- Examples/JoinHiderBot/JoinHiderBot.csproj | 14 +- Examples/JoinHiderBot/Program.cs | 24 +- .../JoinHiderBot/forms/GroupManageForm.cs | 23 +- Examples/JoinHiderBot/forms/Start.cs | 34 +- Examples/SystemCommandsBot/Program.cs | 54 +- .../SystemCommandsBot.csproj | 16 +- .../SystemCommandsBot/commands/Commando.cs | 28 +- Examples/SystemCommandsBot/config/Config.cs | 138 +- Examples/SystemCommandsBot/forms/CmdForm.cs | 306 ++- Examples/SystemCommandsBot/forms/StartForm.cs | 57 +- .../ImageExtensions.cs | 18 +- TelegramBotBase.Extensions.Images/README.md | 1 - .../TelegramBotBase.Extensions.Images.csproj | 36 +- .../BotBaseBuilderExtensions.cs | 29 +- .../MSSQLSerializer.cs | 38 +- .../README.md | 1 - ...xtensions.Serializer.Database.MSSQL.csproj | 48 +- .../create_tables.sql | 100 +- TelegramBotBase.Test/App.config | 18 +- TelegramBotBase.Test/Program.cs | 139 +- .../Properties/AssemblyInfo.cs | 2 +- .../TelegramBotBaseTest.csproj | 59 +- TelegramBotBase.Test/Tests/ButtonTestForm.cs | 125 +- .../Tests/Controls/ButtonGridForm.cs | 100 +- .../Tests/Controls/ButtonGridPagingForm.cs | 92 +- .../Tests/Controls/ButtonGridTagForm.cs | 121 +- .../Tests/Controls/CalendarPickerForm.cs | 128 +- .../Tests/Controls/CheckedButtonListForm.cs | 120 +- .../Tests/Controls/MonthPickerForm.cs | 124 +- .../Tests/Controls/MultiToggleButtons.cs | 86 +- .../Tests/Controls/MultiViewForm.cs | 84 +- .../Tests/Controls/Subclass/MultiViewTest.cs | 82 +- .../Tests/Controls/ToggleButtons.cs | 84 +- .../Tests/Controls/TreeViewForms.cs | 175 +- TelegramBotBase.Test/Tests/DataForm.cs | 146 +- .../Tests/DataSources/CustomDataSource.cs | 146 ++ .../Tests/DataSources/List.cs | 51 + .../Tests/Datasources/CustomDataSource.cs | 143 -- .../Tests/Datasources/List.cs | 55 - .../Tests/Groups/GroupChange.cs | 128 +- .../Tests/Groups/LinkReplaceTest.cs | 306 +-- .../Tests/Groups/WelcomeUser.cs | 151 +- TelegramBotBase.Test/Tests/Menu.cs | 449 ++--- .../Tests/Navigation/CustomController.cs | 65 +- .../Tests/Navigation/Form1.cs | 151 +- .../Tests/Navigation/Start.cs | 143 +- .../Tests/Notifications/Start.cs | 106 +- TelegramBotBase.Test/Tests/ProgressTest.cs | 216 +- .../Tests/Register/PerForm.cs | 162 +- .../Tests/Register/PerStep.cs | 51 +- TelegramBotBase.Test/Tests/Register/Start.cs | 86 +- .../Tests/Register/Steps/Data.cs | 16 +- .../Tests/Register/Steps/Step1.cs | 104 +- .../Tests/Register/Steps/Step2.cs | 70 +- .../Tests/Register/Steps/Step3.cs | 104 +- TelegramBotBase.Test/Tests/SimpleForm.cs | 108 +- TelegramBotBase.Test/Tests/Start.cs | 56 +- TelegramBotBase.Test/Tests/TestForm.cs | 123 +- TelegramBotBase.Test/Tests/TestForm2.cs | 209 +- TelegramBotBase.Test/packages.config | 8 +- TelegramBotBase/Args/BotCommandEventArgs.cs | 64 +- .../Args/ButtonClickedEventArgs.cs | 73 +- .../Args/CheckedChangedEventArgs.cs | 65 +- TelegramBotBase/Args/GroupChangedEventArgs.cs | 26 +- TelegramBotBase/Args/InitEventArgs.cs | 19 +- TelegramBotBase/Args/LoadStateEventArgs.cs | 102 +- TelegramBotBase/Args/MemberChangeEventArgs.cs | 45 +- .../Args/MessageDeletedEventArgs.cs | 21 +- .../Args/MessageIncomeEventArgs.cs | 34 +- .../Args/MessageReceivedEventArgs.cs | 22 +- TelegramBotBase/Args/MessageSentEventArgs.cs | 36 +- .../Args/PromptDialogCompletedEventArgs.cs | 14 +- TelegramBotBase/Args/RenderViewEventArgs.cs | 21 +- TelegramBotBase/Args/SaveStateEventArgs.cs | 67 +- TelegramBotBase/Args/SaveStatesEventArgs.cs | 18 +- TelegramBotBase/Args/SessionBeginEventArgs.cs | 23 +- .../Args/SystemExceptionEventArgs.cs | 45 +- .../Args/UnhandledCallEventArgs.cs | 65 +- TelegramBotBase/Attributes/IgnoreState.cs | 20 +- TelegramBotBase/Attributes/SaveState.cs | 18 +- TelegramBotBase/Base/Async.cs | 33 +- TelegramBotBase/Base/ControlBase.cs | 106 +- TelegramBotBase/Base/DataResult.cs | 318 ++- TelegramBotBase/Base/FormBase.cs | 827 ++++---- TelegramBotBase/Base/MessageClient.cs | 365 ++-- TelegramBotBase/Base/MessageResult.cs | 202 +- TelegramBotBase/Base/ResultBase.cs | 78 +- TelegramBotBase/Base/StateContainer.cs | 44 +- TelegramBotBase/Base/StateEntry.cs | 67 +- TelegramBotBase/Base/UpdateResult.cs | 52 +- TelegramBotBase/BotBase.cs | 784 ++++---- TelegramBotBase/Builder/BotBaseBuilder.cs | 710 ++++--- .../Interfaces/IAPIKeySelectionStage.cs | 67 +- .../Builder/Interfaces/IBotCommandsStage.cs | 54 +- .../Builder/Interfaces/IBuildingStage.cs | 11 +- .../Interfaces/ILanguageSelectionStage.cs | 51 +- .../Interfaces/IMessageLoopSelectionStage.cs | 58 +- .../Interfaces/INetworkingSelectionStage.cs | 72 +- .../Interfaces/ISessionSerializationStage.cs | 68 +- .../Interfaces/IStartFormSelectionStage.cs | 75 +- TelegramBotBase/Commands/Extensions.cs | 300 +-- TelegramBotBase/Constants/Telegram.cs | 28 +- TelegramBotBase/Controls/Hybrid/ButtonGrid.cs | 1204 +++++------ TelegramBotBase/Controls/Hybrid/ButtonRow.cs | 182 +- .../Controls/Hybrid/CheckedButtonList.cs | 1453 +++++++------- TelegramBotBase/Controls/Hybrid/MultiView.cs | 231 +-- .../Controls/Hybrid/TaggedButtonGrid.cs | 1760 +++++++++-------- .../Controls/Inline/CalendarPicker.cs | 423 ++-- .../Controls/Inline/MonthPicker.cs | 20 +- .../Controls/Inline/MultiToggleButton.cs | 231 ++- .../Controls/Inline/ProgressBar.cs | 509 +++-- .../Controls/Inline/ToggleButton.cs | 256 ++- TelegramBotBase/Controls/Inline/TreeView.cs | 178 +- .../Controls/Inline/TreeViewNode.cs | 111 +- .../DataSources/ButtonFormDataSource.cs | 254 +-- .../DataSources/StaticDataSource.cs | 62 +- TelegramBotBase/Enums/eDeleteMode.cs | 35 +- TelegramBotBase/Enums/eDeleteSide.cs | 35 +- TelegramBotBase/Enums/eKeyboardType.cs | 26 +- TelegramBotBase/Enums/eMonthPickerMode.cs | 35 +- .../Enums/eNavigationBarVisibility.cs | 34 +- TelegramBotBase/Enums/eSettings.cs | 52 +- .../Exceptions/MaxLengthException.cs | 16 +- .../Exceptions/MaximumColsException.cs | 16 +- .../Exceptions/MaximumRowsException.cs | 16 +- .../Factories/DefaultStartFormFactory.cs | 31 +- .../Factories/LambdaStartFormFactory.cs | 31 +- .../ServiceProviderStartFormFactory.cs | 41 +- TelegramBotBase/Form/AlertDialog.cs | 29 +- TelegramBotBase/Form/ArrayPromptDialog.cs | 169 +- TelegramBotBase/Form/AutoCleanForm.cs | 278 +-- TelegramBotBase/Form/ButtonBase.cs | 116 +- TelegramBotBase/Form/ButtonForm.cs | 626 +++--- TelegramBotBase/Form/CallbackData.cs | 133 +- TelegramBotBase/Form/ConfirmDialog.cs | 212 +- TelegramBotBase/Form/DynamicButton.cs | 53 +- TelegramBotBase/Form/GroupForm.cs | 110 +- TelegramBotBase/Form/ModalDialog.cs | 33 +- .../Form/Navigation/NavigationController.cs | 624 +++--- TelegramBotBase/Form/PromptDialog.cs | 203 +- TelegramBotBase/Form/SplitterForm.cs | 155 +- TelegramBotBase/Form/TagButtonBase.cs | 86 +- TelegramBotBase/Interfaces/IDataSource.cs | 58 +- TelegramBotBase/Interfaces/IDeviceSession.cs | 58 +- .../Interfaces/IMessageLoopFactory.cs | 16 +- .../Interfaces/IStartFormFactory.cs | 11 +- TelegramBotBase/Interfaces/IStateForm.cs | 21 +- TelegramBotBase/Interfaces/IStateMachine.cs | 15 +- TelegramBotBase/Localizations/Default.cs | 14 +- TelegramBotBase/Localizations/English.cs | 66 +- TelegramBotBase/Localizations/German.cs | 66 +- TelegramBotBase/Localizations/Localization.cs | 14 +- TelegramBotBase/Markdown/Generator.cs | 300 +-- .../MessageLoops/FormBaseMessageLoop.cs | 170 +- .../MessageLoops/FullMessageLoop.cs | 150 +- .../MessageLoops/MinimalMessageLoop.cs | 65 +- TelegramBotBase/Properties/AssemblyInfo.cs | 2 +- TelegramBotBase/SessionBase.cs | 542 ++--- TelegramBotBase/Sessions/DeviceSession.cs | 1746 ++++++++-------- TelegramBotBase/States/JSONStateMachine.cs | 126 +- .../States/SimpleJSONStateMachine.cs | 111 +- TelegramBotBase/States/XMLStateMachine.cs | 157 +- TelegramBotBase/TelegramBotBase.csproj | 102 +- TelegramBotBase/TelegramBotBase.nuspec | 52 +- TelegramBotBase/Tools/Arrays.cs | 19 +- TelegramBotBase/Tools/Console.cs | 115 +- TelegramBotBase/Tools/Conversion.cs | 41 +- TelegramBotBase/Tools/Time.cs | 85 +- 180 files changed, 13136 insertions(+), 13081 deletions(-) create mode 100644 TelegramBotBase.Test/Tests/DataSources/CustomDataSource.cs create mode 100644 TelegramBotBase.Test/Tests/DataSources/List.cs delete mode 100644 TelegramBotBase.Test/Tests/Datasources/CustomDataSource.cs delete mode 100644 TelegramBotBase.Test/Tests/Datasources/List.cs diff --git a/Examples/AsyncFormUpdates/App.config b/Examples/AsyncFormUpdates/App.config index 8ffc026..e784e10 100644 --- a/Examples/AsyncFormUpdates/App.config +++ b/Examples/AsyncFormUpdates/App.config @@ -1,378 +1,426 @@ - + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Examples/AsyncFormUpdates/AsyncFormUpdates.csproj b/Examples/AsyncFormUpdates/AsyncFormUpdates.csproj index 579f062..6c2fe0b 100644 --- a/Examples/AsyncFormUpdates/AsyncFormUpdates.csproj +++ b/Examples/AsyncFormUpdates/AsyncFormUpdates.csproj @@ -1,74 +1,74 @@  - - - Debug - AnyCPU - {673A56F5-6110-4AED-A68D-562FD6ED3EA6} - Exe - AsyncFormUpdates - AsyncFormUpdates - v4.8 - 512 - true - true - - - - AnyCPU - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - AnyCPU - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - - - - - - - - - - ..\..\packages\Telegram.Bot.17.0.0\lib\netstandard2.0\Telegram.Bot.dll - - - - - - - - - - - - - - - {0bd16fb9-7ed4-4ccb-83eb-5cee538e1b6c} - TelegramBotBase - - - - - - - - - - - \ No newline at end of file + + + Debug + AnyCPU + {673A56F5-6110-4AED-A68D-562FD6ED3EA6} + Exe + AsyncFormUpdates + AsyncFormUpdates + v4.8 + 512 + true + true + + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + ..\..\packages\Telegram.Bot.17.0.0\lib\netstandard2.0\Telegram.Bot.dll + + + + + + + + + + + + + + + {0bd16fb9-7ed4-4ccb-83eb-5cee538e1b6c} + TelegramBotBase + + + + + + + + + + + diff --git a/Examples/AsyncFormUpdates/Program.cs b/Examples/AsyncFormUpdates/Program.cs index 27283f7..facc257 100644 --- a/Examples/AsyncFormUpdates/Program.cs +++ b/Examples/AsyncFormUpdates/Program.cs @@ -15,8 +15,8 @@ namespace AsyncFormUpdates var apiKey = "APIKey"; __bot = BotBaseBuilder.Create() - .QuickStart(apiKey) - .Build(); + .QuickStart(apiKey) + .Build(); __bot.Start(); @@ -33,17 +33,17 @@ namespace AsyncFormUpdates private static async void Timer_Elapsed(object sender, ElapsedEventArgs e) { - - foreach(var s in __bot.Sessions.SessionList) + foreach (var s in __bot.Sessions.SessionList) { //Only for AsyncUpdateForm - if (s.Value.ActiveForm.GetType() != typeof(AsyncFormUpdate) && s.Value.ActiveForm.GetType() != typeof(AsyncFormEdit)) + if (s.Value.ActiveForm.GetType() != typeof(AsyncFormUpdate) && + s.Value.ActiveForm.GetType() != typeof(AsyncFormEdit)) + { continue; + } await __bot.InvokeMessageLoop(s.Key); } - - } } -} +} \ No newline at end of file diff --git a/Examples/AsyncFormUpdates/Properties/AssemblyInfo.cs b/Examples/AsyncFormUpdates/Properties/AssemblyInfo.cs index 7703157..f89e22b 100644 --- a/Examples/AsyncFormUpdates/Properties/AssemblyInfo.cs +++ b/Examples/AsyncFormUpdates/Properties/AssemblyInfo.cs @@ -32,4 +32,4 @@ using System.Runtime.InteropServices; // indem Sie "*" wie unten gezeigt eingeben: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] \ No newline at end of file diff --git a/Examples/AsyncFormUpdates/forms/AsyncFormEdit.cs b/Examples/AsyncFormUpdates/forms/AsyncFormEdit.cs index c24b8c2..2ad3694 100644 --- a/Examples/AsyncFormUpdates/forms/AsyncFormEdit.cs +++ b/Examples/AsyncFormUpdates/forms/AsyncFormEdit.cs @@ -46,8 +46,6 @@ namespace AsyncFormUpdates.forms var m = await Device.Send($"Your current count is at: {_counter}", bf, disableNotification: true); _messageId = m.MessageId; } - } - } -} +} \ No newline at end of file diff --git a/Examples/AsyncFormUpdates/forms/AsyncFormUpdate.cs b/Examples/AsyncFormUpdates/forms/AsyncFormUpdate.cs index 9e888a5..8a3b0b1 100644 --- a/Examples/AsyncFormUpdates/forms/AsyncFormUpdate.cs +++ b/Examples/AsyncFormUpdates/forms/AsyncFormUpdate.cs @@ -38,7 +38,5 @@ namespace AsyncFormUpdates.forms await Device.Send($"Your current count is at: {_counter}", bf, disableNotification: true); } - - } -} +} \ No newline at end of file diff --git a/Examples/AsyncFormUpdates/forms/Start.cs b/Examples/AsyncFormUpdates/forms/Start.cs index a8a726d..8713a04 100644 --- a/Examples/AsyncFormUpdates/forms/Start.cs +++ b/Examples/AsyncFormUpdates/forms/Start.cs @@ -6,8 +6,6 @@ namespace AsyncFormUpdates.forms { public class Start : AutoCleanForm { - - public override async Task Action(MessageResult message) { await message.ConfirmAction(); @@ -30,7 +28,6 @@ namespace AsyncFormUpdates.forms break; } - } public override async Task Render(MessageResult message) @@ -43,6 +40,5 @@ namespace AsyncFormUpdates.forms await Device.Send("Choose your option", bf); } - } -} +} \ No newline at end of file diff --git a/Examples/EFCoreBot/Database/BotDbContext.cs b/Examples/EFCoreBot/Database/BotDbContext.cs index 18a3c4a..da7e42d 100644 --- a/Examples/EFCoreBot/Database/BotDbContext.cs +++ b/Examples/EFCoreBot/Database/BotDbContext.cs @@ -9,4 +9,4 @@ public class BotDbContext : DbContext } public DbSet Users { get; set; } -} +} \ No newline at end of file diff --git a/Examples/EFCoreBot/Database/User.cs b/Examples/EFCoreBot/Database/User.cs index e106815..fbe1662 100644 --- a/Examples/EFCoreBot/Database/User.cs +++ b/Examples/EFCoreBot/Database/User.cs @@ -4,4 +4,4 @@ public class User { public long Id { get; set; } public string LastMessage { get; set; } -} +} \ No newline at end of file diff --git a/Examples/EFCoreBot/EFCoreBot.csproj b/Examples/EFCoreBot/EFCoreBot.csproj index 7421594..885fc87 100644 --- a/Examples/EFCoreBot/EFCoreBot.csproj +++ b/Examples/EFCoreBot/EFCoreBot.csproj @@ -8,12 +8,12 @@ - - + + - + diff --git a/Examples/EFCoreBot/Program.cs b/Examples/EFCoreBot/Program.cs index fa427ee..3d983e1 100644 --- a/Examples/EFCoreBot/Program.cs +++ b/Examples/EFCoreBot/Program.cs @@ -10,14 +10,15 @@ var serviceCollection = new ServiceCollection() var serviceProvider = serviceCollection.BuildServiceProvider(); var bot = BotBaseBuilder.Create() - .WithAPIKey(Environment.GetEnvironmentVariable("API_KEY") ?? throw new Exception("API_KEY is not set")) - .DefaultMessageLoop() - .WithServiceProvider(serviceProvider) - .NoProxy() - .NoCommands() - .NoSerialization() - .DefaultLanguage() - .Build(); + .WithAPIKey(Environment.GetEnvironmentVariable("API_KEY") ?? + throw new Exception("API_KEY is not set")) + .DefaultMessageLoop() + .WithServiceProvider(serviceProvider) + .NoProxy() + .NoCommands() + .NoSerialization() + .DefaultLanguage() + .Build(); bot.Start(); -await Task.Delay(-1); +await Task.Delay(-1); \ No newline at end of file diff --git a/Examples/EFCoreBot/StartForm.cs b/Examples/EFCoreBot/StartForm.cs index 1bfee77..7081c1a 100644 --- a/Examples/EFCoreBot/StartForm.cs +++ b/Examples/EFCoreBot/StartForm.cs @@ -33,4 +33,4 @@ public class StartForm : FormBase user.LastMessage = string.IsNullOrWhiteSpace(message.MessageText) ? "" : message.MessageText; await _dbContext.SaveChangesAsync(); } -} +} \ No newline at end of file diff --git a/Examples/JoinHiderBot/JoinHiderBot.csproj b/Examples/JoinHiderBot/JoinHiderBot.csproj index aa8f8d7..76dddc9 100644 --- a/Examples/JoinHiderBot/JoinHiderBot.csproj +++ b/Examples/JoinHiderBot/JoinHiderBot.csproj @@ -1,12 +1,12 @@  - - Exe - net6.0 - + + Exe + net6.0 + - - - + + + diff --git a/Examples/JoinHiderBot/Program.cs b/Examples/JoinHiderBot/Program.cs index 369b758..9c0bfff 100644 --- a/Examples/JoinHiderBot/Program.cs +++ b/Examples/JoinHiderBot/Program.cs @@ -2,22 +2,20 @@ using JoinHiderBot.forms; using TelegramBotBase.Builder; -namespace JoinHiderBot +namespace JoinHiderBot; + +internal class Program { - internal class Program + private static void Main(string[] args) { - private static void Main(string[] args) - { + var apiKey = ""; - var apiKey = ""; + var bot = BotBaseBuilder.Create() + .QuickStart(apiKey) + .Build(); - var bot = BotBaseBuilder.Create() - .QuickStart(apiKey) - .Build(); + bot.Start(); - bot.Start(); - - Console.ReadLine(); - } + Console.ReadLine(); } -} +} \ No newline at end of file diff --git a/Examples/JoinHiderBot/forms/GroupManageForm.cs b/Examples/JoinHiderBot/forms/GroupManageForm.cs index 61fdadc..6ccf246 100644 --- a/Examples/JoinHiderBot/forms/GroupManageForm.cs +++ b/Examples/JoinHiderBot/forms/GroupManageForm.cs @@ -3,21 +3,20 @@ using Telegram.Bot.Types.Enums; using TelegramBotBase.Args; using TelegramBotBase.Form; -namespace JoinHiderBot.forms +namespace JoinHiderBot.forms; + +public class GroupManageForm : GroupForm { - public class GroupManageForm : GroupForm + public override async Task OnMemberChanges(MemberChangeEventArgs e) { - - public override async Task OnMemberChanges(MemberChangeEventArgs e) + if (e.Type != MessageType.ChatMembersAdded && e.Type != MessageType.ChatMemberLeft) { - if (e.Type != MessageType.ChatMembersAdded && e.Type != MessageType.ChatMemberLeft) - return; - - - var m = e.Result.Message; - - await Device.DeleteMessage(m); + return; } + + var m = e.Result.Message; + + await Device.DeleteMessage(m); } -} +} \ No newline at end of file diff --git a/Examples/JoinHiderBot/forms/Start.cs b/Examples/JoinHiderBot/forms/Start.cs index f506451..0b868b6 100644 --- a/Examples/JoinHiderBot/forms/Start.cs +++ b/Examples/JoinHiderBot/forms/Start.cs @@ -2,25 +2,23 @@ using TelegramBotBase.Base; using TelegramBotBase.Form; -namespace JoinHiderBot.forms +namespace JoinHiderBot.forms; + +public class Start : SplitterForm { - public class Start : SplitterForm + public override async Task Open(MessageResult e) { - public override async Task Open(MessageResult e) - { - await Device.Send("This bot works only in groups."); - - return true; - } - - public override async Task OpenGroup(MessageResult e) - { - var gmf = new GroupManageForm(); - - await NavigateTo(gmf); - - return true; - } + await Device.Send("This bot works only in groups."); + return true; } -} + + public override async Task OpenGroup(MessageResult e) + { + var gmf = new GroupManageForm(); + + await NavigateTo(gmf); + + return true; + } +} \ No newline at end of file diff --git a/Examples/SystemCommandsBot/Program.cs b/Examples/SystemCommandsBot/Program.cs index d0131f9..b5330ac 100644 --- a/Examples/SystemCommandsBot/Program.cs +++ b/Examples/SystemCommandsBot/Program.cs @@ -3,39 +3,35 @@ using SystemCommandsBot.config; using SystemCommandsBot.forms; using TelegramBotBase.Builder; -namespace SystemCommandsBot +namespace SystemCommandsBot; + +internal class Program { - internal class Program + public static Config BotConfig { get; set; } + + + private static void Main(string[] args) { - public static Config BotConfig { get; set; } + BotConfig = Config.Load(); - - private static void Main(string[] args) + if (BotConfig.ApiKey == null || BotConfig.ApiKey.Trim() == "") { - - BotConfig = Config.Load(); - - if (BotConfig.ApiKey == null || BotConfig.ApiKey.Trim() == "") - { - Console.WriteLine("Config created..."); - Console.ReadLine(); - return; - } - - var bot = BotBaseBuilder.Create() - .QuickStart(BotConfig.ApiKey) - .Build(); - - bot.Start(); - - Console.WriteLine("Bot started"); - + Console.WriteLine("Config created..."); Console.ReadLine(); - - - bot.Stop(); - - + return; } + + var bot = BotBaseBuilder.Create() + .QuickStart(BotConfig.ApiKey) + .Build(); + + bot.Start(); + + Console.WriteLine("Bot started"); + + Console.ReadLine(); + + + bot.Stop(); } -} +} \ No newline at end of file diff --git a/Examples/SystemCommandsBot/SystemCommandsBot.csproj b/Examples/SystemCommandsBot/SystemCommandsBot.csproj index 4e20f6a..95990e5 100644 --- a/Examples/SystemCommandsBot/SystemCommandsBot.csproj +++ b/Examples/SystemCommandsBot/SystemCommandsBot.csproj @@ -1,13 +1,13 @@ - - Exe - net6.0 - + + Exe + net6.0 + - - - - + + + + diff --git a/Examples/SystemCommandsBot/commands/Commando.cs b/Examples/SystemCommandsBot/commands/Commando.cs index d93eb81..8eb56d1 100644 --- a/Examples/SystemCommandsBot/commands/Commando.cs +++ b/Examples/SystemCommandsBot/commands/Commando.cs @@ -1,25 +1,21 @@ -namespace SystemCommandsBot.commands +namespace SystemCommandsBot.commands; + +public class Commando { - public class Commando - { - public int Id { get; set; } + public int Id { get; set; } - public string Title { get; set; } + public string Title { get; set; } - public string ShellCmd { get; set; } + public string ShellCmd { get; set; } - public bool Enabled { get; set; } = true; + public bool Enabled { get; set; } = true; - public string Action { get; set; } + public string Action { get; set; } - public bool UseShell { get; set; } = true; + public bool UseShell { get; set; } = true; - public int? MaxInstances { get; set; } + public int? MaxInstances { get; set; } - public string ProcName - { - get;set; - } - } -} + public string ProcName { get; set; } +} \ No newline at end of file diff --git a/Examples/SystemCommandsBot/config/Config.cs b/Examples/SystemCommandsBot/config/Config.cs index f63b8fc..3125790 100644 --- a/Examples/SystemCommandsBot/config/Config.cs +++ b/Examples/SystemCommandsBot/config/Config.cs @@ -4,90 +4,90 @@ using System.IO; using Newtonsoft.Json; using SystemCommandsBot.commands; -namespace SystemCommandsBot.config +namespace SystemCommandsBot.config; + +public class Config { - public class Config + public Config() { - public string Password { get; set; } + Commandos = new List(); + } - public string ApiKey { get; set; } + public string Password { get; set; } - public List Commandos { get; set; } + public string ApiKey { get; set; } + public List Commandos { get; set; } - public Config() + public void LoadDefaultValues() + { + ApiKey = ""; + Commandos.Add(new Commando { - Commandos = new List(); + Id = 0, Enabled = true, Title = "Test Befehl", ShellCmd = "explorer.exe", Action = "start", MaxInstances = 2 + }); + } + + + public static Config Load() + { + try + { + return Load(AppContext.BaseDirectory + "config\\default.cfg"); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); } - public void LoadDefaultValues() + return null; + } + + + public static Config Load(string path) + { + try { - ApiKey = ""; - Commandos.Add(new Commando { Id = 0, Enabled = true, Title = "Test Befehl", ShellCmd = "explorer.exe", Action = "start", MaxInstances = 2 }); + var cfg = JsonConvert.DeserializeObject(File.ReadAllText(path)); + return cfg; + } + catch (DirectoryNotFoundException) + { + var di = new DirectoryInfo(path); + + if (!Directory.Exists(di.Parent.FullName)) + { + Directory.CreateDirectory(di.Parent.FullName); + } + + var cfg = new Config(); + cfg.LoadDefaultValues(); + cfg.Save(path); + return cfg; + } + catch (FileNotFoundException) + { + var cfg = new Config(); + cfg.LoadDefaultValues(); + cfg.Save(path); + return cfg; + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); } + return null; + } - public static Config Load() + public void Save(string path) + { + try { - try - { - return Load(AppContext.BaseDirectory + "config\\default.cfg"); - - - } - catch(Exception ex) - { - Console.WriteLine(ex.Message); - } - return null; + File.WriteAllText(path, JsonConvert.SerializeObject(this)); } - - - public static Config Load(string path) + catch { - try - { - var cfg = JsonConvert.DeserializeObject(File.ReadAllText(path)); - return cfg; - } - catch (DirectoryNotFoundException) - { - var di = new DirectoryInfo(path); - - if (!Directory.Exists(di.Parent.FullName)) - { - Directory.CreateDirectory(di.Parent.FullName); - } - - var cfg = new Config(); - cfg.LoadDefaultValues(); - cfg.Save(path); - return cfg; - } - catch (FileNotFoundException) - { - var cfg = new Config(); - cfg.LoadDefaultValues(); - cfg.Save(path); - return cfg; - } - catch(Exception ex) - { - Console.WriteLine(ex.Message); - } - return null; - } - - public void Save(string path) - { - try - { - File.WriteAllText(path, JsonConvert.SerializeObject(this)); - } - catch - { - - } } } -} +} \ No newline at end of file diff --git a/Examples/SystemCommandsBot/forms/CmdForm.cs b/Examples/SystemCommandsBot/forms/CmdForm.cs index d42e713..a5660fe 100644 --- a/Examples/SystemCommandsBot/forms/CmdForm.cs +++ b/Examples/SystemCommandsBot/forms/CmdForm.cs @@ -6,167 +6,151 @@ using System.Threading.Tasks; using TelegramBotBase.Base; using TelegramBotBase.Form; -namespace SystemCommandsBot.forms +namespace SystemCommandsBot.forms; + +public class CmdForm : AutoCleanForm { - public class CmdForm : AutoCleanForm + public DateTime ExpiresAt { get; set; } + + public int? MessageId { get; set; } + + public override Task Load(MessageResult message) { - public DateTime ExpiresAt { get; set; } - - public int? MessageId { get; set; } - - public override Task Load(MessageResult message) - { - return Task.CompletedTask; - } - - public override async Task Action(MessageResult message) - { - var btn = message.RawData; - - var id = -1; - - if (!int.TryParse(btn, out id)) - { - - return; - } - - var cmd = Program.BotConfig.Commandos.Where(a => a.Enabled && a.Id == id).FirstOrDefault(); - if (cmd == null) - { - await Device.Send("Cmd nicht verfügbar."); - return; - } - - message.Handled = true; - - switch (cmd.Action) - { - case "start": - - var fi = new FileInfo(cmd.ShellCmd); - - if (cmd.MaxInstances != null && cmd.MaxInstances >= 0) - { - - if (Process.GetProcessesByName(cmd.ProcName).Count() >= cmd.MaxInstances) - { - await Device.Send("Anwendung läuft bereits."); - await message.ConfirmAction("Anwendung läuft bereits."); - - return; - } - - } - - var psi = new ProcessStartInfo - { - FileName = cmd.ShellCmd, - WorkingDirectory = fi.DirectoryName, - UseShellExecute = cmd.UseShell - }; - - Process.Start(psi); - - await Device.Send(fi.Name + " wurde gestarted."); - - await message.ConfirmAction(fi.Name + " wurde gestarted."); - - break; - - case "kill": - - var fi2 = new FileInfo(cmd.ShellCmd); - - var pros = fi2.Name.Replace(fi2.Extension, ""); - - var proc = Process.GetProcessesByName(pros).ToList(); - - foreach (var p in proc) - { - try - { - p.Kill(); - } - catch - { - - } - } - - await Device.Send(fi2.Name + " wurde beendet."); - - await message.ConfirmAction(fi2.Name + " wurde beendet."); - - break; - - case "restart": - - var fi3 = new FileInfo(cmd.ShellCmd); - - var pros2 = fi3.Name.Replace(fi3.Extension, ""); - - var proc2 = Process.GetProcessesByName(pros2).ToList(); - - foreach (var p in proc2) - { - try - { - p.Kill(); - } - catch - { - - } - } - - var fi4 = new FileInfo(cmd.ShellCmd); - - var psi2 = new ProcessStartInfo - { - FileName = cmd.ShellCmd, - WorkingDirectory = fi4.DirectoryName - }; - psi2.FileName = cmd.ShellCmd; - psi2.UseShellExecute = cmd.UseShell; - - Process.Start(psi2); - - await Device.Send(fi3.Name + " wurde neugestarted."); - await message.ConfirmAction(fi3.Name + " wurde neugestarted."); - - - break; - - default: - - await message.ConfirmAction(); - - break; - - } - - - - - } - - public override async Task Render(MessageResult message) - { - if (MessageId == null) - { - var buttons = Program.BotConfig.Commandos.Where(a => a.Enabled).Select(a => new ButtonBase(a.Title, a.Id.ToString())); - - var bf = new ButtonForm(); - bf.AddSplitted(buttons, 1); - await Device.Send("Deine Optionen", bf); - } - - - } - - - - + return Task.CompletedTask; } -} + + public override async Task Action(MessageResult message) + { + var btn = message.RawData; + + var id = -1; + + if (!int.TryParse(btn, out id)) + { + return; + } + + var cmd = Program.BotConfig.Commandos.Where(a => a.Enabled && a.Id == id).FirstOrDefault(); + if (cmd == null) + { + await Device.Send("Cmd nicht verfügbar."); + return; + } + + message.Handled = true; + + switch (cmd.Action) + { + case "start": + + var fi = new FileInfo(cmd.ShellCmd); + + if (cmd.MaxInstances != null && cmd.MaxInstances >= 0) + { + if (Process.GetProcessesByName(cmd.ProcName).Count() >= cmd.MaxInstances) + { + await Device.Send("Anwendung läuft bereits."); + await message.ConfirmAction("Anwendung läuft bereits."); + + return; + } + } + + var psi = new ProcessStartInfo + { + FileName = cmd.ShellCmd, + WorkingDirectory = fi.DirectoryName, + UseShellExecute = cmd.UseShell + }; + + Process.Start(psi); + + await Device.Send(fi.Name + " wurde gestarted."); + + await message.ConfirmAction(fi.Name + " wurde gestarted."); + + break; + + case "kill": + + var fi2 = new FileInfo(cmd.ShellCmd); + + var pros = fi2.Name.Replace(fi2.Extension, ""); + + var proc = Process.GetProcessesByName(pros).ToList(); + + foreach (var p in proc) + { + try + { + p.Kill(); + } + catch + { + } + } + + await Device.Send(fi2.Name + " wurde beendet."); + + await message.ConfirmAction(fi2.Name + " wurde beendet."); + + break; + + case "restart": + + var fi3 = new FileInfo(cmd.ShellCmd); + + var pros2 = fi3.Name.Replace(fi3.Extension, ""); + + var proc2 = Process.GetProcessesByName(pros2).ToList(); + + foreach (var p in proc2) + { + try + { + p.Kill(); + } + catch + { + } + } + + var fi4 = new FileInfo(cmd.ShellCmd); + + var psi2 = new ProcessStartInfo + { + FileName = cmd.ShellCmd, + WorkingDirectory = fi4.DirectoryName + }; + psi2.FileName = cmd.ShellCmd; + psi2.UseShellExecute = cmd.UseShell; + + Process.Start(psi2); + + await Device.Send(fi3.Name + " wurde neugestarted."); + await message.ConfirmAction(fi3.Name + " wurde neugestarted."); + + + break; + + default: + + await message.ConfirmAction(); + + break; + } + } + + public override async Task Render(MessageResult message) + { + if (MessageId == null) + { + var buttons = Program.BotConfig.Commandos.Where(a => a.Enabled) + .Select(a => new ButtonBase(a.Title, a.Id.ToString())); + + var bf = new ButtonForm(); + bf.AddSplitted(buttons, 1); + await Device.Send("Deine Optionen", bf); + } + } +} \ No newline at end of file diff --git a/Examples/SystemCommandsBot/forms/StartForm.cs b/Examples/SystemCommandsBot/forms/StartForm.cs index ede4203..7b34f4d 100644 --- a/Examples/SystemCommandsBot/forms/StartForm.cs +++ b/Examples/SystemCommandsBot/forms/StartForm.cs @@ -3,39 +3,36 @@ using System.Threading.Tasks; using TelegramBotBase.Base; using TelegramBotBase.Form; -namespace SystemCommandsBot.forms +namespace SystemCommandsBot.forms; + +public class StartForm : FormBase { - public class StartForm : FormBase + public string Password { get; set; } + + public override Task Load(MessageResult message) { - public string Password { get; set; } - - public override Task Load(MessageResult message) + var inp = message.MessageText; + if (Program.BotConfig.Password == inp) { - var inp = message.MessageText; - if (Program.BotConfig.Password == inp) - { - Password = inp; - } - - return Task.CompletedTask; - } - - - public override async Task Render(MessageResult message) - { - if (Password == null || Password.Trim() == "") - { - await Device.Send("Bitte gib dein Passwort an."); - return; - } - - - var cmd = new CmdForm(); - cmd.ExpiresAt = DateTime.Now.AddDays(14); - - await NavigateTo(cmd); - + Password = inp; } + return Task.CompletedTask; } -} + + + public override async Task Render(MessageResult message) + { + if (Password == null || Password.Trim() == "") + { + await Device.Send("Bitte gib dein Passwort an."); + return; + } + + + var cmd = new CmdForm(); + cmd.ExpiresAt = DateTime.Now.AddDays(14); + + await NavigateTo(cmd); + } +} \ No newline at end of file diff --git a/TelegramBotBase.Extensions.Images/ImageExtensions.cs b/TelegramBotBase.Extensions.Images/ImageExtensions.cs index 314679c..7ed5dc0 100644 --- a/TelegramBotBase.Extensions.Images/ImageExtensions.cs +++ b/TelegramBotBase.Extensions.Images/ImageExtensions.cs @@ -20,7 +20,7 @@ namespace TelegramBotBase.Extensions.Images } /// - /// Sends an image + /// Sends an image /// /// /// @@ -28,18 +28,20 @@ namespace TelegramBotBase.Extensions.Images /// /// /// - public static async Task SendPhoto(this DeviceSession session, Image image, string name, string caption, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false) + public static async Task SendPhoto(this DeviceSession session, Image image, string name, + string caption, ButtonForm buttons = null, int replyTo = 0, + bool disableNotification = false) { using (var fileStream = ToStream(image, ImageFormat.Png)) { var fts = new InputOnlineFile(fileStream, name); - return await session.SendPhoto(fts, caption: caption, buttons, replyTo, disableNotification); + return await session.SendPhoto(fts, caption, buttons, replyTo, disableNotification); } } /// - /// Sends an image + /// Sends an image /// /// /// @@ -47,14 +49,16 @@ namespace TelegramBotBase.Extensions.Images /// /// /// - public static async Task SendPhoto(this DeviceSession session, Bitmap image, string name, string caption, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false) + public static async Task SendPhoto(this DeviceSession session, Bitmap image, string name, + string caption, ButtonForm buttons = null, int replyTo = 0, + bool disableNotification = false) { using (var fileStream = ToStream(image, ImageFormat.Png)) { var fts = new InputOnlineFile(fileStream, name); - return await session.SendPhoto(fts, caption: caption, buttons, replyTo, disableNotification); + return await session.SendPhoto(fts, caption, buttons, replyTo, disableNotification); } } } -} +} \ No newline at end of file diff --git a/TelegramBotBase.Extensions.Images/README.md b/TelegramBotBase.Extensions.Images/README.md index 2611a85..072c797 100644 --- a/TelegramBotBase.Extensions.Images/README.md +++ b/TelegramBotBase.Extensions.Images/README.md @@ -3,6 +3,5 @@ [![NuGet version (TelegramBotBase)](https://img.shields.io/nuget/v/TelegramBotBase.Extensions.Images.svg?style=flat-square)](https://www.nuget.org/packages/TelegramBotBase.Extensions.Images/) [![Telegram chat](https://img.shields.io/badge/Support_Chat-Telegram-blue.svg?style=flat-square)](https://www.t.me/tgbotbase) - [![License](https://img.shields.io/github/license/MajMcCloud/telegrambotframework.svg?style=flat-square&maxAge=2592000&label=License)](https://raw.githubusercontent.com/MajMcCloud/TelegramBotFramework/master/LICENCE.md) [![Package Downloads](https://img.shields.io/nuget/dt/TelegramBotBase.Extensions.Images.svg?style=flat-square&label=Package%20Downloads)](https://www.nuget.org/packages/TelegramBotBase.Extensions.Images) diff --git a/TelegramBotBase.Extensions.Images/TelegramBotBase.Extensions.Images.csproj b/TelegramBotBase.Extensions.Images/TelegramBotBase.Extensions.Images.csproj index 0b84053..942981b 100644 --- a/TelegramBotBase.Extensions.Images/TelegramBotBase.Extensions.Images.csproj +++ b/TelegramBotBase.Extensions.Images/TelegramBotBase.Extensions.Images.csproj @@ -1,24 +1,24 @@  - - netstandard2.0;net5;netcoreapp3.1;net6 - https://github.com/MajMcCloud/TelegramBotFramework - https://github.com/MajMcCloud/TelegramBotFramework - MIT - true - snupkg - + + netstandard2.0;net5;netcoreapp3.1;net6 + https://github.com/MajMcCloud/TelegramBotFramework + https://github.com/MajMcCloud/TelegramBotFramework + MIT + true + snupkg + - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + - - - + + + diff --git a/TelegramBotBase.Extensions.Serializer.Database.MSSQL/BotBaseBuilderExtensions.cs b/TelegramBotBase.Extensions.Serializer.Database.MSSQL/BotBaseBuilderExtensions.cs index 06e1611..028cc02 100644 --- a/TelegramBotBase.Extensions.Serializer.Database.MSSQL/BotBaseBuilderExtensions.cs +++ b/TelegramBotBase.Extensions.Serializer.Database.MSSQL/BotBaseBuilderExtensions.cs @@ -6,16 +6,17 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL { public static class BotBaseBuilderExtensions { - /// - /// Uses an Microsoft SQL Server Database to save and restore sessions. + /// Uses an Microsoft SQL Server Database to save and restore sessions. /// /// /// /// /// /// - public static ILanguageSelectionStage UseSqlDatabase(this ISessionSerializationStage builder, string connectionString, Type fallbackForm = null, string tablePrefix = "tgb_") + public static ILanguageSelectionStage UseSqlDatabase(this ISessionSerializationStage builder, + string connectionString, Type fallbackForm = null, + string tablePrefix = "tgb_") { var serializer = new MssqlSerializer(connectionString, tablePrefix, fallbackForm); @@ -26,7 +27,7 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL /// - /// Uses an Microsoft SQL Server Database to save and restore sessions. + /// Uses an Microsoft SQL Server Database to save and restore sessions. /// /// /// @@ -36,9 +37,12 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL /// /// /// - public static ILanguageSelectionStage UseSqlDatabase(this ISessionSerializationStage builder, string hostOrIP, string databaseName, string userId, string password, Type fallbackForm = null, string tablePrefix = "tgb_") + public static ILanguageSelectionStage UseSqlDatabase(this ISessionSerializationStage builder, string hostOrIP, + string databaseName, string userId, string password, + Type fallbackForm = null, string tablePrefix = "tgb_") { - var connectionString = $"Server={hostOrIP}; Database={databaseName}; User Id={userId}; Password={password}; TrustServerCertificate=true;"; + var connectionString = + $"Server={hostOrIP}; Database={databaseName}; User Id={userId}; Password={password}; TrustServerCertificate=true;"; var serializer = new MssqlSerializer(connectionString, tablePrefix, fallbackForm); @@ -48,7 +52,7 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL } /// - /// Uses an Microsoft SQL Server Database with Windows Authentication to save and restore sessions. + /// Uses an Microsoft SQL Server Database with Windows Authentication to save and restore sessions. /// /// /// @@ -56,12 +60,17 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL /// /// /// - public static ILanguageSelectionStage UseSqlDatabase(this ISessionSerializationStage builder, string hostOrIP, string databaseName, bool integratedSecurity = true, Type fallbackForm = null, string tablePrefix = "tgb_") + public static ILanguageSelectionStage UseSqlDatabase(this ISessionSerializationStage builder, string hostOrIP, + string databaseName, bool integratedSecurity = true, + Type fallbackForm = null, string tablePrefix = "tgb_") { if (!integratedSecurity) + { throw new ArgumentOutOfRangeException(); + } - var connectionString = $"Server={hostOrIP}; Database={databaseName}; Integrated Security=true; TrustServerCertificate=true;"; + var connectionString = + $"Server={hostOrIP}; Database={databaseName}; Integrated Security=true; TrustServerCertificate=true;"; var serializer = new MssqlSerializer(connectionString, tablePrefix, fallbackForm); @@ -70,4 +79,4 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL return builder as BotBaseBuilder; } } -} +} \ No newline at end of file diff --git a/TelegramBotBase.Extensions.Serializer.Database.MSSQL/MSSQLSerializer.cs b/TelegramBotBase.Extensions.Serializer.Database.MSSQL/MSSQLSerializer.cs index fe271e0..ed08d95 100644 --- a/TelegramBotBase.Extensions.Serializer.Database.MSSQL/MSSQLSerializer.cs +++ b/TelegramBotBase.Extensions.Serializer.Database.MSSQL/MSSQLSerializer.cs @@ -11,19 +11,19 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL { public class MssqlSerializer : IStateMachine { - public Type FallbackStateForm { get; set; } - public string ConnectionString { get; } - public string TablePrefix { get; set; } - /// - /// Will initialize the state machine. + /// Will initialize the state machine. /// /// Path of the file and name where to save the session details. - /// Type of Form which will be saved instead of Form which has attribute declared. Needs to be subclass of . + /// + /// Type of Form which will be saved instead of Form which has + /// attribute declared. Needs to be subclass of + /// . + /// /// Declares of the file could be overwritten. public MssqlSerializer(string connectionString, string tablePrefix = "tgb_", Type fallbackStateForm = null) { - this.ConnectionString = connectionString ?? throw new ArgumentNullException(nameof(connectionString)); + ConnectionString = connectionString ?? throw new ArgumentNullException(nameof(connectionString)); TablePrefix = tablePrefix; @@ -35,6 +35,10 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL } } + public string ConnectionString { get; } + public string TablePrefix { get; set; } + public Type FallbackStateForm { get; set; } + public StateContainer LoadFormStates() { var sc = new StateContainer(); @@ -44,7 +48,8 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL connection.Open(); var command = connection.CreateCommand(); - command.CommandText = "SELECT deviceId, deviceTitle, FormUri, QualifiedName FROM " + TablePrefix + "devices_sessions"; + command.CommandText = "SELECT deviceId, deviceTitle, FormUri, QualifiedName FROM " + TablePrefix + + "devices_sessions"; var dataTable = new DataTable(); using (var dataAdapter = new SqlDataAdapter(command)) @@ -73,7 +78,8 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL } var command2 = connection.CreateCommand(); - command2.CommandText = "SELECT [key], value, type FROM " + TablePrefix + "devices_sessions_data WHERE deviceId = @deviceId"; + command2.CommandText = "SELECT [key], value, type FROM " + TablePrefix + + "devices_sessions_data WHERE deviceId = @deviceId"; command2.Parameters.Add(new SqlParameter("@deviceId", r["deviceId"])); var dataTable2 = new DataTable(); @@ -91,13 +97,10 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL se.Values.Add(key, value); } } - } - } - connection.Close(); } @@ -127,13 +130,15 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL var sessionCommand = connection.CreateCommand(); var dataCommand = connection.CreateCommand(); - sessionCommand.CommandText = "INSERT INTO " + TablePrefix + "devices_sessions (deviceId, deviceTitle, FormUri, QualifiedName) VALUES (@deviceId, @deviceTitle, @FormUri, @QualifiedName)"; + sessionCommand.CommandText = "INSERT INTO " + TablePrefix + + "devices_sessions (deviceId, deviceTitle, FormUri, QualifiedName) VALUES (@deviceId, @deviceTitle, @FormUri, @QualifiedName)"; sessionCommand.Parameters.Add(new SqlParameter("@deviceId", "")); sessionCommand.Parameters.Add(new SqlParameter("@deviceTitle", "")); sessionCommand.Parameters.Add(new SqlParameter("@FormUri", "")); sessionCommand.Parameters.Add(new SqlParameter("@QualifiedName", "")); - dataCommand.CommandText = "INSERT INTO " + TablePrefix + "devices_sessions_data (deviceId, [key], value, type) VALUES (@deviceId, @key, @value, @type)"; + dataCommand.CommandText = "INSERT INTO " + TablePrefix + + "devices_sessions_data (deviceId, [key], value, type) VALUES (@deviceId, @key, @value, @type)"; dataCommand.Parameters.Add(new SqlParameter("@deviceId", "")); dataCommand.Parameters.Add(new SqlParameter("@key", "")); dataCommand.Parameters.Add(new SqlParameter("@value", "")); @@ -169,13 +174,10 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL dataCommand.ExecuteNonQuery(); } - } connection.Close(); } - - } } -} +} \ No newline at end of file diff --git a/TelegramBotBase.Extensions.Serializer.Database.MSSQL/README.md b/TelegramBotBase.Extensions.Serializer.Database.MSSQL/README.md index 1a7f027..1255d6e 100644 --- a/TelegramBotBase.Extensions.Serializer.Database.MSSQL/README.md +++ b/TelegramBotBase.Extensions.Serializer.Database.MSSQL/README.md @@ -3,7 +3,6 @@ [![NuGet version (TelegramBotBase)](https://img.shields.io/nuget/v/TelegramBotBase.Extensions.Serializer.Database.MSSQL.svg?style=flat-square)](https://www.nuget.org/packages/TelegramBotBase.Extensions.Serializer.Database.MSSQL/) [![Telegram chat](https://img.shields.io/badge/Support_Chat-Telegram-blue.svg?style=flat-square)](https://www.t.me/tgbotbase) - [![License](https://img.shields.io/github/license/MajMcCloud/telegrambotframework.svg?style=flat-square&maxAge=2592000&label=License)](https://raw.githubusercontent.com/MajMcCloud/TelegramBotFramework/master/LICENCE.md) [![Package Downloads](https://img.shields.io/nuget/dt/TelegramBotBase.Extensions.Serializer.Database.MSSQL.svg?style=flat-square&label=Package%20Downloads)](https://www.nuget.org/packages/TelegramBotBase.Extensions.Serializer.Database.MSSQL) diff --git a/TelegramBotBase.Extensions.Serializer.Database.MSSQL/TelegramBotBase.Extensions.Serializer.Database.MSSQL.csproj b/TelegramBotBase.Extensions.Serializer.Database.MSSQL/TelegramBotBase.Extensions.Serializer.Database.MSSQL.csproj index a0d40f7..4782e67 100644 --- a/TelegramBotBase.Extensions.Serializer.Database.MSSQL/TelegramBotBase.Extensions.Serializer.Database.MSSQL.csproj +++ b/TelegramBotBase.Extensions.Serializer.Database.MSSQL/TelegramBotBase.Extensions.Serializer.Database.MSSQL.csproj @@ -1,30 +1,30 @@  - - netstandard2.0;net5;netcoreapp3.1;net6 - True - https://github.com/MajMcCloud/TelegramBotFramework - https://github.com/MajMcCloud/TelegramBotFramework - MIT - true - snupkg - 1.0.1 - 1.0.1 - 1.0.1 - A session serializer for Microsoft SQL Server. - - + + netstandard2.0;net5;netcoreapp3.1;net6 + True + https://github.com/MajMcCloud/TelegramBotFramework + https://github.com/MajMcCloud/TelegramBotFramework + MIT + true + snupkg + 1.0.1 + 1.0.1 + 1.0.1 + A session serializer for Microsoft SQL Server. + + - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + - - - + + + diff --git a/TelegramBotBase.Extensions.Serializer.Database.MSSQL/create_tables.sql b/TelegramBotBase.Extensions.Serializer.Database.MSSQL/create_tables.sql index 587eb4f..8d895f8 100644 --- a/TelegramBotBase.Extensions.Serializer.Database.MSSQL/create_tables.sql +++ b/TelegramBotBase.Extensions.Serializer.Database.MSSQL/create_tables.sql @@ -1,37 +1,81 @@ -USE [telegram_bot] +USE +[telegram_bot] GO /****** Object: Table [dbo].[tgb_devices_sessions] Script Date: 30.06.2022 16:22:09 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -CREATE TABLE [dbo].[tgb_devices_sessions]( - [deviceId] [bigint] NOT NULL, - [deviceTitle] [nvarchar](512) NOT NULL, - [FormUri] [nvarchar](512) NOT NULL, - [QualifiedName] [nvarchar](512) NOT NULL, - CONSTRAINT [PK_tgb_devices_sessions_1] PRIMARY KEY CLUSTERED +CREATE TABLE [dbo].[tgb_devices_sessions] ( - [deviceId] ASC -)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY] -) ON [PRIMARY] -GO + [ + deviceId] [ + bigint] + NOT + NULL, [ + deviceTitle] [ + nvarchar] +( + 512 +) NOT NULL, + [FormUri] [nvarchar] +( + 512 +) NOT NULL, + [QualifiedName] [nvarchar] +( + 512 +) NOT NULL, + CONSTRAINT [PK_tgb_devices_sessions_1] PRIMARY KEY CLUSTERED +( +[ + deviceId] ASC +) + WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) + ON [PRIMARY] + ) + ON [PRIMARY] + GO /****** Object: Table [dbo].[tgb_devices_sessions_data] Script Date: 30.06.2022 16:22:09 ******/ -SET ANSI_NULLS ON -GO -SET QUOTED_IDENTIFIER ON -GO -CREATE TABLE [dbo].[tgb_devices_sessions_data]( - [Id] [uniqueidentifier] NOT NULL, - [deviceId] [bigint] NOT NULL, - [key] [nvarchar](512) NOT NULL, - [value] [nvarchar](max) NOT NULL, - [type] [nvarchar](512) NOT NULL, - CONSTRAINT [PK_tgb_devices_session_data] PRIMARY KEY CLUSTERED + SET ANSI_NULLS + ON + GO + SET QUOTED_IDENTIFIER + ON + GO +CREATE TABLE [dbo].[tgb_devices_sessions_data] ( - [Id] ASC -)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY] -) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] -GO -ALTER TABLE [dbo].[tgb_devices_sessions_data] ADD CONSTRAINT [DF_tgb_devices_session_data_Id] DEFAULT (newid()) FOR [Id] -GO + [ + Id] [ + uniqueidentifier] + NOT + NULL, [ + deviceId] [ + bigint] + NOT + NULL, [ + key] [ + nvarchar] +( + 512 +) NOT NULL, + [value] [nvarchar] +( + max +) NOT NULL, + [type] [nvarchar] +( + 512 +) NOT NULL, + CONSTRAINT [PK_tgb_devices_session_data] PRIMARY KEY CLUSTERED +( +[ + Id] ASC +) + WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) + ON [PRIMARY] + ) + ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] + GO +ALTER TABLE [dbo].[tgb_devices_sessions_data] ADD CONSTRAINT [DF_tgb_devices_session_data_Id] DEFAULT (newid()) FOR [Id] + GO diff --git a/TelegramBotBase.Test/App.config b/TelegramBotBase.Test/App.config index fa1ddef..94f3e49 100644 --- a/TelegramBotBase.Test/App.config +++ b/TelegramBotBase.Test/App.config @@ -1,14 +1,14 @@ - + - - - - - - - - + + + + + + + + diff --git a/TelegramBotBase.Test/Program.cs b/TelegramBotBase.Test/Program.cs index a1d4b31..044dba2 100644 --- a/TelegramBotBase.Test/Program.cs +++ b/TelegramBotBase.Test/Program.cs @@ -7,109 +7,106 @@ using TelegramBotBase.Commands; using TelegramBotBase.Enums; using TelegramBotBaseTest.Tests; -namespace TelegramBotBaseTest +namespace TelegramBotBaseTest; + +internal class Program { - internal class Program + private static void Main(string[] args) { - private static void Main(string[] args) + var apiKey = ""; + + var bb = BotBaseBuilder + .Create() + .WithAPIKey(apiKey) + .DefaultMessageLoop() + .WithStartForm() + .NoProxy() + .CustomCommands(a => + { + a.Start("Starts the bot"); + a.Add("myid", "Returns my Device ID"); + a.Help("Should show you some help"); + a.Settings("Should show you some settings"); + a.Add("form1", "Opens test form 1"); + a.Add("form2", "Opens test form 2"); + a.Add("params", "Returns all send parameters as a message."); + }) + .NoSerialization() + .UseEnglish() + .Build(); + + + bb.BotCommand += Bb_BotCommand; + + //Update Bot commands to botfather + bb.UploadBotCommands().Wait(); + + bb.SetSetting(ESettings.LogAllMessages, true); + + bb.Message += (s, en) => { + Console.WriteLine(en.DeviceId + " " + en.Message.MessageText + " " + (en.Message.RawData ?? "")); + }; - var apiKey = ""; + bb.Start(); - var bb = BotBaseBuilder - .Create() - .WithAPIKey(apiKey) - .DefaultMessageLoop() - .WithStartForm() - .NoProxy() - .CustomCommands(a => - { - a.Start("Starts the bot"); - a.Add("myid", "Returns my Device ID"); - a.Help("Should show you some help"); - a.Settings("Should show you some settings"); - a.Add("form1", "Opens test form 1"); - a.Add("form2", "Opens test form 2"); - a.Add("params", "Returns all send parameters as a message."); - }) - .NoSerialization() - .UseEnglish() - .Build(); + Console.WriteLine("Telegram Bot started..."); + + Console.WriteLine("Press q to quit application."); - bb.BotCommand += Bb_BotCommand; + Console.ReadLine(); - //Update Bot commands to botfather - bb.UploadBotCommands().Wait(); + bb.Stop(); + } - bb.SetSetting(ESettings.LogAllMessages, true); - - bb.Message += (s, en) => - { - Console.WriteLine(en.DeviceId + " " + en.Message.MessageText + " " + (en.Message.RawData ?? "")); - }; - - bb.Start(); - - Console.WriteLine("Telegram Bot started..."); - - Console.WriteLine("Press q to quit application."); - - - Console.ReadLine(); - - bb.Stop(); - - } - - private static async Task Bb_BotCommand(object sender, BotCommandEventArgs en) + private static async Task Bb_BotCommand(object sender, BotCommandEventArgs en) + { + switch (en.Command) { - switch (en.Command) - { - case "/start": + case "/start": - var start = new Menu(); + var start = new Menu(); - await en.Device.ActiveForm.NavigateTo(start); + await en.Device.ActiveForm.NavigateTo(start); - break; - case "/form1": + break; + case "/form1": - var form1 = new TestForm(); + var form1 = new TestForm(); - await en.Device.ActiveForm.NavigateTo(form1); + await en.Device.ActiveForm.NavigateTo(form1); - break; + break; - case "/form2": + case "/form2": - var form2 = new TestForm2(); + var form2 = new TestForm2(); - await en.Device.ActiveForm.NavigateTo(form2); + await en.Device.ActiveForm.NavigateTo(form2); - break; + break; - case "/myid": + case "/myid": - await en.Device.Send($"Your Device ID is: {en.DeviceId}"); + await en.Device.Send($"Your Device ID is: {en.DeviceId}"); - en.Handled = true; + en.Handled = true; - break; + break; - case "/params": + case "/params": - var m = en.Parameters.DefaultIfEmpty("").Aggregate((a, b) => a + " and " + b); + var m = en.Parameters.DefaultIfEmpty("").Aggregate((a, b) => a + " and " + b); - await en.Device.Send("Your parameters are: " + m, replyTo: en.Device.LastMessageId); + await en.Device.Send("Your parameters are: " + m, replyTo: en.Device.LastMessageId); - en.Handled = true; + en.Handled = true; - break; - } + break; } } } diff --git a/TelegramBotBase.Test/Properties/AssemblyInfo.cs b/TelegramBotBase.Test/Properties/AssemblyInfo.cs index 53a2683..af85f77 100644 --- a/TelegramBotBase.Test/Properties/AssemblyInfo.cs +++ b/TelegramBotBase.Test/Properties/AssemblyInfo.cs @@ -32,4 +32,4 @@ using System.Runtime.InteropServices; // übernehmen, indem Sie "*" eingeben: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] \ No newline at end of file diff --git a/TelegramBotBase.Test/TelegramBotBaseTest.csproj b/TelegramBotBase.Test/TelegramBotBaseTest.csproj index a1abbf6..c40ee57 100644 --- a/TelegramBotBase.Test/TelegramBotBaseTest.csproj +++ b/TelegramBotBase.Test/TelegramBotBaseTest.csproj @@ -1,34 +1,35 @@  - - Exe - netcoreapp3.1;net5;net6 - false - Debug;Release - - - AnyCPU - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - AnyCPU - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - + + Exe + netcoreapp3.1;net5;net6 + 10 + false + Debug;Release + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + - - - - + + + + diff --git a/TelegramBotBase.Test/Tests/ButtonTestForm.cs b/TelegramBotBase.Test/Tests/ButtonTestForm.cs index 8f89af6..f19b7d0 100644 --- a/TelegramBotBase.Test/Tests/ButtonTestForm.cs +++ b/TelegramBotBase.Test/Tests/ButtonTestForm.cs @@ -3,97 +3,92 @@ using System.Threading.Tasks; using TelegramBotBase.Base; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests +namespace TelegramBotBaseTest.Tests; + +public class ButtonTestForm : AutoCleanForm { - public class ButtonTestForm : AutoCleanForm + public ButtonTestForm() { + Opened += ButtonTestForm_Opened; + } - public ButtonTestForm() + private async Task ButtonTestForm_Opened(object sender, EventArgs e) + { + await Device.Send("Hello world! (Click 'back' to get back to Start)"); + } + + public override async Task Action(MessageResult message) + { + var call = message.GetData(); + + await message.ConfirmAction(); + + + if (call == null) { - Opened += ButtonTestForm_Opened; + return; } - private async Task ButtonTestForm_Opened(object sender, EventArgs e) + message.Handled = true; + + switch (call.Value) { - await Device.Send("Hello world! (Click 'back' to get back to Start)"); - } + case "button1": - public override async Task Action(MessageResult message) - { + await Device.Send("Button 1 pressed"); - var call = message.GetData(); + break; - await message.ConfirmAction(); + case "button2": + await Device.Send("Button 2 pressed"); - if (call == null) - return; + break; - message.Handled = true; + case "button3": - switch (call.Value) - { - case "button1": + await Device.Send("Button 3 pressed"); - await Device.Send("Button 1 pressed"); + break; - break; + case "button4": - case "button2": + await Device.Send("Button 4 pressed"); - await Device.Send("Button 2 pressed"); + break; - break; + case "back": - case "button3": + var st = new Menu(); - await Device.Send("Button 3 pressed"); + await NavigateTo(st); - break; + break; - case "button4": - - await Device.Send("Button 4 pressed"); - - break; - - case "back": - - var st = new Menu(); - - await NavigateTo(st); - - break; - - default: - - message.Handled = false; - - break; - } - - - } - - - public override async Task Render(MessageResult message) - { - - var btn = new ButtonForm(); - - btn.AddButtonRow(new ButtonBase("Button 1", new CallbackData("a", "button1").Serialize()), new ButtonBase("Button 2", new CallbackData("a", "button2").Serialize())); - - btn.AddButtonRow(new ButtonBase("Button 3", new CallbackData("a", "button3").Serialize()), new ButtonBase("Button 4", new CallbackData("a", "button4").Serialize())); - - btn.AddButtonRow(new ButtonBase("Google.com", "google", "https://www.google.com"), new ButtonBase("Telegram", "telegram", "https://telegram.org/")); - - btn.AddButtonRow(new ButtonBase("Back", new CallbackData("a", "back").Serialize())); - - await Device.Send("Click a button", btn); + default: + message.Handled = false; + break; } } -} + public override async Task Render(MessageResult message) + { + var btn = new ButtonForm(); + + btn.AddButtonRow(new ButtonBase("Button 1", new CallbackData("a", "button1").Serialize()), + new ButtonBase("Button 2", new CallbackData("a", "button2").Serialize())); + + btn.AddButtonRow(new ButtonBase("Button 3", new CallbackData("a", "button3").Serialize()), + new ButtonBase("Button 4", new CallbackData("a", "button4").Serialize())); + + btn.AddButtonRow(new ButtonBase("Google.com", "google", "https://www.google.com"), + new ButtonBase("Telegram", "telegram", "https://telegram.org/")); + + btn.AddButtonRow(new ButtonBase("Back", new CallbackData("a", "back").Serialize())); + + await Device.Send("Click a button", btn); + } +} \ No newline at end of file diff --git a/TelegramBotBase.Test/Tests/Controls/ButtonGridForm.cs b/TelegramBotBase.Test/Tests/Controls/ButtonGridForm.cs index 3a7bdd9..0669d2e 100644 --- a/TelegramBotBase.Test/Tests/Controls/ButtonGridForm.cs +++ b/TelegramBotBase.Test/Tests/Controls/ButtonGridForm.cs @@ -4,68 +4,66 @@ using TelegramBotBase.Controls.Hybrid; using TelegramBotBase.Enums; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Controls +namespace TelegramBotBaseTest.Tests.Controls; + +public class ButtonGridForm : AutoCleanForm { - public class ButtonGridForm : AutoCleanForm + private ButtonGrid _mButtons; + + public ButtonGridForm() { - private ButtonGrid _mButtons; + DeleteMode = EDeleteMode.OnLeavingForm; - public ButtonGridForm() + Init += ButtonGridForm_Init; + } + + private Task ButtonGridForm_Init(object sender, InitEventArgs e) + { + _mButtons = new ButtonGrid { - DeleteMode = EDeleteMode.OnLeavingForm; + KeyboardType = EKeyboardType.InlineKeyBoard + }; - Init += ButtonGridForm_Init; + var bf = new ButtonForm(); + + bf.AddButtonRow(new ButtonBase("Back", "back"), new ButtonBase("Switch Keyboard", "switch")); + + bf.AddButtonRow(new ButtonBase("Button1", "b1"), new ButtonBase("Button2", "b2")); + + bf.AddButtonRow(new ButtonBase("Button3", "b3"), new ButtonBase("Button4", "b4")); + + _mButtons.ButtonsForm = bf; + + _mButtons.ButtonClicked += Bg_ButtonClicked; + + AddControl(_mButtons); + return Task.CompletedTask; + } + + private async Task Bg_ButtonClicked(object sender, ButtonClickedEventArgs e) + { + if (e.Button == null) + { + return; } - private Task ButtonGridForm_Init(object sender, InitEventArgs e) + if (e.Button.Value == "back") { - _mButtons = new ButtonGrid + var start = new Menu(); + await NavigateTo(start); + } + else if (e.Button.Value == "switch") + { + _mButtons.KeyboardType = _mButtons.KeyboardType switch { - KeyboardType = EKeyboardType.InlineKeyBoard + EKeyboardType.ReplyKeyboard => EKeyboardType.InlineKeyBoard, + EKeyboardType.InlineKeyBoard => EKeyboardType.ReplyKeyboard, + _ => _mButtons.KeyboardType }; - - var bf = new ButtonForm(); - - bf.AddButtonRow(new ButtonBase("Back", "back"), new ButtonBase("Switch Keyboard", "switch")); - - bf.AddButtonRow(new ButtonBase("Button1", "b1"), new ButtonBase("Button2", "b2")); - - bf.AddButtonRow(new ButtonBase("Button3", "b3"), new ButtonBase("Button4", "b4")); - - _mButtons.ButtonsForm = bf; - - _mButtons.ButtonClicked += Bg_ButtonClicked; - - AddControl(_mButtons); - return Task.CompletedTask; } - - private async Task Bg_ButtonClicked(object sender, ButtonClickedEventArgs e) + else { - if (e.Button == null) - return; - - if (e.Button.Value == "back") - { - var start = new Menu(); - await NavigateTo(start); - } - else if (e.Button.Value == "switch") - { - _mButtons.KeyboardType = _mButtons.KeyboardType switch - { - EKeyboardType.ReplyKeyboard => EKeyboardType.InlineKeyBoard, - EKeyboardType.InlineKeyBoard => EKeyboardType.ReplyKeyboard, - _ => _mButtons.KeyboardType - }; - } - else - { - - await Device.Send($"Button clicked with Text: {e.Button.Text} and Value {e.Button.Value}"); - } - - + await Device.Send($"Button clicked with Text: {e.Button.Text} and Value {e.Button.Value}"); } } -} +} \ No newline at end of file diff --git a/TelegramBotBase.Test/Tests/Controls/ButtonGridPagingForm.cs b/TelegramBotBase.Test/Tests/Controls/ButtonGridPagingForm.cs index cc62321..47d6205 100644 --- a/TelegramBotBase.Test/Tests/Controls/ButtonGridPagingForm.cs +++ b/TelegramBotBase.Test/Tests/Controls/ButtonGridPagingForm.cs @@ -6,63 +6,61 @@ using TelegramBotBase.Controls.Hybrid; using TelegramBotBase.Enums; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Controls +namespace TelegramBotBaseTest.Tests.Controls; + +public class ButtonGridPagingForm : AutoCleanForm { - public class ButtonGridPagingForm : AutoCleanForm + private ButtonGrid _mButtons; + + public ButtonGridPagingForm() { - private ButtonGrid _mButtons; + DeleteMode = EDeleteMode.OnLeavingForm; - public ButtonGridPagingForm() + Init += ButtonGridForm_Init; + } + + private Task ButtonGridForm_Init(object sender, InitEventArgs e) + { + _mButtons = new ButtonGrid { - DeleteMode = EDeleteMode.OnLeavingForm; + KeyboardType = EKeyboardType.ReplyKeyboard, + EnablePaging = true, + EnableSearch = true, + HeadLayoutButtonRow = new List { new("Back", "back") } + }; - Init += ButtonGridForm_Init; + var countries = CultureInfo.GetCultures(CultureTypes.SpecificCultures); + + var bf = new ButtonForm(); + + foreach (var c in countries) + { + bf.AddButtonRow(new ButtonBase(c.EnglishName, c.EnglishName)); } - private Task ButtonGridForm_Init(object sender, InitEventArgs e) + _mButtons.ButtonsForm = bf; + + _mButtons.ButtonClicked += Bg_ButtonClicked; + + AddControl(_mButtons); + return Task.CompletedTask; + } + + private async Task Bg_ButtonClicked(object sender, ButtonClickedEventArgs e) + { + if (e.Button == null) { - _mButtons = new ButtonGrid - { - KeyboardType = EKeyboardType.ReplyKeyboard, - EnablePaging = true, - EnableSearch = true, - HeadLayoutButtonRow = new List { new ButtonBase("Back", "back") } - }; - - var countries = CultureInfo.GetCultures(CultureTypes.SpecificCultures); - - var bf = new ButtonForm(); - - foreach (var c in countries) - { - bf.AddButtonRow(new ButtonBase(c.EnglishName, c.EnglishName)); - } - - _mButtons.ButtonsForm = bf; - - _mButtons.ButtonClicked += Bg_ButtonClicked; - - AddControl(_mButtons); - return Task.CompletedTask; + return; } - private async Task Bg_ButtonClicked(object sender, ButtonClickedEventArgs e) + if (e.Button.Value == "back") { - if (e.Button == null) - return; - - if (e.Button.Value == "back") - { - var start = new Menu(); - await NavigateTo(start); - } - else - { - - await Device.Send($"Button clicked with Text: {e.Button.Text} and Value {e.Button.Value}"); - } - - + var start = new Menu(); + await NavigateTo(start); + } + else + { + await Device.Send($"Button clicked with Text: {e.Button.Text} and Value {e.Button.Value}"); } } -} +} \ No newline at end of file diff --git a/TelegramBotBase.Test/Tests/Controls/ButtonGridTagForm.cs b/TelegramBotBase.Test/Tests/Controls/ButtonGridTagForm.cs index 510f208..23b4b1d 100644 --- a/TelegramBotBase.Test/Tests/Controls/ButtonGridTagForm.cs +++ b/TelegramBotBase.Test/Tests/Controls/ButtonGridTagForm.cs @@ -8,68 +8,67 @@ using TelegramBotBase.DataSources; using TelegramBotBase.Enums; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Controls +namespace TelegramBotBaseTest.Tests.Controls; + +public class ButtonGridTagForm : AutoCleanForm { - public class ButtonGridTagForm : AutoCleanForm + private TaggedButtonGrid _mButtons; + + public ButtonGridTagForm() { - private TaggedButtonGrid _mButtons; + DeleteMode = EDeleteMode.OnLeavingForm; - public ButtonGridTagForm() - { - DeleteMode = EDeleteMode.OnLeavingForm; - - Init += ButtonGridTagForm_Init; - } - - private Task ButtonGridTagForm_Init(object sender, InitEventArgs e) - { - _mButtons = new TaggedButtonGrid - { - KeyboardType = EKeyboardType.ReplyKeyboard, - EnablePaging = true, - HeadLayoutButtonRow = new List { new ButtonBase("Back", "back") } - }; - - - var countries = CultureInfo.GetCultures(CultureTypes.SpecificCultures); - - var bf = new ButtonForm(); - - foreach (var c in countries) - { - bf.AddButtonRow(new TagButtonBase(c.EnglishName, c.EnglishName, c.Parent.EnglishName)); - } - - _mButtons.Tags = countries.Select(a => a.Parent.EnglishName).Distinct().OrderBy(a => a).ToList(); - _mButtons.SelectedTags = countries.Select(a => a.Parent.EnglishName).Distinct().OrderBy(a => a).ToList(); - - _mButtons.EnableCheckAllTools = true; - - _mButtons.DataSource = new ButtonFormDataSource(bf); - - _mButtons.ButtonClicked += Bg_ButtonClicked; - - AddControl(_mButtons); - return Task.CompletedTask; - } - - private async Task Bg_ButtonClicked(object sender, ButtonClickedEventArgs e) - { - if (e.Button == null) - return; - - switch (e.Button.Value) - { - - case "back": - var start = new Menu(); - await NavigateTo(start); - return; - - } - - - await Device.Send($"Button clicked with Text: {e.Button.Text} and Value {e.Button.Value}"); - } + Init += ButtonGridTagForm_Init; } -} + + private Task ButtonGridTagForm_Init(object sender, InitEventArgs e) + { + _mButtons = new TaggedButtonGrid + { + KeyboardType = EKeyboardType.ReplyKeyboard, + EnablePaging = true, + HeadLayoutButtonRow = new List { new("Back", "back") } + }; + + + var countries = CultureInfo.GetCultures(CultureTypes.SpecificCultures); + + var bf = new ButtonForm(); + + foreach (var c in countries) + { + bf.AddButtonRow(new TagButtonBase(c.EnglishName, c.EnglishName, c.Parent.EnglishName)); + } + + _mButtons.Tags = countries.Select(a => a.Parent.EnglishName).Distinct().OrderBy(a => a).ToList(); + _mButtons.SelectedTags = countries.Select(a => a.Parent.EnglishName).Distinct().OrderBy(a => a).ToList(); + + _mButtons.EnableCheckAllTools = true; + + _mButtons.DataSource = new ButtonFormDataSource(bf); + + _mButtons.ButtonClicked += Bg_ButtonClicked; + + AddControl(_mButtons); + return Task.CompletedTask; + } + + private async Task Bg_ButtonClicked(object sender, ButtonClickedEventArgs e) + { + if (e.Button == null) + { + return; + } + + switch (e.Button.Value) + { + case "back": + var start = new Menu(); + await NavigateTo(start); + return; + } + + + await Device.Send($"Button clicked with Text: {e.Button.Text} and Value {e.Button.Value}"); + } +} \ No newline at end of file diff --git a/TelegramBotBase.Test/Tests/Controls/CalendarPickerForm.cs b/TelegramBotBase.Test/Tests/Controls/CalendarPickerForm.cs index 4d1eaac..69de30f 100644 --- a/TelegramBotBase.Test/Tests/Controls/CalendarPickerForm.cs +++ b/TelegramBotBase.Test/Tests/Controls/CalendarPickerForm.cs @@ -5,75 +5,65 @@ using TelegramBotBase.Controls.Inline; using TelegramBotBase.Enums; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Controls +namespace TelegramBotBaseTest.Tests.Controls; + +public class CalendarPickerForm : AutoCleanForm { - public class CalendarPickerForm : AutoCleanForm + public CalendarPickerForm() { - - public CalendarPicker Picker { get; set; } - - private int? SelectedDateMessage { get; set; } - - public CalendarPickerForm() - { - DeleteMode = EDeleteMode.OnLeavingForm; - Init += CalendarPickerForm_Init; - } - - private Task CalendarPickerForm_Init(object sender, InitEventArgs e) - { - Picker = new CalendarPicker - { - Title = "Datum auswählen / Pick date" - }; - - AddControl(Picker); - return Task.CompletedTask; - } - - - public override async Task Action(MessageResult message) - { - - switch(message.RawData) - { - case "back": - - var s = new Menu(); - - await NavigateTo(s); - - break; - } - - } - - public override async Task Render(MessageResult message) - { - var s = ""; - - s = "Selected date is " + Picker.SelectedDate.ToShortDateString() + "\r\n"; - s += "Selected month is " + Picker.Culture.DateTimeFormat.MonthNames[Picker.VisibleMonth.Month - 1] + "\r\n"; - s += "Selected year is " + Picker.VisibleMonth.Year; - - var bf = new ButtonForm(); - bf.AddButtonRow(new ButtonBase("Back","back")); - - if (SelectedDateMessage != null) - { - await Device.Edit(SelectedDateMessage.Value, s, bf); - } - else - { - var m = await Device.Send(s, bf); - SelectedDateMessage = m.MessageId; - } - - - - } - - - + DeleteMode = EDeleteMode.OnLeavingForm; + Init += CalendarPickerForm_Init; } -} + + public CalendarPicker Picker { get; set; } + + private int? SelectedDateMessage { get; set; } + + private Task CalendarPickerForm_Init(object sender, InitEventArgs e) + { + Picker = new CalendarPicker + { + Title = "Datum auswählen / Pick date" + }; + + AddControl(Picker); + return Task.CompletedTask; + } + + + public override async Task Action(MessageResult message) + { + switch (message.RawData) + { + case "back": + + var s = new Menu(); + + await NavigateTo(s); + + break; + } + } + + public override async Task Render(MessageResult message) + { + var s = ""; + + s = "Selected date is " + Picker.SelectedDate.ToShortDateString() + "\r\n"; + s += "Selected month is " + Picker.Culture.DateTimeFormat.MonthNames[Picker.VisibleMonth.Month - 1] + "\r\n"; + s += "Selected year is " + Picker.VisibleMonth.Year; + + var bf = new ButtonForm(); + bf.AddButtonRow(new ButtonBase("Back", "back")); + + if (SelectedDateMessage != null) + { + await Device.Edit(SelectedDateMessage.Value, s, bf); + } + else + { + var m = await Device.Send(s, bf); + SelectedDateMessage = m.MessageId; + } + } +} \ No newline at end of file diff --git a/TelegramBotBase.Test/Tests/Controls/CheckedButtonListForm.cs b/TelegramBotBase.Test/Tests/Controls/CheckedButtonListForm.cs index 6906c4f..33849ae 100644 --- a/TelegramBotBase.Test/Tests/Controls/CheckedButtonListForm.cs +++ b/TelegramBotBase.Test/Tests/Controls/CheckedButtonListForm.cs @@ -6,81 +6,81 @@ using TelegramBotBase.DataSources; using TelegramBotBase.Enums; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Controls +namespace TelegramBotBaseTest.Tests.Controls; + +public class CheckedButtonListForm : AutoCleanForm { - public class CheckedButtonListForm : AutoCleanForm + private CheckedButtonList _mButtons; + + public CheckedButtonListForm() { - private CheckedButtonList _mButtons; + DeleteMode = EDeleteMode.OnLeavingForm; - public CheckedButtonListForm() + Init += CheckedButtonListForm_Init; + } + + private Task CheckedButtonListForm_Init(object sender, InitEventArgs e) + { + _mButtons = new CheckedButtonList { - DeleteMode = EDeleteMode.OnLeavingForm; + KeyboardType = EKeyboardType.InlineKeyBoard, + EnablePaging = true, + HeadLayoutButtonRow = new List { new("Back", "back"), new("Switch Keyboard", "switch") }, + SubHeadLayoutButtonRow = new List { new("No checked items", "$") } + }; - Init += CheckedButtonListForm_Init; + var bf = new ButtonForm(); + + for (var i = 0; i < 30; i++) + { + bf.AddButtonRow($"{i + 1}. Item", i.ToString()); } - private Task CheckedButtonListForm_Init(object sender, InitEventArgs e) + _mButtons.DataSource = new ButtonFormDataSource(bf); + + _mButtons.ButtonClicked += Bg_ButtonClicked; + _mButtons.CheckedChanged += M_Buttons_CheckedChanged; + + AddControl(_mButtons); + return Task.CompletedTask; + } + + private Task M_Buttons_CheckedChanged(object sender, CheckedChangedEventArgs e) + { + _mButtons.SubHeadLayoutButtonRow = new List + { new($"{_mButtons.CheckedItems.Count} checked items", "$") }; + return Task.CompletedTask; + } + + private async Task Bg_ButtonClicked(object sender, ButtonClickedEventArgs e) + { + if (e.Button == null) { - _mButtons = new CheckedButtonList - { - KeyboardType = EKeyboardType.InlineKeyBoard, - EnablePaging = true, - HeadLayoutButtonRow = new List { new ButtonBase("Back", "back"), new ButtonBase("Switch Keyboard", "switch") }, - SubHeadLayoutButtonRow = new List { new ButtonBase("No checked items", "$") } - }; - - var bf = new ButtonForm(); - - for (var i = 0; i < 30; i++) - { - bf.AddButtonRow($"{i + 1}. Item", i.ToString()); - } - - _mButtons.DataSource = new ButtonFormDataSource(bf); - - _mButtons.ButtonClicked += Bg_ButtonClicked; - _mButtons.CheckedChanged += M_Buttons_CheckedChanged; - - AddControl(_mButtons); - return Task.CompletedTask; + return; } - private Task M_Buttons_CheckedChanged(object sender, CheckedChangedEventArgs e) + switch (e.Button.Value) { - _mButtons.SubHeadLayoutButtonRow = new List { new ButtonBase($"{_mButtons.CheckedItems.Count} checked items", "$") }; - return Task.CompletedTask; - } + case "back": - private async Task Bg_ButtonClicked(object sender, ButtonClickedEventArgs e) - { - if (e.Button == null) - return; - - switch (e.Button.Value) - { - case "back": - - var start = new Menu(); - await NavigateTo(start); - break; + var start = new Menu(); + await NavigateTo(start); + break; - case "switch": - _mButtons.KeyboardType = _mButtons.KeyboardType switch - { - EKeyboardType.ReplyKeyboard => EKeyboardType.InlineKeyBoard, - EKeyboardType.InlineKeyBoard => EKeyboardType.ReplyKeyboard, - _ => _mButtons.KeyboardType - }; - - break; - - default: - await Device.Send($"Button clicked with Text: {e.Button.Text} and Value {e.Button.Value}"); - break; - } + case "switch": + _mButtons.KeyboardType = _mButtons.KeyboardType switch + { + EKeyboardType.ReplyKeyboard => EKeyboardType.InlineKeyBoard, + EKeyboardType.InlineKeyBoard => EKeyboardType.ReplyKeyboard, + _ => _mButtons.KeyboardType + }; + break; + default: + await Device.Send($"Button clicked with Text: {e.Button.Text} and Value {e.Button.Value}"); + break; } } -} +} \ No newline at end of file diff --git a/TelegramBotBase.Test/Tests/Controls/MonthPickerForm.cs b/TelegramBotBase.Test/Tests/Controls/MonthPickerForm.cs index 3774430..c44021f 100644 --- a/TelegramBotBase.Test/Tests/Controls/MonthPickerForm.cs +++ b/TelegramBotBase.Test/Tests/Controls/MonthPickerForm.cs @@ -5,73 +5,63 @@ using TelegramBotBase.Controls.Inline; using TelegramBotBase.Enums; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Controls +namespace TelegramBotBaseTest.Tests.Controls; + +public class MonthPickerForm : AutoCleanForm { - public class MonthPickerForm : AutoCleanForm + public MonthPickerForm() { - - public MonthPicker Picker { get; set; } - - private int? SelectedDateMessage { get; set; } - - public MonthPickerForm() - { - DeleteMode = EDeleteMode.OnLeavingForm; - Init += MonthPickerForm_Init; - } - - private Task MonthPickerForm_Init(object sender, InitEventArgs e) - { - Picker = new MonthPicker - { - Title = "Monat auswählen / Pick month" - }; - AddControl(Picker); - return Task.CompletedTask; - } - - - public override async Task Action(MessageResult message) - { - - switch(message.RawData) - { - case "back": - - var s = new Menu(); - - await NavigateTo(s); - - break; - } - - } - - public override async Task Render(MessageResult message) - { - var s = ""; - - s += "Selected month is " + Picker.Culture.DateTimeFormat.MonthNames[Picker.SelectedDate.Month - 1] + "\r\n"; - s += "Selected year is " + Picker.VisibleMonth.Year; - - var bf = new ButtonForm(); - bf.AddButtonRow(new ButtonBase("Back","back")); - - if (SelectedDateMessage != null) - { - await Device.Edit(SelectedDateMessage.Value, s, bf); - } - else - { - var m = await Device.Send(s, bf); - SelectedDateMessage = m.MessageId; - } - - - - } - - - + DeleteMode = EDeleteMode.OnLeavingForm; + Init += MonthPickerForm_Init; } -} + + public MonthPicker Picker { get; set; } + + private int? SelectedDateMessage { get; set; } + + private Task MonthPickerForm_Init(object sender, InitEventArgs e) + { + Picker = new MonthPicker + { + Title = "Monat auswählen / Pick month" + }; + AddControl(Picker); + return Task.CompletedTask; + } + + + public override async Task Action(MessageResult message) + { + switch (message.RawData) + { + case "back": + + var s = new Menu(); + + await NavigateTo(s); + + break; + } + } + + public override async Task Render(MessageResult message) + { + var s = ""; + + s += "Selected month is " + Picker.Culture.DateTimeFormat.MonthNames[Picker.SelectedDate.Month - 1] + "\r\n"; + s += "Selected year is " + Picker.VisibleMonth.Year; + + var bf = new ButtonForm(); + bf.AddButtonRow(new ButtonBase("Back", "back")); + + if (SelectedDateMessage != null) + { + await Device.Edit(SelectedDateMessage.Value, s, bf); + } + else + { + var m = await Device.Send(s, bf); + SelectedDateMessage = m.MessageId; + } + } +} \ No newline at end of file diff --git a/TelegramBotBase.Test/Tests/Controls/MultiToggleButtons.cs b/TelegramBotBase.Test/Tests/Controls/MultiToggleButtons.cs index dfa774f..c75c065 100644 --- a/TelegramBotBase.Test/Tests/Controls/MultiToggleButtons.cs +++ b/TelegramBotBase.Test/Tests/Controls/MultiToggleButtons.cs @@ -7,51 +7,49 @@ using TelegramBotBase.Controls.Inline; using TelegramBotBase.Enums; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Controls +namespace TelegramBotBaseTest.Tests.Controls; + +public class MultiToggleButtons : AutoCleanForm { - public class MultiToggleButtons : AutoCleanForm + public MultiToggleButtons() { - public MultiToggleButtons() - { - DeleteMode = EDeleteMode.OnLeavingForm; + DeleteMode = EDeleteMode.OnLeavingForm; - Init += ToggleButtons_Init; - } - - private Task ToggleButtons_Init(object sender, InitEventArgs e) - { - - var mtb = new MultiToggleButton - { - Options = new List { new ButtonBase("Option 1", "1"), new ButtonBase("Option 2", "2"), new ButtonBase("Option 3", "3") } - }; - - mtb.SelectedOption = mtb.Options.FirstOrDefault(); - mtb.Toggled += Tb_Toggled; - AddControl(mtb); - - mtb = new MultiToggleButton - { - Options = new List { new ButtonBase("Option 4", "4"), new ButtonBase("Option 5", "5"), new ButtonBase("Option 6", "6") } - }; - - mtb.SelectedOption = mtb.Options.FirstOrDefault(); - mtb.AllowEmptySelection = false; - mtb.Toggled += Tb_Toggled; - AddControl(mtb); - return Task.CompletedTask; - } - - private void Tb_Toggled(object sender, EventArgs e) - { - var tb = sender as MultiToggleButton; - if (tb.SelectedOption != null) - { - Console.WriteLine(tb.Id + " was pressed, and toggled to " + tb.SelectedOption.Value); - return; - } - - Console.WriteLine("Selection for " + tb.Id + " has been removed."); - } + Init += ToggleButtons_Init; } -} + + private Task ToggleButtons_Init(object sender, InitEventArgs e) + { + var mtb = new MultiToggleButton + { + Options = new List { new("Option 1", "1"), new("Option 2", "2"), new("Option 3", "3") } + }; + + mtb.SelectedOption = mtb.Options.FirstOrDefault(); + mtb.Toggled += Tb_Toggled; + AddControl(mtb); + + mtb = new MultiToggleButton + { + Options = new List { new("Option 4", "4"), new("Option 5", "5"), new("Option 6", "6") } + }; + + mtb.SelectedOption = mtb.Options.FirstOrDefault(); + mtb.AllowEmptySelection = false; + mtb.Toggled += Tb_Toggled; + AddControl(mtb); + return Task.CompletedTask; + } + + private void Tb_Toggled(object sender, EventArgs e) + { + var tb = sender as MultiToggleButton; + if (tb.SelectedOption != null) + { + Console.WriteLine(tb.Id + " was pressed, and toggled to " + tb.SelectedOption.Value); + return; + } + + Console.WriteLine("Selection for " + tb.Id + " has been removed."); + } +} \ No newline at end of file diff --git a/TelegramBotBase.Test/Tests/Controls/MultiViewForm.cs b/TelegramBotBase.Test/Tests/Controls/MultiViewForm.cs index e5f6431..0511cb6 100644 --- a/TelegramBotBase.Test/Tests/Controls/MultiViewForm.cs +++ b/TelegramBotBase.Test/Tests/Controls/MultiViewForm.cs @@ -5,50 +5,46 @@ using TelegramBotBase.Enums; using TelegramBotBase.Form; using TelegramBotBaseTest.Tests.Controls.Subclass; -namespace TelegramBotBaseTest.Tests.Controls +namespace TelegramBotBaseTest.Tests.Controls; + +public class MultiViewForm : AutoCleanForm { - public class MultiViewForm : AutoCleanForm + private ButtonGrid _bg; + private MultiViewTest _mvt; + + public MultiViewForm() { - private MultiViewTest _mvt; - - private ButtonGrid _bg; - - public MultiViewForm() - { - DeleteMode = EDeleteMode.OnLeavingForm; - Init += MultiViewForm_Init; - } - - private Task MultiViewForm_Init(object sender, InitEventArgs e) - { - _mvt = new MultiViewTest(); - - AddControl(_mvt); - - _bg = new ButtonGrid - { - ButtonsForm = new ButtonForm() - }; - _bg.ButtonsForm.AddButtonRow("Back", "$back$"); - _bg.ButtonClicked += Bg_ButtonClicked; - _bg.KeyboardType = EKeyboardType.ReplyKeyboard; - AddControl(_bg); - return Task.CompletedTask; - } - - private async Task Bg_ButtonClicked(object sender, ButtonClickedEventArgs e) - { - switch(e.Button.Value) - { - case "$back$": - - var mn = new Menu(); - await NavigateTo(mn); - - break; - } - } - - + DeleteMode = EDeleteMode.OnLeavingForm; + Init += MultiViewForm_Init; } -} + + private Task MultiViewForm_Init(object sender, InitEventArgs e) + { + _mvt = new MultiViewTest(); + + AddControl(_mvt); + + _bg = new ButtonGrid + { + ButtonsForm = new ButtonForm() + }; + _bg.ButtonsForm.AddButtonRow("Back", "$back$"); + _bg.ButtonClicked += Bg_ButtonClicked; + _bg.KeyboardType = EKeyboardType.ReplyKeyboard; + AddControl(_bg); + return Task.CompletedTask; + } + + private async Task Bg_ButtonClicked(object sender, ButtonClickedEventArgs e) + { + switch (e.Button.Value) + { + case "$back$": + + var mn = new Menu(); + await NavigateTo(mn); + + break; + } + } +} \ No newline at end of file diff --git a/TelegramBotBase.Test/Tests/Controls/Subclass/MultiViewTest.cs b/TelegramBotBase.Test/Tests/Controls/Subclass/MultiViewTest.cs index 79dfeab..08c7649 100644 --- a/TelegramBotBase.Test/Tests/Controls/Subclass/MultiViewTest.cs +++ b/TelegramBotBase.Test/Tests/Controls/Subclass/MultiViewTest.cs @@ -4,59 +4,49 @@ using TelegramBotBase.Base; using TelegramBotBase.Controls.Hybrid; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Controls.Subclass +namespace TelegramBotBaseTest.Tests.Controls.Subclass; + +public class MultiViewTest : MultiView { - public class MultiViewTest : MultiView + public override Task Action(MessageResult result, string value = null) { - - - public override Task Action(MessageResult result, string value = null) + switch (result.RawData) { - switch (result.RawData) - { - case "back": + case "back": - SelectedViewIndex--; + SelectedViewIndex--; - break; - case "next": + break; + case "next": - SelectedViewIndex++; + SelectedViewIndex++; - break; - } - - return Task.CompletedTask; + break; } - public override async Task RenderView(RenderViewEventArgs e) - { - - var bf = new ButtonForm(); - bf.AddButtonRow(new ButtonBase("Back", "back"), new ButtonBase("Next", "next")); - - switch (e.CurrentView) - { - case 0: - case 1: - case 2: - - await Device.Send($"Page {e.CurrentView + 1}", bf); - - break; - - default: - - await Device.Send("Unknown Page", bf); - - break; - - - } - - } - - - + return Task.CompletedTask; } -} + + public override async Task RenderView(RenderViewEventArgs e) + { + var bf = new ButtonForm(); + bf.AddButtonRow(new ButtonBase("Back", "back"), new ButtonBase("Next", "next")); + + switch (e.CurrentView) + { + case 0: + case 1: + case 2: + + await Device.Send($"Page {e.CurrentView + 1}", bf); + + break; + + default: + + await Device.Send("Unknown Page", bf); + + break; + } + } +} \ No newline at end of file diff --git a/TelegramBotBase.Test/Tests/Controls/ToggleButtons.cs b/TelegramBotBase.Test/Tests/Controls/ToggleButtons.cs index cb46305..67db7e7 100644 --- a/TelegramBotBase.Test/Tests/Controls/ToggleButtons.cs +++ b/TelegramBotBase.Test/Tests/Controls/ToggleButtons.cs @@ -5,50 +5,48 @@ using TelegramBotBase.Controls.Inline; using TelegramBotBase.Enums; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Controls +namespace TelegramBotBaseTest.Tests.Controls; + +public class ToggleButtons : AutoCleanForm { - public class ToggleButtons : AutoCleanForm + public ToggleButtons() { - public ToggleButtons() - { - DeleteMode = EDeleteMode.OnLeavingForm; + DeleteMode = EDeleteMode.OnLeavingForm; - Init += ToggleButtons_Init; - } - - private Task ToggleButtons_Init(object sender, InitEventArgs e) - { - - var tb = new ToggleButton - { - Checked = true - }; - tb.Toggled += Tb_Toggled; - - AddControl(tb); - - tb = new ToggleButton - { - Checked = false - }; - tb.Toggled += Tb_Toggled; - - AddControl(tb); - - tb = new ToggleButton - { - Checked = true - }; - tb.Toggled += Tb_Toggled; - - AddControl(tb); - return Task.CompletedTask; - } - - private void Tb_Toggled(object sender, EventArgs e) - { - var tb = sender as ToggleButton; - Console.WriteLine(tb.Id + " was pressed, and toggled to " + (tb.Checked ? "Checked" : "Unchecked")); - } + Init += ToggleButtons_Init; } -} + + private Task ToggleButtons_Init(object sender, InitEventArgs e) + { + var tb = new ToggleButton + { + Checked = true + }; + tb.Toggled += Tb_Toggled; + + AddControl(tb); + + tb = new ToggleButton + { + Checked = false + }; + tb.Toggled += Tb_Toggled; + + AddControl(tb); + + tb = new ToggleButton + { + Checked = true + }; + tb.Toggled += Tb_Toggled; + + AddControl(tb); + return Task.CompletedTask; + } + + private void Tb_Toggled(object sender, EventArgs e) + { + var tb = sender as ToggleButton; + Console.WriteLine(tb.Id + " was pressed, and toggled to " + (tb.Checked ? "Checked" : "Unchecked")); + } +} \ No newline at end of file diff --git a/TelegramBotBase.Test/Tests/Controls/TreeViewForms.cs b/TelegramBotBase.Test/Tests/Controls/TreeViewForms.cs index 4a41460..b5d7465 100644 --- a/TelegramBotBase.Test/Tests/Controls/TreeViewForms.cs +++ b/TelegramBotBase.Test/Tests/Controls/TreeViewForms.cs @@ -5,93 +5,94 @@ using TelegramBotBase.Controls.Inline; using TelegramBotBase.Enums; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Controls +namespace TelegramBotBaseTest.Tests.Controls; + +public class TreeViewForms : AutoCleanForm { - public class TreeViewForms : AutoCleanForm + public TreeViewForms() { - public TreeView View { get; set; } - - private int? MessageId { get; set; } - - public TreeViewForms() - { - DeleteMode = EDeleteMode.OnLeavingForm; - Init += TreeViewForms_Init; - } - - private Task TreeViewForms_Init(object sender, InitEventArgs e) - { - View = new TreeView(); - - var tvn = new TreeViewNode("Cars", "cars"); - - tvn.AddNode(new TreeViewNode("Porsche", "porsche", new TreeViewNode("Website", "web", "https://www.porsche.com/germany/"), new TreeViewNode("911", "911"), new TreeViewNode("918 Spyder", "918"))); - tvn.AddNode(new TreeViewNode("BMW", "bmw")); - tvn.AddNode(new TreeViewNode("Audi", "audi")); - tvn.AddNode(new TreeViewNode("VW", "vw")); - tvn.AddNode(new TreeViewNode("Lamborghini", "lamborghini")); - - View.Nodes.Add(tvn); - - tvn = new TreeViewNode("Fruits", "fruits"); - - tvn.AddNode(new TreeViewNode("Apple", "apple")); - tvn.AddNode(new TreeViewNode("Orange", "orange")); - tvn.AddNode(new TreeViewNode("Lemon", "lemon")); - - View.Nodes.Add(tvn); - - AddControl(View); - return Task.CompletedTask; - } - - public override async Task Action(MessageResult message) - { - await message.ConfirmAction(); - - if (message.Handled) - return; - - switch (message.RawData) - { - case "back": - - message.Handled = true; - - var start = new Menu(); - - await NavigateTo(start); - - break; - - } - - } - - public override async Task Render(MessageResult message) - { - var s = ""; - - s += "Selected Node: " + (View.SelectedNode?.Text ?? "(null)") + "\r\n"; - - s += "Visible Node: " + (View.VisibleNode?.Text ?? "(top)") + "\r\n"; - - s += "Visible Path: " + View.GetPath() + "\r\n"; - s += "Selected Path: " + (View.SelectedNode?.GetPath() ?? "(null)") + "\r\n"; - - var bf = new ButtonForm(); - bf.AddButtonRow(new ButtonBase("Back", "back")); - - if (MessageId != null) - { - await Device.Edit(MessageId.Value, s, bf); - } - else - { - var m = await Device.Send(s, bf); - MessageId = m.MessageId; - } - } - + DeleteMode = EDeleteMode.OnLeavingForm; + Init += TreeViewForms_Init; } -} + + public TreeView View { get; set; } + + private int? MessageId { get; set; } + + private Task TreeViewForms_Init(object sender, InitEventArgs e) + { + View = new TreeView(); + + var tvn = new TreeViewNode("Cars", "cars"); + + tvn.AddNode(new TreeViewNode("Porsche", "porsche", + new TreeViewNode("Website", "web", "https://www.porsche.com/germany/"), + new TreeViewNode("911", "911"), + new TreeViewNode("918 Spyder", "918"))); + tvn.AddNode(new TreeViewNode("BMW", "bmw")); + tvn.AddNode(new TreeViewNode("Audi", "audi")); + tvn.AddNode(new TreeViewNode("VW", "vw")); + tvn.AddNode(new TreeViewNode("Lamborghini", "lamborghini")); + + View.Nodes.Add(tvn); + + tvn = new TreeViewNode("Fruits", "fruits"); + + tvn.AddNode(new TreeViewNode("Apple", "apple")); + tvn.AddNode(new TreeViewNode("Orange", "orange")); + tvn.AddNode(new TreeViewNode("Lemon", "lemon")); + + View.Nodes.Add(tvn); + + AddControl(View); + return Task.CompletedTask; + } + + public override async Task Action(MessageResult message) + { + await message.ConfirmAction(); + + if (message.Handled) + { + return; + } + + switch (message.RawData) + { + case "back": + + message.Handled = true; + + var start = new Menu(); + + await NavigateTo(start); + + break; + } + } + + public override async Task Render(MessageResult message) + { + var s = ""; + + s += "Selected Node: " + (View.SelectedNode?.Text ?? "(null)") + "\r\n"; + + s += "Visible Node: " + (View.VisibleNode?.Text ?? "(top)") + "\r\n"; + + s += "Visible Path: " + View.GetPath() + "\r\n"; + s += "Selected Path: " + (View.SelectedNode?.GetPath() ?? "(null)") + "\r\n"; + + var bf = new ButtonForm(); + bf.AddButtonRow(new ButtonBase("Back", "back")); + + if (MessageId != null) + { + await Device.Edit(MessageId.Value, s, bf); + } + else + { + var m = await Device.Send(s, bf); + MessageId = m.MessageId; + } + } +} \ No newline at end of file diff --git a/TelegramBotBase.Test/Tests/DataForm.cs b/TelegramBotBase.Test/Tests/DataForm.cs index 509e58b..7811d33 100644 --- a/TelegramBotBase.Test/Tests/DataForm.cs +++ b/TelegramBotBase.Test/Tests/DataForm.cs @@ -7,134 +7,126 @@ using Telegram.Bot.Types.ReplyMarkups; using TelegramBotBase.Base; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests +namespace TelegramBotBaseTest.Tests; + +public class DataForm : AutoCleanForm { - public class DataForm : AutoCleanForm + public override async Task SentData(DataResult data) { + var tmp = ""; + InputOnlineFile file; - - public override async Task SentData(DataResult data) + switch (data.Type) { - var tmp = ""; - InputOnlineFile file; + case MessageType.Contact: - switch (data.Type) - { - case MessageType.Contact: + tmp += "Firstname: " + data.Contact.FirstName + "\r\n"; + tmp += "Lastname: " + data.Contact.LastName + "\r\n"; + tmp += "Phonenumber: " + data.Contact.PhoneNumber + "\r\n"; + tmp += "UserId: " + data.Contact.UserId + "\r\n"; - tmp += "Firstname: " + data.Contact.FirstName + "\r\n"; - tmp += "Lastname: " + data.Contact.LastName + "\r\n"; - tmp += "Phonenumber: " + data.Contact.PhoneNumber + "\r\n"; - tmp += "UserId: " + data.Contact.UserId + "\r\n"; + await Device.Send("Your contact: \r\n" + tmp, replyTo: data.MessageId); - await Device.Send("Your contact: \r\n" + tmp, replyTo: data.MessageId); + break; - break; + case MessageType.Document: - case MessageType.Document: + file = new InputOnlineFile(data.Document.FileId); - file = new InputOnlineFile(data.Document.FileId); - - await Device.SendDocument(file, "Your uploaded document"); + await Device.SendDocument(file, "Your uploaded document"); - break; + break; - case MessageType.Video: + case MessageType.Video: - file = new InputOnlineFile(data.Document.FileId); + file = new InputOnlineFile(data.Document.FileId); - await Device.SendDocument(file, "Your uploaded video"); + await Device.SendDocument(file, "Your uploaded video"); - break; + break; - case MessageType.Audio: + case MessageType.Audio: - file = new InputOnlineFile(data.Document.FileId); + file = new InputOnlineFile(data.Document.FileId); - await Device.SendDocument(file, "Your uploaded audio"); + await Device.SendDocument(file, "Your uploaded audio"); - break; + break; - case MessageType.Location: + case MessageType.Location: - tmp += "Lat: " + data.Location.Latitude + "\r\n"; - tmp += "Lng: " + data.Location.Longitude + "\r\n"; + tmp += "Lat: " + data.Location.Latitude + "\r\n"; + tmp += "Lng: " + data.Location.Longitude + "\r\n"; - await Device.Send("Your location: \r\n" + tmp, replyTo: data.MessageId); + await Device.Send("Your location: \r\n" + tmp, replyTo: data.MessageId); - break; + break; - case MessageType.Photo: + case MessageType.Photo: - var photo = new InputOnlineFile(data.Photos.Last().FileId); + var photo = new InputOnlineFile(data.Photos.Last().FileId); - await Device.Send("Your image: ", replyTo: data.MessageId); - await Client.TelegramClient.SendPhotoAsync(Device.DeviceId, photo); + await Device.Send("Your image: ", replyTo: data.MessageId); + await Client.TelegramClient.SendPhotoAsync(Device.DeviceId, photo); - break; + break; - default: + default: - await Device.Send("Unknown response"); + await Device.Send("Unknown response"); - break; - } + break; + } + } + public override async Task Action(MessageResult message) + { + await message.ConfirmAction(); + + if (message.Handled) + { + return; } - public override async Task Action(MessageResult message) + switch (message.RawData) { - await message.ConfirmAction(); + case "contact": - if (message.Handled) - return; + await Device.RequestContact(); - switch (message.RawData) - { - case "contact": + break; - await Device.RequestContact(); + case "location": - break; + await Device.RequestLocation(); - case "location": + break; - await Device.RequestLocation(); + case "back": - break; + message.Handled = true; - case "back": - - message.Handled = true; - - var start = new Menu(); - - await NavigateTo(start); - - break; - } + var start = new Menu(); + await NavigateTo(start); + break; } + } - public override async Task Render(MessageResult message) - { - var bf = new ButtonForm(); + public override async Task Render(MessageResult message) + { + var bf = new ButtonForm(); - bf.AddButtonRow(new ButtonBase("Request User contact", "contact")); + bf.AddButtonRow(new ButtonBase("Request User contact", "contact")); - bf.AddButtonRow(new ButtonBase("Request User location", "location")); + bf.AddButtonRow(new ButtonBase("Request User location", "location")); - bf.AddButtonRow(new ButtonBase("Back", "back")); + bf.AddButtonRow(new ButtonBase("Back", "back")); - InlineKeyboardMarkup ikv = bf; - - await Device.Send("Please upload a contact, photo, video, audio, document or location.", bf); - - - - } + InlineKeyboardMarkup ikv = bf; + await Device.Send("Please upload a contact, photo, video, audio, document or location.", bf); } } diff --git a/TelegramBotBase.Test/Tests/DataSources/CustomDataSource.cs b/TelegramBotBase.Test/Tests/DataSources/CustomDataSource.cs new file mode 100644 index 0000000..0246920 --- /dev/null +++ b/TelegramBotBase.Test/Tests/DataSources/CustomDataSource.cs @@ -0,0 +1,146 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using Newtonsoft.Json; +using TelegramBotBase.Controls.Hybrid; +using TelegramBotBase.DataSources; +using TelegramBotBase.Form; + +namespace TelegramBotBaseTest.Tests.DataSources; + +public class CustomDataSource : ButtonFormDataSource +{ + public List Countries = new() { "Country 1", "Country 2", "Country 3" }; + + public CustomDataSource() + { + LoadData(); + } + + public override int Count => Countries.Count; + + public override int ColumnCount => 1; + + public override int RowCount => Count; + + /// + /// This method has the example purpose of creating and loading some example data. + /// When using a database you do not need this kind of method. + /// + private void LoadData() + { + //Exists data source? Read it + if (File.Exists(AppContext.BaseDirectory + "countries.json")) + { + try + { + var list = JsonConvert.DeserializeObject>(File.ReadAllText("countries.json")); + + + Countries = list; + } + catch + { + } + + + return; + } + + //If not, create it + try + { + var countries = CultureInfo.GetCultures(CultureTypes.SpecificCultures).Select(a => a.DisplayName).ToList(); + + Countries = countries; + + var tmp = JsonConvert.SerializeObject(countries); + + File.WriteAllText(AppContext.BaseDirectory + "countries.json", tmp); + } + catch + { + } + } + + public override ButtonRow ItemAt(int index) + { + var item = Countries.ElementAt(index); + if (item == null) + { + return new ButtonRow(); + } + + return Render(item); + } + + public override List ItemRange(int start, int count) + { + var items = Countries.Skip(start).Take(count); + + var lst = new List(); + foreach (var c in items) + { + lst.Add(Render(c)); + } + + return lst; + } + + public override List AllItems() + { + var lst = new List(); + foreach (var c in Countries) + { + lst.Add(Render(c)); + } + + return lst; + } + + public override ButtonForm PickItems(int start, int count, string filter = null) + { + var rows = ItemRange(start, count); + + var lst = new ButtonForm(); + foreach (var c in rows) + { + lst.AddButtonRow(c); + } + + return lst; + } + + public override ButtonForm PickAllItems(string filter = null) + { + var rows = AllItems(); + + var bf = new ButtonForm(); + + bf.AddButtonRows(rows); + + return bf; + } + + public override int CalculateMax(string filter = null) + { + if (filter == null) + { + return Countries.Count; + } + + return Countries.Where(a => a.IndexOf(filter, StringComparison.InvariantCultureIgnoreCase) != -1).Count(); + } + + public override ButtonRow Render(object data) + { + if (!(data is string s)) + { + return new ButtonRow(new ButtonBase("Empty", "zero")); + } + + return new ButtonRow(new ButtonBase(s, s)); + } +} diff --git a/TelegramBotBase.Test/Tests/DataSources/List.cs b/TelegramBotBase.Test/Tests/DataSources/List.cs new file mode 100644 index 0000000..35c55d7 --- /dev/null +++ b/TelegramBotBase.Test/Tests/DataSources/List.cs @@ -0,0 +1,51 @@ +using System.Threading.Tasks; +using TelegramBotBase.Args; +using TelegramBotBase.Controls.Hybrid; +using TelegramBotBase.Enums; +using TelegramBotBase.Form; + +namespace TelegramBotBaseTest.Tests.DataSources; + +public class List : FormBase +{ + private ButtonGrid _buttons; + + public List() + { + Init += List_Init; + } + + private Task List_Init(object sender, InitEventArgs e) + { + _buttons = new ButtonGrid + { + EnablePaging = true, + EnableSearch = false + }; + + _buttons.ButtonClicked += __buttons_ButtonClicked; + _buttons.KeyboardType = EKeyboardType.ReplyKeyboard; + _buttons.DeleteReplyMessage = true; + + _buttons.HeadLayoutButtonRow = new ButtonRow(new ButtonBase("Back", "back")); + + var cds = new CustomDataSource(); + _buttons.DataSource = cds; + + AddControl(_buttons); + return Task.CompletedTask; + } + + private async Task __buttons_ButtonClicked(object sender, ButtonClickedEventArgs e) + { + switch (e.Button.Value) + { + case "back": + + var mn = new Menu(); + await NavigateTo(mn); + + break; + } + } +} diff --git a/TelegramBotBase.Test/Tests/Datasources/CustomDataSource.cs b/TelegramBotBase.Test/Tests/Datasources/CustomDataSource.cs deleted file mode 100644 index 1e418e8..0000000 --- a/TelegramBotBase.Test/Tests/Datasources/CustomDataSource.cs +++ /dev/null @@ -1,143 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Globalization; -using System.IO; -using System.Linq; -using Newtonsoft.Json; -using TelegramBotBase.Controls.Hybrid; -using TelegramBotBase.DataSources; -using TelegramBotBase.Form; - -namespace TelegramBotBaseTest.Tests.Datasources -{ - public class CustomDataSource : ButtonFormDataSource - { - - public List Countries = new List { "Country 1", "Country 2", "Country 3" }; - - public CustomDataSource() - { - LoadData(); - } - - /// - /// This method has the example purpose of creating and loading some example data. - /// When using a database you do not need this kind of method. - /// - private void LoadData() - { - //Exists data source? Read it - if (File.Exists(AppContext.BaseDirectory + "countries.json")) - { - try - { - var list = JsonConvert.DeserializeObject>(File.ReadAllText("countries.json")); - - - Countries = list; - } - catch - { - - } - - - return; - } - - //If not, create it - try - { - var countries = CultureInfo.GetCultures(CultureTypes.SpecificCultures).Select(a => a.DisplayName).ToList(); - - Countries = countries; - - var tmp = JsonConvert.SerializeObject(countries); - - File.WriteAllText( AppContext.BaseDirectory + "countries.json", tmp); - } - catch - { - - } - - } - - public override ButtonRow ItemAt(int index) - { - var item = Countries.ElementAt(index); - if (item == null) - return new ButtonRow(); - - return Render(item); - } - - public override List ItemRange(int start, int count) - { - var items = Countries.Skip(start).Take(count); - - var lst = new List(); - foreach (var c in items) - { - lst.Add(Render(c)); - } - - return lst; - } - - public override List AllItems() - { - var lst = new List(); - foreach (var c in Countries) - { - lst.Add(Render(c)); - } - return lst; - } - - public override ButtonForm PickItems(int start, int count, string filter = null) - { - var rows = ItemRange(start, count); - - var lst = new ButtonForm(); - foreach (var c in rows) - { - lst.AddButtonRow(c); - } - return lst; - } - - public override ButtonForm PickAllItems(string filter = null) - { - var rows = AllItems(); - - var bf = new ButtonForm(); - - bf.AddButtonRows(rows); - - return bf; - } - - public override int CalculateMax(string filter = null) - { - if (filter == null) - return Countries.Count; - - return Countries.Where(a => a.IndexOf(filter, StringComparison.InvariantCultureIgnoreCase) != -1).Count(); - } - - public override ButtonRow Render(object data) - { - if (!(data is string s)) - return new ButtonRow(new ButtonBase("Empty", "zero")); - - return new ButtonRow(new ButtonBase(s, s)); - } - - public override int Count => Countries.Count; - - public override int ColumnCount => 1; - - public override int RowCount => Count; - } -} diff --git a/TelegramBotBase.Test/Tests/Datasources/List.cs b/TelegramBotBase.Test/Tests/Datasources/List.cs deleted file mode 100644 index d73d92a..0000000 --- a/TelegramBotBase.Test/Tests/Datasources/List.cs +++ /dev/null @@ -1,55 +0,0 @@ -using System.Threading.Tasks; -using TelegramBotBase.Args; -using TelegramBotBase.Controls.Hybrid; -using TelegramBotBase.Enums; -using TelegramBotBase.Form; - -namespace TelegramBotBaseTest.Tests.Datasources -{ - public class List : FormBase - { - private ButtonGrid _buttons; - - public List() - { - Init += List_Init; - } - - private Task List_Init(object sender, InitEventArgs e) - { - - _buttons = new ButtonGrid - { - EnablePaging = true, - EnableSearch = false - }; - - _buttons.ButtonClicked += __buttons_ButtonClicked; - _buttons.KeyboardType = EKeyboardType.ReplyKeyboard; - _buttons.DeleteReplyMessage = true; - - _buttons.HeadLayoutButtonRow = new ButtonRow(new ButtonBase("Back", "back")); - - var cds = new CustomDataSource(); - _buttons.DataSource = cds; - - AddControl(_buttons); - return Task.CompletedTask; - } - - private async Task __buttons_ButtonClicked(object sender, ButtonClickedEventArgs e) - { - switch(e.Button.Value) - { - case "back": - - var mn = new Menu(); - await NavigateTo(mn); - - break; - } - } - - - } -} diff --git a/TelegramBotBase.Test/Tests/Groups/GroupChange.cs b/TelegramBotBase.Test/Tests/Groups/GroupChange.cs index 1d75ccf..fd984b6 100644 --- a/TelegramBotBase.Test/Tests/Groups/GroupChange.cs +++ b/TelegramBotBase.Test/Tests/Groups/GroupChange.cs @@ -4,71 +4,69 @@ using TelegramBotBase.Args; using TelegramBotBase.Base; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Groups +namespace TelegramBotBaseTest.Tests.Groups; + +public class GroupChange : GroupForm { - public class GroupChange : GroupForm + public GroupChange() { - public GroupChange() - { - Opened += GroupChange_Opened; - } - - - private async Task GroupChange_Opened(object sender, EventArgs e) - { - - var bf = new ButtonForm(); - - bf.AddButtonRow(new ButtonBase("Open GroupChange Test", "groupchange")); - bf.AddButtonRow(new ButtonBase("Open WelcomeUser Test", "welcomeuser")); - bf.AddButtonRow(new ButtonBase("Open LinkReplace Test", "linkreplace")); - - await Device.Send("GroupChange started, click to switch", bf); - - } - - public override async Task Action(MessageResult message) - { - if (message.Handled) - return; - - - var bn = message.RawData; - - await message.ConfirmAction(); - message.Handled = true; - - switch (bn) - { - case "groupchange": - - var gc = new GroupChange(); - - await NavigateTo(gc); - - break; - case "welcomeuser": - - var wu = new WelcomeUser(); - - await NavigateTo(wu); - - break; - case "linkreplace": - - var lr = new LinkReplaceTest(); - - await NavigateTo(lr); - - break; - } - - } - - public override async Task OnGroupChanged(GroupChangedEventArgs e) - { - await Device.Send("Group has been changed by " + e.OriginalMessage.Message.From.FirstName + " " + e.OriginalMessage.Message.From.LastName); - } - + Opened += GroupChange_Opened; } -} + + + private async Task GroupChange_Opened(object sender, EventArgs e) + { + var bf = new ButtonForm(); + + bf.AddButtonRow(new ButtonBase("Open GroupChange Test", "groupchange")); + bf.AddButtonRow(new ButtonBase("Open WelcomeUser Test", "welcomeuser")); + bf.AddButtonRow(new ButtonBase("Open LinkReplace Test", "linkreplace")); + + await Device.Send("GroupChange started, click to switch", bf); + } + + public override async Task Action(MessageResult message) + { + if (message.Handled) + { + return; + } + + + var bn = message.RawData; + + await message.ConfirmAction(); + message.Handled = true; + + switch (bn) + { + case "groupchange": + + var gc = new GroupChange(); + + await NavigateTo(gc); + + break; + case "welcomeuser": + + var wu = new WelcomeUser(); + + await NavigateTo(wu); + + break; + case "linkreplace": + + var lr = new LinkReplaceTest(); + + await NavigateTo(lr); + + break; + } + } + + public override async Task OnGroupChanged(GroupChangedEventArgs e) + { + await Device.Send("Group has been changed by " + e.OriginalMessage.Message.From.FirstName + " " + + e.OriginalMessage.Message.From.LastName); + } +} \ No newline at end of file diff --git a/TelegramBotBase.Test/Tests/Groups/LinkReplaceTest.cs b/TelegramBotBase.Test/Tests/Groups/LinkReplaceTest.cs index 243d7d4..dd36756 100644 --- a/TelegramBotBase.Test/Tests/Groups/LinkReplaceTest.cs +++ b/TelegramBotBase.Test/Tests/Groups/LinkReplaceTest.cs @@ -7,159 +7,159 @@ using Telegram.Bot.Types.Enums; using TelegramBotBase.Base; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Groups +namespace TelegramBotBaseTest.Tests.Groups; + +public class LinkReplaceTest : GroupForm { - public class LinkReplaceTest : GroupForm + private const int Maximum = 3; + + + public LinkReplaceTest() { - private Dictionary Counter { get; set; } = new Dictionary(); - - private const int Maximum = 3; - - - public LinkReplaceTest() - { - Opened += LinkReplaceTest_Opened; - } - - private async Task LinkReplaceTest_Opened(object sender, EventArgs e) - { - - var bf = new ButtonForm(); - - bf.AddButtonRow(new ButtonBase("Open GroupChange Test", "groupchange")); - bf.AddButtonRow(new ButtonBase("Open WelcomeUser Test", "welcomeuser")); - bf.AddButtonRow(new ButtonBase("Open LinkReplace Test", "linkreplace")); - - await Device.Send("LinkReplaceTest started, click to switch", bf); - - } - - public override async Task Action(MessageResult message) - { - if (message.Handled) - return; - - var bn = message.RawData; - - await message.ConfirmAction(); - message.Handled = true; - - switch (bn) - { - case "groupchange": - - var gc = new GroupChange(); - - await NavigateTo(gc); - - break; - case "welcomeuser": - - var wu = new WelcomeUser(); - - await NavigateTo(wu); - - break; - case "linkreplace": - - var lr = new LinkReplaceTest(); - - await NavigateTo(lr); - - break; - } - - } - - public override async Task OnMessage(MessageResult e) - { - var from = e.Message.From.Id; - - if (e.Message.From.IsBot) - return; - - //Are urls inside his message ? - if (!HasLinks(e.MessageText)) - return; - - var u = await Device.GetChatUser(from); - - //Don't kick Admins or Creators - if (u.Status == ChatMemberStatus.Administrator | u.Status == ChatMemberStatus.Creator) - { - await Device.Send("You won't get kicked,...not this time."); - return; - } - - await e.Device.DeleteMessage(e.MessageId); - - var cp = new ChatPermissions - { - CanAddWebPagePreviews = false, - CanChangeInfo = false, - CanInviteUsers = false, - CanPinMessages = false, - CanSendMediaMessages = false, - CanSendMessages = false, - CanSendOtherMessages = false, - CanSendPolls = false - }; - - //Collect user "mistakes" with sending url, after 3 he gets kicked out. - if (Counter.ContainsKey(from)) - { - Counter[from]++; - } - else - { - Counter[from] = 1; - } - - - if (Counter[from] >= 3) - { - await e.Device.KickUser(from); - - await e.Device.Send(e.Message.From.FirstName + " " + e.Message.From.LastName + " has been removed from the group"); - } - else - { - await e.Device.RestrictUser(from, cp, DateTime.UtcNow.AddSeconds(30)); - - await e.Device.Send(e.Message.From.FirstName + " " + e.Message.From.LastName + " has been blocked for 30 seconds"); - } - - - - } - - /// - /// Call onmessage also on edited message, if someone want to spoof a failed message and insert a link. - /// - /// - /// - public override async Task OnMessageEdit(MessageResult message) - { - await OnMessage(message); - } - - /// - /// https://stackoverflow.com/a/20651284 - /// - /// - /// - private bool HasLinks(string str) - { - var tmp = str; - - var pattern = @"^(http|https|ftp|)\://|[a-zA-Z0-9\-\.]+\.[a-zA-Z](:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&%\$#\=~])*[^\.\,\)\(\s]$"; - var r = new Regex(pattern); - - var matches = r.Matches(tmp); - - return (matches.Count > 0); - } - - + Opened += LinkReplaceTest_Opened; } -} + + private Dictionary Counter { get; } = new(); + + private async Task LinkReplaceTest_Opened(object sender, EventArgs e) + { + var bf = new ButtonForm(); + + bf.AddButtonRow(new ButtonBase("Open GroupChange Test", "groupchange")); + bf.AddButtonRow(new ButtonBase("Open WelcomeUser Test", "welcomeuser")); + bf.AddButtonRow(new ButtonBase("Open LinkReplace Test", "linkreplace")); + + await Device.Send("LinkReplaceTest started, click to switch", bf); + } + + public override async Task Action(MessageResult message) + { + if (message.Handled) + { + return; + } + + var bn = message.RawData; + + await message.ConfirmAction(); + message.Handled = true; + + switch (bn) + { + case "groupchange": + + var gc = new GroupChange(); + + await NavigateTo(gc); + + break; + case "welcomeuser": + + var wu = new WelcomeUser(); + + await NavigateTo(wu); + + break; + case "linkreplace": + + var lr = new LinkReplaceTest(); + + await NavigateTo(lr); + + break; + } + } + + public override async Task OnMessage(MessageResult e) + { + var from = e.Message.From.Id; + + if (e.Message.From.IsBot) + { + return; + } + + //Are urls inside his message ? + if (!HasLinks(e.MessageText)) + { + return; + } + + var u = await Device.GetChatUser(from); + + //Don't kick Admins or Creators + if ((u.Status == ChatMemberStatus.Administrator) | (u.Status == ChatMemberStatus.Creator)) + { + await Device.Send("You won't get kicked,...not this time."); + return; + } + + await e.Device.DeleteMessage(e.MessageId); + + var cp = new ChatPermissions + { + CanAddWebPagePreviews = false, + CanChangeInfo = false, + CanInviteUsers = false, + CanPinMessages = false, + CanSendMediaMessages = false, + CanSendMessages = false, + CanSendOtherMessages = false, + CanSendPolls = false + }; + + //Collect user "mistakes" with sending url, after 3 he gets kicked out. + if (Counter.ContainsKey(from)) + { + Counter[from]++; + } + else + { + Counter[from] = 1; + } + + + if (Counter[from] >= 3) + { + await e.Device.KickUser(from); + + await e.Device.Send(e.Message.From.FirstName + " " + e.Message.From.LastName + + " has been removed from the group"); + } + else + { + await e.Device.RestrictUser(from, cp, DateTime.UtcNow.AddSeconds(30)); + + await e.Device.Send(e.Message.From.FirstName + " " + e.Message.From.LastName + + " has been blocked for 30 seconds"); + } + } + + /// + /// Call onmessage also on edited message, if someone want to spoof a failed message and insert a link. + /// + /// + /// + public override async Task OnMessageEdit(MessageResult message) + { + await OnMessage(message); + } + + /// + /// https://stackoverflow.com/a/20651284 + /// + /// + /// + private bool HasLinks(string str) + { + var tmp = str; + + var pattern = + @"^(http|https|ftp|)\://|[a-zA-Z0-9\-\.]+\.[a-zA-Z](:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&%\$#\=~])*[^\.\,\)\(\s]$"; + var r = new Regex(pattern); + + var matches = r.Matches(tmp); + + return matches.Count > 0; + } +} \ No newline at end of file diff --git a/TelegramBotBase.Test/Tests/Groups/WelcomeUser.cs b/TelegramBotBase.Test/Tests/Groups/WelcomeUser.cs index c700f85..3dc8048 100644 --- a/TelegramBotBase.Test/Tests/Groups/WelcomeUser.cs +++ b/TelegramBotBase.Test/Tests/Groups/WelcomeUser.cs @@ -6,86 +6,77 @@ using TelegramBotBase.Args; using TelegramBotBase.Base; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Groups +namespace TelegramBotBaseTest.Tests.Groups; + +public class WelcomeUser : GroupForm { - public class WelcomeUser : GroupForm + public WelcomeUser() { - - public WelcomeUser() - { - Opened += WelcomeUser_Opened; - } - - - private async Task WelcomeUser_Opened(object sender, EventArgs e) - { - - var bf = new ButtonForm(); - - bf.AddButtonRow(new ButtonBase("Open GroupChange Test", "groupchange")); - bf.AddButtonRow(new ButtonBase("Open WelcomeUser Test", "welcomeuser")); - bf.AddButtonRow(new ButtonBase("Open LinkReplace Test", "linkreplace")); - - await Device.Send("WelcomeUser started, click to switch", bf); - - } - - public override async Task Action(MessageResult message) - { - if (message.Handled) - return; - - var bn = message.RawData; - - await message.ConfirmAction(); - message.Handled = true; - - switch (bn) - { - case "groupchange": - - var gc = new GroupChange(); - - await NavigateTo(gc); - - break; - case "welcomeuser": - - var wu = new WelcomeUser(); - - await NavigateTo(wu); - - break; - case "linkreplace": - - var lr = new LinkReplaceTest(); - - await NavigateTo(lr); - - break; - } - - } - - public override async Task OnMemberChanges(MemberChangeEventArgs e) - { - - if (e.Type == MessageType.ChatMembersAdded) - { - - await Device.Send("Welcome you new members!\r\n\r\n" + e.Members.Select(a => a.FirstName + " " + a.LastName).Aggregate((a, b) => a + "\r\n" + b)); - - } - else if (e.Type == MessageType.ChatMemberLeft) - { - await Device.Send(e.Members.Select(a => a.FirstName + " " + a.LastName).Aggregate((a, b) => a + " and " + b) + " has left the group"); - - } - - } - - - - + Opened += WelcomeUser_Opened; } -} + + + private async Task WelcomeUser_Opened(object sender, EventArgs e) + { + var bf = new ButtonForm(); + + bf.AddButtonRow(new ButtonBase("Open GroupChange Test", "groupchange")); + bf.AddButtonRow(new ButtonBase("Open WelcomeUser Test", "welcomeuser")); + bf.AddButtonRow(new ButtonBase("Open LinkReplace Test", "linkreplace")); + + await Device.Send("WelcomeUser started, click to switch", bf); + } + + public override async Task Action(MessageResult message) + { + if (message.Handled) + { + return; + } + + var bn = message.RawData; + + await message.ConfirmAction(); + message.Handled = true; + + switch (bn) + { + case "groupchange": + + var gc = new GroupChange(); + + await NavigateTo(gc); + + break; + case "welcomeuser": + + var wu = new WelcomeUser(); + + await NavigateTo(wu); + + break; + case "linkreplace": + + var lr = new LinkReplaceTest(); + + await NavigateTo(lr); + + break; + } + } + + public override async Task OnMemberChanges(MemberChangeEventArgs e) + { + if (e.Type == MessageType.ChatMembersAdded) + { + await Device.Send("Welcome you new members!\r\n\r\n" + e.Members.Select(a => a.FirstName + " " + a.LastName) + .Aggregate((a, b) => a + "\r\n" + b)); + } + else if (e.Type == MessageType.ChatMemberLeft) + { + await Device.Send( + e.Members.Select(a => a.FirstName + " " + a.LastName).Aggregate((a, b) => a + " and " + b) + + " has left the group"); + } + } +} \ No newline at end of file diff --git a/TelegramBotBase.Test/Tests/Menu.cs b/TelegramBotBase.Test/Tests/Menu.cs index 3f9d04d..3b161db 100644 --- a/TelegramBotBase.Test/Tests/Menu.cs +++ b/TelegramBotBase.Test/Tests/Menu.cs @@ -4,261 +4,262 @@ using TelegramBotBase.Base; using TelegramBotBase.Enums; using TelegramBotBase.Form; using TelegramBotBaseTest.Tests.Controls; -using TelegramBotBaseTest.Tests.Datasources; +using TelegramBotBaseTest.Tests.DataSources; using TelegramBotBaseTest.Tests.Groups; -namespace TelegramBotBaseTest.Tests +namespace TelegramBotBaseTest.Tests; + +public class Menu : AutoCleanForm { - public class Menu : AutoCleanForm + public Menu() { - public Menu() + DeleteMode = EDeleteMode.OnLeavingForm; + } + + public override async Task Load(MessageResult message) + { + if ((message.Message.Chat.Type == ChatType.Group) | (message.Message.Chat.Type == ChatType.Supergroup)) { - DeleteMode = EDeleteMode.OnLeavingForm; + var sf = new WelcomeUser(); + + await NavigateTo(sf); } - public override async Task Load(MessageResult message) + + await Device.HideReplyKeyboard(); + } + + public override async Task Action(MessageResult message) + { + var call = message.GetData(); + + await message.ConfirmAction(); + + + if (call == null) { + return; + } + message.Handled = true; - if (message.Message.Chat.Type == ChatType.Group | message.Message.Chat.Type == ChatType.Supergroup) - { - var sf = new WelcomeUser(); + switch (call.Value) + { + case "text": + + var sf = new SimpleForm(); await NavigateTo(sf); - } + + break; + + case "buttons": + + var bf = new ButtonTestForm(); + + await NavigateTo(bf); + + break; + + case "progress": + + var pf = new ProgressTest(); + + await NavigateTo(pf); + + break; + + case "registration": + + var reg = new Register.Start(); + + await NavigateTo(reg); + + break; + + case "form1": + + var form1 = new TestForm(); + + await NavigateTo(form1); + + break; + + case "form2": + + var form2 = new TestForm2(); + + await NavigateTo(form2); + + break; + + case "data": + + var data = new DataForm(); + + await NavigateTo(data); + + break; + + case "calendar": + + var calendar = new CalendarPickerForm(); + + await NavigateTo(calendar); + + break; + + case "month": + + var month = new MonthPickerForm(); + + await NavigateTo(month); + + break; + + case "treeview": + + var tree = new TreeViewForms(); + + await NavigateTo(tree); + + break; + + case "togglebuttons": + + var tb = new ToggleButtons(); + + await NavigateTo(tb); + + break; + + case "multitogglebuttons": + + var mtb = new MultiToggleButtons(); + + await NavigateTo(mtb); + + break; + + case "buttongrid": + + var bg = new ButtonGridForm(); + + await NavigateTo(bg); + + break; + + case "buttongridfilter": + + var bg2 = new ButtonGridPagingForm(); + + await NavigateTo(bg2); + + break; + + case "buttongridtags": + + var bg3 = new ButtonGridTagForm(); + + await NavigateTo(bg3); + + break; + + case "multiview": + + var mvf = new MultiViewForm(); + + await NavigateTo(mvf); - await Device.HideReplyKeyboard(); + break; + + case "checkedbuttonlist": + + var cbl = new CheckedButtonListForm(); + + await NavigateTo(cbl); + + + break; + + case "navigationcontroller": + + var nc = new Navigation.Start(); + + await NavigateTo(nc); + + + break; + + case "dynamicbuttongrid": + + var dg = new List(); + + await NavigateTo(dg); + + break; + + case "notifications": + + var not = new Notifications.Start(); + await NavigateTo(not); + + break; + + default: + + message.Handled = false; + + break; } + } - public override async Task Action(MessageResult message) - { - var call = message.GetData(); + public override async Task Render(MessageResult message) + { + var btn = new ButtonForm(); - await message.ConfirmAction(); + btn.AddButtonRow(new ButtonBase("#1 Simple Text", new CallbackData("a", "text").Serialize()), + new ButtonBase("#2 Button Test", new CallbackData("a", "buttons").Serialize())); + btn.AddButtonRow(new ButtonBase("#3 Progress Bar", new CallbackData("a", "progress").Serialize())); + btn.AddButtonRow(new ButtonBase("#4 Registration Example", new CallbackData("a", "registration").Serialize())); + btn.AddButtonRow(new ButtonBase("#5 Form1 Command", new CallbackData("a", "form1").Serialize())); - if (call == null) - return; + btn.AddButtonRow(new ButtonBase("#6 Form2 Command", new CallbackData("a", "form2").Serialize())); - message.Handled = true; + btn.AddButtonRow(new ButtonBase("#7 Data Handling", new CallbackData("a", "data").Serialize())); + btn.AddButtonRow(new ButtonBase("#8 Calendar Picker", new CallbackData("a", "calendar").Serialize())); + btn.AddButtonRow(new ButtonBase("#9 Month Picker", new CallbackData("a", "month").Serialize())); - switch (call.Value) - { - case "text": + btn.AddButtonRow(new ButtonBase("#10 TreeView", new CallbackData("a", "treeview").Serialize())); - var sf = new SimpleForm(); + btn.AddButtonRow(new ButtonBase("#11 ToggleButtons", new CallbackData("a", "togglebuttons").Serialize())); - await NavigateTo(sf); + btn.AddButtonRow(new ButtonBase("#11.2 MultiToggleButtons", + new CallbackData("a", "multitogglebuttons").Serialize())); - break; + btn.AddButtonRow(new ButtonBase("#12 ButtonGrid", new CallbackData("a", "buttongrid").Serialize())); - case "buttons": + btn.AddButtonRow(new ButtonBase("#13 ButtonGrid Paging & Filter", + new CallbackData("a", "buttongridfilter").Serialize())); - var bf = new ButtonTestForm(); + btn.AddButtonRow(new ButtonBase("#14 ButtonGrid Tags (Filter)", + new CallbackData("a", "buttongridtags").Serialize())); - await NavigateTo(bf); + btn.AddButtonRow(new ButtonBase("#15 MultiView", new CallbackData("a", "multiview").Serialize())); - break; + btn.AddButtonRow( + new ButtonBase("#16 CheckedButtonList", new CallbackData("a", "checkedbuttonlist").Serialize())); - case "progress": + btn.AddButtonRow(new ButtonBase("#17 NavigationController (Push/Pop)", + new CallbackData("a", "navigationcontroller").Serialize())); - var pf = new ProgressTest(); - - await NavigateTo(pf); - - break; - - case "registration": - - var reg = new Register.Start(); - - await NavigateTo(reg); - - break; - - case "form1": - - var form1 = new TestForm(); - - await NavigateTo(form1); - - break; - - case "form2": - - var form2 = new TestForm2(); - - await NavigateTo(form2); - - break; - - case "data": - - var data = new DataForm(); - - await NavigateTo(data); - - break; - - case "calendar": - - var calendar = new CalendarPickerForm(); - - await NavigateTo(calendar); - - break; - - case "month": - - var month = new MonthPickerForm(); - - await NavigateTo(month); - - break; - - case "treeview": - - var tree = new TreeViewForms(); - - await NavigateTo(tree); - - break; - - case "togglebuttons": - - var tb = new ToggleButtons(); - - await NavigateTo(tb); - - break; - - case "multitogglebuttons": - - var mtb = new MultiToggleButtons(); - - await NavigateTo(mtb); - - break; - - case "buttongrid": - - var bg = new ButtonGridForm(); - - await NavigateTo(bg); - - break; - - case "buttongridfilter": - - var bg2 = new ButtonGridPagingForm(); - - await NavigateTo(bg2); - - break; - - case "buttongridtags": - - var bg3 = new ButtonGridTagForm(); - - await NavigateTo(bg3); - - break; - - case "multiview": - - var mvf = new MultiViewForm(); - - await NavigateTo(mvf); - - - break; - - case "checkedbuttonlist": - - var cbl = new CheckedButtonListForm(); - - await NavigateTo(cbl); - - - break; - - case "navigationcontroller": - - var nc = new Navigation.Start(); - - await NavigateTo(nc); - - - break; - - case "dynamicbuttongrid": - - var dg = new List(); - - await NavigateTo(dg); - - break; - - case "notifications": - - var not = new Notifications.Start(); - await NavigateTo(not); - - break; - - default: - - message.Handled = false; - - break; - } - - - } - - public override async Task Render(MessageResult message) - { - - var btn = new ButtonForm(); - - btn.AddButtonRow(new ButtonBase("#1 Simple Text", new CallbackData("a", "text").Serialize()), new ButtonBase("#2 Button Test", new CallbackData("a", "buttons").Serialize())); - btn.AddButtonRow(new ButtonBase("#3 Progress Bar", new CallbackData("a", "progress").Serialize())); - btn.AddButtonRow(new ButtonBase("#4 Registration Example", new CallbackData("a", "registration").Serialize())); - - btn.AddButtonRow(new ButtonBase("#5 Form1 Command", new CallbackData("a", "form1").Serialize())); - - btn.AddButtonRow(new ButtonBase("#6 Form2 Command", new CallbackData("a", "form2").Serialize())); - - btn.AddButtonRow(new ButtonBase("#7 Data Handling", new CallbackData("a", "data").Serialize())); - btn.AddButtonRow(new ButtonBase("#8 Calendar Picker", new CallbackData("a", "calendar").Serialize())); - btn.AddButtonRow(new ButtonBase("#9 Month Picker", new CallbackData("a", "month").Serialize())); - - btn.AddButtonRow(new ButtonBase("#10 TreeView", new CallbackData("a", "treeview").Serialize())); - - btn.AddButtonRow(new ButtonBase("#11 ToggleButtons", new CallbackData("a", "togglebuttons").Serialize())); - - btn.AddButtonRow(new ButtonBase("#11.2 MultiToggleButtons", new CallbackData("a", "multitogglebuttons").Serialize())); - - btn.AddButtonRow(new ButtonBase("#12 ButtonGrid", new CallbackData("a", "buttongrid").Serialize())); - - btn.AddButtonRow(new ButtonBase("#13 ButtonGrid Paging & Filter", new CallbackData("a", "buttongridfilter").Serialize())); - - btn.AddButtonRow(new ButtonBase("#14 ButtonGrid Tags (Filter)", new CallbackData("a", "buttongridtags").Serialize())); - - btn.AddButtonRow(new ButtonBase("#15 MultiView", new CallbackData("a", "multiview").Serialize())); - - btn.AddButtonRow(new ButtonBase("#16 CheckedButtonList", new CallbackData("a", "checkedbuttonlist").Serialize())); - - btn.AddButtonRow(new ButtonBase("#17 NavigationController (Push/Pop)", new CallbackData("a", "navigationcontroller").Serialize())); - - btn.AddButtonRow(new ButtonBase("#18 Dynamic ButtonGrid (DataSources)", new CallbackData("a", "dynamicbuttongrid").Serialize())); - - btn.AddButtonRow(new ButtonBase("#19 Notifications", new CallbackData("a", "notifications").Serialize())); - - await Device.Send("Choose your test:", btn); - } + btn.AddButtonRow(new ButtonBase("#18 Dynamic ButtonGrid (DataSources)", + new CallbackData("a", "dynamicbuttongrid").Serialize())); + btn.AddButtonRow(new ButtonBase("#19 Notifications", new CallbackData("a", "notifications").Serialize())); + await Device.Send("Choose your test:", btn); } } diff --git a/TelegramBotBase.Test/Tests/Navigation/CustomController.cs b/TelegramBotBase.Test/Tests/Navigation/CustomController.cs index 5dff6fd..28d7015 100644 --- a/TelegramBotBase.Test/Tests/Navigation/CustomController.cs +++ b/TelegramBotBase.Test/Tests/Navigation/CustomController.cs @@ -3,40 +3,37 @@ using System.Threading.Tasks; using TelegramBotBase.Form; using TelegramBotBase.Form.Navigation; -namespace TelegramBotBaseTest.Tests.Navigation +namespace TelegramBotBaseTest.Tests.Navigation; + +internal class CustomController : NavigationController { - internal class CustomController : NavigationController + public CustomController(FormBase form) : base(form) { - public CustomController(FormBase form) : base(form) - { - - } - - - public override Task PushAsync(FormBase form, params object[] args) - { - Console.WriteLine($"Pushes form (Count on stack {Index + 1})"); - //Device.Send($"Pushes form (Count on stack {this.Index + 1})"); - - return base.PushAsync(form, args); - } - - - public override Task PopAsync() - { - Console.WriteLine($"Pops one form (Count on stack {Index + 1})"); - //Device.Send($"Pops one form (Count on stack {this.Index + 1})"); - - return base.PopAsync(); - } - - public override Task PopToRootAsync() - { - Console.WriteLine($"Moved back to root (Count on stack {Index + 1})"); - //Device.Send($"Moved back to root (Count on stack {this.Index + 1})"); - - return base.PopToRootAsync(); - } - } -} + + + public override Task PushAsync(FormBase form, params object[] args) + { + Console.WriteLine($"Pushes form (Count on stack {Index + 1})"); + //Device.Send($"Pushes form (Count on stack {this.Index + 1})"); + + return base.PushAsync(form, args); + } + + + public override Task PopAsync() + { + Console.WriteLine($"Pops one form (Count on stack {Index + 1})"); + //Device.Send($"Pops one form (Count on stack {this.Index + 1})"); + + return base.PopAsync(); + } + + public override Task PopToRootAsync() + { + Console.WriteLine($"Moved back to root (Count on stack {Index + 1})"); + //Device.Send($"Moved back to root (Count on stack {this.Index + 1})"); + + return base.PopToRootAsync(); + } +} \ No newline at end of file diff --git a/TelegramBotBase.Test/Tests/Navigation/Form1.cs b/TelegramBotBase.Test/Tests/Navigation/Form1.cs index b7270a6..c000fe7 100644 --- a/TelegramBotBase.Test/Tests/Navigation/Form1.cs +++ b/TelegramBotBase.Test/Tests/Navigation/Form1.cs @@ -4,83 +4,80 @@ using Telegram.Bot.Types; using TelegramBotBase.Base; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Navigation +namespace TelegramBotBaseTest.Tests.Navigation; + +public class Form1 : FormBase { - public class Form1 : FormBase + private Message _msg; + + public Form1() { - private Message _msg; - - public Form1() - { - Closed += Form1_Closed; - } - - private async Task Form1_Closed(object sender, EventArgs e) - { - if (_msg == null) - return; - - await Device.DeleteMessage(_msg); - } - - public override async Task Action(MessageResult message) - { - if (message.Handled) - return; - - await message.ConfirmAction(); - - switch (message.RawData) - { - case "next": - - message.Handled = true; - - var f1 = new Form1(); - - await NavigationController.PushAsync(f1); - - - break; - - case "previous": - - message.Handled = true; - - //Pop's the current form and move the previous one. The root form will be the Start class. - await NavigationController.PopAsync(); - - break; - - case "root": - - message.Handled = true; - - await NavigationController.PopToRootAsync(); - - break; - - - } - - - - } - - public override async Task Render(MessageResult message) - { - if (_msg != null) - return; - - var bf = new ButtonForm(); - bf.AddButtonRow("Next page", "next"); - bf.AddButtonRow("Previous page", "previous"); - bf.AddButtonRow("Back to root", "root"); - - _msg = await Device.Send($"Choose your options (Count on stack {NavigationController.Index + 1})", bf); - - } - - + Closed += Form1_Closed; } -} + + private async Task Form1_Closed(object sender, EventArgs e) + { + if (_msg == null) + { + return; + } + + await Device.DeleteMessage(_msg); + } + + public override async Task Action(MessageResult message) + { + if (message.Handled) + { + return; + } + + await message.ConfirmAction(); + + switch (message.RawData) + { + case "next": + + message.Handled = true; + + var f1 = new Form1(); + + await NavigationController.PushAsync(f1); + + + break; + + case "previous": + + message.Handled = true; + + //Pop's the current form and move the previous one. The root form will be the Start class. + await NavigationController.PopAsync(); + + break; + + case "root": + + message.Handled = true; + + await NavigationController.PopToRootAsync(); + + break; + } + } + + public override async Task Render(MessageResult message) + { + if (_msg != null) + { + return; + } + + var bf = new ButtonForm(); + bf.AddButtonRow("Next page", "next"); + bf.AddButtonRow("Previous page", "previous"); + bf.AddButtonRow("Back to root", "root"); + + _msg = await Device.Send($"Choose your options (Count on stack {NavigationController.Index + 1})", bf); + } +} \ No newline at end of file diff --git a/TelegramBotBase.Test/Tests/Navigation/Start.cs b/TelegramBotBase.Test/Tests/Navigation/Start.cs index 2599ff3..034a653 100644 --- a/TelegramBotBase.Test/Tests/Navigation/Start.cs +++ b/TelegramBotBase.Test/Tests/Navigation/Start.cs @@ -3,77 +3,78 @@ using Telegram.Bot.Types; using TelegramBotBase.Base; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Navigation +namespace TelegramBotBaseTest.Tests.Navigation; + +public class Start : FormBase { - public class Start : FormBase + private Message _msg; + + + public override Task Load(MessageResult message) { - private Message _msg; - - - public override Task Load(MessageResult message) - { - return Task.CompletedTask; - } - - public override async Task Action(MessageResult message) - { - if (message.Handled) - return; - - await message.ConfirmAction(); - - switch (message.RawData) - { - case "yes": - - message.Handled = true; - - //Create navigation controller and navigate to it, keep the current form as root form so we can get back to here later - var nc = new CustomController(this); - nc.ForceCleanupOnLastPop = true; - - var f1 = new Form1(); - - await nc.PushAsync(f1); - - await NavigateTo(nc); - - if (_msg == null) - return; - - await Device.DeleteMessage(_msg); - - - break; - case "no": - - message.Handled = true; - - var mn = new Menu(); - - await NavigateTo(mn); - - if (_msg == null) - return; - - await Device.DeleteMessage(_msg); - - break; - } - - } - - public override async Task Render(MessageResult message) - { - var bf = new ButtonForm(); - - bf.AddButtonRow("Yes", "yes"); - bf.AddButtonRow("No", "no"); - - _msg = await Device.Send("Open controller?", bf); - - - } - + return Task.CompletedTask; } -} + + public override async Task Action(MessageResult message) + { + if (message.Handled) + { + return; + } + + await message.ConfirmAction(); + + switch (message.RawData) + { + case "yes": + + message.Handled = true; + + //Create navigation controller and navigate to it, keep the current form as root form so we can get back to here later + var nc = new CustomController(this); + nc.ForceCleanupOnLastPop = true; + + var f1 = new Form1(); + + await nc.PushAsync(f1); + + await NavigateTo(nc); + + if (_msg == null) + { + return; + } + + await Device.DeleteMessage(_msg); + + + break; + case "no": + + message.Handled = true; + + var mn = new Menu(); + + await NavigateTo(mn); + + if (_msg == null) + { + return; + } + + await Device.DeleteMessage(_msg); + + break; + } + } + + public override async Task Render(MessageResult message) + { + var bf = new ButtonForm(); + + bf.AddButtonRow("Yes", "yes"); + bf.AddButtonRow("No", "no"); + + _msg = await Device.Send("Open controller?", bf); + } +} \ No newline at end of file diff --git a/TelegramBotBase.Test/Tests/Notifications/Start.cs b/TelegramBotBase.Test/Tests/Notifications/Start.cs index 702a9e7..a04b770 100644 --- a/TelegramBotBase.Test/Tests/Notifications/Start.cs +++ b/TelegramBotBase.Test/Tests/Notifications/Start.cs @@ -3,59 +3,59 @@ using TelegramBotBase.Base; using TelegramBotBase.Enums; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Notifications +namespace TelegramBotBaseTest.Tests.Notifications; + +public class Start : AutoCleanForm { - public class Start : AutoCleanForm + private bool _sent; + + public Start() { - private bool _sent; - - public Start() - { - DeleteMode = EDeleteMode.OnLeavingForm; - } - - public override async Task Action(MessageResult message) - { - if (message.Handled) - return; - - switch (message.RawData) - { - case "alert": - - await message.ConfirmAction("This is an alert.", true); - - break; - case "back": - - var mn = new Menu(); - await NavigateTo(mn); - - break; - default: - - await message.ConfirmAction("This is feedback"); - - break; - - } - - } - - public override async Task Render(MessageResult message) - { - if (_sent) - return; - - var bf = new ButtonForm(); - bf.AddButtonRow("Normal feeback", "normal"); - bf.AddButtonRow("Alert Box", "alert"); - bf.AddButtonRow("Back", "back"); - - await Device.Send("Choose your test", bf); - - _sent = true; - } - + DeleteMode = EDeleteMode.OnLeavingForm; } -} + + public override async Task Action(MessageResult message) + { + if (message.Handled) + { + return; + } + + switch (message.RawData) + { + case "alert": + + await message.ConfirmAction("This is an alert.", true); + + break; + case "back": + + var mn = new Menu(); + await NavigateTo(mn); + + break; + default: + + await message.ConfirmAction("This is feedback"); + + break; + } + } + + public override async Task Render(MessageResult message) + { + if (_sent) + { + return; + } + + var bf = new ButtonForm(); + bf.AddButtonRow("Normal feeback", "normal"); + bf.AddButtonRow("Alert Box", "alert"); + bf.AddButtonRow("Back", "back"); + + await Device.Send("Choose your test", bf); + + _sent = true; + } +} \ No newline at end of file diff --git a/TelegramBotBase.Test/Tests/ProgressTest.cs b/TelegramBotBase.Test/Tests/ProgressTest.cs index 0657c82..a8dcf70 100644 --- a/TelegramBotBase.Test/Tests/ProgressTest.cs +++ b/TelegramBotBase.Test/Tests/ProgressTest.cs @@ -6,133 +6,131 @@ using TelegramBotBase.Controls.Inline; using TelegramBotBase.Enums; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests +namespace TelegramBotBaseTest.Tests; + +public class ProgressTest : AutoCleanForm { - public class ProgressTest : AutoCleanForm + public ProgressTest() { + DeleteMode = EDeleteMode.OnLeavingForm; + Opened += ProgressTest_Opened; + Closed += ProgressTest_Closed; + } - public ProgressTest() + + private async Task ProgressTest_Opened(object sender, EventArgs e) + { + await Device.Send("Welcome to ProgressTest"); + } + + public override async Task Action(MessageResult message) + { + var call = message.GetData(); + + await message.ConfirmAction(); + + + if (call == null) { - DeleteMode = EDeleteMode.OnLeavingForm; - Opened += ProgressTest_Opened; - Closed += ProgressTest_Closed; + return; } + ProgressBar bar = null; - private async Task ProgressTest_Opened(object sender, EventArgs e) + switch (call.Value) { - await Device.Send("Welcome to ProgressTest"); - } + case "standard": - public override async Task Action(MessageResult message) - { - var call = message.GetData(); + bar = new ProgressBar(0, 100, ProgressBar.EProgressStyle.standard) + { + Device = Device + }; - await message.ConfirmAction(); + break; + case "squares": + + bar = new ProgressBar(0, 100, ProgressBar.EProgressStyle.squares) + { + Device = Device + }; + + break; + + case "circles": + + bar = new ProgressBar(0, 100, ProgressBar.EProgressStyle.circles) + { + Device = Device + }; + + break; + + case "lines": + + bar = new ProgressBar(0, 100, ProgressBar.EProgressStyle.lines) + { + Device = Device + }; + + break; + + case "squaredlines": + + bar = new ProgressBar(0, 100, ProgressBar.EProgressStyle.squaredLines) + { + Device = Device + }; + + break; + + case "start": + + var sf = new Menu(); + + await NavigateTo(sf); - if (call == null) return; - ProgressBar bar = null; + default: - switch (call.Value) - { - case "standard": - - bar = new ProgressBar(0, 100, ProgressBar.EProgressStyle.standard) - { - Device = Device - }; - - break; - - case "squares": - - bar = new ProgressBar(0, 100, ProgressBar.EProgressStyle.squares) - { - Device = Device - }; - - break; - - case "circles": - - bar = new ProgressBar(0, 100, ProgressBar.EProgressStyle.circles) - { - Device = Device - }; - - break; - - case "lines": - - bar = new ProgressBar(0, 100, ProgressBar.EProgressStyle.lines) - { - Device = Device - }; - - break; - - case "squaredlines": - - bar = new ProgressBar(0, 100, ProgressBar.EProgressStyle.squaredLines) - { - Device = Device - }; - - break; - - case "start": - - var sf = new Menu(); - - await NavigateTo(sf); - - return; - - default: - - return; - - } + return; + } - //Render Progress bar and show some "example" progress + //Render Progress bar and show some "example" progress + await bar.Render(message); + + Controls.Add(bar); + + for (var i = 0; i <= 100; i++) + { + bar.Value++; await bar.Render(message); - Controls.Add(bar); - - for (var i = 0; i <= 100; i++) - { - bar.Value++; - await bar.Render(message); - - Thread.Sleep(250); - } - - + Thread.Sleep(250); } - - - public override async Task Render(MessageResult message) - { - var btn = new ButtonForm(); - btn.AddButtonRow(new ButtonBase("Standard", new CallbackData("a", "standard").Serialize()), new ButtonBase("Squares", new CallbackData("a", "squares").Serialize())); - - btn.AddButtonRow(new ButtonBase("Circles", new CallbackData("a", "circles").Serialize()), new ButtonBase("Lines", new CallbackData("a", "lines").Serialize())); - - btn.AddButtonRow(new ButtonBase("Squared Line", new CallbackData("a", "squaredlines").Serialize())); - - btn.AddButtonRow(new ButtonBase("Back to start", new CallbackData("a", "start").Serialize())); - - await Device.Send("Choose your progress bar:", btn); - } - - private async Task ProgressTest_Closed(object sender, EventArgs e) - { - await Device.Send("Ciao from ProgressTest"); - } - } -} + + + public override async Task Render(MessageResult message) + { + var btn = new ButtonForm(); + btn.AddButtonRow(new ButtonBase("Standard", new CallbackData("a", "standard").Serialize()), + new ButtonBase("Squares", new CallbackData("a", "squares").Serialize())); + + btn.AddButtonRow(new ButtonBase("Circles", new CallbackData("a", "circles").Serialize()), + new ButtonBase("Lines", new CallbackData("a", "lines").Serialize())); + + btn.AddButtonRow(new ButtonBase("Squared Line", new CallbackData("a", "squaredlines").Serialize())); + + btn.AddButtonRow(new ButtonBase("Back to start", new CallbackData("a", "start").Serialize())); + + await Device.Send("Choose your progress bar:", btn); + } + + private async Task ProgressTest_Closed(object sender, EventArgs e) + { + await Device.Send("Ciao from ProgressTest"); + } +} \ No newline at end of file diff --git a/TelegramBotBase.Test/Tests/Register/PerForm.cs b/TelegramBotBase.Test/Tests/Register/PerForm.cs index ab703f7..fde7e05 100644 --- a/TelegramBotBase.Test/Tests/Register/PerForm.cs +++ b/TelegramBotBase.Test/Tests/Register/PerForm.cs @@ -2,99 +2,97 @@ using TelegramBotBase.Base; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Register +namespace TelegramBotBaseTest.Tests.Register; + +public class PerForm : AutoCleanForm { - public class PerForm : AutoCleanForm + public string EMail { get; set; } + + public string Firstname { get; set; } + + public string Lastname { get; set; } + + public override Task Load(MessageResult message) { - public string EMail { get; set; } - - public string Firstname { get; set; } - - public string Lastname { get; set; } - - public override Task Load(MessageResult message) + if (message.MessageText.Trim() == "") { - if (message.MessageText.Trim() == "") - return Task.CompletedTask; - - if (Firstname == null) - { - Firstname = message.MessageText; - return Task.CompletedTask; - } - - if (Lastname == null) - { - Lastname = message.MessageText; - return Task.CompletedTask; - } - - if (EMail == null) - { - EMail = message.MessageText; - return Task.CompletedTask; - } - return Task.CompletedTask; } - public override async Task Action(MessageResult message) + if (Firstname == null) { - var call = message.GetData(); - - await message.ConfirmAction(); - - if (call == null) - return; - - switch (call.Value) - { - case "back": - - var start = new Start(); - - await NavigateTo(start); - - break; - - } - - + Firstname = message.MessageText; + return Task.CompletedTask; } - public override async Task Render(MessageResult message) + if (Lastname == null) { - if (Firstname == null) - { - await Device.Send("Please sent your firstname:"); - return; - } - - if (Lastname == null) - { - await Device.Send("Please sent your lastname:"); - return; - } - - if (EMail == null) - { - await Device.Send("Please sent your email address:"); - return; - } - - - var s = ""; - - s += "Firstname: " + Firstname + "\r\n"; - s += "Lastname: " + Lastname + "\r\n"; - s += "E-Mail: " + EMail + "\r\n"; - - var bf = new ButtonForm(); - bf.AddButtonRow(new ButtonBase("Back", new CallbackData("a", "back").Serialize())); - - await Device.Send("Your details:\r\n" + s, bf); + Lastname = message.MessageText; + return Task.CompletedTask; } + if (EMail == null) + { + EMail = message.MessageText; + return Task.CompletedTask; + } + return Task.CompletedTask; } -} + + public override async Task Action(MessageResult message) + { + var call = message.GetData(); + + await message.ConfirmAction(); + + if (call == null) + { + return; + } + + switch (call.Value) + { + case "back": + + var start = new Start(); + + await NavigateTo(start); + + break; + } + } + + public override async Task Render(MessageResult message) + { + if (Firstname == null) + { + await Device.Send("Please sent your firstname:"); + return; + } + + if (Lastname == null) + { + await Device.Send("Please sent your lastname:"); + return; + } + + if (EMail == null) + { + await Device.Send("Please sent your email address:"); + return; + } + + + var s = ""; + + s += "Firstname: " + Firstname + "\r\n"; + s += "Lastname: " + Lastname + "\r\n"; + s += "E-Mail: " + EMail + "\r\n"; + + var bf = new ButtonForm(); + bf.AddButtonRow(new ButtonBase("Back", new CallbackData("a", "back").Serialize())); + + await Device.Send("Your details:\r\n" + s, bf); + } +} \ No newline at end of file diff --git a/TelegramBotBase.Test/Tests/Register/PerStep.cs b/TelegramBotBase.Test/Tests/Register/PerStep.cs index b31779a..437dbce 100644 --- a/TelegramBotBase.Test/Tests/Register/PerStep.cs +++ b/TelegramBotBase.Test/Tests/Register/PerStep.cs @@ -3,42 +3,39 @@ using TelegramBotBase.Base; using TelegramBotBase.Form; using TelegramBotBaseTest.Tests.Register.Steps; -namespace TelegramBotBaseTest.Tests.Register +namespace TelegramBotBaseTest.Tests.Register; + +public class PerStep : AutoCleanForm { - public class PerStep: AutoCleanForm + public override async Task Action(MessageResult message) { + await message.ConfirmAction(); - public override async Task Action(MessageResult message) + switch (message.RawData) { - await message.ConfirmAction(); + case "start": - switch (message.RawData) - { - case "start": + var step1 = new Step1(); - var step1 = new Step1(); + await NavigateTo(step1); - await NavigateTo(step1); + break; + case "back": - break; - case "back": + var start = new Start(); - var start = new Start(); + await NavigateTo(start); - await NavigateTo(start); - - break; - - } - } - - public override async Task Render(MessageResult message) - { - var bf = new ButtonForm(); - bf.AddButtonRow(new ButtonBase("Goto Step 1", "start")); - bf.AddButtonRow(new ButtonBase("Back", "back")); - - await Device.Send("Register Steps", bf); + break; } } -} + + public override async Task Render(MessageResult message) + { + var bf = new ButtonForm(); + bf.AddButtonRow(new ButtonBase("Goto Step 1", "start")); + bf.AddButtonRow(new ButtonBase("Back", "back")); + + await Device.Send("Register Steps", bf); + } +} \ No newline at end of file diff --git a/TelegramBotBase.Test/Tests/Register/Start.cs b/TelegramBotBase.Test/Tests/Register/Start.cs index a37c5c7..09b3516 100644 --- a/TelegramBotBase.Test/Tests/Register/Start.cs +++ b/TelegramBotBase.Test/Tests/Register/Start.cs @@ -2,62 +2,56 @@ using TelegramBotBase.Base; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Register +namespace TelegramBotBaseTest.Tests.Register; + +public class Start : AutoCleanForm { - public class Start : AutoCleanForm + public override async Task Action(MessageResult message) { - public override async Task Action(MessageResult message) + var call = message.GetData(); + + await message.ConfirmAction(); + + + if (call == null) { - var call = message.GetData(); - - await message.ConfirmAction(); - - - if (call == null) - return; - - switch (call.Value) - { - case "form": - - var form = new PerForm(); - - await NavigateTo(form); - - break; - case "step": - - var step = new PerStep(); - - await NavigateTo(step); - - break; - case "backtodashboard": - - var start = new Menu(); - - await NavigateTo(start); - - break; - } - - + return; } - public override async Task Render(MessageResult message) + switch (call.Value) { + case "form": - var btn = new ButtonForm(); + var form = new PerForm(); - btn.AddButtonRow(new ButtonBase("#4.1 Per Form", new CallbackData("a", "form").Serialize())); - btn.AddButtonRow(new ButtonBase("#4.2 Per Step", new CallbackData("a", "step").Serialize())); - btn.AddButtonRow(new ButtonBase("Back", new CallbackData("a", "backtodashboard").Serialize())); + await NavigateTo(form); - await Device.Send("Choose your test:", btn); + break; + case "step": + var step = new PerStep(); + await NavigateTo(step); + + break; + case "backtodashboard": + + var start = new Menu(); + + await NavigateTo(start); + + break; } - - } -} + + public override async Task Render(MessageResult message) + { + var btn = new ButtonForm(); + + btn.AddButtonRow(new ButtonBase("#4.1 Per Form", new CallbackData("a", "form").Serialize())); + btn.AddButtonRow(new ButtonBase("#4.2 Per Step", new CallbackData("a", "step").Serialize())); + btn.AddButtonRow(new ButtonBase("Back", new CallbackData("a", "backtodashboard").Serialize())); + + await Device.Send("Choose your test:", btn); + } +} \ No newline at end of file diff --git a/TelegramBotBase.Test/Tests/Register/Steps/Data.cs b/TelegramBotBase.Test/Tests/Register/Steps/Data.cs index fab243b..63a56ff 100644 --- a/TelegramBotBase.Test/Tests/Register/Steps/Data.cs +++ b/TelegramBotBase.Test/Tests/Register/Steps/Data.cs @@ -1,12 +1,10 @@ -namespace TelegramBotBaseTest.Tests.Register.Steps +namespace TelegramBotBaseTest.Tests.Register.Steps; + +public class Data { - public class Data - { - public string EMail { get; set; } + public string EMail { get; set; } - public string Firstname { get; set; } + public string Firstname { get; set; } - public string Lastname { get; set; } - - } -} + public string Lastname { get; set; } +} \ No newline at end of file diff --git a/TelegramBotBase.Test/Tests/Register/Steps/Step1.cs b/TelegramBotBase.Test/Tests/Register/Steps/Step1.cs index 0b0616d..3cf1570 100644 --- a/TelegramBotBase.Test/Tests/Register/Steps/Step1.cs +++ b/TelegramBotBase.Test/Tests/Register/Steps/Step1.cs @@ -3,57 +3,59 @@ using TelegramBotBase.Args; using TelegramBotBase.Base; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Register.Steps +namespace TelegramBotBaseTest.Tests.Register.Steps; + +public class Step1 : AutoCleanForm { - public class Step1 : AutoCleanForm + public Step1() { - public Data UserData { get; set; } - - public Step1() - { - Init += Step1_Init; - } - - private Task Step1_Init(object sender, InitEventArgs e) - { - UserData = new Data(); - return Task.CompletedTask; - } - - - public override Task Load(MessageResult message) - { - if (message.Handled) - return Task.CompletedTask; - - if (message.MessageText.Trim() == "") - return Task.CompletedTask; - - if (UserData.Firstname == null) - { - UserData.Firstname = message.MessageText; - return Task.CompletedTask; - } - - return Task.CompletedTask; - } - - public override async Task Render(MessageResult message) - { - if (UserData.Firstname == null) - { - await Device.Send("Please sent your firstname:"); - return; - } - - message.Handled = true; - - var step2 = new Step2(); - - step2.UserData = UserData; - - await NavigateTo(step2); - } - + Init += Step1_Init; } -} + + public Data UserData { get; set; } + + private Task Step1_Init(object sender, InitEventArgs e) + { + UserData = new Data(); + return Task.CompletedTask; + } + + + public override Task Load(MessageResult message) + { + if (message.Handled) + { + return Task.CompletedTask; + } + + if (message.MessageText.Trim() == "") + { + return Task.CompletedTask; + } + + if (UserData.Firstname == null) + { + UserData.Firstname = message.MessageText; + return Task.CompletedTask; + } + + return Task.CompletedTask; + } + + public override async Task Render(MessageResult message) + { + if (UserData.Firstname == null) + { + await Device.Send("Please sent your firstname:"); + return; + } + + message.Handled = true; + + var step2 = new Step2(); + + step2.UserData = UserData; + + await NavigateTo(step2); + } +} \ No newline at end of file diff --git a/TelegramBotBase.Test/Tests/Register/Steps/Step2.cs b/TelegramBotBase.Test/Tests/Register/Steps/Step2.cs index 5a954f4..fffd190 100644 --- a/TelegramBotBase.Test/Tests/Register/Steps/Step2.cs +++ b/TelegramBotBase.Test/Tests/Register/Steps/Step2.cs @@ -2,47 +2,49 @@ using TelegramBotBase.Base; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Register.Steps +namespace TelegramBotBaseTest.Tests.Register.Steps; + +public class Step2 : AutoCleanForm { - public class Step2 : AutoCleanForm + public Data UserData { get; set; } + + + public override Task Load(MessageResult message) { - public Data UserData { get; set; } - - - public override Task Load(MessageResult message) + if (message.Handled) { - if (message.Handled) - return Task.CompletedTask; - - if (message.MessageText.Trim() == "") - return Task.CompletedTask; - - if (UserData.Lastname == null) - { - UserData.Lastname = message.MessageText; - return Task.CompletedTask; - } - return Task.CompletedTask; } - - public override async Task Render(MessageResult message) + if (message.MessageText.Trim() == "") { - if (UserData.Lastname == null) - { - await Device.Send("Please sent your lastname:"); - return; - } - - message.Handled = true; - - var step3 = new Step3(); - - step3.UserData = UserData; - - await NavigateTo(step3); + return Task.CompletedTask; } + if (UserData.Lastname == null) + { + UserData.Lastname = message.MessageText; + return Task.CompletedTask; + } + + return Task.CompletedTask; } -} + + + public override async Task Render(MessageResult message) + { + if (UserData.Lastname == null) + { + await Device.Send("Please sent your lastname:"); + return; + } + + message.Handled = true; + + var step3 = new Step3(); + + step3.UserData = UserData; + + await NavigateTo(step3); + } +} \ No newline at end of file diff --git a/TelegramBotBase.Test/Tests/Register/Steps/Step3.cs b/TelegramBotBase.Test/Tests/Register/Steps/Step3.cs index 1f22924..45eaea8 100644 --- a/TelegramBotBase.Test/Tests/Register/Steps/Step3.cs +++ b/TelegramBotBase.Test/Tests/Register/Steps/Step3.cs @@ -2,68 +2,68 @@ using TelegramBotBase.Base; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Register.Steps +namespace TelegramBotBaseTest.Tests.Register.Steps; + +public class Step3 : AutoCleanForm { - public class Step3 : AutoCleanForm + public Data UserData { get; set; } + + public override Task Load(MessageResult message) { - public Data UserData { get; set; } - - public override Task Load(MessageResult message) + if (message.Handled) { - if (message.Handled) - return Task.CompletedTask; - - if (message.MessageText.Trim() == "") - return Task.CompletedTask; - - if (UserData.EMail == null) - { - UserData.EMail = message.MessageText; - return Task.CompletedTask; - } - return Task.CompletedTask; } - public override async Task Action(MessageResult message) + if (message.MessageText.Trim() == "") { - await message.ConfirmAction(); - - switch (message.RawData) - { - case "back": - - var start = new Start(); - - await NavigateTo(start); - - break; - - } - + return Task.CompletedTask; } - public override async Task Render(MessageResult message) + if (UserData.EMail == null) { - if (UserData.EMail == null) - { - await Device.Send("Please sent your email:"); - return; - } - - message.Handled = true; - - var s = ""; - - s += "Firstname: " + UserData.Firstname + "\r\n"; - s += "Lastname: " + UserData.Lastname + "\r\n"; - s += "E-Mail: " + UserData.EMail + "\r\n"; - - var bf = new ButtonForm(); - bf.AddButtonRow(new ButtonBase("Back", "back")); - - await Device.Send("Your details:\r\n" + s, bf); + UserData.EMail = message.MessageText; + return Task.CompletedTask; } + return Task.CompletedTask; } -} + + public override async Task Action(MessageResult message) + { + await message.ConfirmAction(); + + switch (message.RawData) + { + case "back": + + var start = new Start(); + + await NavigateTo(start); + + break; + } + } + + public override async Task Render(MessageResult message) + { + if (UserData.EMail == null) + { + await Device.Send("Please sent your email:"); + return; + } + + message.Handled = true; + + var s = ""; + + s += "Firstname: " + UserData.Firstname + "\r\n"; + s += "Lastname: " + UserData.Lastname + "\r\n"; + s += "E-Mail: " + UserData.EMail + "\r\n"; + + var bf = new ButtonForm(); + bf.AddButtonRow(new ButtonBase("Back", "back")); + + await Device.Send("Your details:\r\n" + s, bf); + } +} \ No newline at end of file diff --git a/TelegramBotBase.Test/Tests/SimpleForm.cs b/TelegramBotBase.Test/Tests/SimpleForm.cs index 4f5c5fa..d776936 100644 --- a/TelegramBotBase.Test/Tests/SimpleForm.cs +++ b/TelegramBotBase.Test/Tests/SimpleForm.cs @@ -4,63 +4,59 @@ using TelegramBotBase.Base; using TelegramBotBase.Enums; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests +namespace TelegramBotBaseTest.Tests; + +public class SimpleForm : AutoCleanForm { - public class SimpleForm : AutoCleanForm + public SimpleForm() { + DeleteSide = EDeleteSide.Both; + DeleteMode = EDeleteMode.OnLeavingForm; - public SimpleForm() - { - DeleteSide = EDeleteSide.Both; - DeleteMode = EDeleteMode.OnLeavingForm; - - Opened += SimpleForm_Opened; - } - - private async Task SimpleForm_Opened(object sender, EventArgs e) - { - await Device.Send("Hello world! (send 'back' to get back to Start)\r\nOr\r\nhi, hello, maybe, bye and ciao"); - } - - public override async Task Load(MessageResult message) - { - //message.MessageText will work also, cause it is a string you could manage a lot different scenerios here - - var messageId = message.MessageId; - - switch (message.Command) - { - case "hello": - case "hi": - - //Send him a simple message - await Device.Send("Hello you there !"); - break; - - case "maybe": - - //Send him a simple message and reply to the one of himself - await Device.Send("Maybe what?", replyTo: messageId); - - break; - - case "bye": - case "ciao": - - //Send him a simple message - await Device.Send("Ok, take care !"); - break; - - case "back": - - var st = new Menu(); - - await NavigateTo(st); - - break; - } - } - - + Opened += SimpleForm_Opened; } -} + + private async Task SimpleForm_Opened(object sender, EventArgs e) + { + await Device.Send("Hello world! (send 'back' to get back to Start)\r\nOr\r\nhi, hello, maybe, bye and ciao"); + } + + public override async Task Load(MessageResult message) + { + //message.MessageText will work also, cause it is a string you could manage a lot different scenerios here + + var messageId = message.MessageId; + + switch (message.Command) + { + case "hello": + case "hi": + + //Send him a simple message + await Device.Send("Hello you there !"); + break; + + case "maybe": + + //Send him a simple message and reply to the one of himself + await Device.Send("Maybe what?", replyTo: messageId); + + break; + + case "bye": + case "ciao": + + //Send him a simple message + await Device.Send("Ok, take care !"); + break; + + case "back": + + var st = new Menu(); + + await NavigateTo(st); + + break; + } + } +} \ No newline at end of file diff --git a/TelegramBotBase.Test/Tests/Start.cs b/TelegramBotBase.Test/Tests/Start.cs index 5933011..bbe1783 100644 --- a/TelegramBotBase.Test/Tests/Start.cs +++ b/TelegramBotBase.Test/Tests/Start.cs @@ -3,36 +3,34 @@ using TelegramBotBase.Base; using TelegramBotBase.Form; using TelegramBotBaseTest.Tests.Groups; -namespace TelegramBotBaseTest.Tests +namespace TelegramBotBaseTest.Tests; + +public class Start : SplitterForm { - public class Start : SplitterForm + public override async Task Open(MessageResult e) { - public override async Task Open(MessageResult e) - { - var st = new Menu(); - await NavigateTo(st); - - return true; - } - - - public override async Task OpenGroup(MessageResult e) - { - var st = new LinkReplaceTest(); - await NavigateTo(st); - - return true; - } - - public override Task OpenChannel(MessageResult e) - { - return base.OpenChannel(e); - } - - public override Task OpenSupergroup(MessageResult e) - { - return base.OpenSupergroup(e); - } + var st = new Menu(); + await NavigateTo(st); + return true; } -} + + + public override async Task OpenGroup(MessageResult e) + { + var st = new LinkReplaceTest(); + await NavigateTo(st); + + return true; + } + + public override Task OpenChannel(MessageResult e) + { + return base.OpenChannel(e); + } + + public override Task OpenSupergroup(MessageResult e) + { + return base.OpenSupergroup(e); + } +} \ No newline at end of file diff --git a/TelegramBotBase.Test/Tests/TestForm.cs b/TelegramBotBase.Test/Tests/TestForm.cs index e248414..30cb824 100644 --- a/TelegramBotBase.Test/Tests/TestForm.cs +++ b/TelegramBotBase.Test/Tests/TestForm.cs @@ -3,70 +3,65 @@ using System.Threading.Tasks; using TelegramBotBase.Base; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests +namespace TelegramBotBaseTest.Tests; + +public class TestForm : FormBase { - public class TestForm : FormBase + public TestForm() { - private string LastMessage { get; set; } - - public TestForm() - { - Opened += TestForm_Opened; - Closed += TestForm_Closed; - } - - private async Task TestForm_Opened(object sender, EventArgs e) - { - await Device.Send("Welcome to Form 1"); - } - - private async Task TestForm_Closed(object sender, EventArgs e) - { - await Device.Send("Ciao from Form 1"); - } - - - public override async Task Action(MessageResult message) - { - switch (message.Command) - { - case "reply": - - - break; - - case "navigate": - - var tf = new TestForm2(); - - await NavigateTo(tf); - - break; - - default: - - if (message.UpdateData == null) - return; - - LastMessage = message.Message.Text; - - break; - } - - - } - - - public override async Task Render(MessageResult message) - { - if (message.Command == "reply") - { - - await Device.Send("Last message: " + LastMessage); - - } - - } - + Opened += TestForm_Opened; + Closed += TestForm_Closed; } -} + + private string LastMessage { get; set; } + + private async Task TestForm_Opened(object sender, EventArgs e) + { + await Device.Send("Welcome to Form 1"); + } + + private async Task TestForm_Closed(object sender, EventArgs e) + { + await Device.Send("Ciao from Form 1"); + } + + + public override async Task Action(MessageResult message) + { + switch (message.Command) + { + case "reply": + + + break; + + case "navigate": + + var tf = new TestForm2(); + + await NavigateTo(tf); + + break; + + default: + + if (message.UpdateData == null) + { + return; + } + + LastMessage = message.Message.Text; + + break; + } + } + + + public override async Task Render(MessageResult message) + { + if (message.Command == "reply") + { + await Device.Send("Last message: " + LastMessage); + } + } +} \ No newline at end of file diff --git a/TelegramBotBase.Test/Tests/TestForm2.cs b/TelegramBotBase.Test/Tests/TestForm2.cs index 93cced0..2cff462 100644 --- a/TelegramBotBase.Test/Tests/TestForm2.cs +++ b/TelegramBotBase.Test/Tests/TestForm2.cs @@ -6,118 +6,103 @@ using TelegramBotBase.Base; using TelegramBotBase.Extensions.Images; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests +namespace TelegramBotBaseTest.Tests; + +public class TestForm2 : FormBase { - public class TestForm2 : FormBase + public TestForm2() { - - - public TestForm2() - { - Opened += TestForm2_Opened; - Closed += TestForm2_Closed; - } - - private async Task TestForm2_Opened(object sender, EventArgs e) - { - await Device.Send("Welcome to Form 2"); - } - - private async Task TestForm2_Closed(object sender, EventArgs e) - { - await Device.Send("Ciao from Form 2"); - } - - - - - public override async Task Action(MessageResult message) - { - var call = message.GetData(); - - await message.ConfirmAction(); - - await message.DeleteMessage(); - - message.Handled = true; - - if (call.Value == "testform1") - { - - var tf = new TestForm(); - - await NavigateTo(tf); - } - else if (call.Value == "alert") - { - var ad = new AlertDialog("This is a message", "Ok"); - - ad.ButtonClicked += async (s, en) => - { - var fto = new TestForm2(); - await NavigateTo(fto); - }; - - await NavigateTo(ad); - } - else if (call.Value == "confirm") - { - var pd = new ConfirmDialog("Please confirm", new ButtonBase("Ok", "ok"), new ButtonBase("Cancel", "cancel")); - - pd.ButtonClicked += async (s, en) => - { - var tf = new TestForm2(); - - await pd.NavigateTo(tf); - }; - - await NavigateTo(pd); - } - else if (call.Value == "prompt") - { - var pd = new PromptDialog("Please tell me your name ?"); - - pd.Completed += async (s, en) => - { - await Device.Send("Hello " + pd.Value); - }; - - await OpenModal(pd); - } - - - } - - public override async Task Render(MessageResult message) - { - - var bmp = new Bitmap(800, 600); - using (var g = Graphics.FromImage(bmp)) - { - - g.FillRectangle(Brushes.White, 0, 0, bmp.Width, bmp.Height); - - g.DrawString("Test Image", new Font("Arial", 24, FontStyle.Bold, GraphicsUnit.Pixel), Brushes.Black, new PointF(50, 50)); - - } - - await Device.SetAction(ChatAction.UploadPhoto); - - var btn = new ButtonForm(); - - //btn.AddButtonRow(new ButtonBase("Zum Testformular 1", CallbackData.Create("navigate", "testform1")), new ButtonBase("Zum Testformular 1", CallbackData.Create("navigate", "testform1"))); - - btn.AddButtonRow(new ButtonBase("Information Prompt", CallbackData.Create("navigate", "alert"))); - - btn.AddButtonRow(new ButtonBase("Confirmation Prompt with event", CallbackData.Create("navigate", "confirm"))); - - btn.AddButtonRow(new ButtonBase("Request Prompt", CallbackData.Create("navigate", "prompt"))); - - - await Device.SendPhoto(bmp, "Test", "", btn); - - } - - + Opened += TestForm2_Opened; + Closed += TestForm2_Closed; } -} + + private async Task TestForm2_Opened(object sender, EventArgs e) + { + await Device.Send("Welcome to Form 2"); + } + + private async Task TestForm2_Closed(object sender, EventArgs e) + { + await Device.Send("Ciao from Form 2"); + } + + + public override async Task Action(MessageResult message) + { + var call = message.GetData(); + + await message.ConfirmAction(); + + await message.DeleteMessage(); + + message.Handled = true; + + if (call.Value == "testform1") + { + var tf = new TestForm(); + + await NavigateTo(tf); + } + else if (call.Value == "alert") + { + var ad = new AlertDialog("This is a message", "Ok"); + + ad.ButtonClicked += async (s, en) => + { + var fto = new TestForm2(); + await NavigateTo(fto); + }; + + await NavigateTo(ad); + } + else if (call.Value == "confirm") + { + var pd = new ConfirmDialog("Please confirm", new ButtonBase("Ok", "ok"), + new ButtonBase("Cancel", "cancel")); + + pd.ButtonClicked += async (s, en) => + { + var tf = new TestForm2(); + + await pd.NavigateTo(tf); + }; + + await NavigateTo(pd); + } + else if (call.Value == "prompt") + { + var pd = new PromptDialog("Please tell me your name ?"); + + pd.Completed += async (s, en) => { await Device.Send("Hello " + pd.Value); }; + + await OpenModal(pd); + } + } + + public override async Task Render(MessageResult message) + { + var bmp = new Bitmap(800, 600); + using (var g = Graphics.FromImage(bmp)) + { + g.FillRectangle(Brushes.White, 0, 0, bmp.Width, bmp.Height); + + g.DrawString("Test Image", new Font("Arial", 24, FontStyle.Bold, GraphicsUnit.Pixel), Brushes.Black, + new PointF(50, 50)); + } + + await Device.SetAction(ChatAction.UploadPhoto); + + var btn = new ButtonForm(); + + //btn.AddButtonRow(new ButtonBase("Zum Testformular 1", CallbackData.Create("navigate", "testform1")), new ButtonBase("Zum Testformular 1", CallbackData.Create("navigate", "testform1"))); + + btn.AddButtonRow(new ButtonBase("Information Prompt", CallbackData.Create("navigate", "alert"))); + + btn.AddButtonRow(new ButtonBase("Confirmation Prompt with event", CallbackData.Create("navigate", "confirm"))); + + btn.AddButtonRow(new ButtonBase("Request Prompt", CallbackData.Create("navigate", "prompt"))); + + + await Device.SendPhoto(bmp, "Test", "", btn); + } +} \ No newline at end of file diff --git a/TelegramBotBase.Test/packages.config b/TelegramBotBase.Test/packages.config index d654912..f74d058 100644 --- a/TelegramBotBase.Test/packages.config +++ b/TelegramBotBase.Test/packages.config @@ -1,6 +1,6 @@  - - - - \ No newline at end of file + + + + diff --git a/TelegramBotBase/Args/BotCommandEventArgs.cs b/TelegramBotBase/Args/BotCommandEventArgs.cs index 3f3d545..02ec9d8 100644 --- a/TelegramBotBase/Args/BotCommandEventArgs.cs +++ b/TelegramBotBase/Args/BotCommandEventArgs.cs @@ -3,40 +3,36 @@ using System.Collections.Generic; using Telegram.Bot.Types; using TelegramBotBase.Sessions; -namespace TelegramBotBase.Args +namespace TelegramBotBase.Args; + +/// +/// Base class for given bot command results +/// +public class BotCommandEventArgs : EventArgs { - /// - /// Base class for given bot command results - /// - public class BotCommandEventArgs : EventArgs + public BotCommandEventArgs() { - public string Command { get; set; } - - public List Parameters { get; set; } - - public long DeviceId { get; set; } - - public DeviceSession Device { get; set; } - - public bool Handled { get; set; } = false; - - public Message OriginalMessage { get; set; } - - - public BotCommandEventArgs() - { - - - } - - public BotCommandEventArgs(string command, List parameters, Message message, long deviceId, DeviceSession device) - { - this.Command = command; - this.Parameters = parameters; - OriginalMessage = message; - this.DeviceId = deviceId; - this.Device = device; - } - } -} + + public BotCommandEventArgs(string command, List parameters, Message message, long deviceId, + DeviceSession device) + { + Command = command; + Parameters = parameters; + OriginalMessage = message; + DeviceId = deviceId; + Device = device; + } + + public string Command { get; set; } + + public List Parameters { get; set; } + + public long DeviceId { get; set; } + + public DeviceSession Device { get; set; } + + public bool Handled { get; set; } = false; + + public Message OriginalMessage { get; set; } +} \ No newline at end of file diff --git a/TelegramBotBase/Args/ButtonClickedEventArgs.cs b/TelegramBotBase/Args/ButtonClickedEventArgs.cs index 2227abd..1bb69a4 100644 --- a/TelegramBotBase/Args/ButtonClickedEventArgs.cs +++ b/TelegramBotBase/Args/ButtonClickedEventArgs.cs @@ -2,44 +2,41 @@ using TelegramBotBase.Controls.Hybrid; using TelegramBotBase.Form; -namespace TelegramBotBase.Args +namespace TelegramBotBase.Args; + +/// +/// Button get clicked event +/// +public class ButtonClickedEventArgs : EventArgs { - /// - /// Button get clicked event - /// - public class ButtonClickedEventArgs : EventArgs + public ButtonClickedEventArgs() { - public ButtonBase Button { get; set; } - - public int Index { get; set; } - - public object Tag { get; set; } - - public ButtonRow Row { get; set; } - - - public ButtonClickedEventArgs() - { - - } - - public ButtonClickedEventArgs(ButtonBase button) - { - Button = button; - Index = -1; - } - - public ButtonClickedEventArgs(ButtonBase button, int index) - { - Button = button; - this.Index = index; - } - - public ButtonClickedEventArgs(ButtonBase button, int index, ButtonRow row) - { - Button = button; - this.Index = index; - Row = row; - } } -} + + public ButtonClickedEventArgs(ButtonBase button) + { + Button = button; + Index = -1; + } + + public ButtonClickedEventArgs(ButtonBase button, int index) + { + Button = button; + Index = index; + } + + public ButtonClickedEventArgs(ButtonBase button, int index, ButtonRow row) + { + Button = button; + Index = index; + Row = row; + } + + public ButtonBase Button { get; set; } + + public int Index { get; set; } + + public object Tag { get; set; } + + public ButtonRow Row { get; set; } +} \ No newline at end of file diff --git a/TelegramBotBase/Args/CheckedChangedEventArgs.cs b/TelegramBotBase/Args/CheckedChangedEventArgs.cs index 5ec61d3..6e5288e 100644 --- a/TelegramBotBase/Args/CheckedChangedEventArgs.cs +++ b/TelegramBotBase/Args/CheckedChangedEventArgs.cs @@ -1,41 +1,36 @@ using System; using TelegramBotBase.Controls.Hybrid; -namespace TelegramBotBase.Args +namespace TelegramBotBase.Args; + +public class CheckedChangedEventArgs : EventArgs { - public class CheckedChangedEventArgs : EventArgs + public CheckedChangedEventArgs() { - /// - /// Contains the index of the row where the button is inside. - /// Contains -1 when it is a layout button or not found. - /// - public int Index { get; set; } - - - /// - /// Contains all buttons within this row, excluding the checkbox. - /// - public ButtonRow Row { get; set; } - - - /// - /// Contains the new checked status of the row. - /// - public bool Checked { get; set; } - - - public CheckedChangedEventArgs() - { - - } - - public CheckedChangedEventArgs(ButtonRow row, int index, bool @checked) - { - Row = row; - this.Index = index; - this.Checked = @checked; - } - - } -} + + public CheckedChangedEventArgs(ButtonRow row, int index, bool @checked) + { + Row = row; + Index = index; + Checked = @checked; + } + + /// + /// Contains the index of the row where the button is inside. + /// Contains -1 when it is a layout button or not found. + /// + public int Index { get; set; } + + + /// + /// Contains all buttons within this row, excluding the checkbox. + /// + public ButtonRow Row { get; set; } + + + /// + /// Contains the new checked status of the row. + /// + public bool Checked { get; set; } +} \ No newline at end of file diff --git a/TelegramBotBase/Args/GroupChangedEventArgs.cs b/TelegramBotBase/Args/GroupChangedEventArgs.cs index 5493f9d..5d8b9ae 100644 --- a/TelegramBotBase/Args/GroupChangedEventArgs.cs +++ b/TelegramBotBase/Args/GroupChangedEventArgs.cs @@ -2,21 +2,17 @@ using Telegram.Bot.Types.Enums; using TelegramBotBase.Base; -namespace TelegramBotBase.Args +namespace TelegramBotBase.Args; + +public class GroupChangedEventArgs : EventArgs { - public class GroupChangedEventArgs : EventArgs + public GroupChangedEventArgs(MessageType type, MessageResult message) { - public MessageType Type { get; set; } - - public MessageResult OriginalMessage { get; set; } - - public GroupChangedEventArgs(MessageType type, MessageResult message) - { - Type = type; - OriginalMessage = message; - } - - - + Type = type; + OriginalMessage = message; } -} + + public MessageType Type { get; set; } + + public MessageResult OriginalMessage { get; set; } +} \ No newline at end of file diff --git a/TelegramBotBase/Args/InitEventArgs.cs b/TelegramBotBase/Args/InitEventArgs.cs index 360aaa1..a0af03a 100644 --- a/TelegramBotBase/Args/InitEventArgs.cs +++ b/TelegramBotBase/Args/InitEventArgs.cs @@ -1,14 +1,13 @@ using System; -namespace TelegramBotBase.Args -{ - public class InitEventArgs : EventArgs - { - public object[] Args { get; set; } +namespace TelegramBotBase.Args; - public InitEventArgs(params object[] args) - { - Args = args; - } +public class InitEventArgs : EventArgs +{ + public InitEventArgs(params object[] args) + { + Args = args; } -} + + public object[] Args { get; set; } +} \ No newline at end of file diff --git a/TelegramBotBase/Args/LoadStateEventArgs.cs b/TelegramBotBase/Args/LoadStateEventArgs.cs index 06834c7..42fc51b 100644 --- a/TelegramBotBase/Args/LoadStateEventArgs.cs +++ b/TelegramBotBase/Args/LoadStateEventArgs.cs @@ -1,55 +1,59 @@ using System.Collections.Generic; using System.Linq; -namespace TelegramBotBase.Args +namespace TelegramBotBase.Args; + +public class LoadStateEventArgs { - public class LoadStateEventArgs + public LoadStateEventArgs() { - public Dictionary Values { get; set; } - - public LoadStateEventArgs() - { - Values = new Dictionary(); - } - - public List Keys => Values.Keys.ToList(); - - public string Get(string key) - { - return Values[key].ToString(); - } - - public int GetInt(string key) - { - var i = 0; - if (int.TryParse(Values[key].ToString(), out i)) - return i; - - return 0; - } - - public double GetDouble(string key) - { - double d = 0; - if (double.TryParse(Values[key].ToString(), out d)) - return d; - - return 0; - } - - public bool GetBool(string key) - { - var b = false; - if (bool.TryParse(Values[key].ToString(), out b)) - return b; - - return false; - } - - public object GetObject(string key) - { - return Values[key]; - } - + Values = new Dictionary(); } -} + + public Dictionary Values { get; set; } + + public List Keys => Values.Keys.ToList(); + + public string Get(string key) + { + return Values[key].ToString(); + } + + public int GetInt(string key) + { + var i = 0; + if (int.TryParse(Values[key].ToString(), out i)) + { + return i; + } + + return 0; + } + + public double GetDouble(string key) + { + double d = 0; + if (double.TryParse(Values[key].ToString(), out d)) + { + return d; + } + + return 0; + } + + public bool GetBool(string key) + { + var b = false; + if (bool.TryParse(Values[key].ToString(), out b)) + { + return b; + } + + return false; + } + + public object GetObject(string key) + { + return Values[key]; + } +} \ No newline at end of file diff --git a/TelegramBotBase/Args/MemberChangeEventArgs.cs b/TelegramBotBase/Args/MemberChangeEventArgs.cs index 34519a9..f59f8c0 100644 --- a/TelegramBotBase/Args/MemberChangeEventArgs.cs +++ b/TelegramBotBase/Args/MemberChangeEventArgs.cs @@ -5,32 +5,25 @@ using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; using TelegramBotBase.Base; -namespace TelegramBotBase.Args +namespace TelegramBotBase.Args; + +public class MemberChangeEventArgs : EventArgs { - public class MemberChangeEventArgs : EventArgs + public MemberChangeEventArgs() { - public List Members { get; set; } - - public MessageType Type { get; set; } - - public MessageResult Result { get; set; } - - public MemberChangeEventArgs() - { - Members = new List(); - - } - - public MemberChangeEventArgs(MessageType type, MessageResult result, params User[] members) - { - Type = type; - Result = result; - Members = members.ToList(); - } - - - - - + Members = new List(); } -} + + public MemberChangeEventArgs(MessageType type, MessageResult result, params User[] members) + { + Type = type; + Result = result; + Members = members.ToList(); + } + + public List Members { get; set; } + + public MessageType Type { get; set; } + + public MessageResult Result { get; set; } +} \ No newline at end of file diff --git a/TelegramBotBase/Args/MessageDeletedEventArgs.cs b/TelegramBotBase/Args/MessageDeletedEventArgs.cs index bab0af6..34f174b 100644 --- a/TelegramBotBase/Args/MessageDeletedEventArgs.cs +++ b/TelegramBotBase/Args/MessageDeletedEventArgs.cs @@ -1,16 +1,11 @@ -namespace TelegramBotBase.Args +namespace TelegramBotBase.Args; + +public class MessageDeletedEventArgs { - public class MessageDeletedEventArgs + public MessageDeletedEventArgs(int messageId) { - public int MessageId - { - get;set; - } - - public MessageDeletedEventArgs(int messageId) - { - MessageId = messageId; - } - + MessageId = messageId; } -} + + public int MessageId { get; set; } +} \ No newline at end of file diff --git a/TelegramBotBase/Args/MessageIncomeEventArgs.cs b/TelegramBotBase/Args/MessageIncomeEventArgs.cs index 5e6de76..ddc0ac8 100644 --- a/TelegramBotBase/Args/MessageIncomeEventArgs.cs +++ b/TelegramBotBase/Args/MessageIncomeEventArgs.cs @@ -1,26 +1,20 @@ using System; using TelegramBotBase.Sessions; -namespace TelegramBotBase.Base +namespace TelegramBotBase.Base; + +public class MessageIncomeEventArgs : EventArgs { - public class MessageIncomeEventArgs : EventArgs + public MessageIncomeEventArgs(long deviceId, DeviceSession device, MessageResult message) { - - public long DeviceId { get; set; } - - public DeviceSession Device { get; set; } - - public MessageResult Message { get; set; } - - public MessageIncomeEventArgs(long deviceId, DeviceSession device, MessageResult message) - { - this.DeviceId = deviceId; - this.Device = device; - Message = message; - } - - - - + DeviceId = deviceId; + Device = device; + Message = message; } -} + + public long DeviceId { get; set; } + + public DeviceSession Device { get; set; } + + public MessageResult Message { get; set; } +} \ No newline at end of file diff --git a/TelegramBotBase/Args/MessageReceivedEventArgs.cs b/TelegramBotBase/Args/MessageReceivedEventArgs.cs index 497782f..85fce86 100644 --- a/TelegramBotBase/Args/MessageReceivedEventArgs.cs +++ b/TelegramBotBase/Args/MessageReceivedEventArgs.cs @@ -1,17 +1,15 @@ using Telegram.Bot.Types; -namespace TelegramBotBase.Args +namespace TelegramBotBase.Args; + +public class MessageReceivedEventArgs { - public class MessageReceivedEventArgs + public MessageReceivedEventArgs(Message m) { - public int MessageId => Message.MessageId; - - public Message Message { get; set; } - - public MessageReceivedEventArgs(Message m) - { - Message = m; - } - + Message = m; } -} + + public int MessageId => Message.MessageId; + + public Message Message { get; set; } +} \ No newline at end of file diff --git a/TelegramBotBase/Args/MessageSentEventArgs.cs b/TelegramBotBase/Args/MessageSentEventArgs.cs index a776207..3086908 100644 --- a/TelegramBotBase/Args/MessageSentEventArgs.cs +++ b/TelegramBotBase/Args/MessageSentEventArgs.cs @@ -1,26 +1,22 @@ using System; using Telegram.Bot.Types; -namespace TelegramBotBase.Args +namespace TelegramBotBase.Args; + +public class MessageSentEventArgs : EventArgs { - public class MessageSentEventArgs : EventArgs + public MessageSentEventArgs(Message message, Type origin) { - public int MessageId => Message.MessageId; - - public Message Message { get; set; } - - /// - /// Contains the element, which has called the method. - /// - public Type Origin { get; set; } - - - public MessageSentEventArgs(Message message, Type origin) - { - Message = message; - this.Origin = origin; - } - - + Message = message; + Origin = origin; } -} + + public int MessageId => Message.MessageId; + + public Message Message { get; set; } + + /// + /// Contains the element, which has called the method. + /// + public Type Origin { get; set; } +} \ No newline at end of file diff --git a/TelegramBotBase/Args/PromptDialogCompletedEventArgs.cs b/TelegramBotBase/Args/PromptDialogCompletedEventArgs.cs index b0b7e04..9de7888 100644 --- a/TelegramBotBase/Args/PromptDialogCompletedEventArgs.cs +++ b/TelegramBotBase/Args/PromptDialogCompletedEventArgs.cs @@ -1,10 +1,8 @@ -namespace TelegramBotBase.Args +namespace TelegramBotBase.Args; + +public class PromptDialogCompletedEventArgs { - public class PromptDialogCompletedEventArgs - { - public object Tag { get; set; } + public object Tag { get; set; } - public string Value { get; set; } - - } -} + public string Value { get; set; } +} \ No newline at end of file diff --git a/TelegramBotBase/Args/RenderViewEventArgs.cs b/TelegramBotBase/Args/RenderViewEventArgs.cs index 82df8e5..cc736eb 100644 --- a/TelegramBotBase/Args/RenderViewEventArgs.cs +++ b/TelegramBotBase/Args/RenderViewEventArgs.cs @@ -1,18 +1,13 @@ using System; -namespace TelegramBotBase.Args +namespace TelegramBotBase.Args; + +public class RenderViewEventArgs : EventArgs { - public class RenderViewEventArgs : EventArgs + public RenderViewEventArgs(int viewIndex) { - public int CurrentView { get; set; } - - - public RenderViewEventArgs(int viewIndex) - { - - CurrentView = viewIndex; - } - - + CurrentView = viewIndex; } -} + + public int CurrentView { get; set; } +} \ No newline at end of file diff --git a/TelegramBotBase/Args/SaveStateEventArgs.cs b/TelegramBotBase/Args/SaveStateEventArgs.cs index bfc3984..39d3e46 100644 --- a/TelegramBotBase/Args/SaveStateEventArgs.cs +++ b/TelegramBotBase/Args/SaveStateEventArgs.cs @@ -1,39 +1,38 @@ using System.Collections.Generic; -namespace TelegramBotBase.Args +namespace TelegramBotBase.Args; + +public class SaveStateEventArgs { - public class SaveStateEventArgs + public SaveStateEventArgs() { - public Dictionary Values { get; set; } - - public SaveStateEventArgs() - { - Values = new Dictionary(); - } - - public void Set(string key, string value) - { - Values[key] = value; - } - - public void SetInt(string key, int value) - { - Values[key] = value; - } - - public void SetBool(string key, bool value) - { - Values[key] = value; - } - - public void SetDouble(string key, double value) - { - Values[key] = value; - } - public void SetObject(string key, object value) - { - Values[key] = value; - } - + Values = new Dictionary(); } -} + + public Dictionary Values { get; set; } + + public void Set(string key, string value) + { + Values[key] = value; + } + + public void SetInt(string key, int value) + { + Values[key] = value; + } + + public void SetBool(string key, bool value) + { + Values[key] = value; + } + + public void SetDouble(string key, double value) + { + Values[key] = value; + } + + public void SetObject(string key, object value) + { + Values[key] = value; + } +} \ No newline at end of file diff --git a/TelegramBotBase/Args/SaveStatesEventArgs.cs b/TelegramBotBase/Args/SaveStatesEventArgs.cs index e2d44f6..b300d11 100644 --- a/TelegramBotBase/Args/SaveStatesEventArgs.cs +++ b/TelegramBotBase/Args/SaveStatesEventArgs.cs @@ -1,15 +1,13 @@ using TelegramBotBase.Base; -namespace TelegramBotBase.Args +namespace TelegramBotBase.Args; + +public class SaveStatesEventArgs { - public class SaveStatesEventArgs + public SaveStatesEventArgs(StateContainer states) { - public StateContainer States { get; set; } - - - public SaveStatesEventArgs(StateContainer states) - { - States = states; - } + States = states; } -} + + public StateContainer States { get; set; } +} \ No newline at end of file diff --git a/TelegramBotBase/Args/SessionBeginEventArgs.cs b/TelegramBotBase/Args/SessionBeginEventArgs.cs index 9187f0b..53a54b9 100644 --- a/TelegramBotBase/Args/SessionBeginEventArgs.cs +++ b/TelegramBotBase/Args/SessionBeginEventArgs.cs @@ -1,18 +1,17 @@ using System; using TelegramBotBase.Sessions; -namespace TelegramBotBase.Base +namespace TelegramBotBase.Base; + +public class SessionBeginEventArgs : EventArgs { - public class SessionBeginEventArgs : EventArgs + public SessionBeginEventArgs(long deviceId, DeviceSession device) { - public long DeviceId { get; set; } - - public DeviceSession Device { get; set; } - - public SessionBeginEventArgs(long deviceId, DeviceSession device) - { - this.DeviceId = deviceId; - this.Device = device; - } + DeviceId = deviceId; + Device = device; } -} + + public long DeviceId { get; set; } + + public DeviceSession Device { get; set; } +} \ No newline at end of file diff --git a/TelegramBotBase/Args/SystemExceptionEventArgs.cs b/TelegramBotBase/Args/SystemExceptionEventArgs.cs index cc19a62..5fbaf69 100644 --- a/TelegramBotBase/Args/SystemExceptionEventArgs.cs +++ b/TelegramBotBase/Args/SystemExceptionEventArgs.cs @@ -1,32 +1,27 @@ using System; using TelegramBotBase.Sessions; -namespace TelegramBotBase.Args +namespace TelegramBotBase.Args; + +public class SystemExceptionEventArgs : EventArgs { - public class SystemExceptionEventArgs : EventArgs + public SystemExceptionEventArgs() { - - public string Command { get; set; } - - public long DeviceId { get; set; } - - public DeviceSession Device { get; set; } - - public Exception Error { get; set; } - - public SystemExceptionEventArgs() - { - - - } - - public SystemExceptionEventArgs(string command, long deviceId, DeviceSession device, Exception error) - { - this.Command = command; - this.DeviceId = deviceId; - this.Device = device; - Error = error; - } } -} + public SystemExceptionEventArgs(string command, long deviceId, DeviceSession device, Exception error) + { + Command = command; + DeviceId = deviceId; + Device = device; + Error = error; + } + + public string Command { get; set; } + + public long DeviceId { get; set; } + + public DeviceSession Device { get; set; } + + public Exception Error { get; set; } +} \ No newline at end of file diff --git a/TelegramBotBase/Args/UnhandledCallEventArgs.cs b/TelegramBotBase/Args/UnhandledCallEventArgs.cs index 279170f..844bc43 100644 --- a/TelegramBotBase/Args/UnhandledCallEventArgs.cs +++ b/TelegramBotBase/Args/UnhandledCallEventArgs.cs @@ -2,40 +2,37 @@ using Telegram.Bot.Types; using TelegramBotBase.Sessions; -namespace TelegramBotBase.Args +namespace TelegramBotBase.Args; + +public class UnhandledCallEventArgs : EventArgs { - public class UnhandledCallEventArgs : EventArgs + public UnhandledCallEventArgs() { - public string Command { get; set; } - - public long DeviceId { get; set; } - - public DeviceSession Device {get;set;} - - public string RawData { get; set; } - - public int MessageId { get; set; } - - public Message Message { get; set; } - - public bool Handled { get; set; } - - - public UnhandledCallEventArgs() - { - Handled = false; - - } - - public UnhandledCallEventArgs(string command,string rawData, long deviceId, int messageId, Message message, DeviceSession device) : this() - { - this.Command = command; - this.RawData = rawData; - this.DeviceId = deviceId; - this.MessageId = messageId; - Message = message; - this.Device = device; - } - + Handled = false; } -} + + public UnhandledCallEventArgs(string command, string rawData, long deviceId, int messageId, Message message, + DeviceSession device) : this() + { + Command = command; + RawData = rawData; + DeviceId = deviceId; + MessageId = messageId; + Message = message; + Device = device; + } + + public string Command { get; set; } + + public long DeviceId { get; set; } + + public DeviceSession Device { get; set; } + + public string RawData { get; set; } + + public int MessageId { get; set; } + + public Message Message { get; set; } + + public bool Handled { get; set; } +} \ No newline at end of file diff --git a/TelegramBotBase/Attributes/IgnoreState.cs b/TelegramBotBase/Attributes/IgnoreState.cs index 72c4381..3deb6f4 100644 --- a/TelegramBotBase/Attributes/IgnoreState.cs +++ b/TelegramBotBase/Attributes/IgnoreState.cs @@ -1,15 +1,11 @@ using System; -namespace TelegramBotBase.Attributes +namespace TelegramBotBase.Attributes; + +/// +/// Declares that this class should not be getting serialized +/// +[AttributeUsage(AttributeTargets.Class)] +public class IgnoreState : Attribute { - - /// - /// Declares that this class should not be getting serialized - /// - [AttributeUsage(AttributeTargets.Class)] - public class IgnoreState : Attribute - { - - - } -} +} \ No newline at end of file diff --git a/TelegramBotBase/Attributes/SaveState.cs b/TelegramBotBase/Attributes/SaveState.cs index 9b9190b..71f5edc 100644 --- a/TelegramBotBase/Attributes/SaveState.cs +++ b/TelegramBotBase/Attributes/SaveState.cs @@ -1,13 +1,11 @@ using System; -namespace TelegramBotBase.Attributes -{ - /// - /// Declares that the field or property should be save and recovered an restart. - /// - public class SaveState : Attribute - { - public string Key { get; set; } +namespace TelegramBotBase.Attributes; - } -} +/// +/// Declares that the field or property should be save and recovered an restart. +/// +public class SaveState : Attribute +{ + public string Key { get; set; } +} \ No newline at end of file diff --git a/TelegramBotBase/Base/Async.cs b/TelegramBotBase/Base/Async.cs index 9eff287..9efe5be 100644 --- a/TelegramBotBase/Base/Async.cs +++ b/TelegramBotBase/Base/Async.cs @@ -3,22 +3,25 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -namespace TelegramBotBase.Base -{ - public static class Async - { - public delegate Task AsyncEventHandler(object sender, TEventArgs e) where TEventArgs : EventArgs; +namespace TelegramBotBase.Base; - public static IEnumerable> GetHandlers( +public static class Async +{ + public delegate Task AsyncEventHandler(object sender, TEventArgs e) where TEventArgs : EventArgs; + + public static IEnumerable> GetHandlers( this AsyncEventHandler handler) where TEventArgs : EventArgs - => handler.GetInvocationList().Cast>(); - - public static Task InvokeAllAsync(this AsyncEventHandler handler, object sender, TEventArgs e) - where TEventArgs : EventArgs - => Task.WhenAll( - handler.GetHandlers() - .Select(handleAsync => handleAsync(sender, e))); - + { + return handler.GetInvocationList().Cast>(); } -} + + public static Task InvokeAllAsync(this AsyncEventHandler handler, object sender, + TEventArgs e) + where TEventArgs : EventArgs + { + return Task.WhenAll( + handler.GetHandlers() + .Select(handleAsync => handleAsync(sender, e))); + } +} \ No newline at end of file diff --git a/TelegramBotBase/Base/ControlBase.cs b/TelegramBotBase/Base/ControlBase.cs index b06b2d3..4c25177 100644 --- a/TelegramBotBase/Base/ControlBase.cs +++ b/TelegramBotBase/Base/ControlBase.cs @@ -1,63 +1,59 @@ using System.Threading.Tasks; using TelegramBotBase.Sessions; -namespace TelegramBotBase.Base +namespace TelegramBotBase.Base; + +/// +/// Base class for controls +/// +public class ControlBase { + public DeviceSession Device { get; set; } + + public int Id { get; set; } + + public string ControlId => "#c" + Id; + /// - /// Base class for controls + /// Defines if the control should be rendered and invoked with actions /// - public class ControlBase + public bool Enabled { get; set; } = true; + + /// + /// Get invoked when control will be added to a form and invoked. + /// + /// + public virtual void Init() { - public DeviceSession Device { get; set; } - - public int Id { get; set; } - - public string ControlId => "#c" + Id; - - /// - /// Defines if the control should be rendered and invoked with actions - /// - public bool Enabled { get; set; } = true; - - /// - /// Get invoked when control will be added to a form and invoked. - /// - /// - public virtual void Init() - { - - } - - public virtual Task Load(MessageResult result) - { - return Task.CompletedTask; - } - - public virtual Task Action(MessageResult result, string value = null) - { - return Task.CompletedTask; - } - - - - public virtual Task Render(MessageResult result) - { - return Task.CompletedTask; - } - - public virtual Task Hidden(bool formClose) - { - return Task.CompletedTask; - } - - /// - /// Will be called on a cleanup. - /// - /// - public virtual Task Cleanup() - { - return Task.CompletedTask; - } - } -} + + public virtual Task Load(MessageResult result) + { + return Task.CompletedTask; + } + + public virtual Task Action(MessageResult result, string value = null) + { + return Task.CompletedTask; + } + + + public virtual Task Render(MessageResult result) + { + return Task.CompletedTask; + } + + public virtual Task Hidden(bool formClose) + { + return Task.CompletedTask; + } + + /// + /// Will be called on a cleanup. + /// + /// + public virtual Task Cleanup() + { + return Task.CompletedTask; + } +} \ No newline at end of file diff --git a/TelegramBotBase/Base/DataResult.cs b/TelegramBotBase/Base/DataResult.cs index bebef80..14c7d9b 100644 --- a/TelegramBotBase/Base/DataResult.cs +++ b/TelegramBotBase/Base/DataResult.cs @@ -7,166 +7,164 @@ using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; using Telegram.Bot.Types.InputFiles; -namespace TelegramBotBase.Base +namespace TelegramBotBase.Base; + +/// +/// Returns a class to manage attachments within messages. +/// +public class DataResult : ResultBase { - /// - /// Returns a class to manage attachments within messages. - /// - public class DataResult : ResultBase + public DataResult(UpdateResult update) { - - //public Telegram.Bot.Args.MessageEventArgs RawMessageData { get; set; } - - public UpdateResult UpdateData { get; set; } - - - public Contact Contact => Message.Contact; - - public Location Location => Message.Location; - - public Document Document => Message.Document; - - public Audio Audio => Message.Audio; - - public Video Video => Message.Video; - - public PhotoSize[] Photos => Message.Photo; - - - public MessageType Type => Message?.Type ?? MessageType.Unknown; - - public override Message Message => UpdateData?.Message; - - /// - /// Returns the FileId of the first reachable element. - /// - public string FileId => - (Document?.FileId ?? - Audio?.FileId ?? - Video?.FileId ?? - Photos.FirstOrDefault()?.FileId); - - public DataResult(UpdateResult update) - { - UpdateData = update; - } - - - public async Task DownloadDocument() - { - var encryptedContent = new MemoryStream(); - encryptedContent.SetLength(Document.FileSize.Value); - var file = await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(Document.FileId, encryptedContent); - - return new InputOnlineFile(encryptedContent, Document.FileName); - } - - - /// - /// Downloads a file and saves it to the given path. - /// - /// - /// - public async Task DownloadDocument(string path) - { - var file = await Device.Client.TelegramClient.GetFileAsync(Document.FileId); - var fs = new FileStream(path, FileMode.Create); - await Device.Client.TelegramClient.DownloadFileAsync(file.FilePath, fs); - fs.Close(); - fs.Dispose(); - } - - /// - /// Downloads the document and returns an byte array. - /// - /// - public async Task DownloadRawDocument() - { - var ms = new MemoryStream(); - await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(Document.FileId, ms); - return ms.ToArray(); - } - - /// - /// Downloads a document and returns it as string. (txt,csv,etc) Default encoding ist UTF8. - /// - /// - public async Task DownloadRawTextDocument() - { - return await DownloadRawTextDocument(Encoding.UTF8); - } - - /// - /// Downloads a document and returns it as string. (txt,csv,etc) - /// - /// - public async Task DownloadRawTextDocument(Encoding encoding) - { - var ms = new MemoryStream(); - await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(Document.FileId, ms); - - ms.Position = 0; - - var sr = new StreamReader(ms, encoding); - - return sr.ReadToEnd(); - } - - public async Task DownloadVideo() - { - var encryptedContent = new MemoryStream(); - encryptedContent.SetLength(Video.FileSize.Value); - var file = await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(Video.FileId, encryptedContent); - - return new InputOnlineFile(encryptedContent, ""); - } - - public async Task DownloadVideo(string path) - { - var file = await Device.Client.TelegramClient.GetFileAsync(Video.FileId); - var fs = new FileStream(path, FileMode.Create); - await Device.Client.TelegramClient.DownloadFileAsync(file.FilePath, fs); - fs.Close(); - fs.Dispose(); - } - - public async Task DownloadAudio() - { - var encryptedContent = new MemoryStream(); - encryptedContent.SetLength(Audio.FileSize.Value); - var file = await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(Audio.FileId, encryptedContent); - - return new InputOnlineFile(encryptedContent, ""); - } - - public async Task DownloadAudio(string path) - { - var file = await Device.Client.TelegramClient.GetFileAsync(Audio.FileId); - var fs = new FileStream(path, FileMode.Create); - await Device.Client.TelegramClient.DownloadFileAsync(file.FilePath, fs); - fs.Close(); - fs.Dispose(); - } - - public async Task DownloadPhoto(int index) - { - var photo = Photos[index]; - var encryptedContent = new MemoryStream(); - encryptedContent.SetLength(photo.FileSize.Value); - var file = await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(photo.FileId, encryptedContent); - - return new InputOnlineFile(encryptedContent, ""); - } - - public async Task DownloadPhoto(int index, string path) - { - var photo = Photos[index]; - var file = await Device.Client.TelegramClient.GetFileAsync(photo.FileId); - var fs = new FileStream(path, FileMode.Create); - await Device.Client.TelegramClient.DownloadFileAsync(file.FilePath, fs); - fs.Close(); - fs.Dispose(); - } - + UpdateData = update; } -} + + //public Telegram.Bot.Args.MessageEventArgs RawMessageData { get; set; } + + public UpdateResult UpdateData { get; set; } + + + public Contact Contact => Message.Contact; + + public Location Location => Message.Location; + + public Document Document => Message.Document; + + public Audio Audio => Message.Audio; + + public Video Video => Message.Video; + + public PhotoSize[] Photos => Message.Photo; + + + public MessageType Type => Message?.Type ?? MessageType.Unknown; + + public override Message Message => UpdateData?.Message; + + /// + /// Returns the FileId of the first reachable element. + /// + public string FileId => + Document?.FileId ?? + Audio?.FileId ?? + Video?.FileId ?? + Photos.FirstOrDefault()?.FileId; + + + public async Task DownloadDocument() + { + var encryptedContent = new MemoryStream(); + encryptedContent.SetLength(Document.FileSize.Value); + var file = await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(Document.FileId, + encryptedContent); + + return new InputOnlineFile(encryptedContent, Document.FileName); + } + + + /// + /// Downloads a file and saves it to the given path. + /// + /// + /// + public async Task DownloadDocument(string path) + { + var file = await Device.Client.TelegramClient.GetFileAsync(Document.FileId); + var fs = new FileStream(path, FileMode.Create); + await Device.Client.TelegramClient.DownloadFileAsync(file.FilePath, fs); + fs.Close(); + fs.Dispose(); + } + + /// + /// Downloads the document and returns an byte array. + /// + /// + public async Task DownloadRawDocument() + { + var ms = new MemoryStream(); + await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(Document.FileId, ms); + return ms.ToArray(); + } + + /// + /// Downloads a document and returns it as string. (txt,csv,etc) Default encoding ist UTF8. + /// + /// + public async Task DownloadRawTextDocument() + { + return await DownloadRawTextDocument(Encoding.UTF8); + } + + /// + /// Downloads a document and returns it as string. (txt,csv,etc) + /// + /// + public async Task DownloadRawTextDocument(Encoding encoding) + { + var ms = new MemoryStream(); + await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(Document.FileId, ms); + + ms.Position = 0; + + var sr = new StreamReader(ms, encoding); + + return sr.ReadToEnd(); + } + + public async Task DownloadVideo() + { + var encryptedContent = new MemoryStream(); + encryptedContent.SetLength(Video.FileSize.Value); + var file = await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(Video.FileId, encryptedContent); + + return new InputOnlineFile(encryptedContent, ""); + } + + public async Task DownloadVideo(string path) + { + var file = await Device.Client.TelegramClient.GetFileAsync(Video.FileId); + var fs = new FileStream(path, FileMode.Create); + await Device.Client.TelegramClient.DownloadFileAsync(file.FilePath, fs); + fs.Close(); + fs.Dispose(); + } + + public async Task DownloadAudio() + { + var encryptedContent = new MemoryStream(); + encryptedContent.SetLength(Audio.FileSize.Value); + var file = await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(Audio.FileId, encryptedContent); + + return new InputOnlineFile(encryptedContent, ""); + } + + public async Task DownloadAudio(string path) + { + var file = await Device.Client.TelegramClient.GetFileAsync(Audio.FileId); + var fs = new FileStream(path, FileMode.Create); + await Device.Client.TelegramClient.DownloadFileAsync(file.FilePath, fs); + fs.Close(); + fs.Dispose(); + } + + public async Task DownloadPhoto(int index) + { + var photo = Photos[index]; + var encryptedContent = new MemoryStream(); + encryptedContent.SetLength(photo.FileSize.Value); + var file = await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(photo.FileId, encryptedContent); + + return new InputOnlineFile(encryptedContent, ""); + } + + public async Task DownloadPhoto(int index, string path) + { + var photo = Photos[index]; + var file = await Device.Client.TelegramClient.GetFileAsync(photo.FileId); + var fs = new FileStream(path, FileMode.Create); + await Device.Client.TelegramClient.DownloadFileAsync(file.FilePath, fs); + fs.Close(); + fs.Dispose(); + } +} \ No newline at end of file diff --git a/TelegramBotBase/Base/FormBase.cs b/TelegramBotBase/Base/FormBase.cs index 583eabe..7557348 100644 --- a/TelegramBotBase/Base/FormBase.cs +++ b/TelegramBotBase/Base/FormBase.cs @@ -9,421 +9,442 @@ using TelegramBotBase.Form.Navigation; using TelegramBotBase.Sessions; using static TelegramBotBase.Base.Async; -namespace TelegramBotBase.Form +namespace TelegramBotBase.Form; + +/// +/// Base class for forms +/// +public class FormBase : IDisposable { - /// - /// Base class for forms - /// - public class FormBase : IDisposable + private static readonly object EvInit = new(); + + private static readonly object EvOpened = new(); + + private static readonly object EvClosed = new(); + + + public EventHandlerList Events = new(); + + + public FormBase() { + Controls = new List(); + } - public NavigationController NavigationController { get; set; } + public FormBase(MessageClient client) : this() + { + Client = client; + } - public DeviceSession Device { get; set; } + public NavigationController NavigationController { get; set; } - public MessageClient Client { get; set; } + public DeviceSession Device { get; set; } - /// - /// has this formular already been disposed ? - /// - public bool IsDisposed { get; set; } + public MessageClient Client { get; set; } - public List Controls { get; set; } + /// + /// has this formular already been disposed ? + /// + public bool IsDisposed { get; set; } + + public List Controls { get; set; } + + /// + /// Cleanup + /// + public void Dispose() + { + Client = null; + Device = null; + IsDisposed = true; + } - public EventHandlerList Events = new EventHandlerList(); - - - private static readonly object EvInit = new object(); - - private static readonly object EvOpened = new object(); - - private static readonly object EvClosed = new object(); - - - public FormBase() + public async Task OnInit(InitEventArgs e) + { + var handler = Events[EvInit]?.GetInvocationList().Cast>(); + if (handler == null) { - Controls = new List(); + return; } - public FormBase(MessageClient client) : this() + foreach (var h in handler) { - this.Client = client; - } - - - public async Task OnInit(InitEventArgs e) - { - var handler = Events[EvInit]?.GetInvocationList().Cast>(); - if (handler == null) - return; - - foreach (var h in handler) - { - await h.InvokeAllAsync(this, e); - } - } - - ///// - ///// Will get called at the initialization (once per context) - ///// - public event AsyncEventHandler Init - { - add => Events.AddHandler(EvInit, value); - remove => Events.RemoveHandler(EvInit, value); - } - - - - public async Task OnOpened(EventArgs e) - { - var handler = Events[EvOpened]?.GetInvocationList().Cast>(); - if (handler == null) - return; - - foreach (var h in handler) - { - await h.InvokeAllAsync(this, e); - } - } - - /// - /// Gets invoked if gets navigated to this form - /// - /// - public event AsyncEventHandler Opened - { - add => Events.AddHandler(EvOpened, value); - remove => Events.RemoveHandler(EvOpened, value); - } - - - - public async Task OnClosed(EventArgs e) - { - var handler = Events[EvClosed]?.GetInvocationList().Cast>(); - if (handler == null) - return; - - foreach (var h in handler) - { - await h.InvokeAllAsync(this, e); - } - } - - - /// - /// Form has been closed (left) - /// - /// - public event AsyncEventHandler Closed - { - add => Events.AddHandler(EvClosed, value); - remove => Events.RemoveHandler(EvClosed, value); - } - - /// - /// Get invoked when a modal child from has been closed. - /// - /// - /// - public virtual Task ReturnFromModal(ModalDialog modal) - { - return Task.CompletedTask; - } - - - /// - /// Pre to form close, cleanup all controls - /// - /// - public Task CloseControls() - { - foreach (var b in Controls) - { - b.Cleanup().Wait(); - } - - return Task.CompletedTask; - } - - public virtual Task PreLoad(MessageResult message) - { - return Task.CompletedTask; - } - - /// - /// Gets invoked if a message was sent or an action triggered - /// - /// - /// - public virtual async Task LoadControls(MessageResult message) - { - //Looking for the control by id, if not listened, raise event for all - if (message.RawData?.StartsWith("#c") ?? false) - { - var c = Controls.FirstOrDefault(a => a.ControlId == message.RawData.Split('_')[0]); - if (c != null) - { - await c.Load(message); - return; - } - } - - foreach (var b in Controls) - { - if (!b.Enabled) - continue; - - await b.Load(message); - } - } - - /// - /// Gets invoked if the form gets loaded and on every message belongs to this context - /// - /// - /// - public virtual Task Load(MessageResult message) - { - return Task.CompletedTask; - } - - /// - /// Gets invoked, when a messages has been edited. - /// - /// - /// - public virtual Task Edited(MessageResult message) - { - return Task.CompletedTask; - } - - - /// - /// Gets invoked if the user clicked a button. - /// - /// - /// - public virtual async Task ActionControls(MessageResult message) - { - //Looking for the control by id, if not listened, raise event for all - if (message.RawData.StartsWith("#c")) - { - var c = Controls.FirstOrDefault(a => a.ControlId == message.RawData.Split('_')[0]); - if (c != null) - { - await c.Action(message, message.RawData.Split('_')[1]); - return; - } - } - - foreach (var b in Controls) - { - if (!b.Enabled) - continue; - - await b.Action(message); - - if (message.Handled) - return; - } - } - - /// - /// Gets invoked if the user has clicked a button. - /// - /// - /// - public virtual Task Action(MessageResult message) - { - return Task.CompletedTask; - } - - /// - /// Gets invoked if the user has sent some media (Photo, Audio, Video, Contact, Location, Document) - /// - /// - /// - public virtual Task SentData(DataResult message) - { - return Task.CompletedTask; - } - - /// - /// Gets invoked at the end of the cycle to "Render" text, images, buttons, etc... - /// - /// - /// - public virtual async Task RenderControls(MessageResult message) - { - foreach (var b in Controls) - { - if (!b.Enabled) - continue; - - await b.Render(message); - } - } - - /// - /// Gets invoked at the end of the cycle to "Render" text, images, buttons, etc... - /// - /// - /// - public virtual Task Render(MessageResult message) - { - return Task.CompletedTask; - } - - - - /// - /// Navigates to a new form - /// - /// - /// - public virtual async Task NavigateTo(FormBase newForm, params object[] args) - { - var ds = Device; - if (ds == null) - return; - - ds.FormSwitched = true; - - ds.PreviousForm = ds.ActiveForm; - - ds.ActiveForm = newForm; - newForm.Client = Client; - newForm.Device = ds; - - //Notify prior to close - foreach (var b in Controls) - { - if (!b.Enabled) - continue; - - await b.Hidden(true); - } - - CloseControls().Wait(); - - await OnClosed(EventArgs.Empty); - - await newForm.OnInit(new InitEventArgs(args)); - - await newForm.OnOpened(EventArgs.Empty); - } - - /// - /// Opens this form modal, but don't closes the original ones - /// - /// - /// - public virtual async Task OpenModal(ModalDialog newForm, params object[] args) - { - var ds = Device; - if (ds == null) - return; - - var parentForm = this; - - ds.FormSwitched = true; - - ds.PreviousForm = ds.ActiveForm; - - ds.ActiveForm = newForm; - newForm.Client = parentForm.Client; - newForm.Device = ds; - newForm.ParentForm = parentForm; - - newForm.Closed += async (s, en) => - { - await CloseModal(newForm, parentForm); - }; - - foreach (var b in Controls) - { - if (!b.Enabled) - continue; - - await b.Hidden(false); - } - - await newForm.OnInit(new InitEventArgs(args)); - - await newForm.OnOpened(EventArgs.Empty); - } - - public Task CloseModal(ModalDialog modalForm, FormBase oldForm) - { - var ds = Device; - if (ds == null) - return Task.CompletedTask; - - if (modalForm == null) - throw new Exception("No modal form"); - - ds.FormSwitched = true; - - ds.PreviousForm = ds.ActiveForm; - - ds.ActiveForm = oldForm; - return Task.CompletedTask; - } - - /// - /// Adds a control to the formular and sets its ID and Device. - /// - /// - public void AddControl(ControlBase control) - { - //Duplicate check - if (Controls.Contains(control)) - throw new ArgumentException("Control has been already added."); - - control.Id = Controls.Count + 1; - control.Device = Device; - Controls.Add(control); - - control.Init(); - } - - /// - /// Removes control from the formular and runs a cleanup on it. - /// - /// - public void RemoveControl(ControlBase control) - { - if (!Controls.Contains(control)) - return; - - control.Cleanup().Wait(); - - Controls.Remove(control); - } - - /// - /// Removes all controls. - /// - public void RemoveAllControls() - { - foreach(var c in Controls) - { - c.Cleanup().Wait(); - - Controls.Remove(c); - } - } - - /// - /// Cleanup - /// - public void Dispose() - { - Client = null; - Device = null; - IsDisposed = true; + await h.InvokeAllAsync(this, e); } } -} + + ///// + ///// Will get called at the initialization (once per context) + ///// + public event AsyncEventHandler Init + { + add => Events.AddHandler(EvInit, value); + remove => Events.RemoveHandler(EvInit, value); + } + + + public async Task OnOpened(EventArgs e) + { + var handler = Events[EvOpened]?.GetInvocationList().Cast>(); + if (handler == null) + { + return; + } + + foreach (var h in handler) + { + await h.InvokeAllAsync(this, e); + } + } + + /// + /// Gets invoked if gets navigated to this form + /// + /// + public event AsyncEventHandler Opened + { + add => Events.AddHandler(EvOpened, value); + remove => Events.RemoveHandler(EvOpened, value); + } + + + public async Task OnClosed(EventArgs e) + { + var handler = Events[EvClosed]?.GetInvocationList().Cast>(); + if (handler == null) + { + return; + } + + foreach (var h in handler) + { + await h.InvokeAllAsync(this, e); + } + } + + + /// + /// Form has been closed (left) + /// + /// + public event AsyncEventHandler Closed + { + add => Events.AddHandler(EvClosed, value); + remove => Events.RemoveHandler(EvClosed, value); + } + + /// + /// Get invoked when a modal child from has been closed. + /// + /// + /// + public virtual Task ReturnFromModal(ModalDialog modal) + { + return Task.CompletedTask; + } + + + /// + /// Pre to form close, cleanup all controls + /// + /// + public Task CloseControls() + { + foreach (var b in Controls) + { + b.Cleanup().Wait(); + } + + return Task.CompletedTask; + } + + public virtual Task PreLoad(MessageResult message) + { + return Task.CompletedTask; + } + + /// + /// Gets invoked if a message was sent or an action triggered + /// + /// + /// + public virtual async Task LoadControls(MessageResult message) + { + //Looking for the control by id, if not listened, raise event for all + if (message.RawData?.StartsWith("#c") ?? false) + { + var c = Controls.FirstOrDefault(a => a.ControlId == message.RawData.Split('_')[0]); + if (c != null) + { + await c.Load(message); + return; + } + } + + foreach (var b in Controls) + { + if (!b.Enabled) + { + continue; + } + + await b.Load(message); + } + } + + /// + /// Gets invoked if the form gets loaded and on every message belongs to this context + /// + /// + /// + public virtual Task Load(MessageResult message) + { + return Task.CompletedTask; + } + + /// + /// Gets invoked, when a messages has been edited. + /// + /// + /// + public virtual Task Edited(MessageResult message) + { + return Task.CompletedTask; + } + + + /// + /// Gets invoked if the user clicked a button. + /// + /// + /// + public virtual async Task ActionControls(MessageResult message) + { + //Looking for the control by id, if not listened, raise event for all + if (message.RawData.StartsWith("#c")) + { + var c = Controls.FirstOrDefault(a => a.ControlId == message.RawData.Split('_')[0]); + if (c != null) + { + await c.Action(message, message.RawData.Split('_')[1]); + return; + } + } + + foreach (var b in Controls) + { + if (!b.Enabled) + { + continue; + } + + await b.Action(message); + + if (message.Handled) + { + return; + } + } + } + + /// + /// Gets invoked if the user has clicked a button. + /// + /// + /// + public virtual Task Action(MessageResult message) + { + return Task.CompletedTask; + } + + /// + /// Gets invoked if the user has sent some media (Photo, Audio, Video, Contact, Location, Document) + /// + /// + /// + public virtual Task SentData(DataResult message) + { + return Task.CompletedTask; + } + + /// + /// Gets invoked at the end of the cycle to "Render" text, images, buttons, etc... + /// + /// + /// + public virtual async Task RenderControls(MessageResult message) + { + foreach (var b in Controls) + { + if (!b.Enabled) + { + continue; + } + + await b.Render(message); + } + } + + /// + /// Gets invoked at the end of the cycle to "Render" text, images, buttons, etc... + /// + /// + /// + public virtual Task Render(MessageResult message) + { + return Task.CompletedTask; + } + + + /// + /// Navigates to a new form + /// + /// + /// + public virtual async Task NavigateTo(FormBase newForm, params object[] args) + { + var ds = Device; + if (ds == null) + { + return; + } + + ds.FormSwitched = true; + + ds.PreviousForm = ds.ActiveForm; + + ds.ActiveForm = newForm; + newForm.Client = Client; + newForm.Device = ds; + + //Notify prior to close + foreach (var b in Controls) + { + if (!b.Enabled) + { + continue; + } + + await b.Hidden(true); + } + + CloseControls().Wait(); + + await OnClosed(EventArgs.Empty); + + await newForm.OnInit(new InitEventArgs(args)); + + await newForm.OnOpened(EventArgs.Empty); + } + + /// + /// Opens this form modal, but don't closes the original ones + /// + /// + /// + public virtual async Task OpenModal(ModalDialog newForm, params object[] args) + { + var ds = Device; + if (ds == null) + { + return; + } + + var parentForm = this; + + ds.FormSwitched = true; + + ds.PreviousForm = ds.ActiveForm; + + ds.ActiveForm = newForm; + newForm.Client = parentForm.Client; + newForm.Device = ds; + newForm.ParentForm = parentForm; + + newForm.Closed += async (s, en) => { await CloseModal(newForm, parentForm); }; + + foreach (var b in Controls) + { + if (!b.Enabled) + { + continue; + } + + await b.Hidden(false); + } + + await newForm.OnInit(new InitEventArgs(args)); + + await newForm.OnOpened(EventArgs.Empty); + } + + public Task CloseModal(ModalDialog modalForm, FormBase oldForm) + { + var ds = Device; + if (ds == null) + { + return Task.CompletedTask; + } + + if (modalForm == null) + { + throw new Exception("No modal form"); + } + + ds.FormSwitched = true; + + ds.PreviousForm = ds.ActiveForm; + + ds.ActiveForm = oldForm; + return Task.CompletedTask; + } + + /// + /// Adds a control to the formular and sets its ID and Device. + /// + /// + public void AddControl(ControlBase control) + { + //Duplicate check + if (Controls.Contains(control)) + { + throw new ArgumentException("Control has been already added."); + } + + control.Id = Controls.Count + 1; + control.Device = Device; + Controls.Add(control); + + control.Init(); + } + + /// + /// Removes control from the formular and runs a cleanup on it. + /// + /// + public void RemoveControl(ControlBase control) + { + if (!Controls.Contains(control)) + { + return; + } + + control.Cleanup().Wait(); + + Controls.Remove(control); + } + + /// + /// Removes all controls. + /// + public void RemoveAllControls() + { + foreach (var c in Controls) + { + c.Cleanup().Wait(); + + Controls.Remove(c); + } + } +} \ No newline at end of file diff --git a/TelegramBotBase/Base/MessageClient.cs b/TelegramBotBase/Base/MessageClient.cs index 4813d86..a47ea16 100644 --- a/TelegramBotBase/Base/MessageClient.cs +++ b/TelegramBotBase/Base/MessageClient.cs @@ -10,193 +10,186 @@ using Telegram.Bot.Exceptions; using Telegram.Bot.Extensions.Polling; using Telegram.Bot.Types; -namespace TelegramBotBase.Base +namespace TelegramBotBase.Base; + +/// +/// Base class for message handling +/// +public class MessageClient { - /// - /// Base class for message handling - /// - public class MessageClient + private static readonly object EvOnMessageLoop = new(); + + private static object __evOnMessage = new(); + + private static object __evOnMessageEdit = new(); + + private static object __evCallbackQuery = new(); + + private CancellationTokenSource _cancellationTokenSource; + + + public MessageClient(string apiKey) { + ApiKey = apiKey; + TelegramClient = new TelegramBotClient(apiKey); - - public string ApiKey { get; set; } - - public ITelegramBotClient TelegramClient { get; set; } - - private EventHandlerList Events { get; set; } = new EventHandlerList(); - - private static readonly object EvOnMessageLoop = new object(); - - private static object __evOnMessage = new object(); - - private static object __evOnMessageEdit = new object(); - - private static object __evCallbackQuery = new object(); - - private CancellationTokenSource _cancellationTokenSource; - - - public MessageClient(string apiKey) - { - this.ApiKey = apiKey; - TelegramClient = new TelegramBotClient(apiKey); - - Prepare(); - } - - public MessageClient(string apiKey, HttpClient proxy) - { - this.ApiKey = apiKey; - TelegramClient = new TelegramBotClient(apiKey, proxy); - - - Prepare(); - } - - - - public MessageClient(string apiKey, Uri proxyUrl, NetworkCredential credential = null) - { - this.ApiKey = apiKey; - - var proxy = new WebProxy(proxyUrl) - { - Credentials = credential - }; - - var httpClient = new HttpClient( - new HttpClientHandler { Proxy = proxy, UseProxy = true } - ); - - TelegramClient = new TelegramBotClient(apiKey, httpClient); - - Prepare(); - } - - /// - /// Initializes the client with a proxy - /// - /// - /// i.e. 127.0.0.1 - /// i.e. 10000 - public MessageClient(string apiKey, string proxyHost, int proxyPort) - { - this.ApiKey = apiKey; - - var proxy = new WebProxy(proxyHost, proxyPort); - - var httpClient = new HttpClient( - new HttpClientHandler { Proxy = proxy, UseProxy = true } - ); - - TelegramClient = new TelegramBotClient(apiKey, httpClient); - - Prepare(); - } - - - - public MessageClient(string apiKey, TelegramBotClient client) - { - this.ApiKey = apiKey; - TelegramClient = client; - - Prepare(); - } - - - public void Prepare() - { - TelegramClient.Timeout = new TimeSpan(0, 0, 30); - - } - - - - public void StartReceiving() - { - _cancellationTokenSource = new CancellationTokenSource(); - - var receiverOptions = new ReceiverOptions(); - - TelegramClient.StartReceiving(HandleUpdateAsync, HandleErrorAsync, receiverOptions, _cancellationTokenSource.Token); - } - - public void StopReceiving() - { - _cancellationTokenSource.Cancel(); - } - - - public Task HandleUpdateAsync(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken) - { - OnMessageLoop(new UpdateResult(update, null)); - - return Task.CompletedTask; - } - - public Task HandleErrorAsync(ITelegramBotClient botClient, Exception exception, CancellationToken cancellationToken) - { - if (exception is ApiRequestException exApi) - { - Console.WriteLine($"Telegram API Error:\n[{exApi.ErrorCode}]\n{exApi.Message}"); - } - else - { - Console.WriteLine(exception.ToString()); - } - return Task.CompletedTask; - } - - - /// - /// This will return the current list of bot commands. - /// - /// - public async Task GetBotCommands(BotCommandScope scope = null, string languageCode = null) - { - return await TelegramClient.GetMyCommandsAsync(scope, languageCode); - } - - - /// - /// This will set your bot commands to the given list. - /// - /// - /// - public async Task SetBotCommands(List botcommands, BotCommandScope scope = null, string languageCode = null) - { - await TelegramClient.SetMyCommandsAsync(botcommands, scope, languageCode); - } - - /// - /// This will delete the current list of bot commands. - /// - /// - public async Task DeleteBotCommands(BotCommandScope scope = null, string languageCode = null) - { - await TelegramClient.DeleteMyCommandsAsync(scope, languageCode); - } - - - #region "Events" - - - - public event Async.AsyncEventHandler MessageLoop - { - add => Events.AddHandler(EvOnMessageLoop, value); - remove => Events.RemoveHandler(EvOnMessageLoop, value); - } - - public void OnMessageLoop(UpdateResult update) - { - (Events[EvOnMessageLoop] as Async.AsyncEventHandler)?.Invoke(this, update); - } - - - #endregion - - + Prepare(); } -} + + public MessageClient(string apiKey, HttpClient proxy) + { + ApiKey = apiKey; + TelegramClient = new TelegramBotClient(apiKey, proxy); + + + Prepare(); + } + + + public MessageClient(string apiKey, Uri proxyUrl, NetworkCredential credential = null) + { + ApiKey = apiKey; + + var proxy = new WebProxy(proxyUrl) + { + Credentials = credential + }; + + var httpClient = new HttpClient( + new HttpClientHandler { Proxy = proxy, UseProxy = true } + ); + + TelegramClient = new TelegramBotClient(apiKey, httpClient); + + Prepare(); + } + + /// + /// Initializes the client with a proxy + /// + /// + /// i.e. 127.0.0.1 + /// i.e. 10000 + public MessageClient(string apiKey, string proxyHost, int proxyPort) + { + ApiKey = apiKey; + + var proxy = new WebProxy(proxyHost, proxyPort); + + var httpClient = new HttpClient( + new HttpClientHandler { Proxy = proxy, UseProxy = true } + ); + + TelegramClient = new TelegramBotClient(apiKey, httpClient); + + Prepare(); + } + + + public MessageClient(string apiKey, TelegramBotClient client) + { + ApiKey = apiKey; + TelegramClient = client; + + Prepare(); + } + + + public string ApiKey { get; set; } + + public ITelegramBotClient TelegramClient { get; set; } + + private EventHandlerList Events { get; } = new(); + + + public void Prepare() + { + TelegramClient.Timeout = new TimeSpan(0, 0, 30); + } + + + public void StartReceiving() + { + _cancellationTokenSource = new CancellationTokenSource(); + + var receiverOptions = new ReceiverOptions(); + + TelegramClient.StartReceiving(HandleUpdateAsync, HandleErrorAsync, receiverOptions, + _cancellationTokenSource.Token); + } + + public void StopReceiving() + { + _cancellationTokenSource.Cancel(); + } + + + public Task HandleUpdateAsync(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken) + { + OnMessageLoop(new UpdateResult(update, null)); + + return Task.CompletedTask; + } + + public Task HandleErrorAsync(ITelegramBotClient botClient, Exception exception, + CancellationToken cancellationToken) + { + if (exception is ApiRequestException exApi) + { + Console.WriteLine($"Telegram API Error:\n[{exApi.ErrorCode}]\n{exApi.Message}"); + } + else + { + Console.WriteLine(exception.ToString()); + } + + return Task.CompletedTask; + } + + + /// + /// This will return the current list of bot commands. + /// + /// + public async Task GetBotCommands(BotCommandScope scope = null, string languageCode = null) + { + return await TelegramClient.GetMyCommandsAsync(scope, languageCode); + } + + + /// + /// This will set your bot commands to the given list. + /// + /// + /// + public async Task SetBotCommands(List botcommands, BotCommandScope scope = null, + string languageCode = null) + { + await TelegramClient.SetMyCommandsAsync(botcommands, scope, languageCode); + } + + /// + /// This will delete the current list of bot commands. + /// + /// + public async Task DeleteBotCommands(BotCommandScope scope = null, string languageCode = null) + { + await TelegramClient.DeleteMyCommandsAsync(scope, languageCode); + } + + + #region "Events" + + public event Async.AsyncEventHandler MessageLoop + { + add => Events.AddHandler(EvOnMessageLoop, value); + remove => Events.RemoveHandler(EvOnMessageLoop, value); + } + + public void OnMessageLoop(UpdateResult update) + { + (Events[EvOnMessageLoop] as Async.AsyncEventHandler)?.Invoke(this, update); + } + + #endregion +} \ No newline at end of file diff --git a/TelegramBotBase/Base/MessageResult.cs b/TelegramBotBase/Base/MessageResult.cs index 7d39fe7..531edf4 100644 --- a/TelegramBotBase/Base/MessageResult.cs +++ b/TelegramBotBase/Base/MessageResult.cs @@ -5,136 +5,134 @@ using Newtonsoft.Json; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; -namespace TelegramBotBase.Base +namespace TelegramBotBase.Base; + +public class MessageResult : ResultBase { - public class MessageResult : ResultBase + internal MessageResult() { + } - public Update UpdateData { get; set; } + public MessageResult(Update update) + { + UpdateData = update; + } - /// - /// Returns the Device/ChatId - /// - public override long DeviceId => - UpdateData?.Message?.Chat?.Id - ?? UpdateData?.EditedMessage?.Chat.Id - ?? UpdateData?.CallbackQuery.Message?.Chat.Id - ?? Device?.DeviceId - ?? 0; + public Update UpdateData { get; set; } - /// - /// The message id - /// - public new int MessageId => - UpdateData?.Message?.MessageId - ?? Message?.MessageId - ?? UpdateData?.CallbackQuery?.Message?.MessageId - ?? 0; + /// + /// Returns the Device/ChatId + /// + public override long DeviceId => + UpdateData?.Message?.Chat?.Id + ?? UpdateData?.EditedMessage?.Chat.Id + ?? UpdateData?.CallbackQuery.Message?.Chat.Id + ?? Device?.DeviceId + ?? 0; - public string Command => UpdateData?.Message?.Text ?? ""; + /// + /// The message id + /// + public new int MessageId => + UpdateData?.Message?.MessageId + ?? Message?.MessageId + ?? UpdateData?.CallbackQuery?.Message?.MessageId + ?? 0; - public string MessageText => UpdateData?.Message?.Text ?? ""; + public string Command => UpdateData?.Message?.Text ?? ""; - public MessageType MessageType => Message?.Type ?? MessageType.Unknown; + public string MessageText => UpdateData?.Message?.Text ?? ""; - /// - /// Is this an action ? (i.e. button click) - /// - public bool IsAction => (UpdateData.CallbackQuery != null); + public MessageType MessageType => Message?.Type ?? MessageType.Unknown; - /// - /// Is this a command ? Starts with a slash '/' and a command - /// - public bool IsBotCommand => (MessageText.StartsWith("/")); + /// + /// Is this an action ? (i.e. button click) + /// + public bool IsAction => UpdateData.CallbackQuery != null; - /// - /// Returns a List of all parameters which has been sent with the command itself (i.e. /start 123 456 789 => 123,456,789) - /// - public List BotCommandParameters + /// + /// Is this a command ? Starts with a slash '/' and a command + /// + public bool IsBotCommand => MessageText.StartsWith("/"); + + /// + /// Returns a List of all parameters which has been sent with the command itself (i.e. /start 123 456 789 => + /// 123,456,789) + /// + public List BotCommandParameters + { + get { - get + if (!IsBotCommand) { - if (!IsBotCommand) - return new List(); - - //Split by empty space and skip first entry (command itself), return as list - return MessageText.Split(' ').Skip(1).ToList(); - } - } - - /// - /// Returns just the command (i.e. /start 1 2 3 => /start) - /// - public string BotCommand - { - get - { - if (!IsBotCommand) - return null; - - return MessageText.Split(' ')[0]; - } - } - - /// - /// Returns if this message will be used on the first form or not. - /// - public bool IsFirstHandler { get; set; } = true; - - public bool Handled { get; set; } = false; - - public string RawData => UpdateData?.CallbackQuery?.Data; - - public T GetData() - where T : class - { - T cd = null; - try - { - cd = JsonConvert.DeserializeObject(RawData); - - return cd; - } - catch - { - + return new List(); } - return null; + //Split by empty space and skip first entry (command itself), return as list + return MessageText.Split(' ').Skip(1).ToList(); } + } - /// - /// Confirm incomming action (i.e. Button click) - /// - /// - /// - public async Task ConfirmAction(string message = "", bool showAlert = false, string urlToOpen = null) + /// + /// Returns just the command (i.e. /start 1 2 3 => /start) + /// + public string BotCommand + { + get { - await Device.ConfirmAction(UpdateData.CallbackQuery.Id, message, showAlert, urlToOpen); - } - - public override async Task DeleteMessage() - { - try + if (!IsBotCommand) { - await base.DeleteMessage(MessageId); + return null; } - catch - { - } + return MessageText.Split(' ')[0]; } + } - internal MessageResult() + /// + /// Returns if this message will be used on the first form or not. + /// + public bool IsFirstHandler { get; set; } = true; + + public bool Handled { get; set; } = false; + + public string RawData => UpdateData?.CallbackQuery?.Data; + + public T GetData() + where T : class + { + T cd = null; + try { + cd = JsonConvert.DeserializeObject(RawData); + return cd; } - - public MessageResult(Update update) + catch { - UpdateData = update; - } + return null; + } + + /// + /// Confirm incomming action (i.e. Button click) + /// + /// + /// + public async Task ConfirmAction(string message = "", bool showAlert = false, string urlToOpen = null) + { + await Device.ConfirmAction(UpdateData.CallbackQuery.Id, message, showAlert, urlToOpen); + } + + public override async Task DeleteMessage() + { + try + { + await base.DeleteMessage(MessageId); + } + catch + { + } } } diff --git a/TelegramBotBase/Base/ResultBase.cs b/TelegramBotBase/Base/ResultBase.cs index 59a130f..2845237 100644 --- a/TelegramBotBase/Base/ResultBase.cs +++ b/TelegramBotBase/Base/ResultBase.cs @@ -4,48 +4,42 @@ using Telegram.Bot; using Telegram.Bot.Types; using TelegramBotBase.Sessions; -namespace TelegramBotBase.Base +namespace TelegramBotBase.Base; + +public class ResultBase : EventArgs { - public class ResultBase : EventArgs + public DeviceSession Device { get; set; } + + public virtual long DeviceId { get; set; } + + public int MessageId => Message.MessageId; + + public virtual Message Message { get; set; } + + /// + /// Deletes the current message + /// + /// + /// + public virtual async Task DeleteMessage() { - public DeviceSession Device - { - get; - set; - } - - public virtual long DeviceId { get; set; } - - public int MessageId => Message.MessageId; - - public virtual Message Message { get; set; } - - /// - /// Deletes the current message - /// - /// - /// - public virtual async Task DeleteMessage() - { - await DeleteMessage(MessageId); - } - - /// - ///Deletes the current message or the given one. - /// - /// - /// - public virtual async Task DeleteMessage(int messageId = -1) - { - try - { - await Device.Client.TelegramClient.DeleteMessageAsync(DeviceId, (messageId == -1 ? MessageId : messageId)); - } - catch - { - - } - } - + await DeleteMessage(MessageId); } -} + + /// + /// Deletes the current message or the given one. + /// + /// + /// + public virtual async Task DeleteMessage(int messageId = -1) + { + try + { + await Device.Client.TelegramClient.DeleteMessageAsync(DeviceId, + messageId == -1 ? MessageId : messageId); + } + catch + { + } + } +} \ No newline at end of file diff --git a/TelegramBotBase/Base/StateContainer.cs b/TelegramBotBase/Base/StateContainer.cs index 7e74cc6..de6b766 100644 --- a/TelegramBotBase/Base/StateContainer.cs +++ b/TelegramBotBase/Base/StateContainer.cs @@ -1,32 +1,24 @@ using System.Collections.Generic; using System.Linq; -namespace TelegramBotBase.Base +namespace TelegramBotBase.Base; + +public class StateContainer { - public class StateContainer + public StateContainer() { - public List States { get; set; } - - public List ChatIds - { - get - { - return States.Where(a => a.DeviceId > 0).Select(a => a.DeviceId).ToList(); - } - } - - public List GroupIds - { - get - { - return States.Where(a => a.DeviceId < 0).Select(a => a.DeviceId).ToList(); - } - } - - public StateContainer() - { - States = new List(); - } - + States = new List(); } -} + + public List States { get; set; } + + public List ChatIds + { + get { return States.Where(a => a.DeviceId > 0).Select(a => a.DeviceId).ToList(); } + } + + public List GroupIds + { + get { return States.Where(a => a.DeviceId < 0).Select(a => a.DeviceId).ToList(); } + } +} \ No newline at end of file diff --git a/TelegramBotBase/Base/StateEntry.cs b/TelegramBotBase/Base/StateEntry.cs index 13e272f..8513804 100644 --- a/TelegramBotBase/Base/StateEntry.cs +++ b/TelegramBotBase/Base/StateEntry.cs @@ -1,41 +1,38 @@ using System.Collections.Generic; using System.Diagnostics; -namespace TelegramBotBase.Base +namespace TelegramBotBase.Base; + +[DebuggerDisplay("Device: {DeviceId}, {FormUri}")] +public class StateEntry { - - [DebuggerDisplay("Device: {DeviceId}, {FormUri}")] - public class StateEntry + public StateEntry() { - /// - /// Contains the DeviceId of the entry. - /// - public long DeviceId { get; set; } - - /// - /// Contains the Username (on privat chats) or Group title on groups/channels. - /// - public string ChatTitle { get; set; } - - /// - /// Contains additional values to save. - /// - public Dictionary Values { get; set; } - - /// - /// Contains the full qualified namespace of the form to used for reload it via reflection. - /// - public string FormUri {get;set;} - - /// - /// Contains the assembly, where to find that form. - /// - public string QualifiedName { get; set; } - - public StateEntry() - { - Values = new Dictionary(); - } - + Values = new Dictionary(); } -} + + /// + /// Contains the DeviceId of the entry. + /// + public long DeviceId { get; set; } + + /// + /// Contains the Username (on privat chats) or Group title on groups/channels. + /// + public string ChatTitle { get; set; } + + /// + /// Contains additional values to save. + /// + public Dictionary Values { get; set; } + + /// + /// Contains the full qualified namespace of the form to used for reload it via reflection. + /// + public string FormUri { get; set; } + + /// + /// Contains the assembly, where to find that form. + /// + public string QualifiedName { get; set; } +} \ No newline at end of file diff --git a/TelegramBotBase/Base/UpdateResult.cs b/TelegramBotBase/Base/UpdateResult.cs index 4d8e430..82d46b3 100644 --- a/TelegramBotBase/Base/UpdateResult.cs +++ b/TelegramBotBase/Base/UpdateResult.cs @@ -1,35 +1,31 @@ using Telegram.Bot.Types; using TelegramBotBase.Sessions; -namespace TelegramBotBase.Base +namespace TelegramBotBase.Base; + +public class UpdateResult : ResultBase { - public class UpdateResult : ResultBase + public UpdateResult(Update rawData, DeviceSession device) { - public UpdateResult(Update rawData, DeviceSession device) - { - RawData = rawData; - Device = device; - - - } - - /// - /// Returns the Device/ChatId - /// - public override long DeviceId => - RawData?.Message?.Chat?.Id - ?? RawData?.CallbackQuery?.Message?.Chat?.Id - ?? Device?.DeviceId - ?? 0; - - public Update RawData { get; set; } - - public override Message Message => - RawData?.Message - ?? RawData?.EditedMessage - ?? RawData?.ChannelPost - ?? RawData?.EditedChannelPost - ?? RawData?.CallbackQuery?.Message; + RawData = rawData; + Device = device; } -} + /// + /// Returns the Device/ChatId + /// + public override long DeviceId => + RawData?.Message?.Chat?.Id + ?? RawData?.CallbackQuery?.Message?.Chat?.Id + ?? Device?.DeviceId + ?? 0; + + public Update RawData { get; set; } + + public override Message Message => + RawData?.Message + ?? RawData?.EditedMessage + ?? RawData?.ChannelPost + ?? RawData?.EditedChannelPost + ?? RawData?.CallbackQuery?.Message; +} \ No newline at end of file diff --git a/TelegramBotBase/BotBase.cs b/TelegramBotBase/BotBase.cs index 45b8a92..bac92e3 100644 --- a/TelegramBotBase/BotBase.cs +++ b/TelegramBotBase/BotBase.cs @@ -2,413 +2,409 @@ using System.Collections.Generic; using System.ComponentModel; using System.Linq; -using System.Text; -using System.Threading; using System.Threading.Tasks; using Telegram.Bot; -using Telegram.Bot.Exceptions; using Telegram.Bot.Types; -using Telegram.Bot.Types.Enums; using TelegramBotBase.Args; -using TelegramBotBase.Attributes; using TelegramBotBase.Base; using TelegramBotBase.Enums; -using TelegramBotBase.MessageLoops; -using TelegramBotBase.Form; using TelegramBotBase.Interfaces; using TelegramBotBase.Sessions; +using Console = TelegramBotBase.Tools.Console; -namespace TelegramBotBase +namespace TelegramBotBase; + +/// +/// Bot base class for full Device/Context and Messagehandling +/// +/// +public class BotBase { - /// - /// Bot base class for full Device/Context and Messagehandling - /// - /// - public class BotBase + public BotBase() { - public MessageClient Client { get; set; } + SystemSettings = new Dictionary(); - /// - /// Your TelegramBot APIKey - /// - public string ApiKey { get; set; } = ""; + SetSetting(ESettings.MaxNumberOfRetries, 5); + SetSetting(ESettings.NavigationMaximum, 10); + SetSetting(ESettings.LogAllMessages, false); + SetSetting(ESettings.SkipAllMessages, false); + SetSetting(ESettings.SaveSessionsOnConsoleExit, false); - /// - /// List of all running/active sessions - /// - public SessionBase Sessions { get; set; } + BotCommandScopes = new Dictionary>(); - /// - /// Contains System commands which will be available at everytime and didnt get passed to forms, i.e. /start - /// - public Dictionary> BotCommandScopes { get; set; } = new Dictionary>(); - - - #region "Events" - - private readonly EventHandlerList _events = new EventHandlerList(); - - private static readonly object EvSessionBegins = new object(); - - private static readonly object EvMessage = new object(); - - private static object __evSystemCall = new object(); - - public delegate Task BotCommandEventHandler(object sender, BotCommandEventArgs e); - - private static readonly object EvException = new object(); - - private static readonly object EvUnhandledCall = new object(); - - #endregion - - - /// - /// Enable the SessionState (you need to implement on call forms the IStateForm interface) - /// - public IStateMachine StateMachine { get; set; } - - /// - /// Offers functionality to manage the creation process of the start form. - /// - public IStartFormFactory StartFormFactory { get; set; } - - /// - /// Contains the message loop factory, which cares about "message-management." - /// - public IMessageLoopFactory MessageLoopFactory { get; set; } - - /// - /// All internal used settings. - /// - public Dictionary SystemSettings { get; private set; } - - public BotBase() + Sessions = new SessionBase { - SystemSettings = new Dictionary(); - - SetSetting(ESettings.MaxNumberOfRetries, 5); - SetSetting(ESettings.NavigationMaximum, 10); - SetSetting(ESettings.LogAllMessages, false); - SetSetting(ESettings.SkipAllMessages, false); - SetSetting(ESettings.SaveSessionsOnConsoleExit, false); - - BotCommandScopes = new Dictionary>(); - - Sessions = new SessionBase - { - BotBase = this - }; - } - - - - /// - /// Start your Bot - /// - public void Start() - { - if (Client == null) - return; - - Client.MessageLoop += Client_MessageLoop; - - - if (StateMachine != null) - { - Sessions.LoadSessionStates(StateMachine); - } - - //Enable auto session saving - if (GetSetting(ESettings.SaveSessionsOnConsoleExit, false)) - { - Tools.Console.SetHandler(() => - { - Sessions.SaveSessionStates(); - }); - } - - DeviceSession.MaxNumberOfRetries = GetSetting(ESettings.MaxNumberOfRetries, 5); - - Client.StartReceiving(); - } - - - private async Task Client_MessageLoop(object sender, UpdateResult e) - { - var ds = Sessions.GetSession(e.DeviceId); - if (ds == null) - { - ds = Sessions.StartSession(e.DeviceId).GetAwaiter().GetResult(); - e.Device = ds; - ds.LastMessage = e.RawData.Message; - - OnSessionBegins(new SessionBeginEventArgs(e.DeviceId, ds)); - } - - var mr = new MessageResult(e.RawData); - - var i = 0; - - //Should formulars get navigated (allow maximum of 10, to dont get loops) - do - { - i++; - - //Reset navigation - ds.FormSwitched = false; - - await MessageLoopFactory.MessageLoop(this, ds, e, mr); - - mr.IsFirstHandler = false; - - } while (ds.FormSwitched && i < GetSetting(ESettings.NavigationMaximum, 10)); - } - - - /// - /// Stop your Bot - /// - public void Stop() - { - if (Client == null) - return; - - Client.MessageLoop -= Client_MessageLoop; - - - Client.StopReceiving(); - - Sessions.SaveSessionStates(); - } - - /// - /// Send a message to all active Sessions. - /// - /// - /// - public async Task SentToAll(string message) - { - if (Client == null) - return; - - foreach (var s in Sessions.SessionList) - { - await Client.TelegramClient.SendTextMessageAsync(s.Key, message); - } - } - - - - /// - /// This will invoke the full message loop for the device even when no "userevent" like message or action has been raised. - /// - /// Contains the device/chat id of the device to update. - public async Task InvokeMessageLoop(long deviceId) - { - var mr = new MessageResult - { - UpdateData = new Update() - { - Message = new Message() - } - }; - - await InvokeMessageLoop(deviceId, mr); - } - - /// - /// This will invoke the full message loop for the device even when no "userevent" like message or action has been raised. - /// - /// Contains the device/chat id of the device to update. - /// - public async Task InvokeMessageLoop(long deviceId, MessageResult e) - { - try - { - var ds = Sessions.GetSession(deviceId); - e.Device = ds; - - await MessageLoopFactory.MessageLoop(this, ds, new UpdateResult(e.UpdateData, ds), e); - //await Client_Loop(this, e); - } - catch (Exception ex) - { - var ds = Sessions.GetSession(deviceId); - OnException(new SystemExceptionEventArgs(e.Message.Text, deviceId, ds, ex)); - } - } - - - /// - /// Will get invoke on an unhandled call. - /// - /// - /// - public void MessageLoopFactory_UnhandledCall(object sender, UnhandledCallEventArgs e) - { - OnUnhandledCall(e); - } - - /// - /// This method will update all local created bot commands to the botfather. - /// - public async Task UploadBotCommands() - { - foreach (var bs in BotCommandScopes) - { - if(bs.Value !=null) - { - await Client.SetBotCommands(bs.Value, bs.Key); - } - else - { - await Client.DeleteBotCommands(bs.Key); - } - - } - } - - /// - /// Searching if parameter is a known command in all configured BotCommandScopes. - /// - /// - /// - public bool IsKnownBotCommand(string command) - { - foreach (var scope in BotCommandScopes) - { - if (scope.Value.Any(a => "/" + a.Command == command)) - return true; - } - - return false; - } - - /// - /// Could set a variety of settings to improve the bot handling. - /// - /// - /// - public void SetSetting(ESettings set, uint value) - { - SystemSettings[set] = value; - } - - /// - /// Could set a variety of settings to improve the bot handling. - /// - /// - /// - public void SetSetting(ESettings set, bool value) - { - SystemSettings[set] = (value ? 1u : 0u); - } - - /// - /// Could get the current value of a setting - /// - /// - /// - /// - public uint GetSetting(ESettings set, uint defaultValue) - { - if (!SystemSettings.ContainsKey(set)) - return defaultValue; - - return SystemSettings[set]; - } - - /// - /// Could get the current value of a setting - /// - /// - /// - /// - public bool GetSetting(ESettings set, bool defaultValue) - { - if (!SystemSettings.ContainsKey(set)) - return defaultValue; - - return SystemSettings[set] == 0u ? false : true; - } - - #region "Events" - - /// - /// Will be called if a session/context gets started - /// - - public event EventHandler SessionBegins - { - add => _events.AddHandler(EvSessionBegins, value); - remove => _events.RemoveHandler(EvSessionBegins, value); - } - - public void OnSessionBegins(SessionBeginEventArgs e) - { - (_events[EvSessionBegins] as EventHandler)?.Invoke(this, e); - - } - - /// - /// Will be called on incomming message - /// - public event EventHandler Message - { - add => _events.AddHandler(EvMessage, value); - remove => _events.RemoveHandler(EvMessage, value); - } - - public void OnMessage(MessageIncomeEventArgs e) - { - (_events[EvMessage] as EventHandler)?.Invoke(this, e); - - } - - /// - /// Will be called if a bot command gets raised - /// - public event BotCommandEventHandler BotCommand; - - - public async Task OnBotCommand(BotCommandEventArgs e) - { - if (BotCommand != null) - await BotCommand(this, e); - } - - /// - /// Will be called on an inner exception - /// - public event EventHandler Exception - { - add => _events.AddHandler(EvException, value); - remove => _events.RemoveHandler(EvException, value); - } - - public void OnException(SystemExceptionEventArgs e) - { - (_events[EvException] as EventHandler)?.Invoke(this, e); - - } - - /// - /// Will be called if no form handeled this call - /// - public event EventHandler UnhandledCall - { - add => _events.AddHandler(EvUnhandledCall, value); - remove => _events.RemoveHandler(EvUnhandledCall, value); - } - - public void OnUnhandledCall(UnhandledCallEventArgs e) - { - (_events[EvUnhandledCall] as EventHandler)?.Invoke(this, e); - - } - - #endregion - + BotBase = this + }; } -} + + public MessageClient Client { get; set; } + + /// + /// Your TelegramBot APIKey + /// + public string ApiKey { get; set; } = ""; + + /// + /// List of all running/active sessions + /// + public SessionBase Sessions { get; set; } + + /// + /// Contains System commands which will be available at everytime and didnt get passed to forms, i.e. /start + /// + public Dictionary> BotCommandScopes { get; set; } = new(); + + + /// + /// Enable the SessionState (you need to implement on call forms the IStateForm interface) + /// + public IStateMachine StateMachine { get; set; } + + /// + /// Offers functionality to manage the creation process of the start form. + /// + public IStartFormFactory StartFormFactory { get; set; } + + /// + /// Contains the message loop factory, which cares about "message-management." + /// + public IMessageLoopFactory MessageLoopFactory { get; set; } + + /// + /// All internal used settings. + /// + public Dictionary SystemSettings { get; } + + + /// + /// Start your Bot + /// + public void Start() + { + if (Client == null) + { + return; + } + + Client.MessageLoop += Client_MessageLoop; + + + if (StateMachine != null) + { + Sessions.LoadSessionStates(StateMachine); + } + + //Enable auto session saving + if (GetSetting(ESettings.SaveSessionsOnConsoleExit, false)) + { + Console.SetHandler(() => { Sessions.SaveSessionStates(); }); + } + + DeviceSession.MaxNumberOfRetries = GetSetting(ESettings.MaxNumberOfRetries, 5); + + Client.StartReceiving(); + } + + + private async Task Client_MessageLoop(object sender, UpdateResult e) + { + var ds = Sessions.GetSession(e.DeviceId); + if (ds == null) + { + ds = Sessions.StartSession(e.DeviceId).GetAwaiter().GetResult(); + e.Device = ds; + ds.LastMessage = e.RawData.Message; + + OnSessionBegins(new SessionBeginEventArgs(e.DeviceId, ds)); + } + + var mr = new MessageResult(e.RawData); + + var i = 0; + + //Should formulars get navigated (allow maximum of 10, to dont get loops) + do + { + i++; + + //Reset navigation + ds.FormSwitched = false; + + await MessageLoopFactory.MessageLoop(this, ds, e, mr); + + mr.IsFirstHandler = false; + } while (ds.FormSwitched && i < GetSetting(ESettings.NavigationMaximum, 10)); + } + + + /// + /// Stop your Bot + /// + public void Stop() + { + if (Client == null) + { + return; + } + + Client.MessageLoop -= Client_MessageLoop; + + + Client.StopReceiving(); + + Sessions.SaveSessionStates(); + } + + /// + /// Send a message to all active Sessions. + /// + /// + /// + public async Task SentToAll(string message) + { + if (Client == null) + { + return; + } + + foreach (var s in Sessions.SessionList) + { + await Client.TelegramClient.SendTextMessageAsync(s.Key, message); + } + } + + + /// + /// This will invoke the full message loop for the device even when no "userevent" like message or action has been + /// raised. + /// + /// Contains the device/chat id of the device to update. + public async Task InvokeMessageLoop(long deviceId) + { + var mr = new MessageResult + { + UpdateData = new Update + { + Message = new Message() + } + }; + + await InvokeMessageLoop(deviceId, mr); + } + + /// + /// This will invoke the full message loop for the device even when no "userevent" like message or action has been + /// raised. + /// + /// Contains the device/chat id of the device to update. + /// + public async Task InvokeMessageLoop(long deviceId, MessageResult e) + { + try + { + var ds = Sessions.GetSession(deviceId); + e.Device = ds; + + await MessageLoopFactory.MessageLoop(this, ds, new UpdateResult(e.UpdateData, ds), e); + //await Client_Loop(this, e); + } + catch (Exception ex) + { + var ds = Sessions.GetSession(deviceId); + OnException(new SystemExceptionEventArgs(e.Message.Text, deviceId, ds, ex)); + } + } + + + /// + /// Will get invoke on an unhandled call. + /// + /// + /// + public void MessageLoopFactory_UnhandledCall(object sender, UnhandledCallEventArgs e) + { + OnUnhandledCall(e); + } + + /// + /// This method will update all local created bot commands to the botfather. + /// + public async Task UploadBotCommands() + { + foreach (var bs in BotCommandScopes) + { + if (bs.Value != null) + { + await Client.SetBotCommands(bs.Value, bs.Key); + } + else + { + await Client.DeleteBotCommands(bs.Key); + } + } + } + + /// + /// Searching if parameter is a known command in all configured BotCommandScopes. + /// + /// + /// + public bool IsKnownBotCommand(string command) + { + foreach (var scope in BotCommandScopes) + { + if (scope.Value.Any(a => "/" + a.Command == command)) + { + return true; + } + } + + return false; + } + + /// + /// Could set a variety of settings to improve the bot handling. + /// + /// + /// + public void SetSetting(ESettings set, uint value) + { + SystemSettings[set] = value; + } + + /// + /// Could set a variety of settings to improve the bot handling. + /// + /// + /// + public void SetSetting(ESettings set, bool value) + { + SystemSettings[set] = value ? 1u : 0u; + } + + /// + /// Could get the current value of a setting + /// + /// + /// + /// + public uint GetSetting(ESettings set, uint defaultValue) + { + if (!SystemSettings.ContainsKey(set)) + { + return defaultValue; + } + + return SystemSettings[set]; + } + + /// + /// Could get the current value of a setting + /// + /// + /// + /// + public bool GetSetting(ESettings set, bool defaultValue) + { + if (!SystemSettings.ContainsKey(set)) + { + return defaultValue; + } + + return SystemSettings[set] == 0u ? false : true; + } + + + #region "Events" + + private readonly EventHandlerList _events = new(); + + private static readonly object EvSessionBegins = new(); + + private static readonly object EvMessage = new(); + + private static object __evSystemCall = new(); + + public delegate Task BotCommandEventHandler(object sender, BotCommandEventArgs e); + + private static readonly object EvException = new(); + + private static readonly object EvUnhandledCall = new(); + + #endregion + + #region "Events" + + /// + /// Will be called if a session/context gets started + /// + public event EventHandler SessionBegins + { + add => _events.AddHandler(EvSessionBegins, value); + remove => _events.RemoveHandler(EvSessionBegins, value); + } + + public void OnSessionBegins(SessionBeginEventArgs e) + { + (_events[EvSessionBegins] as EventHandler)?.Invoke(this, e); + } + + /// + /// Will be called on incomming message + /// + public event EventHandler Message + { + add => _events.AddHandler(EvMessage, value); + remove => _events.RemoveHandler(EvMessage, value); + } + + public void OnMessage(MessageIncomeEventArgs e) + { + (_events[EvMessage] as EventHandler)?.Invoke(this, e); + } + + /// + /// Will be called if a bot command gets raised + /// + public event BotCommandEventHandler BotCommand; + + + public async Task OnBotCommand(BotCommandEventArgs e) + { + if (BotCommand != null) + { + await BotCommand(this, e); + } + } + + /// + /// Will be called on an inner exception + /// + public event EventHandler Exception + { + add => _events.AddHandler(EvException, value); + remove => _events.RemoveHandler(EvException, value); + } + + public void OnException(SystemExceptionEventArgs e) + { + (_events[EvException] as EventHandler)?.Invoke(this, e); + } + + /// + /// Will be called if no form handeled this call + /// + public event EventHandler UnhandledCall + { + add => _events.AddHandler(EvUnhandledCall, value); + remove => _events.RemoveHandler(EvUnhandledCall, value); + } + + public void OnUnhandledCall(UnhandledCallEventArgs e) + { + (_events[EvUnhandledCall] as EventHandler)?.Invoke(this, e); + } + + #endregion +} \ No newline at end of file diff --git a/TelegramBotBase/Builder/BotBaseBuilder.cs b/TelegramBotBase/Builder/BotBaseBuilder.cs index 216d09f..ffd2d58 100644 --- a/TelegramBotBase/Builder/BotBaseBuilder.cs +++ b/TelegramBotBase/Builder/BotBaseBuilder.cs @@ -13,362 +13,360 @@ using TelegramBotBase.Localizations; using TelegramBotBase.MessageLoops; using TelegramBotBase.States; -namespace TelegramBotBase.Builder +namespace TelegramBotBase.Builder; + +public class BotBaseBuilder : IAPIKeySelectionStage, IMessageLoopSelectionStage, IStartFormSelectionStage, + IBuildingStage, INetworkingSelectionStage, IBotCommandsStage, ISessionSerializationStage, + ILanguageSelectionStage { - public class BotBaseBuilder : IAPIKeySelectionStage, IMessageLoopSelectionStage, IStartFormSelectionStage, IBuildingStage, INetworkingSelectionStage, IBotCommandsStage, ISessionSerializationStage, ILanguageSelectionStage + private string _apiKey; + + private MessageClient _client; + + private IStartFormFactory _factory; + + private IMessageLoopFactory _messageLoopFactory; + + private IStateMachine _statemachine; + + private BotBaseBuilder() { - private string _apiKey; - - private IStartFormFactory _factory; - - private MessageClient _client; - - /// - /// Contains different Botcommands for different areas. - /// - private Dictionary> BotCommandScopes { get; set; } = new Dictionary>(); - - private IStateMachine _statemachine; - - private IMessageLoopFactory _messageLoopFactory; - - private BotBaseBuilder() - { - - } - - public static IAPIKeySelectionStage Create() - { - return new BotBaseBuilder(); - } - - #region "Step 1 (Basic Stuff)" - - public IMessageLoopSelectionStage WithAPIKey(string apiKey) - { - _apiKey = apiKey; - return this; - } - - - public IBuildingStage QuickStart(string apiKey, Type StartForm) - { - _apiKey = apiKey; - _factory = new DefaultStartFormFactory(StartForm); - - DefaultMessageLoop(); - - NoProxy(); - - OnlyStart(); - - NoSerialization(); - - DefaultLanguage(); - - return this; - } - - - public IBuildingStage QuickStart(string apiKey) - where T : FormBase - { - _apiKey = apiKey; - _factory = new DefaultStartFormFactory(typeof(T)); - - DefaultMessageLoop(); - - NoProxy(); - - OnlyStart(); - - NoSerialization(); - - DefaultLanguage(); - - return this; - } - - public IBuildingStage QuickStart(string apiKey, IStartFormFactory StartFormFactory) - { - _apiKey = apiKey; - _factory = StartFormFactory; - - DefaultMessageLoop(); - - NoProxy(); - - OnlyStart(); - - NoSerialization(); - - DefaultLanguage(); - - return this; - } - - #endregion - - - #region "Step 2 (Message Loop)" - - public IStartFormSelectionStage DefaultMessageLoop() - { - _messageLoopFactory = new FormBaseMessageLoop(); - - return this; - } - - - public IStartFormSelectionStage MinimalMessageLoop() - { - _messageLoopFactory = new MinimalMessageLoop(); - - return this; - } - - - public IStartFormSelectionStage CustomMessageLoop(IMessageLoopFactory messageLoopClass) - { - _messageLoopFactory = messageLoopClass; - - return this; - } - - public IStartFormSelectionStage CustomMessageLoop() - where T : class, new() - { - _messageLoopFactory = typeof(T).GetConstructor(new Type[] { })?.Invoke(new object[] { }) as IMessageLoopFactory; - - return this; - } - - #endregion - - - #region "Step 3 (Start Form/Factory)" - - public INetworkingSelectionStage WithStartForm(Type startFormClass) - { - _factory = new DefaultStartFormFactory(startFormClass); - return this; - } - - public INetworkingSelectionStage WithStartForm() - where T : FormBase, new() - { - _factory = new DefaultStartFormFactory(typeof(T)); - return this; - } - - public INetworkingSelectionStage WithServiceProvider(Type startFormClass, IServiceProvider serviceProvider) - { - _factory = new ServiceProviderStartFormFactory(startFormClass, serviceProvider); - return this; - } - - public INetworkingSelectionStage WithServiceProvider(IServiceProvider serviceProvider) - where T : FormBase - { - _factory = new ServiceProviderStartFormFactory(serviceProvider); - return this; - } - - public INetworkingSelectionStage WithStartFormFactory(IStartFormFactory factory) - { - _factory = factory; - return this; - } - - #endregion - - - #region "Step 4 (Network Settings)" - - public IBotCommandsStage WithProxy(string proxyAddress) - { - var url = new Uri(proxyAddress); - _client = new MessageClient(_apiKey, url) - { - TelegramClient = - { - Timeout = new TimeSpan(0, 1, 0) - } - }; - return this; - } - - - public IBotCommandsStage NoProxy() - { - _client = new MessageClient(_apiKey) - { - TelegramClient = - { - Timeout = new TimeSpan(0, 1, 0) - } - }; - return this; - } - - - public IBotCommandsStage WithBotClient(TelegramBotClient tgclient) - { - _client = new MessageClient(_apiKey, tgclient) - { - TelegramClient = - { - Timeout = new TimeSpan(0, 1, 0) - } - }; - return this; - } - - - public IBotCommandsStage WithHostAndPort(string proxyHost, int proxyPort) - { - _client = new MessageClient(_apiKey, proxyHost, proxyPort) - { - TelegramClient = - { - Timeout = new TimeSpan(0, 1, 0) - } - }; - return this; - } - - public IBotCommandsStage WithHttpClient(HttpClient tgclient) - { - _client = new MessageClient(_apiKey, tgclient) - { - TelegramClient = - { - Timeout = new TimeSpan(0, 1, 0) - } - }; - return this; - } - - - #endregion - - - #region "Step 5 (Bot Commands)" - - public ISessionSerializationStage NoCommands() - { - return this; - } - - public ISessionSerializationStage OnlyStart() - { - BotCommandScopes.Start("Starts the bot"); - - return this; - - } - - public ISessionSerializationStage DefaultCommands() - { - BotCommandScopes.Start("Starts the bot"); - BotCommandScopes.Help("Should show you some help"); - BotCommandScopes.Settings("Should show you some settings"); - return this; - } - - public ISessionSerializationStage CustomCommands(Action>> action) - { - action?.Invoke(BotCommandScopes); - return this; - } - - #endregion - - - #region "Step 6 (Serialization)" - - public ILanguageSelectionStage NoSerialization() - { - return this; - } - - public ILanguageSelectionStage UseSerialization(IStateMachine machine) - { - _statemachine = machine; - return this; - } - - - public ILanguageSelectionStage UseJSON(string path) - { - _statemachine = new JsonStateMachine(path); - return this; - } - - public ILanguageSelectionStage UseSimpleJSON(string path) - { - _statemachine = new SimpleJsonStateMachine(path); - return this; - } - - public ILanguageSelectionStage UseXML(string path) - { - _statemachine = new XmlStateMachine(path); - return this; - } - - #endregion - - - #region "Step 7 (Language)" - - public IBuildingStage DefaultLanguage() - { - return this; - } - - public IBuildingStage UseEnglish() - { - Default.Language = new English(); - return this; - } - - public IBuildingStage UseGerman() - { - Default.Language = new German(); - return this; - } - - public IBuildingStage Custom(Localization language) - { - Default.Language = language; - return this; - } - - #endregion - - - public BotBase Build() - { - var bb = new BotBase - { - ApiKey = _apiKey, - StartFormFactory = _factory, - Client = _client - }; - - bb.Sessions.Client = bb.Client; - - bb.BotCommandScopes = BotCommandScopes; - - bb.StateMachine = _statemachine; - - bb.MessageLoopFactory = _messageLoopFactory; - - bb.MessageLoopFactory.UnhandledCall += bb.MessageLoopFactory_UnhandledCall; - - return bb; - } - } -} + + /// + /// Contains different Botcommands for different areas. + /// + private Dictionary> BotCommandScopes { get; } = new(); + + + public BotBase Build() + { + var bb = new BotBase + { + ApiKey = _apiKey, + StartFormFactory = _factory, + Client = _client + }; + + bb.Sessions.Client = bb.Client; + + bb.BotCommandScopes = BotCommandScopes; + + bb.StateMachine = _statemachine; + + bb.MessageLoopFactory = _messageLoopFactory; + + bb.MessageLoopFactory.UnhandledCall += bb.MessageLoopFactory_UnhandledCall; + + return bb; + } + + public static IAPIKeySelectionStage Create() + { + return new BotBaseBuilder(); + } + + #region "Step 1 (Basic Stuff)" + + public IMessageLoopSelectionStage WithAPIKey(string apiKey) + { + _apiKey = apiKey; + return this; + } + + + public IBuildingStage QuickStart(string apiKey, Type StartForm) + { + _apiKey = apiKey; + _factory = new DefaultStartFormFactory(StartForm); + + DefaultMessageLoop(); + + NoProxy(); + + OnlyStart(); + + NoSerialization(); + + DefaultLanguage(); + + return this; + } + + + public IBuildingStage QuickStart(string apiKey) + where T : FormBase + { + _apiKey = apiKey; + _factory = new DefaultStartFormFactory(typeof(T)); + + DefaultMessageLoop(); + + NoProxy(); + + OnlyStart(); + + NoSerialization(); + + DefaultLanguage(); + + return this; + } + + public IBuildingStage QuickStart(string apiKey, IStartFormFactory StartFormFactory) + { + _apiKey = apiKey; + _factory = StartFormFactory; + + DefaultMessageLoop(); + + NoProxy(); + + OnlyStart(); + + NoSerialization(); + + DefaultLanguage(); + + return this; + } + + #endregion + + + #region "Step 2 (Message Loop)" + + public IStartFormSelectionStage DefaultMessageLoop() + { + _messageLoopFactory = new FormBaseMessageLoop(); + + return this; + } + + + public IStartFormSelectionStage MinimalMessageLoop() + { + _messageLoopFactory = new MinimalMessageLoop(); + + return this; + } + + + public IStartFormSelectionStage CustomMessageLoop(IMessageLoopFactory messageLoopClass) + { + _messageLoopFactory = messageLoopClass; + + return this; + } + + public IStartFormSelectionStage CustomMessageLoop() + where T : class, new() + { + _messageLoopFactory = + typeof(T).GetConstructor(new Type[] { })?.Invoke(new object[] { }) as IMessageLoopFactory; + + return this; + } + + #endregion + + + #region "Step 3 (Start Form/Factory)" + + public INetworkingSelectionStage WithStartForm(Type startFormClass) + { + _factory = new DefaultStartFormFactory(startFormClass); + return this; + } + + public INetworkingSelectionStage WithStartForm() + where T : FormBase, new() + { + _factory = new DefaultStartFormFactory(typeof(T)); + return this; + } + + public INetworkingSelectionStage WithServiceProvider(Type startFormClass, IServiceProvider serviceProvider) + { + _factory = new ServiceProviderStartFormFactory(startFormClass, serviceProvider); + return this; + } + + public INetworkingSelectionStage WithServiceProvider(IServiceProvider serviceProvider) + where T : FormBase + { + _factory = new ServiceProviderStartFormFactory(serviceProvider); + return this; + } + + public INetworkingSelectionStage WithStartFormFactory(IStartFormFactory factory) + { + _factory = factory; + return this; + } + + #endregion + + + #region "Step 4 (Network Settings)" + + public IBotCommandsStage WithProxy(string proxyAddress) + { + var url = new Uri(proxyAddress); + _client = new MessageClient(_apiKey, url) + { + TelegramClient = + { + Timeout = new TimeSpan(0, 1, 0) + } + }; + return this; + } + + + public IBotCommandsStage NoProxy() + { + _client = new MessageClient(_apiKey) + { + TelegramClient = + { + Timeout = new TimeSpan(0, 1, 0) + } + }; + return this; + } + + + public IBotCommandsStage WithBotClient(TelegramBotClient tgclient) + { + _client = new MessageClient(_apiKey, tgclient) + { + TelegramClient = + { + Timeout = new TimeSpan(0, 1, 0) + } + }; + return this; + } + + + public IBotCommandsStage WithHostAndPort(string proxyHost, int proxyPort) + { + _client = new MessageClient(_apiKey, proxyHost, proxyPort) + { + TelegramClient = + { + Timeout = new TimeSpan(0, 1, 0) + } + }; + return this; + } + + public IBotCommandsStage WithHttpClient(HttpClient tgclient) + { + _client = new MessageClient(_apiKey, tgclient) + { + TelegramClient = + { + Timeout = new TimeSpan(0, 1, 0) + } + }; + return this; + } + + #endregion + + + #region "Step 5 (Bot Commands)" + + public ISessionSerializationStage NoCommands() + { + return this; + } + + public ISessionSerializationStage OnlyStart() + { + BotCommandScopes.Start("Starts the bot"); + + return this; + } + + public ISessionSerializationStage DefaultCommands() + { + BotCommandScopes.Start("Starts the bot"); + BotCommandScopes.Help("Should show you some help"); + BotCommandScopes.Settings("Should show you some settings"); + return this; + } + + public ISessionSerializationStage CustomCommands(Action>> action) + { + action?.Invoke(BotCommandScopes); + return this; + } + + #endregion + + + #region "Step 6 (Serialization)" + + public ILanguageSelectionStage NoSerialization() + { + return this; + } + + public ILanguageSelectionStage UseSerialization(IStateMachine machine) + { + _statemachine = machine; + return this; + } + + + public ILanguageSelectionStage UseJSON(string path) + { + _statemachine = new JsonStateMachine(path); + return this; + } + + public ILanguageSelectionStage UseSimpleJSON(string path) + { + _statemachine = new SimpleJsonStateMachine(path); + return this; + } + + public ILanguageSelectionStage UseXML(string path) + { + _statemachine = new XmlStateMachine(path); + return this; + } + + #endregion + + + #region "Step 7 (Language)" + + public IBuildingStage DefaultLanguage() + { + return this; + } + + public IBuildingStage UseEnglish() + { + Default.Language = new English(); + return this; + } + + public IBuildingStage UseGerman() + { + Default.Language = new German(); + return this; + } + + public IBuildingStage Custom(Localization language) + { + Default.Language = language; + return this; + } + + #endregion +} \ No newline at end of file diff --git a/TelegramBotBase/Builder/Interfaces/IAPIKeySelectionStage.cs b/TelegramBotBase/Builder/Interfaces/IAPIKeySelectionStage.cs index 44a1bb8..bcbe23b 100644 --- a/TelegramBotBase/Builder/Interfaces/IAPIKeySelectionStage.cs +++ b/TelegramBotBase/Builder/Interfaces/IAPIKeySelectionStage.cs @@ -2,42 +2,41 @@ using TelegramBotBase.Form; using TelegramBotBase.Interfaces; -namespace TelegramBotBase.Builder.Interfaces +namespace TelegramBotBase.Builder.Interfaces; + +public interface IAPIKeySelectionStage { - public interface IAPIKeySelectionStage - { - /// - /// Sets the API Key which will be used by the telegram bot client. - /// - /// - /// - IMessageLoopSelectionStage WithAPIKey(string apiKey); + /// + /// Sets the API Key which will be used by the telegram bot client. + /// + /// + /// + IMessageLoopSelectionStage WithAPIKey(string apiKey); - /// - /// Quick and easy way to create a BotBase instance. - /// Uses: DefaultMessageLoop, NoProxy, OnlyStart, NoSerialization, DefaultLanguage - /// - /// - /// - /// - IBuildingStage QuickStart(string apiKey, Type StartForm); + /// + /// Quick and easy way to create a BotBase instance. + /// Uses: DefaultMessageLoop, NoProxy, OnlyStart, NoSerialization, DefaultLanguage + /// + /// + /// + /// + IBuildingStage QuickStart(string apiKey, Type StartForm); - /// - /// Quick and easy way to create a BotBase instance. - /// Uses: DefaultMessageLoop, NoProxy, OnlyStart, NoSerialization, DefaultLanguage - /// - /// - /// - IBuildingStage QuickStart(string apiKey) where T : FormBase; + /// + /// Quick and easy way to create a BotBase instance. + /// Uses: DefaultMessageLoop, NoProxy, OnlyStart, NoSerialization, DefaultLanguage + /// + /// + /// + IBuildingStage QuickStart(string apiKey) where T : FormBase; - /// - /// Quick and easy way to create a BotBase instance. - /// Uses: DefaultMessageLoop, NoProxy, OnlyStart, NoSerialization, DefaultLanguage - /// - /// - /// - /// - IBuildingStage QuickStart(string apiKey, IStartFormFactory StartFormFactory); - } -} + /// + /// Quick and easy way to create a BotBase instance. + /// Uses: DefaultMessageLoop, NoProxy, OnlyStart, NoSerialization, DefaultLanguage + /// + /// + /// + /// + IBuildingStage QuickStart(string apiKey, IStartFormFactory StartFormFactory); +} \ No newline at end of file diff --git a/TelegramBotBase/Builder/Interfaces/IBotCommandsStage.cs b/TelegramBotBase/Builder/Interfaces/IBotCommandsStage.cs index 2b83453..510db3b 100644 --- a/TelegramBotBase/Builder/Interfaces/IBotCommandsStage.cs +++ b/TelegramBotBase/Builder/Interfaces/IBotCommandsStage.cs @@ -2,39 +2,35 @@ using System.Collections.Generic; using Telegram.Bot.Types; -namespace TelegramBotBase.Builder.Interfaces +namespace TelegramBotBase.Builder.Interfaces; + +public interface IBotCommandsStage { - public interface IBotCommandsStage - { - /// - /// Does not create any commands. - /// - /// - ISessionSerializationStage NoCommands(); + /// + /// Does not create any commands. + /// + /// + ISessionSerializationStage NoCommands(); - /// - /// Creates default commands for start, help and settings. - /// - /// - ISessionSerializationStage DefaultCommands(); + /// + /// Creates default commands for start, help and settings. + /// + /// + ISessionSerializationStage DefaultCommands(); - /// - /// Only adds the start command. - /// - /// - ISessionSerializationStage OnlyStart(); + /// + /// Only adds the start command. + /// + /// + ISessionSerializationStage OnlyStart(); - /// - /// Gives you the ability to add custom commands. - /// - /// - /// - - ISessionSerializationStage CustomCommands(Action>> action); - - - } -} + /// + /// Gives you the ability to add custom commands. + /// + /// + /// + ISessionSerializationStage CustomCommands(Action>> action); +} \ No newline at end of file diff --git a/TelegramBotBase/Builder/Interfaces/IBuildingStage.cs b/TelegramBotBase/Builder/Interfaces/IBuildingStage.cs index d5b70df..17e49cc 100644 --- a/TelegramBotBase/Builder/Interfaces/IBuildingStage.cs +++ b/TelegramBotBase/Builder/Interfaces/IBuildingStage.cs @@ -1,7 +1,6 @@ -namespace TelegramBotBase.Builder.Interfaces +namespace TelegramBotBase.Builder.Interfaces; + +public interface IBuildingStage { - public interface IBuildingStage - { - BotBase Build(); - } -} + BotBase Build(); +} \ No newline at end of file diff --git a/TelegramBotBase/Builder/Interfaces/ILanguageSelectionStage.cs b/TelegramBotBase/Builder/Interfaces/ILanguageSelectionStage.cs index b7bbd28..e32f710 100644 --- a/TelegramBotBase/Builder/Interfaces/ILanguageSelectionStage.cs +++ b/TelegramBotBase/Builder/Interfaces/ILanguageSelectionStage.cs @@ -1,33 +1,30 @@ using TelegramBotBase.Localizations; -namespace TelegramBotBase.Builder.Interfaces +namespace TelegramBotBase.Builder.Interfaces; + +public interface ILanguageSelectionStage { - public interface ILanguageSelectionStage - { + /// + /// Selects the default language for control usage. (English) + /// + /// + IBuildingStage DefaultLanguage(); - /// - /// Selects the default language for control usage. (English) - /// - /// - IBuildingStage DefaultLanguage(); + /// + /// Selects english as the default language for control labels. + /// + /// + IBuildingStage UseEnglish(); - /// - /// Selects english as the default language for control labels. - /// - /// - IBuildingStage UseEnglish(); + /// + /// Selects german as the default language for control labels. + /// + /// + IBuildingStage UseGerman(); - /// - /// Selects german as the default language for control labels. - /// - /// - IBuildingStage UseGerman(); - - /// - /// Selects a custom language as the default language for control labels. - /// - /// - IBuildingStage Custom(Localization language); - - } -} + /// + /// Selects a custom language as the default language for control labels. + /// + /// + IBuildingStage Custom(Localization language); +} \ No newline at end of file diff --git a/TelegramBotBase/Builder/Interfaces/IMessageLoopSelectionStage.cs b/TelegramBotBase/Builder/Interfaces/IMessageLoopSelectionStage.cs index b9a8df0..21223e7 100644 --- a/TelegramBotBase/Builder/Interfaces/IMessageLoopSelectionStage.cs +++ b/TelegramBotBase/Builder/Interfaces/IMessageLoopSelectionStage.cs @@ -1,40 +1,36 @@ using TelegramBotBase.Interfaces; -namespace TelegramBotBase.Builder.Interfaces +namespace TelegramBotBase.Builder.Interfaces; + +public interface IMessageLoopSelectionStage { - public interface IMessageLoopSelectionStage - { - - /// - /// Chooses a default message loop. - /// - /// - /// - IStartFormSelectionStage DefaultMessageLoop(); + /// + /// Chooses a default message loop. + /// + /// + /// + IStartFormSelectionStage DefaultMessageLoop(); - /// - /// Chooses a minimalistic message loop, which catches all update types and only calls the Load function. - /// - /// - IStartFormSelectionStage MinimalMessageLoop(); + /// + /// Chooses a minimalistic message loop, which catches all update types and only calls the Load function. + /// + /// + IStartFormSelectionStage MinimalMessageLoop(); - /// - /// Chooses a custom message loop. - /// - /// - /// - IStartFormSelectionStage CustomMessageLoop(IMessageLoopFactory startFormClass); + /// + /// Chooses a custom message loop. + /// + /// + /// + IStartFormSelectionStage CustomMessageLoop(IMessageLoopFactory startFormClass); - /// - /// Chooses a custom message loop. - /// - /// - /// - IStartFormSelectionStage CustomMessageLoop() where T : class, new(); - - - } -} + /// + /// Chooses a custom message loop. + /// + /// + /// + IStartFormSelectionStage CustomMessageLoop() where T : class, new(); +} \ No newline at end of file diff --git a/TelegramBotBase/Builder/Interfaces/INetworkingSelectionStage.cs b/TelegramBotBase/Builder/Interfaces/INetworkingSelectionStage.cs index a7b0d8e..3e48b21 100644 --- a/TelegramBotBase/Builder/Interfaces/INetworkingSelectionStage.cs +++ b/TelegramBotBase/Builder/Interfaces/INetworkingSelectionStage.cs @@ -1,48 +1,44 @@ using System.Net.Http; using Telegram.Bot; -namespace TelegramBotBase.Builder.Interfaces +namespace TelegramBotBase.Builder.Interfaces; + +public interface INetworkingSelectionStage { - public interface INetworkingSelectionStage - { + /// + /// Chooses a proxy as network configuration. + /// + /// + /// + IBotCommandsStage WithProxy(string proxyAddress); - /// - /// Chooses a proxy as network configuration. - /// - /// - /// - IBotCommandsStage WithProxy(string proxyAddress); - - /// - /// Do not choose a proxy as network configuration. - /// - /// - IBotCommandsStage NoProxy(); + /// + /// Do not choose a proxy as network configuration. + /// + /// + IBotCommandsStage NoProxy(); - /// - /// Chooses a custom instance of TelegramBotClient. - /// - /// - /// - IBotCommandsStage WithBotClient(TelegramBotClient client); + /// + /// Chooses a custom instance of TelegramBotClient. + /// + /// + /// + IBotCommandsStage WithBotClient(TelegramBotClient client); - /// - /// Sets the custom proxy host and port. - /// - /// - /// - /// - IBotCommandsStage WithHostAndPort(string proxyHost, int Port); + /// + /// Sets the custom proxy host and port. + /// + /// + /// + /// + IBotCommandsStage WithHostAndPort(string proxyHost, int Port); - /// - /// Uses a custom http client. - /// - /// - /// - IBotCommandsStage WithHttpClient(HttpClient client); - - - } -} + /// + /// Uses a custom http client. + /// + /// + /// + IBotCommandsStage WithHttpClient(HttpClient client); +} \ No newline at end of file diff --git a/TelegramBotBase/Builder/Interfaces/ISessionSerializationStage.cs b/TelegramBotBase/Builder/Interfaces/ISessionSerializationStage.cs index 9adc70f..5ed022b 100644 --- a/TelegramBotBase/Builder/Interfaces/ISessionSerializationStage.cs +++ b/TelegramBotBase/Builder/Interfaces/ISessionSerializationStage.cs @@ -1,46 +1,44 @@ using TelegramBotBase.Interfaces; -namespace TelegramBotBase.Builder.Interfaces +namespace TelegramBotBase.Builder.Interfaces; + +public interface ISessionSerializationStage { - public interface ISessionSerializationStage - { - /// - /// Do not uses serialization. - /// - /// - ILanguageSelectionStage NoSerialization(); + /// + /// Do not uses serialization. + /// + /// + ILanguageSelectionStage NoSerialization(); - /// - /// Sets the state machine for serialization. - /// - /// - /// - ILanguageSelectionStage UseSerialization(IStateMachine machine); + /// + /// Sets the state machine for serialization. + /// + /// + /// + ILanguageSelectionStage UseSerialization(IStateMachine machine); - /// - /// Using the complex version of .Net JSON, which can serialize all objects. - /// - /// - /// - ILanguageSelectionStage UseJSON(string path); + /// + /// Using the complex version of .Net JSON, which can serialize all objects. + /// + /// + /// + ILanguageSelectionStage UseJSON(string path); - /// - /// Use the easy version of .Net JSON, which can serialize basic types, but not generics and others. - /// - /// - /// - ILanguageSelectionStage UseSimpleJSON(string path); + /// + /// Use the easy version of .Net JSON, which can serialize basic types, but not generics and others. + /// + /// + /// + ILanguageSelectionStage UseSimpleJSON(string path); - /// - /// Uses the XML serializer for session serialization. - /// - /// - /// - ILanguageSelectionStage UseXML(string path); - - } -} + /// + /// Uses the XML serializer for session serialization. + /// + /// + /// + ILanguageSelectionStage UseXML(string path); +} \ No newline at end of file diff --git a/TelegramBotBase/Builder/Interfaces/IStartFormSelectionStage.cs b/TelegramBotBase/Builder/Interfaces/IStartFormSelectionStage.cs index 52c1890..1254693 100644 --- a/TelegramBotBase/Builder/Interfaces/IStartFormSelectionStage.cs +++ b/TelegramBotBase/Builder/Interfaces/IStartFormSelectionStage.cs @@ -2,47 +2,44 @@ using TelegramBotBase.Form; using TelegramBotBase.Interfaces; -namespace TelegramBotBase.Builder.Interfaces +namespace TelegramBotBase.Builder.Interfaces; + +public interface IStartFormSelectionStage { - public interface IStartFormSelectionStage - { + /// + /// Chooses a start form type which will be used for new sessions. + /// + /// + /// + INetworkingSelectionStage WithStartForm(Type startFormClass); - /// - /// Chooses a start form type which will be used for new sessions. - /// - /// - /// - INetworkingSelectionStage WithStartForm(Type startFormClass); + /// + /// Chooses a generic start form which will be used for new sessions. + /// + /// + /// + INetworkingSelectionStage WithStartForm() where T : FormBase, new(); - /// - /// Chooses a generic start form which will be used for new sessions. - /// - /// - /// - INetworkingSelectionStage WithStartForm() where T : FormBase, new(); + /// + /// Chooses a StartFormFactory which will be use for new sessions. + /// + /// + /// + /// + INetworkingSelectionStage WithServiceProvider(Type startFormClass, IServiceProvider serviceProvider); - /// - /// Chooses a StartFormFactory which will be use for new sessions. - /// - /// - /// - /// - INetworkingSelectionStage WithServiceProvider(Type startFormClass, IServiceProvider serviceProvider); + /// + /// Chooses a StartFormFactory which will be use for new sessions. + /// + /// + /// + /// + INetworkingSelectionStage WithServiceProvider(IServiceProvider serviceProvider) where T : FormBase; - /// - /// Chooses a StartFormFactory which will be use for new sessions. - /// - /// - /// - /// - INetworkingSelectionStage WithServiceProvider(IServiceProvider serviceProvider) where T : FormBase; - - /// - /// Chooses a StartFormFactory which will be use for new sessions. - /// - /// - /// - INetworkingSelectionStage WithStartFormFactory(IStartFormFactory factory); - - } -} + /// + /// Chooses a StartFormFactory which will be use for new sessions. + /// + /// + /// + INetworkingSelectionStage WithStartFormFactory(IStartFormFactory factory); +} \ No newline at end of file diff --git a/TelegramBotBase/Commands/Extensions.cs b/TelegramBotBase/Commands/Extensions.cs index 55721b8..6a19ce1 100644 --- a/TelegramBotBase/Commands/Extensions.cs +++ b/TelegramBotBase/Commands/Extensions.cs @@ -2,141 +2,181 @@ using System.Linq; using Telegram.Bot.Types; -namespace TelegramBotBase.Commands +namespace TelegramBotBase.Commands; + +public static class Extensions { - public static class Extensions + /// + /// Adding the command with a description. + /// + /// + /// + /// + public static void Add(this Dictionary> cmds, string command, + string description, BotCommandScope scope = null) { - /// - /// Adding the command with a description. - /// - /// - /// - /// - public static void Add(this Dictionary> cmds, string command, string description, BotCommandScope scope = null) + if (scope == null) { - if (scope == null) - { - scope = BotCommandScope.Default(); - } - - var item = cmds.FirstOrDefault(a => a.Key.Type == scope.Type); - - if (item.Value != null) - { - item.Value.Add(new BotCommand { Command = command, Description = description }); - } - else - { - cmds.Add(scope, new List { new BotCommand { Command = command, Description = description } }); - } + scope = BotCommandScope.Default(); } - /// - /// Adding the command with a description. - /// - /// - /// - /// - public static void Clear(this Dictionary> cmds, BotCommandScope scope = null) + var item = cmds.FirstOrDefault(a => a.Key.Type == scope.Type); + + if (item.Value != null) { - if (scope == null) - { - scope = BotCommandScope.Default(); - } - - var item = cmds.FirstOrDefault(a => a.Key.Type == scope.Type); - - if (item.Key != null) - { - cmds[item.Key] = null; - } - else - { - cmds[scope] = null; - } + item.Value.Add(new BotCommand { Command = command, Description = description }); + } + else + { + cmds.Add(scope, new List { new() { Command = command, Description = description } }); } - - /// - /// Adding the default /start command with a description. - /// - /// - /// - public static void Start(this Dictionary> cmds, string description) => Add(cmds, "start", description); - - /// - /// Adding the default /help command with a description. - /// - /// - /// - public static void Help(this Dictionary> cmds, string description) => Add(cmds, "help", description); - - /// - /// Adding the default /settings command with a description. - /// - /// - /// - public static void Settings(this Dictionary> cmds, string description) => Add(cmds, "settings", description); - - /// - /// Clears all default commands. - /// - /// - public static void ClearDefaultCommands(this Dictionary> cmds) => Clear(cmds); - - /// - /// Clears all commands of a specific device. - /// - /// - public static void ClearChatCommands(this Dictionary> cmds, long deviceId) => Clear(cmds, new BotCommandScopeChat { ChatId = deviceId }); - - /// - /// Adding a chat command with a description. - /// - /// - /// - /// - public static void AddChatCommand(this Dictionary> cmds, long deviceId, string command, string description) => Add(cmds, command, description, new BotCommandScopeChat { ChatId = deviceId }); - - /// - /// Adding a group command with a description. - /// - /// - /// - /// - public static void AddGroupCommand(this Dictionary> cmds, string command, string description) => Add(cmds, command, description, new BotCommandScopeAllGroupChats()); - - /// - /// Clears all group commands. - /// - /// - public static void ClearGroupCommands(this Dictionary> cmds) => Clear(cmds, new BotCommandScopeAllGroupChats()); - - /// - /// Adding group admin command with a description. - /// - /// - /// - /// - public static void AddGroupAdminCommand(this Dictionary> cmds, string command, string description) => Add(cmds, command, description, new BotCommandScopeAllChatAdministrators()); - - /// - /// Clears all group admin commands. - /// - /// - public static void ClearGroupAdminCommand(this Dictionary> cmds) => Clear(cmds, new BotCommandScopeAllChatAdministrators()); - - /// - /// Adding a privat command with a description. - /// - /// - /// - /// - public static void AddPrivateChatCommand(this Dictionary> cmds, string command, string description) => Add(cmds, command, description, new BotCommandScopeAllPrivateChats()); - - /// - /// Clears all private commands. - /// - /// - public static void ClearPrivateChatCommand(this Dictionary> cmds) => Clear(cmds, new BotCommandScopeAllPrivateChats()); } -} + + /// + /// Adding the command with a description. + /// + /// + /// + /// + public static void Clear(this Dictionary> cmds, BotCommandScope scope = null) + { + if (scope == null) + { + scope = BotCommandScope.Default(); + } + + var item = cmds.FirstOrDefault(a => a.Key.Type == scope.Type); + + if (item.Key != null) + { + cmds[item.Key] = null; + } + else + { + cmds[scope] = null; + } + } + + /// + /// Adding the default /start command with a description. + /// + /// + /// + public static void Start(this Dictionary> cmds, string description) + { + Add(cmds, "start", description); + } + + /// + /// Adding the default /help command with a description. + /// + /// + /// + public static void Help(this Dictionary> cmds, string description) + { + Add(cmds, "help", description); + } + + /// + /// Adding the default /settings command with a description. + /// + /// + /// + public static void Settings(this Dictionary> cmds, string description) + { + Add(cmds, "settings", description); + } + + /// + /// Clears all default commands. + /// + /// + public static void ClearDefaultCommands(this Dictionary> cmds) + { + Clear(cmds); + } + + /// + /// Clears all commands of a specific device. + /// + /// + public static void ClearChatCommands(this Dictionary> cmds, long deviceId) + { + Clear(cmds, new BotCommandScopeChat { ChatId = deviceId }); + } + + /// + /// Adding a chat command with a description. + /// + /// + /// + /// + public static void AddChatCommand(this Dictionary> cmds, long deviceId, + string command, string description) + { + Add(cmds, command, description, new BotCommandScopeChat { ChatId = deviceId }); + } + + /// + /// Adding a group command with a description. + /// + /// + /// + /// + public static void AddGroupCommand(this Dictionary> cmds, string command, + string description) + { + Add(cmds, command, description, new BotCommandScopeAllGroupChats()); + } + + /// + /// Clears all group commands. + /// + /// + public static void ClearGroupCommands(this Dictionary> cmds) + { + Clear(cmds, new BotCommandScopeAllGroupChats()); + } + + /// + /// Adding group admin command with a description. + /// + /// + /// + /// + public static void AddGroupAdminCommand(this Dictionary> cmds, string command, + string description) + { + Add(cmds, command, description, new BotCommandScopeAllChatAdministrators()); + } + + /// + /// Clears all group admin commands. + /// + /// + public static void ClearGroupAdminCommand(this Dictionary> cmds) + { + Clear(cmds, new BotCommandScopeAllChatAdministrators()); + } + + /// + /// Adding a privat command with a description. + /// + /// + /// + /// + public static void AddPrivateChatCommand(this Dictionary> cmds, + string command, string description) + { + Add(cmds, command, description, new BotCommandScopeAllPrivateChats()); + } + + /// + /// Clears all private commands. + /// + /// + public static void ClearPrivateChatCommand(this Dictionary> cmds) + { + Clear(cmds, new BotCommandScopeAllPrivateChats()); + } +} \ No newline at end of file diff --git a/TelegramBotBase/Constants/Telegram.cs b/TelegramBotBase/Constants/Telegram.cs index a669022..a2837d7 100644 --- a/TelegramBotBase/Constants/Telegram.cs +++ b/TelegramBotBase/Constants/Telegram.cs @@ -1,21 +1,19 @@ -namespace TelegramBotBase.Constants +namespace TelegramBotBase.Constants; + +public static class Telegram { - public static class Telegram - { - /// - /// The maximum length of message text before the API throws an exception. (We will catch it before) - /// - public const int MaxMessageLength = 4096; + /// + /// The maximum length of message text before the API throws an exception. (We will catch it before) + /// + public const int MaxMessageLength = 4096; - public const int MaxInlineKeyBoardRows = 13; + public const int MaxInlineKeyBoardRows = 13; - public const int MaxInlineKeyBoardCols = 8; + public const int MaxInlineKeyBoardCols = 8; - public const int MaxReplyKeyboardRows = 25; + public const int MaxReplyKeyboardRows = 25; - public const int MaxReplyKeyboardCols = 12; + public const int MaxReplyKeyboardCols = 12; - public const int MessageDeletionsPerSecond = 30; - - } -} + public const int MessageDeletionsPerSecond = 30; +} \ No newline at end of file diff --git a/TelegramBotBase/Controls/Hybrid/ButtonGrid.cs b/TelegramBotBase/Controls/Hybrid/ButtonGrid.cs index f8662b2..e2871d9 100644 --- a/TelegramBotBase/Controls/Hybrid/ButtonGrid.cs +++ b/TelegramBotBase/Controls/Hybrid/ButtonGrid.cs @@ -15,208 +15,339 @@ using TelegramBotBase.Form; using TelegramBotBase.Localizations; using static TelegramBotBase.Base.Async; -namespace TelegramBotBase.Controls.Hybrid +namespace TelegramBotBase.Controls.Hybrid; + +public class ButtonGrid : ControlBase { - public class ButtonGrid : ControlBase + private static readonly object EvButtonClicked = new(); + + private readonly EventHandlerList _events = new(); + + private EKeyboardType _mEKeyboardType = EKeyboardType.ReplyKeyboard; + + private bool _renderNecessary = true; + + public string NextPageLabel = Default.Language["ButtonGrid_NextPage"]; + + public string NoItemsLabel = Default.Language["ButtonGrid_NoItems"]; + + public string PreviousPageLabel = Default.Language["ButtonGrid_PreviousPage"]; + + public string SearchLabel = Default.Language["ButtonGrid_SearchFeature"]; + + public ButtonGrid() { + DataSource = new ButtonFormDataSource(); + } - public string Title { get; set; } = Default.Language["ButtonGrid_Title"]; + public ButtonGrid(EKeyboardType type) : this() + { + _mEKeyboardType = type; + } - public string ConfirmationText { get; set; } = ""; - private bool _renderNecessary = true; + public ButtonGrid(ButtonForm form) + { + DataSource = new ButtonFormDataSource(form); + } - private static readonly object EvButtonClicked = new object(); + public string Title { get; set; } = Default.Language["ButtonGrid_Title"]; - private readonly EventHandlerList _events = new EventHandlerList(); + public string ConfirmationText { get; set; } = ""; - /// - /// - /// - [Obsolete("This property is obsolete. Please use the DataSource property instead.")] - public ButtonForm ButtonsForm + /// + /// + [Obsolete("This property is obsolete. Please use the DataSource property instead.")] + public ButtonForm ButtonsForm + { + get => DataSource.ButtonForm; + set => DataSource = new ButtonFormDataSource(value); + } + + /// + /// Data source of the items. + /// + public ButtonFormDataSource DataSource { get; set; } + + public int? MessageId { get; set; } + + + /// + /// Optional. Requests clients to resize the keyboard vertically for optimal fit (e.g., make the keyboard smaller if + /// there are just two rows of buttons). Defaults to false, in which case the custom keyboard is always of the same + /// height as the app's standard keyboard. + /// Source: https://core.telegram.org/bots/api#replykeyboardmarkup + /// + public bool ResizeKeyboard { get; set; } = false; + + public bool OneTimeKeyboard { get; set; } = false; + + public bool HideKeyboardOnCleanup { get; set; } = true; + + public bool DeletePreviousMessage { get; set; } = true; + + /// + /// Removes the reply message from a user. + /// + public bool DeleteReplyMessage { get; set; } = true; + + /// + /// Parsemode of the message. + /// + public ParseMode MessageParseMode { get; set; } = ParseMode.Markdown; + + /// + /// Enables automatic paging of buttons when the amount of rows is exceeding the limits. + /// + public bool EnablePaging { get; set; } = false; + + + /// + /// Enabled a search function. + /// + public bool EnableSearch { get; set; } = false; + + public string SearchQuery { get; set; } + + public ENavigationBarVisibility NavigationBarVisibility { get; set; } = ENavigationBarVisibility.always; + + + /// + /// Index of the current page + /// + public int CurrentPageIndex { get; set; } + + /// + /// Layout of the buttons which should be displayed always on top. + /// + public ButtonRow HeadLayoutButtonRow { get; set; } + + /// + /// Layout of columns which should be displayed below the header + /// + public ButtonRow SubHeadLayoutButtonRow { get; set; } + + /// + /// Defines which type of Button Keyboard should be rendered. + /// + public EKeyboardType KeyboardType + { + get => _mEKeyboardType; + set { - get => DataSource.ButtonForm; - set => DataSource = new ButtonFormDataSource(value); - } - - /// - /// Data source of the items. - /// - public ButtonFormDataSource DataSource { get; set; } - - public int? MessageId { get; set; } - - - /// - /// Optional. Requests clients to resize the keyboard vertically for optimal fit (e.g., make the keyboard smaller if there are just two rows of buttons). Defaults to false, in which case the custom keyboard is always of the same height as the app's standard keyboard. - /// Source: https://core.telegram.org/bots/api#replykeyboardmarkup - /// - public bool ResizeKeyboard { get; set; } = false; - - public bool OneTimeKeyboard { get; set; } = false; - - public bool HideKeyboardOnCleanup { get; set; } = true; - - public bool DeletePreviousMessage { get; set; } = true; - - /// - /// Removes the reply message from a user. - /// - public bool DeleteReplyMessage { get; set; } = true; - - /// - /// Parsemode of the message. - /// - public ParseMode MessageParseMode { get; set; } = ParseMode.Markdown; - - /// - /// Enables automatic paging of buttons when the amount of rows is exceeding the limits. - /// - public bool EnablePaging { get; set; } = false; - - - /// - /// Enabled a search function. - /// - public bool EnableSearch { get; set; } = false; - - public string SearchQuery { get; set; } - - public ENavigationBarVisibility NavigationBarVisibility { get; set; } = ENavigationBarVisibility.always; - - - /// - /// Index of the current page - /// - public int CurrentPageIndex { get; set; } - - public string PreviousPageLabel = Default.Language["ButtonGrid_PreviousPage"]; - - public string NextPageLabel = Default.Language["ButtonGrid_NextPage"]; - - public string NoItemsLabel = Default.Language["ButtonGrid_NoItems"]; - - public string SearchLabel = Default.Language["ButtonGrid_SearchFeature"]; - - /// - /// Layout of the buttons which should be displayed always on top. - /// - public ButtonRow HeadLayoutButtonRow { get; set; } - - /// - /// Layout of columns which should be displayed below the header - /// - public ButtonRow SubHeadLayoutButtonRow { get; set; } - - /// - /// Defines which type of Button Keyboard should be rendered. - /// - public EKeyboardType KeyboardType - { - get => _mEKeyboardType; - set + if (_mEKeyboardType != value) { - if (_mEKeyboardType != value) - { - _renderNecessary = true; + _renderNecessary = true; - Cleanup().Wait(); - - _mEKeyboardType = value; - } + Cleanup().Wait(); + _mEKeyboardType = value; } } + } - private EKeyboardType _mEKeyboardType = EKeyboardType.ReplyKeyboard; - - public ButtonGrid() + public bool PagingNecessary + { + get { - DataSource = new ButtonFormDataSource(); - - } - - public ButtonGrid(EKeyboardType type) : this() - { - _mEKeyboardType = type; - } - - - public ButtonGrid(ButtonForm form) - { - DataSource = new ButtonFormDataSource(form); - } - - - public event AsyncEventHandler ButtonClicked - { - add => _events.AddHandler(EvButtonClicked, value); - remove => _events.RemoveHandler(EvButtonClicked, value); - } - - public async Task OnButtonClicked(ButtonClickedEventArgs e) - { - var handler = _events[EvButtonClicked]?.GetInvocationList().Cast>(); - if (handler == null) - return; - - foreach (var h in handler) + if (KeyboardType == EKeyboardType.InlineKeyBoard && + TotalRows > Constants.Telegram.MaxInlineKeyBoardRows) { - await h.InvokeAllAsync(this, e); - } - } - - public override void Init() - { - Device.MessageDeleted += Device_MessageDeleted; - } - - private void Device_MessageDeleted(object sender, MessageDeletedEventArgs e) - { - if (MessageId == null) - return; - - if (e.MessageId != MessageId) - return; - - MessageId = null; - } - - public override async Task Load(MessageResult result) - { - if (KeyboardType != EKeyboardType.ReplyKeyboard) - return; - - if (!result.IsFirstHandler) - return; - - if (result.MessageText == null || result.MessageText == "") - return; - - var matches = new List(); - ButtonRow match = null; - var index = -1; - - if (HeadLayoutButtonRow?.Matches(result.MessageText) ?? false) - { - match = HeadLayoutButtonRow; - goto check; + return true; } - if (SubHeadLayoutButtonRow?.Matches(result.MessageText) ?? false) + if (KeyboardType == EKeyboardType.ReplyKeyboard && + TotalRows > Constants.Telegram.MaxReplyKeyboardRows) { - match = SubHeadLayoutButtonRow; - goto check; + return true; } - var br = DataSource.FindRow(result.MessageText); - if (br != null) + return false; + } + } + + public bool IsNavigationBarVisible + { + get + { + if ((NavigationBarVisibility == ENavigationBarVisibility.always) | + (NavigationBarVisibility == ENavigationBarVisibility.auto && PagingNecessary)) { - match = br.Item1; - index = br.Item2; + return true; } + return false; + } + } + + /// + /// Returns the maximum number of rows + /// + public int MaximumRow + { + get + { + return KeyboardType switch + { + EKeyboardType.InlineKeyBoard => Constants.Telegram.MaxInlineKeyBoardRows, + EKeyboardType.ReplyKeyboard => Constants.Telegram.MaxReplyKeyboardRows, + _ => 0 + }; + } + } + + /// + /// Returns the number of all rows (layout + navigation + content); + /// + public int TotalRows => LayoutRows + DataSource.RowCount; + + + /// + /// Contains the Number of Rows which are used by the layout. + /// + private int LayoutRows + { + get + { + var layoutRows = 0; + + if ((NavigationBarVisibility == ENavigationBarVisibility.always) | + (NavigationBarVisibility == ENavigationBarVisibility.auto)) + { + layoutRows += 2; + } + + if (HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0) + { + layoutRows++; + } + + if (SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0) + { + layoutRows++; + } + + return layoutRows; + } + } + + /// + /// Returns the number of item rows per page. + /// + public int ItemRowsPerPage => MaximumRow - LayoutRows; + + /// + /// Return the number of pages. + /// + public int PageCount + { + get + { + if (DataSource.RowCount == 0) + { + return 1; + } + + //var bf = this.DataSource.PickAllItems(this.EnableSearch ? this.SearchQuery : null); + + var max = DataSource.CalculateMax(EnableSearch ? SearchQuery : null); + + //if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "") + //{ + // bf = bf.FilterDuplicate(this.SearchQuery); + //} + + if (max == 0) + { + return 1; + } + + return (int)Math.Ceiling(max / (decimal)ItemRowsPerPage); + } + } + + + public event AsyncEventHandler ButtonClicked + { + add => _events.AddHandler(EvButtonClicked, value); + remove => _events.RemoveHandler(EvButtonClicked, value); + } + + public async Task OnButtonClicked(ButtonClickedEventArgs e) + { + var handler = _events[EvButtonClicked]?.GetInvocationList() + .Cast>(); + if (handler == null) + { + return; + } + + foreach (var h in handler) + { + await h.InvokeAllAsync(this, e); + } + } + + public override void Init() + { + Device.MessageDeleted += Device_MessageDeleted; + } + + private void Device_MessageDeleted(object sender, MessageDeletedEventArgs e) + { + if (MessageId == null) + { + return; + } + + if (e.MessageId != MessageId) + { + return; + } + + MessageId = null; + } + + public override async Task Load(MessageResult result) + { + if (KeyboardType != EKeyboardType.ReplyKeyboard) + { + return; + } + + if (!result.IsFirstHandler) + { + return; + } + + if (result.MessageText == null || result.MessageText == "") + { + return; + } + + var matches = new List(); + ButtonRow match = null; + var index = -1; + + if (HeadLayoutButtonRow?.Matches(result.MessageText) ?? false) + { + match = HeadLayoutButtonRow; + goto check; + } + + if (SubHeadLayoutButtonRow?.Matches(result.MessageText) ?? false) + { + match = SubHeadLayoutButtonRow; + goto check; + } + + var br = DataSource.FindRow(result.MessageText); + if (br != null) + { + match = br.Item1; + index = br.Item2; + } + //var button = HeadLayoutButtonRow?. .FirstOrDefault(a => a.Text.Trim() == result.MessageText) // ?? SubHeadLayoutButtonRow?.FirstOrDefault(a => a.Text.Trim() == result.MessageText); @@ -227,98 +358,106 @@ namespace TelegramBotBase.Controls.Hybrid check: - //Remove button click message - if (DeleteReplyMessage) - await Device.DeleteMessage(result.MessageId); - - if (match != null) - { - await OnButtonClicked(new ButtonClickedEventArgs(match.GetButtonMatch(result.MessageText), index, match)); - - result.Handled = true; - return; - } - - - if (result.MessageText == PreviousPageLabel) - { - if (CurrentPageIndex > 0) - CurrentPageIndex--; - - Updated(); - } - else if (result.MessageText == NextPageLabel) - { - if (CurrentPageIndex < PageCount - 1) - CurrentPageIndex++; - - Updated(); - } - else if (EnableSearch) - { - if (result.MessageText.StartsWith("🔍")) - { - //Sent note about searching - if (SearchQuery == null) - { - await Device.Send(SearchLabel); - } - - SearchQuery = null; - Updated(); - return; - } - - SearchQuery = result.MessageText; - - if (SearchQuery != null && SearchQuery != "") - { - CurrentPageIndex = 0; - Updated(); - } - - } - - - + //Remove button click message + if (DeleteReplyMessage) + { + await Device.DeleteMessage(result.MessageId); } - public override async Task Action(MessageResult result, string value = null) + if (match != null) { - if (result.Handled) - return; + await OnButtonClicked( + new ButtonClickedEventArgs(match.GetButtonMatch(result.MessageText), index, match)); - if (!result.IsFirstHandler) - return; + result.Handled = true; + return; + } - //Find clicked button depending on Text or Value (depending on markup type) - if (KeyboardType != EKeyboardType.InlineKeyBoard) - return; - await result.ConfirmAction(ConfirmationText ?? ""); - - ButtonRow match = null; - var index = -1; - - if (HeadLayoutButtonRow?.Matches(result.RawData, false) ?? false) + if (result.MessageText == PreviousPageLabel) + { + if (CurrentPageIndex > 0) { - match = HeadLayoutButtonRow; - goto check; + CurrentPageIndex--; } - if (SubHeadLayoutButtonRow?.Matches(result.RawData, false) ?? false) + Updated(); + } + else if (result.MessageText == NextPageLabel) + { + if (CurrentPageIndex < PageCount - 1) { - match = SubHeadLayoutButtonRow; - goto check; + CurrentPageIndex++; } - var br = DataSource.FindRow(result.RawData, false); - if (br != null) + Updated(); + } + else if (EnableSearch) + { + if (result.MessageText.StartsWith("🔍")) { - match = br.Item1; - index = br.Item2; + //Sent note about searching + if (SearchQuery == null) + { + await Device.Send(SearchLabel); + } + + SearchQuery = null; + Updated(); + return; } + SearchQuery = result.MessageText; + + if (SearchQuery != null && SearchQuery != "") + { + CurrentPageIndex = 0; + Updated(); + } + } + } + + public override async Task Action(MessageResult result, string value = null) + { + if (result.Handled) + { + return; + } + + if (!result.IsFirstHandler) + { + return; + } + + //Find clicked button depending on Text or Value (depending on markup type) + if (KeyboardType != EKeyboardType.InlineKeyBoard) + { + return; + } + + await result.ConfirmAction(ConfirmationText ?? ""); + + ButtonRow match = null; + var index = -1; + + if (HeadLayoutButtonRow?.Matches(result.RawData, false) ?? false) + { + match = HeadLayoutButtonRow; + goto check; + } + + if (SubHeadLayoutButtonRow?.Matches(result.RawData, false) ?? false) + { + match = SubHeadLayoutButtonRow; + goto check; + } + + var br = DataSource.FindRow(result.RawData, false); + if (br != null) + { + match = br.Item1; + index = br.Item2; + } //var bf = DataSource.ButtonForm; @@ -330,378 +469,281 @@ namespace TelegramBotBase.Controls.Hybrid //var index = bf.FindRowByButton(button); check: - if (match != null) - { - await OnButtonClicked(new ButtonClickedEventArgs(match.GetButtonMatch(result.RawData, false), index, match)); - - result.Handled = true; - return; - } - - switch (result.RawData) - { - case "$previous$": - - if (CurrentPageIndex > 0) - CurrentPageIndex--; - - Updated(); - - break; - case "$next$": - - if (CurrentPageIndex < PageCount - 1) - CurrentPageIndex++; - - Updated(); - - break; - } + if (match != null) + { + await OnButtonClicked(new ButtonClickedEventArgs(match.GetButtonMatch(result.RawData, false), index, + match)); + result.Handled = true; + return; } - /// - /// This method checks of the amount of buttons - /// - private void CheckGrid() + switch (result.RawData) { - switch (_mEKeyboardType) - { - case EKeyboardType.InlineKeyBoard: + case "$previous$": - if (DataSource.RowCount > Constants.Telegram.MaxInlineKeyBoardRows && !EnablePaging) - { - throw new MaximumRowsReachedException { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxInlineKeyBoardRows }; - } - - if (DataSource.ColumnCount > Constants.Telegram.MaxInlineKeyBoardCols) - { - throw new MaximumColsException { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxInlineKeyBoardCols }; - } - - break; - - case EKeyboardType.ReplyKeyboard: - - if (DataSource.RowCount > Constants.Telegram.MaxReplyKeyboardRows && !EnablePaging) - { - throw new MaximumRowsReachedException { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxReplyKeyboardRows }; - } - - if (DataSource.ColumnCount > Constants.Telegram.MaxReplyKeyboardCols) - { - throw new MaximumColsException { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxReplyKeyboardCols }; - } - - break; - } - } - - public override async Task Render(MessageResult result) - { - if (!_renderNecessary) - return; - - //Check for rows and column limits - CheckGrid(); - - _renderNecessary = false; - - var form = DataSource.PickItems(CurrentPageIndex * ItemRowsPerPage, ItemRowsPerPage, (EnableSearch ? SearchQuery : null)); - - - //if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "") - //{ - // form = form.FilterDuplicate(this.SearchQuery, true); - //} - //else - //{ - // form = form.Duplicate(); - //} - - if (EnablePaging) - { - IntegratePagingView(form); - } - - if (HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0) - { - form.InsertButtonRow(0, HeadLayoutButtonRow); - } - - if (SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0) - { - if (IsNavigationBarVisible) + if (CurrentPageIndex > 0) { - form.InsertButtonRow(2, SubHeadLayoutButtonRow); + CurrentPageIndex--; } - else + + Updated(); + + break; + case "$next$": + + if (CurrentPageIndex < PageCount - 1) { - form.InsertButtonRow(1, SubHeadLayoutButtonRow); + CurrentPageIndex++; } - } - Message m = null; + Updated(); - switch (KeyboardType) - { - //Reply Keyboard could only be updated with a new keyboard. - case EKeyboardType.ReplyKeyboard: + break; + } + } + /// + /// This method checks of the amount of buttons + /// + private void CheckGrid() + { + switch (_mEKeyboardType) + { + case EKeyboardType.InlineKeyBoard: - if (form.Count == 0) - { - if (MessageId != null) - { - await Device.HideReplyKeyboard(); - MessageId = null; - } + if (DataSource.RowCount > Constants.Telegram.MaxInlineKeyBoardRows && !EnablePaging) + { + throw new MaximumRowsReachedException + { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxInlineKeyBoardRows }; + } - return; - } + if (DataSource.ColumnCount > Constants.Telegram.MaxInlineKeyBoardCols) + { + throw new MaximumColsException + { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxInlineKeyBoardCols }; + } - //if (this.MessageId != null) - //{ - // if (form.Count == 0) - // { - // await this.Device.HideReplyKeyboard(); - // this.MessageId = null; - // return; - // } - //} + break; - //if (form.Count == 0) - // return; + case EKeyboardType.ReplyKeyboard: + if (DataSource.RowCount > Constants.Telegram.MaxReplyKeyboardRows && !EnablePaging) + { + throw new MaximumRowsReachedException + { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxReplyKeyboardRows }; + } - var rkm = (ReplyKeyboardMarkup)form; - rkm.ResizeKeyboard = ResizeKeyboard; - rkm.OneTimeKeyboard = OneTimeKeyboard; - m = await Device.Send(Title, rkm, disableNotification: true, parseMode: MessageParseMode, markdownV2AutoEscape: false); - - //Prevent flicker of keyboard - if (DeletePreviousMessage && MessageId != null) - await Device.DeleteMessage(MessageId.Value); - - break; - - case EKeyboardType.InlineKeyBoard: - - //Try to edit message if message id is available - //When the returned message is null then the message has been already deleted, resend it - if (MessageId != null) - { - m = await Device.Edit(MessageId.Value, Title, (InlineKeyboardMarkup)form); - if (m != null) - { - MessageId = m.MessageId; - return; - } - } - - //When no message id is available or it has been deleted due the use of AutoCleanForm re-render automatically - m = await Device.Send(Title, (InlineKeyboardMarkup)form, disableNotification: true, parseMode: MessageParseMode, markdownV2AutoEscape: false); - - break; - } - - if (m != null) - { - MessageId = m.MessageId; - } + if (DataSource.ColumnCount > Constants.Telegram.MaxReplyKeyboardCols) + { + throw new MaximumColsException + { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxReplyKeyboardCols }; + } + break; + } + } + public override async Task Render(MessageResult result) + { + if (!_renderNecessary) + { + return; } - private void IntegratePagingView(ButtonForm dataForm) - { - //No Items - if (dataForm.Rows == 0) - { - dataForm.AddButtonRow(new ButtonBase(NoItemsLabel, "$")); - } + //Check for rows and column limits + CheckGrid(); + _renderNecessary = false; + + var form = DataSource.PickItems(CurrentPageIndex * ItemRowsPerPage, ItemRowsPerPage, + EnableSearch ? SearchQuery : null); + + + //if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "") + //{ + // form = form.FilterDuplicate(this.SearchQuery, true); + //} + //else + //{ + // form = form.Duplicate(); + //} + + if (EnablePaging) + { + IntegratePagingView(form); + } + + if (HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0) + { + form.InsertButtonRow(0, HeadLayoutButtonRow); + } + + if (SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0) + { if (IsNavigationBarVisible) { - //🔍 - var row = new ButtonRow(); - row.Add(new ButtonBase(PreviousPageLabel, "$previous$")); - row.Add(new ButtonBase(string.Format(Default.Language["ButtonGrid_CurrentPage"], CurrentPageIndex + 1, PageCount), "$site$")); - row.Add(new ButtonBase(NextPageLabel, "$next$")); - - if (EnableSearch) - { - row.Insert(2, new ButtonBase("🔍 " + (SearchQuery ?? ""), "$search$")); - } - - dataForm.InsertButtonRow(0, row); - - dataForm.AddButtonRow(row); - } - } - - public bool PagingNecessary - { - get - { - if (KeyboardType == EKeyboardType.InlineKeyBoard && TotalRows > Constants.Telegram.MaxInlineKeyBoardRows) - { - return true; - } - - if (KeyboardType == EKeyboardType.ReplyKeyboard && TotalRows > Constants.Telegram.MaxReplyKeyboardRows) - { - return true; - } - - return false; - } - } - - public bool IsNavigationBarVisible - { - get - { - if (NavigationBarVisibility == ENavigationBarVisibility.always | (NavigationBarVisibility == ENavigationBarVisibility.auto && PagingNecessary)) - { - return true; - } - - return false; - } - } - - /// - /// Returns the maximum number of rows - /// - public int MaximumRow - { - get - { - return KeyboardType switch - { - EKeyboardType.InlineKeyBoard => Constants.Telegram.MaxInlineKeyBoardRows, - EKeyboardType.ReplyKeyboard => Constants.Telegram.MaxReplyKeyboardRows, - _ => 0 - }; - } - } - - /// - /// Returns the number of all rows (layout + navigation + content); - /// - public int TotalRows => LayoutRows + DataSource.RowCount; - - - /// - /// Contains the Number of Rows which are used by the layout. - /// - private int LayoutRows - { - get - { - var layoutRows = 0; - - if (NavigationBarVisibility == ENavigationBarVisibility.always | NavigationBarVisibility == ENavigationBarVisibility.auto) - layoutRows += 2; - - if (HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0) - layoutRows++; - - if (SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0) - layoutRows++; - - return layoutRows; - } - } - - /// - /// Returns the number of item rows per page. - /// - public int ItemRowsPerPage => MaximumRow - LayoutRows; - - /// - /// Return the number of pages. - /// - public int PageCount - { - get - { - if (DataSource.RowCount == 0) - return 1; - - //var bf = this.DataSource.PickAllItems(this.EnableSearch ? this.SearchQuery : null); - - var max = DataSource.CalculateMax(EnableSearch ? SearchQuery : null); - - //if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "") - //{ - // bf = bf.FilterDuplicate(this.SearchQuery); - //} - - if (max == 0) - return 1; - - return (int)Math.Ceiling(max / (decimal)ItemRowsPerPage); - } - } - - public override Task Hidden(bool formClose) - { - //Prepare for opening Modal, and comming back - if (!formClose) - { - Updated(); + form.InsertButtonRow(2, SubHeadLayoutButtonRow); } else { - //Remove event handler - Device.MessageDeleted -= Device_MessageDeleted; + form.InsertButtonRow(1, SubHeadLayoutButtonRow); } - - return Task.CompletedTask; } - /// - /// Tells the control that it has been updated. - /// - public void Updated() + Message m = null; + + switch (KeyboardType) { - _renderNecessary = true; - } + //Reply Keyboard could only be updated with a new keyboard. + case EKeyboardType.ReplyKeyboard: - public override async Task Cleanup() - { - if (MessageId == null) - return; - switch (KeyboardType) - { - case EKeyboardType.InlineKeyBoard: - - await Device.DeleteMessage(MessageId.Value); - - MessageId = null; - - break; - case EKeyboardType.ReplyKeyboard: - - if (HideKeyboardOnCleanup) + if (form.Count == 0) + { + if (MessageId != null) { await Device.HideReplyKeyboard(); + MessageId = null; } - MessageId = null; + return; + } - break; - } + //if (this.MessageId != null) + //{ + // if (form.Count == 0) + // { + // await this.Device.HideReplyKeyboard(); + // this.MessageId = null; + // return; + // } + //} + + //if (form.Count == 0) + // return; + var rkm = (ReplyKeyboardMarkup)form; + rkm.ResizeKeyboard = ResizeKeyboard; + rkm.OneTimeKeyboard = OneTimeKeyboard; + m = await Device.Send(Title, rkm, disableNotification: true, parseMode: MessageParseMode, + markdownV2AutoEscape: false); + //Prevent flicker of keyboard + if (DeletePreviousMessage && MessageId != null) + { + await Device.DeleteMessage(MessageId.Value); + } + break; + + case EKeyboardType.InlineKeyBoard: + + //Try to edit message if message id is available + //When the returned message is null then the message has been already deleted, resend it + if (MessageId != null) + { + m = await Device.Edit(MessageId.Value, Title, (InlineKeyboardMarkup)form); + if (m != null) + { + MessageId = m.MessageId; + return; + } + } + + //When no message id is available or it has been deleted due the use of AutoCleanForm re-render automatically + m = await Device.Send(Title, (InlineKeyboardMarkup)form, disableNotification: true, + parseMode: MessageParseMode, markdownV2AutoEscape: false); + + break; } + if (m != null) + { + MessageId = m.MessageId; + } } + private void IntegratePagingView(ButtonForm dataForm) + { + //No Items + if (dataForm.Rows == 0) + { + dataForm.AddButtonRow(new ButtonBase(NoItemsLabel, "$")); + } -} + if (IsNavigationBarVisible) + { + //🔍 + var row = new ButtonRow(); + row.Add(new ButtonBase(PreviousPageLabel, "$previous$")); + row.Add(new ButtonBase( + string.Format(Default.Language["ButtonGrid_CurrentPage"], CurrentPageIndex + 1, PageCount), + "$site$")); + row.Add(new ButtonBase(NextPageLabel, "$next$")); + + if (EnableSearch) + { + row.Insert(2, new ButtonBase("🔍 " + (SearchQuery ?? ""), "$search$")); + } + + dataForm.InsertButtonRow(0, row); + + dataForm.AddButtonRow(row); + } + } + + public override Task Hidden(bool formClose) + { + //Prepare for opening Modal, and comming back + if (!formClose) + { + Updated(); + } + else + //Remove event handler + { + Device.MessageDeleted -= Device_MessageDeleted; + } + + return Task.CompletedTask; + } + + /// + /// Tells the control that it has been updated. + /// + public void Updated() + { + _renderNecessary = true; + } + + public override async Task Cleanup() + { + if (MessageId == null) + { + return; + } + + switch (KeyboardType) + { + case EKeyboardType.InlineKeyBoard: + + await Device.DeleteMessage(MessageId.Value); + + MessageId = null; + + break; + case EKeyboardType.ReplyKeyboard: + + if (HideKeyboardOnCleanup) + { + await Device.HideReplyKeyboard(); + } + + MessageId = null; + + break; + } + } +} \ No newline at end of file diff --git a/TelegramBotBase/Controls/Hybrid/ButtonRow.cs b/TelegramBotBase/Controls/Hybrid/ButtonRow.cs index c2ba68f..fbf6dee 100644 --- a/TelegramBotBase/Controls/Hybrid/ButtonRow.cs +++ b/TelegramBotBase/Controls/Hybrid/ButtonRow.cs @@ -4,93 +4,101 @@ using System.Diagnostics; using System.Linq; using TelegramBotBase.Form; -namespace TelegramBotBase.Controls.Hybrid +namespace TelegramBotBase.Controls.Hybrid; + +[DebuggerDisplay("{Count} columns")] +public class ButtonRow { - [DebuggerDisplay("{Count} columns")] - public class ButtonRow + private List _buttons = new(); + + public ButtonRow() { - private List _buttons = new List(); - - public ButtonRow() - { - - - } - - public ButtonRow(params ButtonBase[] buttons) - { - _buttons = buttons.ToList(); - } - - - public ButtonBase this[int index] => _buttons[index]; - - public int Count => _buttons.Count; - - public void Add(ButtonBase button) - { - _buttons.Add(button); - } - - public void AddRange(ButtonBase button) - { - _buttons.Add(button); - } - - public void Insert(int index, ButtonBase button) - { - _buttons.Insert(index, button); - } - - public IEnumerator GetEnumerator() - { - return _buttons.GetEnumerator(); - } - - public ButtonBase[] ToArray() - { - return _buttons.ToArray(); - } - - public List ToList() - { - return _buttons.ToList(); - } - - public bool Matches(string text, bool useText = true) - { - foreach (var b in _buttons) - { - if (useText && b.Text.Trim().Equals(text, StringComparison.InvariantCultureIgnoreCase)) - return true; - - if (!useText && b.Value.Equals(text, StringComparison.InvariantCultureIgnoreCase)) - return true; - } - return false; - } - - /// - /// Returns the button inside of the row which matches. - /// - /// - /// - /// - public ButtonBase GetButtonMatch(string text, bool useText = true) - { - foreach (var b in _buttons) - { - if (useText && b.Text.Trim().Equals(text, StringComparison.InvariantCultureIgnoreCase)) - return b; - if (!useText && b.Value.Equals(text, StringComparison.InvariantCultureIgnoreCase)) - return b; - } - return null; - } - - public static implicit operator ButtonRow(List list) - { - return new ButtonRow { _buttons = list }; - } } -} + + public ButtonRow(params ButtonBase[] buttons) + { + _buttons = buttons.ToList(); + } + + + public ButtonBase this[int index] => _buttons[index]; + + public int Count => _buttons.Count; + + public void Add(ButtonBase button) + { + _buttons.Add(button); + } + + public void AddRange(ButtonBase button) + { + _buttons.Add(button); + } + + public void Insert(int index, ButtonBase button) + { + _buttons.Insert(index, button); + } + + public IEnumerator GetEnumerator() + { + return _buttons.GetEnumerator(); + } + + public ButtonBase[] ToArray() + { + return _buttons.ToArray(); + } + + public List ToList() + { + return _buttons.ToList(); + } + + public bool Matches(string text, bool useText = true) + { + foreach (var b in _buttons) + { + if (useText && b.Text.Trim().Equals(text, StringComparison.InvariantCultureIgnoreCase)) + { + return true; + } + + if (!useText && b.Value.Equals(text, StringComparison.InvariantCultureIgnoreCase)) + { + return true; + } + } + + return false; + } + + /// + /// Returns the button inside of the row which matches. + /// + /// + /// + /// + public ButtonBase GetButtonMatch(string text, bool useText = true) + { + foreach (var b in _buttons) + { + if (useText && b.Text.Trim().Equals(text, StringComparison.InvariantCultureIgnoreCase)) + { + return b; + } + + if (!useText && b.Value.Equals(text, StringComparison.InvariantCultureIgnoreCase)) + { + return b; + } + } + + return null; + } + + public static implicit operator ButtonRow(List list) + { + return new ButtonRow { _buttons = list }; + } +} \ No newline at end of file diff --git a/TelegramBotBase/Controls/Hybrid/CheckedButtonList.cs b/TelegramBotBase/Controls/Hybrid/CheckedButtonList.cs index 5da90dc..6e49ebe 100644 --- a/TelegramBotBase/Controls/Hybrid/CheckedButtonList.cs +++ b/TelegramBotBase/Controls/Hybrid/CheckedButtonList.cs @@ -15,215 +15,357 @@ using TelegramBotBase.Form; using TelegramBotBase.Localizations; using static TelegramBotBase.Base.Async; -namespace TelegramBotBase.Controls.Hybrid +namespace TelegramBotBase.Controls.Hybrid; + +public class CheckedButtonList : ControlBase { - public class CheckedButtonList : ControlBase + private static readonly object EvButtonClicked = new(); + + private static readonly object EvCheckedChanged = new(); + + private readonly EventHandlerList _events = new(); + + private EKeyboardType _mEKeyboardType = EKeyboardType.ReplyKeyboard; + + private bool _renderNecessary = true; + + public string NextPageLabel = Default.Language["ButtonGrid_NextPage"]; + + public string NoItemsLabel = Default.Language["ButtonGrid_NoItems"]; + + public string PreviousPageLabel = Default.Language["ButtonGrid_PreviousPage"]; + + public CheckedButtonList() { + DataSource = new ButtonFormDataSource(); + } - public string Title { get; set; } = Default.Language["ButtonGrid_Title"]; + public CheckedButtonList(EKeyboardType type) : this() + { + _mEKeyboardType = type; + } - public string ConfirmationText { get; set; } = ""; - private bool _renderNecessary = true; + public CheckedButtonList(ButtonForm form) + { + DataSource = new ButtonFormDataSource(form); + } - private static readonly object EvButtonClicked = new object(); + public string Title { get; set; } = Default.Language["ButtonGrid_Title"]; - private static readonly object EvCheckedChanged = new object(); + public string ConfirmationText { get; set; } = ""; - private readonly EventHandlerList _events = new EventHandlerList(); + [Obsolete("This property is obsolete. Please use the DataSource property instead.")] + public ButtonForm ButtonsForm + { + get => DataSource.ButtonForm; + set => DataSource = new ButtonFormDataSource(value); + } - [Obsolete("This property is obsolete. Please use the DataSource property instead.")] - public ButtonForm ButtonsForm + /// + /// Data source of the items. + /// + public ButtonFormDataSource DataSource { get; set; } + + private List CheckedRows { get; } = new(); + + public int? MessageId { get; set; } + + + /// + /// Optional. Requests clients to resize the keyboard vertically for optimal fit (e.g., make the keyboard smaller if + /// there are just two rows of buttons). Defaults to false, in which case the custom keyboard is always of the same + /// height as the app's standard keyboard. + /// Source: https://core.telegram.org/bots/api#replykeyboardmarkup + /// + public bool ResizeKeyboard { get; set; } = false; + + public bool OneTimeKeyboard { get; set; } = false; + + public bool HideKeyboardOnCleanup { get; set; } = true; + + public bool DeletePreviousMessage { get; set; } = true; + + /// + /// Removes the reply message from a user. + /// + public bool DeleteReplyMessage { get; set; } = true; + + /// + /// Parsemode of the message. + /// + public ParseMode MessageParseMode { get; set; } = ParseMode.Markdown; + + /// + /// Enables automatic paging of buttons when the amount of rows is exceeding the limits. + /// + public bool EnablePaging { get; set; } = false; + + + ///// + ///// Enabled a search function. + ///// + //public bool EnableSearch { get; set; } = false; + + //public String SearchQuery { get; set; } + + public ENavigationBarVisibility NavigationBarVisibility { get; set; } = ENavigationBarVisibility.always; + + + /// + /// Index of the current page + /// + public int CurrentPageIndex { get; set; } + + //public String SearchLabel = Localizations.Default.Language["ButtonGrid_SearchFeature"]; + + public string CheckedIconLabel { get; set; } = "✅"; + + public string UncheckedIconLabel { get; set; } = "◻️"; + + /// + /// Layout of the buttons which should be displayed always on top. + /// + public ButtonRow HeadLayoutButtonRow { get; set; } + + /// + /// Layout of columns which should be displayed below the header + /// + public ButtonRow SubHeadLayoutButtonRow { get; set; } + + /// + /// Defines which type of Button Keyboard should be rendered. + /// + public EKeyboardType KeyboardType + { + get => _mEKeyboardType; + set { - get => DataSource.ButtonForm; - set => DataSource = new ButtonFormDataSource(value); - } - - /// - /// Data source of the items. - /// - public ButtonFormDataSource DataSource { get; set; } - - private List CheckedRows { get; set; } = new List(); - - public int? MessageId { get; set; } - - - /// - /// Optional. Requests clients to resize the keyboard vertically for optimal fit (e.g., make the keyboard smaller if there are just two rows of buttons). Defaults to false, in which case the custom keyboard is always of the same height as the app's standard keyboard. - /// Source: https://core.telegram.org/bots/api#replykeyboardmarkup - /// - public bool ResizeKeyboard { get; set; } = false; - - public bool OneTimeKeyboard { get; set; } = false; - - public bool HideKeyboardOnCleanup { get; set; } = true; - - public bool DeletePreviousMessage { get; set; } = true; - - /// - /// Removes the reply message from a user. - /// - public bool DeleteReplyMessage { get; set; } = true; - - /// - /// Parsemode of the message. - /// - public ParseMode MessageParseMode { get; set; } = ParseMode.Markdown; - - /// - /// Enables automatic paging of buttons when the amount of rows is exceeding the limits. - /// - public bool EnablePaging { get; set; } = false; - - - ///// - ///// Enabled a search function. - ///// - //public bool EnableSearch { get; set; } = false; - - //public String SearchQuery { get; set; } - - public ENavigationBarVisibility NavigationBarVisibility { get; set; } = ENavigationBarVisibility.always; - - - /// - /// Index of the current page - /// - public int CurrentPageIndex { get; set; } - - public string PreviousPageLabel = Default.Language["ButtonGrid_PreviousPage"]; - - public string NextPageLabel = Default.Language["ButtonGrid_NextPage"]; - - public string NoItemsLabel = Default.Language["ButtonGrid_NoItems"]; - - //public String SearchLabel = Localizations.Default.Language["ButtonGrid_SearchFeature"]; - - public string CheckedIconLabel { get; set; } = "✅"; - - public string UncheckedIconLabel { get; set; } = "◻️"; - - /// - /// Layout of the buttons which should be displayed always on top. - /// - public ButtonRow HeadLayoutButtonRow { get; set; } - - /// - /// Layout of columns which should be displayed below the header - /// - public ButtonRow SubHeadLayoutButtonRow { get; set; } - - /// - /// Defines which type of Button Keyboard should be rendered. - /// - public EKeyboardType KeyboardType - { - get => _mEKeyboardType; - set + if (_mEKeyboardType != value) { - if (_mEKeyboardType != value) - { - _renderNecessary = true; + _renderNecessary = true; - Cleanup().Wait(); - - _mEKeyboardType = value; - } + Cleanup().Wait(); + _mEKeyboardType = value; } } + } - private EKeyboardType _mEKeyboardType = EKeyboardType.ReplyKeyboard; - - public CheckedButtonList() + public bool PagingNecessary + { + get { - DataSource = new ButtonFormDataSource(); - - - } - - public CheckedButtonList(EKeyboardType type) : this() - { - _mEKeyboardType = type; - } - - - public CheckedButtonList(ButtonForm form) - { - DataSource = new ButtonFormDataSource(form); - } - - public event AsyncEventHandler ButtonClicked - { - add => _events.AddHandler(EvButtonClicked, value); - remove => _events.RemoveHandler(EvButtonClicked, value); - } - - public async Task OnButtonClicked(ButtonClickedEventArgs e) - { - var handler = _events[EvButtonClicked]?.GetInvocationList().Cast>(); - if (handler == null) - return; - - foreach (var h in handler) + if (KeyboardType == EKeyboardType.InlineKeyBoard && + TotalRows > Constants.Telegram.MaxInlineKeyBoardRows) { - await h.InvokeAllAsync(this, e); - } - } - - public event AsyncEventHandler CheckedChanged - { - add => _events.AddHandler(EvCheckedChanged, value); - remove => _events.RemoveHandler(EvCheckedChanged, value); - } - - public async Task OnCheckedChanged(CheckedChangedEventArgs e) - { - var handler = _events[EvCheckedChanged]?.GetInvocationList().Cast>(); - if (handler == null) - return; - - foreach (var h in handler) - { - await h.InvokeAllAsync(this, e); - } - } - - public override async Task Load(MessageResult result) - { - if (KeyboardType != EKeyboardType.ReplyKeyboard) - return; - - if (!result.IsFirstHandler) - return; - - if (result.MessageText == null || result.MessageText == "") - return; - - var matches = new List(); - ButtonRow match = null; - var index = -1; - - if (HeadLayoutButtonRow?.Matches(result.MessageText) ?? false) - { - match = HeadLayoutButtonRow; - goto check; + return true; } - if (SubHeadLayoutButtonRow?.Matches(result.MessageText) ?? false) + if (KeyboardType == EKeyboardType.ReplyKeyboard && + TotalRows > Constants.Telegram.MaxReplyKeyboardRows) { - match = SubHeadLayoutButtonRow; - goto check; + return true; } - var br = DataSource.FindRow(result.MessageText); - if (br != null) + return false; + } + } + + public bool IsNavigationBarVisible + { + get + { + if ((NavigationBarVisibility == ENavigationBarVisibility.always) | + (NavigationBarVisibility == ENavigationBarVisibility.auto && PagingNecessary)) { - match = br.Item1; - index = br.Item2; + return true; } + return false; + } + } + + /// + /// Returns the maximum number of rows + /// + public int MaximumRow + { + get + { + return KeyboardType switch + { + EKeyboardType.InlineKeyBoard => Constants.Telegram.MaxInlineKeyBoardRows, + EKeyboardType.ReplyKeyboard => Constants.Telegram.MaxReplyKeyboardRows, + _ => 0 + }; + } + } + + /// + /// Returns the number of all rows (layout + navigation + content); + /// + public int TotalRows => LayoutRows + DataSource.RowCount; + + + /// + /// Contains the Number of Rows which are used by the layout. + /// + private int LayoutRows + { + get + { + var layoutRows = 0; + + if ((NavigationBarVisibility == ENavigationBarVisibility.always) | + (NavigationBarVisibility == ENavigationBarVisibility.auto)) + { + layoutRows += 2; + } + + if (HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0) + { + layoutRows++; + } + + if (SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0) + { + layoutRows++; + } + + return layoutRows; + } + } + + /// + /// Returns the number of item rows per page. + /// + public int ItemRowsPerPage => MaximumRow - LayoutRows; + + public int PageCount + { + get + { + if (DataSource.RowCount == 0) + { + return 1; + } + + //var bf = this.DataSource.PickAllItems(this.EnableSearch ? this.SearchQuery : null); + + var max = DataSource.RowCount; + + //if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "") + //{ + // bf = bf.FilterDuplicate(this.SearchQuery); + //} + + if (max == 0) + { + return 1; + } + + return (int)Math.Ceiling(max / (decimal)ItemRowsPerPage); + } + } + + public List CheckedItems + { + get + { + var lst = new List(); + + foreach (var c in CheckedRows) + { + lst.Add(ButtonsForm[c][0]); + } + + return lst; + } + } + + public event AsyncEventHandler ButtonClicked + { + add => _events.AddHandler(EvButtonClicked, value); + remove => _events.RemoveHandler(EvButtonClicked, value); + } + + public async Task OnButtonClicked(ButtonClickedEventArgs e) + { + var handler = _events[EvButtonClicked]?.GetInvocationList() + .Cast>(); + if (handler == null) + { + return; + } + + foreach (var h in handler) + { + await h.InvokeAllAsync(this, e); + } + } + + public event AsyncEventHandler CheckedChanged + { + add => _events.AddHandler(EvCheckedChanged, value); + remove => _events.RemoveHandler(EvCheckedChanged, value); + } + + public async Task OnCheckedChanged(CheckedChangedEventArgs e) + { + var handler = _events[EvCheckedChanged]?.GetInvocationList() + .Cast>(); + if (handler == null) + { + return; + } + + foreach (var h in handler) + { + await h.InvokeAllAsync(this, e); + } + } + + public override async Task Load(MessageResult result) + { + if (KeyboardType != EKeyboardType.ReplyKeyboard) + { + return; + } + + if (!result.IsFirstHandler) + { + return; + } + + if (result.MessageText == null || result.MessageText == "") + { + return; + } + + var matches = new List(); + ButtonRow match = null; + var index = -1; + + if (HeadLayoutButtonRow?.Matches(result.MessageText) ?? false) + { + match = HeadLayoutButtonRow; + goto check; + } + + if (SubHeadLayoutButtonRow?.Matches(result.MessageText) ?? false) + { + match = SubHeadLayoutButtonRow; + goto check; + } + + var br = DataSource.FindRow(result.MessageText); + if (br != null) + { + match = br.Item1; + index = br.Item2; + } + //var button = HeadLayoutButtonRow?. .FirstOrDefault(a => a.Text.Trim() == result.MessageText) // ?? SubHeadLayoutButtonRow?.FirstOrDefault(a => a.Text.Trim() == result.MessageText); @@ -233,142 +375,152 @@ namespace TelegramBotBase.Controls.Hybrid //var index = bf.FindRowByButton(button); - check: - //Remove button click message - if (DeleteReplyMessage) - await Device.DeleteMessage(result.MessageId); - - if (match == null) - { - if (result.MessageText == PreviousPageLabel) - { - if (CurrentPageIndex > 0) - CurrentPageIndex--; - - Updated(); - } - else if (result.MessageText == NextPageLabel) - { - if (CurrentPageIndex < PageCount - 1) - CurrentPageIndex++; - - Updated(); - } - else if (result.MessageText.EndsWith(CheckedIconLabel)) - { - var s = result.MessageText.Split(' ', '.'); - index = int.Parse(s[0]) - 1; - - if (!CheckedRows.Contains(index)) - return; - - CheckedRows.Remove(index); - - Updated(); - - await OnCheckedChanged(new CheckedChangedEventArgs(ButtonsForm[index], index, false)); - - } - else if (result.MessageText.EndsWith(UncheckedIconLabel)) - { - var s = result.MessageText.Split(' ', '.'); - index = int.Parse(s[0]) - 1; - - if (CheckedRows.Contains(index)) - return; - - - CheckedRows.Add(index); - - Updated(); - - await OnCheckedChanged(new CheckedChangedEventArgs(ButtonsForm[index], index, true)); - - } - //else if (this.EnableSearch) - //{ - // if (result.MessageText.StartsWith("🔍")) - // { - // //Sent note about searching - // if (this.SearchQuery == null) - // { - // await this.Device.Send(this.SearchLabel); - // } - - // this.SearchQuery = null; - // this.Updated(); - // return; - // } - - // this.SearchQuery = result.MessageText; - - // if (this.SearchQuery != null && this.SearchQuery != "") - // { - // this.CurrentPageIndex = 0; - // this.Updated(); - // } - - //} - - - - return; - } - - - await OnButtonClicked(new ButtonClickedEventArgs(match.GetButtonMatch(result.MessageText), index, match)); - - result.Handled = true; - - //await OnButtonClicked(new ButtonClickedEventArgs(button, index)); - - ////Remove button click message - //if (this.DeletePreviousMessage) - // await Device.DeleteMessage(result.MessageId); - - //result.Handled = true; - + //Remove button click message + if (DeleteReplyMessage) + { + await Device.DeleteMessage(result.MessageId); } - public override async Task Action(MessageResult result, string value = null) + if (match == null) { - if (result.Handled) - return; - - if (!result.IsFirstHandler) - return; - - //Find clicked button depending on Text or Value (depending on markup type) - if (KeyboardType != EKeyboardType.InlineKeyBoard) - return; - - await result.ConfirmAction(ConfirmationText ?? ""); - - ButtonRow match = null; - var index = -1; - - if (HeadLayoutButtonRow?.Matches(result.RawData, false) ?? false) + if (result.MessageText == PreviousPageLabel) { - match = HeadLayoutButtonRow; - goto check; - } + if (CurrentPageIndex > 0) + { + CurrentPageIndex--; + } - if (SubHeadLayoutButtonRow?.Matches(result.RawData, false) ?? false) + Updated(); + } + else if (result.MessageText == NextPageLabel) { - match = SubHeadLayoutButtonRow; - goto check; - } + if (CurrentPageIndex < PageCount - 1) + { + CurrentPageIndex++; + } - var br = DataSource.FindRow(result.RawData, false); - if (br != null) + Updated(); + } + else if (result.MessageText.EndsWith(CheckedIconLabel)) { - match = br.Item1; - index = br.Item2; - } + var s = result.MessageText.Split(' ', '.'); + index = int.Parse(s[0]) - 1; + if (!CheckedRows.Contains(index)) + { + return; + } + + CheckedRows.Remove(index); + + Updated(); + + await OnCheckedChanged(new CheckedChangedEventArgs(ButtonsForm[index], index, false)); + } + else if (result.MessageText.EndsWith(UncheckedIconLabel)) + { + var s = result.MessageText.Split(' ', '.'); + index = int.Parse(s[0]) - 1; + + if (CheckedRows.Contains(index)) + { + return; + } + + + CheckedRows.Add(index); + + Updated(); + + await OnCheckedChanged(new CheckedChangedEventArgs(ButtonsForm[index], index, true)); + } + //else if (this.EnableSearch) + //{ + // if (result.MessageText.StartsWith("🔍")) + // { + // //Sent note about searching + // if (this.SearchQuery == null) + // { + // await this.Device.Send(this.SearchLabel); + // } + + // this.SearchQuery = null; + // this.Updated(); + // return; + // } + + // this.SearchQuery = result.MessageText; + + // if (this.SearchQuery != null && this.SearchQuery != "") + // { + // this.CurrentPageIndex = 0; + // this.Updated(); + // } + + //} + + + return; + } + + + await OnButtonClicked(new ButtonClickedEventArgs(match.GetButtonMatch(result.MessageText), index, match)); + + result.Handled = true; + + //await OnButtonClicked(new ButtonClickedEventArgs(button, index)); + + ////Remove button click message + //if (this.DeletePreviousMessage) + // await Device.DeleteMessage(result.MessageId); + + //result.Handled = true; + } + + public override async Task Action(MessageResult result, string value = null) + { + if (result.Handled) + { + return; + } + + if (!result.IsFirstHandler) + { + return; + } + + //Find clicked button depending on Text or Value (depending on markup type) + if (KeyboardType != EKeyboardType.InlineKeyBoard) + { + return; + } + + await result.ConfirmAction(ConfirmationText ?? ""); + + ButtonRow match = null; + var index = -1; + + if (HeadLayoutButtonRow?.Matches(result.RawData, false) ?? false) + { + match = HeadLayoutButtonRow; + goto check; + } + + if (SubHeadLayoutButtonRow?.Matches(result.RawData, false) ?? false) + { + match = SubHeadLayoutButtonRow; + goto check; + } + + var br = DataSource.FindRow(result.RawData, false); + if (br != null) + { + match = br.Item1; + index = br.Item2; + } //var bf = DataSource.ButtonForm; @@ -380,458 +532,347 @@ namespace TelegramBotBase.Controls.Hybrid //var index = bf.FindRowByButton(button); check: - if (match != null) - { - await OnButtonClicked(new ButtonClickedEventArgs(match.GetButtonMatch(result.RawData, false), index, match)); - - result.Handled = true; - return; - } - - //if (button != null) - //{ - // await OnButtonClicked(new ButtonClickedEventArgs(button, index)); - - // result.Handled = true; - // return; - //} - - switch (result.RawData) - { - case "$previous$": - - if (CurrentPageIndex > 0) - CurrentPageIndex--; - - Updated(); - - break; - case "$next$": - - if (CurrentPageIndex < PageCount - 1) - CurrentPageIndex++; - - Updated(); - - break; - - default: - - var s = result.RawData.Split('$'); - - - switch (s[0]) - { - case "check": - - index = int.Parse(s[1]); - - if (!CheckedRows.Contains(index)) - { - CheckedRows.Add(index); - - Updated(); - - await OnCheckedChanged(new CheckedChangedEventArgs(ButtonsForm[index], index, true)); - } - - break; - - case "uncheck": - - index = int.Parse(s[1]); - - if (CheckedRows.Contains(index)) - { - CheckedRows.Remove(index); - - Updated(); - - await OnCheckedChanged(new CheckedChangedEventArgs(ButtonsForm[index], index, false)); - } - - break; - } - - - break; - - } + if (match != null) + { + await OnButtonClicked(new ButtonClickedEventArgs(match.GetButtonMatch(result.RawData, false), index, + match)); + result.Handled = true; + return; } - /// - /// This method checks of the amount of buttons - /// - private void CheckGrid() + //if (button != null) + //{ + // await OnButtonClicked(new ButtonClickedEventArgs(button, index)); + + // result.Handled = true; + // return; + //} + + switch (result.RawData) { - switch (_mEKeyboardType) - { - case EKeyboardType.InlineKeyBoard: + case "$previous$": - if (DataSource.RowCount > Constants.Telegram.MaxInlineKeyBoardRows && !EnablePaging) - { - throw new MaximumRowsReachedException { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxInlineKeyBoardRows }; - } + if (CurrentPageIndex > 0) + { + CurrentPageIndex--; + } - if (DataSource.ColumnCount > Constants.Telegram.MaxInlineKeyBoardCols) - { - throw new MaximumColsException { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxInlineKeyBoardCols }; - } + Updated(); - break; + break; + case "$next$": - case EKeyboardType.ReplyKeyboard: + if (CurrentPageIndex < PageCount - 1) + { + CurrentPageIndex++; + } - if (DataSource.RowCount > Constants.Telegram.MaxReplyKeyboardRows && !EnablePaging) - { - throw new MaximumRowsReachedException { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxReplyKeyboardRows }; - } + Updated(); - if (DataSource.ColumnCount > Constants.Telegram.MaxReplyKeyboardCols) - { - throw new MaximumColsException { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxReplyKeyboardCols }; - } + break; - break; - } + default: + + var s = result.RawData.Split('$'); + + + switch (s[0]) + { + case "check": + + index = int.Parse(s[1]); + + if (!CheckedRows.Contains(index)) + { + CheckedRows.Add(index); + + Updated(); + + await OnCheckedChanged(new CheckedChangedEventArgs(ButtonsForm[index], index, true)); + } + + break; + + case "uncheck": + + index = int.Parse(s[1]); + + if (CheckedRows.Contains(index)) + { + CheckedRows.Remove(index); + + Updated(); + + await OnCheckedChanged(new CheckedChangedEventArgs(ButtonsForm[index], index, false)); + } + + break; + } + + + break; + } + } + + /// + /// This method checks of the amount of buttons + /// + private void CheckGrid() + { + switch (_mEKeyboardType) + { + case EKeyboardType.InlineKeyBoard: + + if (DataSource.RowCount > Constants.Telegram.MaxInlineKeyBoardRows && !EnablePaging) + { + throw new MaximumRowsReachedException + { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxInlineKeyBoardRows }; + } + + if (DataSource.ColumnCount > Constants.Telegram.MaxInlineKeyBoardCols) + { + throw new MaximumColsException + { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxInlineKeyBoardCols }; + } + + break; + + case EKeyboardType.ReplyKeyboard: + + if (DataSource.RowCount > Constants.Telegram.MaxReplyKeyboardRows && !EnablePaging) + { + throw new MaximumRowsReachedException + { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxReplyKeyboardRows }; + } + + if (DataSource.ColumnCount > Constants.Telegram.MaxReplyKeyboardCols) + { + throw new MaximumColsException + { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxReplyKeyboardCols }; + } + + break; + } + } + + public override async Task Render(MessageResult result) + { + if (!_renderNecessary) + { + return; } - public override async Task Render(MessageResult result) + //Check for rows and column limits + CheckGrid(); + + _renderNecessary = false; + + Message m = null; + + var form = DataSource.PickItems(CurrentPageIndex * ItemRowsPerPage, ItemRowsPerPage); + + //if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "") + //{ + // form = form.FilterDuplicate(this.SearchQuery, true); + //} + //else + //{ + //form = form.Duplicate(); + //} + + if (EnablePaging) { - if (!_renderNecessary) - return; + IntegratePagingView(form); + } + else + { + form = PrepareCheckableLayout(form); + } - //Check for rows and column limits - CheckGrid(); + if (HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0) + { + form.InsertButtonRow(0, HeadLayoutButtonRow.ToArray()); + } - _renderNecessary = false; - - Message m = null; - - var form = DataSource.PickItems(CurrentPageIndex * ItemRowsPerPage, ItemRowsPerPage); - - //if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "") - //{ - // form = form.FilterDuplicate(this.SearchQuery, true); - //} - //else - //{ - //form = form.Duplicate(); - //} - - if (EnablePaging) + if (SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0) + { + if (IsNavigationBarVisible) { - IntegratePagingView(form); + form.InsertButtonRow(2, SubHeadLayoutButtonRow.ToArray()); } else { - form = PrepareCheckableLayout(form); + form.InsertButtonRow(1, SubHeadLayoutButtonRow.ToArray()); } + } - if (HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0) - { - form.InsertButtonRow(0, HeadLayoutButtonRow.ToArray()); - } + switch (KeyboardType) + { + //Reply Keyboard could only be updated with a new keyboard. + case EKeyboardType.ReplyKeyboard: - if (SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0) - { - if (IsNavigationBarVisible) + if (form.Count == 0) { - form.InsertButtonRow(2, SubHeadLayoutButtonRow.ToArray()); - } - else - { - form.InsertButtonRow(1, SubHeadLayoutButtonRow.ToArray()); - } - } - - switch (KeyboardType) - { - //Reply Keyboard could only be updated with a new keyboard. - case EKeyboardType.ReplyKeyboard: - - if (form.Count == 0) - { - if (MessageId != null) - { - await Device.HideReplyKeyboard(); - MessageId = null; - } - - return; - } - - //if (form.Count == 0) - // return; - - - var rkm = (ReplyKeyboardMarkup)form; - rkm.ResizeKeyboard = ResizeKeyboard; - rkm.OneTimeKeyboard = OneTimeKeyboard; - m = await Device.Send(Title, rkm, disableNotification: true, parseMode: MessageParseMode, markdownV2AutoEscape: false); - - //Prevent flicker of keyboard - if (DeletePreviousMessage && MessageId != null) - await Device.DeleteMessage(MessageId.Value); - - break; - - case EKeyboardType.InlineKeyBoard: - if (MessageId != null) { - m = await Device.Edit(MessageId.Value, Title, (InlineKeyboardMarkup)form); - } - else - { - m = await Device.Send(Title, (InlineKeyboardMarkup)form, disableNotification: true, parseMode: MessageParseMode, markdownV2AutoEscape: false); + await Device.HideReplyKeyboard(); + MessageId = null; } - break; - } - - if (m != null) - { - MessageId = m.MessageId; - } - - - } - - private void IntegratePagingView(ButtonForm dataForm) - { - //No Items - if (dataForm.Rows == 0) - { - dataForm.AddButtonRow(new ButtonBase(NoItemsLabel, "$")); - } - - var bf = new ButtonForm(); - - bf = PrepareCheckableLayout(dataForm); - - - if (IsNavigationBarVisible) - { - //🔍 - var row = new ButtonRow(); - row.Add(new ButtonBase(PreviousPageLabel, "$previous$")); - row.Add(new ButtonBase(string.Format(Default.Language["ButtonGrid_CurrentPage"], CurrentPageIndex + 1, PageCount), "$site$")); - row.Add(new ButtonBase(NextPageLabel, "$next$")); - - - dataForm.InsertButtonRow(0, row); - - dataForm.AddButtonRow(row); - } - } - - private ButtonForm PrepareCheckableLayout(ButtonForm dataForm) - { - var bf = new ButtonForm(); - for (var i = 0; i < dataForm.Rows; i++) - { - var it = (CurrentPageIndex * (MaximumRow - LayoutRows)) + i; - - //if (it > dataForm.Rows - 1) - // break; - - var r = dataForm[i]; - - var s = CheckedRows.Contains(it) ? CheckedIconLabel : UncheckedIconLabel; - - //On reply keyboards we need a unique text. - if (KeyboardType == EKeyboardType.ReplyKeyboard) - { - s = $"{it + 1}. " + s; + return; } - if (CheckedRows.Contains(it)) + //if (form.Count == 0) + // return; + + + var rkm = (ReplyKeyboardMarkup)form; + rkm.ResizeKeyboard = ResizeKeyboard; + rkm.OneTimeKeyboard = OneTimeKeyboard; + m = await Device.Send(Title, rkm, disableNotification: true, parseMode: MessageParseMode, + markdownV2AutoEscape: false); + + //Prevent flicker of keyboard + if (DeletePreviousMessage && MessageId != null) { - r.Insert(0, new ButtonBase(s, "uncheck$" + it)); + await Device.DeleteMessage(MessageId.Value); + } + + break; + + case EKeyboardType.InlineKeyBoard: + + if (MessageId != null) + { + m = await Device.Edit(MessageId.Value, Title, (InlineKeyboardMarkup)form); } else { - r.Insert(0, new ButtonBase(s, "check$" + it)); + m = await Device.Send(Title, (InlineKeyboardMarkup)form, disableNotification: true, + parseMode: MessageParseMode, markdownV2AutoEscape: false); } - bf.AddButtonRow(r); - } - - return bf; + break; } - public bool PagingNecessary + if (m != null) { - get + MessageId = m.MessageId; + } + } + + private void IntegratePagingView(ButtonForm dataForm) + { + //No Items + if (dataForm.Rows == 0) + { + dataForm.AddButtonRow(new ButtonBase(NoItemsLabel, "$")); + } + + var bf = new ButtonForm(); + + bf = PrepareCheckableLayout(dataForm); + + + if (IsNavigationBarVisible) + { + //🔍 + var row = new ButtonRow(); + row.Add(new ButtonBase(PreviousPageLabel, "$previous$")); + row.Add(new ButtonBase( + string.Format(Default.Language["ButtonGrid_CurrentPage"], CurrentPageIndex + 1, PageCount), + "$site$")); + row.Add(new ButtonBase(NextPageLabel, "$next$")); + + + dataForm.InsertButtonRow(0, row); + + dataForm.AddButtonRow(row); + } + } + + private ButtonForm PrepareCheckableLayout(ButtonForm dataForm) + { + var bf = new ButtonForm(); + for (var i = 0; i < dataForm.Rows; i++) + { + var it = CurrentPageIndex * (MaximumRow - LayoutRows) + i; + + //if (it > dataForm.Rows - 1) + // break; + + var r = dataForm[i]; + + var s = CheckedRows.Contains(it) ? CheckedIconLabel : UncheckedIconLabel; + + //On reply keyboards we need a unique text. + if (KeyboardType == EKeyboardType.ReplyKeyboard) { - if (KeyboardType == EKeyboardType.InlineKeyBoard && TotalRows > Constants.Telegram.MaxInlineKeyBoardRows) - { - return true; - } - - if (KeyboardType == EKeyboardType.ReplyKeyboard && TotalRows > Constants.Telegram.MaxReplyKeyboardRows) - { - return true; - } - - return false; + s = $"{it + 1}. " + s; } - } - public bool IsNavigationBarVisible - { - get + if (CheckedRows.Contains(it)) { - if (NavigationBarVisibility == ENavigationBarVisibility.always | (NavigationBarVisibility == ENavigationBarVisibility.auto && PagingNecessary)) - { - return true; - } - - return false; + r.Insert(0, new ButtonBase(s, "uncheck$" + it)); } - } - - /// - /// Returns the maximum number of rows - /// - public int MaximumRow - { - get + else { - return KeyboardType switch - { - EKeyboardType.InlineKeyBoard => Constants.Telegram.MaxInlineKeyBoardRows, - EKeyboardType.ReplyKeyboard => Constants.Telegram.MaxReplyKeyboardRows, - _ => 0 - }; - } - } - - /// - /// Returns the number of all rows (layout + navigation + content); - /// - public int TotalRows => LayoutRows + DataSource.RowCount; - - - /// - /// Contains the Number of Rows which are used by the layout. - /// - private int LayoutRows - { - get - { - var layoutRows = 0; - - if (NavigationBarVisibility == ENavigationBarVisibility.always | NavigationBarVisibility == ENavigationBarVisibility.auto) - layoutRows += 2; - - if (HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0) - layoutRows++; - - if (SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0) - layoutRows++; - - return layoutRows; - } - } - - /// - /// Returns the number of item rows per page. - /// - public int ItemRowsPerPage => MaximumRow - LayoutRows; - - public int PageCount - { - get - { - if (DataSource.RowCount == 0) - return 1; - - //var bf = this.DataSource.PickAllItems(this.EnableSearch ? this.SearchQuery : null); - - var max = DataSource.RowCount; - - //if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "") - //{ - // bf = bf.FilterDuplicate(this.SearchQuery); - //} - - if (max == 0) - return 1; - - return (int)Math.Ceiling(max / (decimal)ItemRowsPerPage); - } - } - - public override Task Hidden(bool formClose) - { - //Prepare for opening Modal, and comming back - if (!formClose) - { - Updated(); + r.Insert(0, new ButtonBase(s, "check$" + it)); } - return Task.CompletedTask; + bf.AddButtonRow(r); } - public List CheckedItems + return bf; + } + + public override Task Hidden(bool formClose) + { + //Prepare for opening Modal, and comming back + if (!formClose) { - get - { - var lst = new List(); - - foreach (var c in CheckedRows) - { - lst.Add(ButtonsForm[c][0]); - } - - return lst; - } - } - - - /// - /// Tells the control that it has been updated. - /// - public void Updated() - { - _renderNecessary = true; - } - - public override async Task Cleanup() - { - if (MessageId == null) - return; - - switch (KeyboardType) - { - case EKeyboardType.InlineKeyBoard: - - await Device.DeleteMessage(MessageId.Value); - - MessageId = null; - - break; - case EKeyboardType.ReplyKeyboard: - - if (HideKeyboardOnCleanup) - { - await Device.HideReplyKeyboard(); - } - - MessageId = null; - - break; - } - - - - + Updated(); } + return Task.CompletedTask; } + /// + /// Tells the control that it has been updated. + /// + public void Updated() + { + _renderNecessary = true; + } + + public override async Task Cleanup() + { + if (MessageId == null) + { + return; + } + + switch (KeyboardType) + { + case EKeyboardType.InlineKeyBoard: + + await Device.DeleteMessage(MessageId.Value); + + MessageId = null; + + break; + case EKeyboardType.ReplyKeyboard: + + if (HideKeyboardOnCleanup) + { + await Device.HideReplyKeyboard(); + } + + MessageId = null; + + break; + } + } } diff --git a/TelegramBotBase/Controls/Hybrid/MultiView.cs b/TelegramBotBase/Controls/Hybrid/MultiView.cs index 5008b73..2c8b98d 100644 --- a/TelegramBotBase/Controls/Hybrid/MultiView.cs +++ b/TelegramBotBase/Controls/Hybrid/MultiView.cs @@ -3,124 +3,125 @@ using System.Threading.Tasks; using TelegramBotBase.Args; using TelegramBotBase.Base; -namespace TelegramBotBase.Controls.Hybrid +namespace TelegramBotBase.Controls.Hybrid; + +/// +/// This Control is for having a basic form content switching control. +/// +public abstract class MultiView : ControlBase { + private int _mISelectedViewIndex; /// - /// This Control is for having a basic form content switching control. + /// Hold if the View has been rendered already. /// - public abstract class MultiView : ControlBase + private bool _rendered; + + + public MultiView() { - /// - /// Index of the current View. - /// - public int SelectedViewIndex - { - get => _mISelectedViewIndex; - set - { - _mISelectedViewIndex = value; - - //Already rendered? Re-Render - if (_rendered) - ForceRender().Wait(); - } - } - - private int _mISelectedViewIndex; - - /// - /// Hold if the View has been rendered already. - /// - private bool _rendered; - - private List Messages { get; set; } - - - public MultiView() - { - Messages = new List(); - } - - - private Task Device_MessageSent(object sender, MessageSentEventArgs e) - { - if (e.Origin == null || !e.Origin.IsSubclassOf(typeof(MultiView))) - return Task.CompletedTask; - - Messages.Add(e.MessageId); - return Task.CompletedTask; - } - - public override void Init() - { - Device.MessageSent += Device_MessageSent; - } - - public override Task Load(MessageResult result) - { - _rendered = false; - return Task.CompletedTask; - } - - - public override async Task Render(MessageResult result) - { - //When already rendered, skip rendering - if (_rendered) - return; - - await CleanUpView(); - - await RenderView(new RenderViewEventArgs(SelectedViewIndex)); - - _rendered = true; - } - - - /// - /// Will get invoked on rendering the current controls view. - /// - /// - public virtual Task RenderView(RenderViewEventArgs e) - { - return Task.CompletedTask; - } - - private async Task CleanUpView() - { - - var tasks = new List(); - - foreach (var msg in Messages) - { - tasks.Add(Device.DeleteMessage(msg)); - } - - await Task.WhenAll(tasks); - - Messages.Clear(); - - } - - /// - /// Forces render of control contents. - /// - public async Task ForceRender() - { - await CleanUpView(); - - await RenderView(new RenderViewEventArgs(SelectedViewIndex)); - - _rendered = true; - } - - public override async Task Cleanup() - { - Device.MessageSent -= Device_MessageSent; - - await CleanUpView(); - } - + Messages = new List(); } -} + + /// + /// Index of the current View. + /// + public int SelectedViewIndex + { + get => _mISelectedViewIndex; + set + { + _mISelectedViewIndex = value; + + //Already rendered? Re-Render + if (_rendered) + { + ForceRender().Wait(); + } + } + } + + private List Messages { get; } + + + private Task Device_MessageSent(object sender, MessageSentEventArgs e) + { + if (e.Origin == null || !e.Origin.IsSubclassOf(typeof(MultiView))) + { + return Task.CompletedTask; + } + + Messages.Add(e.MessageId); + return Task.CompletedTask; + } + + public override void Init() + { + Device.MessageSent += Device_MessageSent; + } + + public override Task Load(MessageResult result) + { + _rendered = false; + return Task.CompletedTask; + } + + + public override async Task Render(MessageResult result) + { + //When already rendered, skip rendering + if (_rendered) + { + return; + } + + await CleanUpView(); + + await RenderView(new RenderViewEventArgs(SelectedViewIndex)); + + _rendered = true; + } + + + /// + /// Will get invoked on rendering the current controls view. + /// + /// + public virtual Task RenderView(RenderViewEventArgs e) + { + return Task.CompletedTask; + } + + private async Task CleanUpView() + { + var tasks = new List(); + + foreach (var msg in Messages) + { + tasks.Add(Device.DeleteMessage(msg)); + } + + await Task.WhenAll(tasks); + + Messages.Clear(); + } + + /// + /// Forces render of control contents. + /// + public async Task ForceRender() + { + await CleanUpView(); + + await RenderView(new RenderViewEventArgs(SelectedViewIndex)); + + _rendered = true; + } + + public override async Task Cleanup() + { + Device.MessageSent -= Device_MessageSent; + + await CleanUpView(); + } +} \ No newline at end of file diff --git a/TelegramBotBase/Controls/Hybrid/TaggedButtonGrid.cs b/TelegramBotBase/Controls/Hybrid/TaggedButtonGrid.cs index 1270b8f..b3ce36c 100644 --- a/TelegramBotBase/Controls/Hybrid/TaggedButtonGrid.cs +++ b/TelegramBotBase/Controls/Hybrid/TaggedButtonGrid.cs @@ -15,237 +15,373 @@ using TelegramBotBase.Form; using TelegramBotBase.Localizations; using static TelegramBotBase.Base.Async; -namespace TelegramBotBase.Controls.Hybrid +namespace TelegramBotBase.Controls.Hybrid; + +public class TaggedButtonGrid : MultiView { - public class TaggedButtonGrid : MultiView + private static readonly object EvButtonClicked = new(); + + private readonly EventHandlerList _events = new(); + + private EKeyboardType _mEKeyboardType = EKeyboardType.ReplyKeyboard; + + private bool _renderNecessary = true; + + public string BackLabel = Default.Language["ButtonGrid_Back"]; + + public string CheckAllLabel = Default.Language["ButtonGrid_CheckAll"]; + + public string NextPageLabel = Default.Language["ButtonGrid_NextPage"]; + + public string NoItemsLabel = Default.Language["ButtonGrid_NoItems"]; + + public string PreviousPageLabel = Default.Language["ButtonGrid_PreviousPage"]; + + public string SearchLabel = Default.Language["ButtonGrid_SearchFeature"]; + + public string UncheckAllLabel = Default.Language["ButtonGrid_UncheckAll"]; + + public TaggedButtonGrid() { + DataSource = new ButtonFormDataSource(); - public string Title { get; set; } = Default.Language["ButtonGrid_Title"]; + SelectedViewIndex = 0; + } - public string ConfirmationText { get; set; } + public TaggedButtonGrid(EKeyboardType type) : this() + { + _mEKeyboardType = type; + } - private bool _renderNecessary = true; - private static readonly object EvButtonClicked = new object(); + public TaggedButtonGrid(ButtonForm form) + { + DataSource = new ButtonFormDataSource(form); + } - private readonly EventHandlerList _events = new EventHandlerList(); + public string Title { get; set; } = Default.Language["ButtonGrid_Title"]; - [Obsolete("This property is obsolete. Please use the DataSource property instead.")] - public ButtonForm ButtonsForm + public string ConfirmationText { get; set; } + + [Obsolete("This property is obsolete. Please use the DataSource property instead.")] + public ButtonForm ButtonsForm + { + get => DataSource.ButtonForm; + set => DataSource = new ButtonFormDataSource(value); + } + + /// + /// Data source of the items. + /// + public ButtonFormDataSource DataSource { get; set; } + + public int? MessageId { get; set; } + + + /// + /// Optional. Requests clients to resize the keyboard vertically for optimal fit (e.g., make the keyboard smaller if + /// there are just two rows of buttons). Defaults to false, in which case the custom keyboard is always of the same + /// height as the app's standard keyboard. + /// Source: https://core.telegram.org/bots/api#replykeyboardmarkup + /// + public bool ResizeKeyboard { get; set; } = false; + + public bool OneTimeKeyboard { get; set; } = false; + + public bool HideKeyboardOnCleanup { get; set; } = true; + + public bool DeletePreviousMessage { get; set; } = true; + + /// + /// Removes the reply message from a user. + /// + public bool DeleteReplyMessage { get; set; } = true; + + /// + /// Parsemode of the message. + /// + public ParseMode MessageParseMode { get; set; } = ParseMode.Markdown; + + /// + /// Enables automatic paging of buttons when the amount of rows is exceeding the limits. + /// + public bool EnablePaging { get; set; } = false; + + /// + /// Shows un-/check all tags options + /// + public bool EnableCheckAllTools { get; set; } = false; + + /// + /// Enabled a search function. + /// + public bool EnableSearch { get; set; } = false; + + public string SearchQuery { get; set; } + + public ENavigationBarVisibility NavigationBarVisibility { get; set; } = ENavigationBarVisibility.always; + + + /// + /// Index of the current page + /// + public int CurrentPageIndex { get; set; } + + /// + /// Layout of the buttons which should be displayed always on top. + /// + public ButtonRow HeadLayoutButtonRow { get; set; } + + /// + /// Layout of columns which should be displayed below the header + /// + public ButtonRow SubHeadLayoutButtonRow { get; set; } + + /// + /// Layout of columns which should be displayed below the header + /// + private ButtonRow TagsSubHeadLayoutButtonRow { get; set; } + + /// + /// List of Tags which will be allowed to filter by. + /// + public List Tags { get; set; } + + /// + /// List of Tags selected by the User. + /// + public List SelectedTags { get; set; } + + /// + /// Defines which type of Button Keyboard should be rendered. + /// + public EKeyboardType KeyboardType + { + get => _mEKeyboardType; + set { - get => DataSource.ButtonForm; - set => DataSource = new ButtonFormDataSource(value); - } - - /// - /// Data source of the items. - /// - public ButtonFormDataSource DataSource { get; set; } - - public int? MessageId { get; set; } - - - /// - /// Optional. Requests clients to resize the keyboard vertically for optimal fit (e.g., make the keyboard smaller if there are just two rows of buttons). Defaults to false, in which case the custom keyboard is always of the same height as the app's standard keyboard. - /// Source: https://core.telegram.org/bots/api#replykeyboardmarkup - /// - public bool ResizeKeyboard { get; set; } = false; - - public bool OneTimeKeyboard { get; set; } = false; - - public bool HideKeyboardOnCleanup { get; set; } = true; - - public bool DeletePreviousMessage { get; set; } = true; - - /// - /// Removes the reply message from a user. - /// - public bool DeleteReplyMessage { get; set; } = true; - - /// - /// Parsemode of the message. - /// - public ParseMode MessageParseMode { get; set; } = ParseMode.Markdown; - - /// - /// Enables automatic paging of buttons when the amount of rows is exceeding the limits. - /// - public bool EnablePaging { get; set; } = false; - - /// - /// Shows un-/check all tags options - /// - public bool EnableCheckAllTools { get; set; } = false; - - /// - /// Enabled a search function. - /// - public bool EnableSearch { get; set; } = false; - - public string SearchQuery { get; set; } - - public ENavigationBarVisibility NavigationBarVisibility { get; set; } = ENavigationBarVisibility.always; - - - /// - /// Index of the current page - /// - public int CurrentPageIndex { get; set; } - - public string PreviousPageLabel = Default.Language["ButtonGrid_PreviousPage"]; - - public string NextPageLabel = Default.Language["ButtonGrid_NextPage"]; - - public string NoItemsLabel = Default.Language["ButtonGrid_NoItems"]; - - public string SearchLabel = Default.Language["ButtonGrid_SearchFeature"]; - - public string BackLabel = Default.Language["ButtonGrid_Back"]; - - public string CheckAllLabel = Default.Language["ButtonGrid_CheckAll"]; - - public string UncheckAllLabel = Default.Language["ButtonGrid_UncheckAll"]; - - /// - /// Layout of the buttons which should be displayed always on top. - /// - public ButtonRow HeadLayoutButtonRow { get; set; } - - /// - /// Layout of columns which should be displayed below the header - /// - public ButtonRow SubHeadLayoutButtonRow { get; set; } - - /// - /// Layout of columns which should be displayed below the header - /// - private ButtonRow TagsSubHeadLayoutButtonRow { get; set; } - - /// - /// List of Tags which will be allowed to filter by. - /// - public List Tags { get; set; } - - /// - /// List of Tags selected by the User. - /// - public List SelectedTags { get; set; } - - /// - /// Defines which type of Button Keyboard should be rendered. - /// - public EKeyboardType KeyboardType - { - get => _mEKeyboardType; - set + if (_mEKeyboardType != value) { - if (_mEKeyboardType != value) - { - _renderNecessary = true; + _renderNecessary = true; - Cleanup().Wait(); - - _mEKeyboardType = value; - } + Cleanup().Wait(); + _mEKeyboardType = value; } } + } - private EKeyboardType _mEKeyboardType = EKeyboardType.ReplyKeyboard; - public TaggedButtonGrid() + public bool PagingNecessary + { + get { - DataSource = new ButtonFormDataSource(); - - SelectedViewIndex = 0; - } - - public TaggedButtonGrid(EKeyboardType type) : this() - { - _mEKeyboardType = type; - } - - - public TaggedButtonGrid(ButtonForm form) - { - DataSource = new ButtonFormDataSource(form); - } - - - public event AsyncEventHandler ButtonClicked - { - add => _events.AddHandler(EvButtonClicked, value); - remove => _events.RemoveHandler(EvButtonClicked, value); - } - - public async Task OnButtonClicked(ButtonClickedEventArgs e) - { - var handler = _events[EvButtonClicked]?.GetInvocationList().Cast>(); - if (handler == null) - return; - - foreach (var h in handler) + if (KeyboardType == EKeyboardType.InlineKeyBoard && + TotalRows > Constants.Telegram.MaxInlineKeyBoardRows) { - await h.InvokeAllAsync(this, e); - } - } - - public override void Init() - { - Device.MessageDeleted += Device_MessageDeleted; - } - - private void Device_MessageDeleted(object sender, MessageDeletedEventArgs e) - { - if (MessageId == null) - return; - - if (e.MessageId != MessageId) - return; - - MessageId = null; - } - - public override async Task Load(MessageResult result) - { - if (KeyboardType != EKeyboardType.ReplyKeyboard) - return; - - if (!result.IsFirstHandler) - return; - - if (result.MessageText == null || result.MessageText == "") - return; - - var matches = new List(); - ButtonRow match = null; - var index = -1; - - if (HeadLayoutButtonRow?.Matches(result.MessageText) ?? false) - { - match = HeadLayoutButtonRow; - goto check; + return true; } - if (SubHeadLayoutButtonRow?.Matches(result.MessageText) ?? false) + if (KeyboardType == EKeyboardType.ReplyKeyboard && + TotalRows > Constants.Telegram.MaxReplyKeyboardRows) { - match = SubHeadLayoutButtonRow; - goto check; + return true; } - if (TagsSubHeadLayoutButtonRow?.Matches(result.MessageText) ?? false) + return false; + } + } + + public bool IsNavigationBarVisible + { + get + { + if ((NavigationBarVisibility == ENavigationBarVisibility.always) | + (NavigationBarVisibility == ENavigationBarVisibility.auto && PagingNecessary)) { - match = TagsSubHeadLayoutButtonRow; - goto check; + return true; } - var br = DataSource.FindRow(result.MessageText); - if (br != null) + return false; + } + } + + /// + /// Returns the maximum number of rows + /// + public int MaximumRow + { + get + { + return KeyboardType switch { - match = br.Item1; - index = br.Item2; + EKeyboardType.InlineKeyBoard => Constants.Telegram.MaxInlineKeyBoardRows, + EKeyboardType.ReplyKeyboard => Constants.Telegram.MaxReplyKeyboardRows, + _ => 0 + }; + } + } + + /// + /// Returns the number of all rows (layout + navigation + content); + /// + public int TotalRows => LayoutRows + DataSource.RowCount; + + + /// + /// Contains the Number of Rows which are used by the layout. + /// + private int LayoutRows + { + get + { + var layoutRows = 0; + + if ((NavigationBarVisibility == ENavigationBarVisibility.always) | + (NavigationBarVisibility == ENavigationBarVisibility.auto)) + { + layoutRows += 2; } + if (HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0) + { + layoutRows++; + } + + if (SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0) + { + layoutRows++; + } + + if (EnableCheckAllTools && SelectedViewIndex == 1) + { + layoutRows++; + } + + return layoutRows; + } + } + + /// + /// Returns the number of item rows per page. + /// + public int ItemRowsPerPage => MaximumRow - LayoutRows; + + public int PageCount + { + get + { + if (DataSource.RowCount == 0) + { + return 1; + } + + //var bf = this.DataSource.PickAllItems(this.EnableSearch ? this.SearchQuery : null); + + var max = DataSource.CalculateMax(EnableSearch ? SearchQuery : null); + + //if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "") + //{ + // bf = bf.FilterDuplicate(this.SearchQuery); + //} + + if (max == 0) + { + return 1; + } + + return (int)Math.Ceiling(max / (decimal)ItemRowsPerPage); + } + } + + + public event AsyncEventHandler ButtonClicked + { + add => _events.AddHandler(EvButtonClicked, value); + remove => _events.RemoveHandler(EvButtonClicked, value); + } + + public async Task OnButtonClicked(ButtonClickedEventArgs e) + { + var handler = _events[EvButtonClicked]?.GetInvocationList() + .Cast>(); + if (handler == null) + { + return; + } + + foreach (var h in handler) + { + await h.InvokeAllAsync(this, e); + } + } + + public override void Init() + { + Device.MessageDeleted += Device_MessageDeleted; + } + + private void Device_MessageDeleted(object sender, MessageDeletedEventArgs e) + { + if (MessageId == null) + { + return; + } + + if (e.MessageId != MessageId) + { + return; + } + + MessageId = null; + } + + public override async Task Load(MessageResult result) + { + if (KeyboardType != EKeyboardType.ReplyKeyboard) + { + return; + } + + if (!result.IsFirstHandler) + { + return; + } + + if (result.MessageText == null || result.MessageText == "") + { + return; + } + + var matches = new List(); + ButtonRow match = null; + var index = -1; + + if (HeadLayoutButtonRow?.Matches(result.MessageText) ?? false) + { + match = HeadLayoutButtonRow; + goto check; + } + + if (SubHeadLayoutButtonRow?.Matches(result.MessageText) ?? false) + { + match = SubHeadLayoutButtonRow; + goto check; + } + + if (TagsSubHeadLayoutButtonRow?.Matches(result.MessageText) ?? false) + { + match = TagsSubHeadLayoutButtonRow; + goto check; + } + + var br = DataSource.FindRow(result.MessageText); + if (br != null) + { + match = br.Item1; + index = br.Item2; + } + //var button = HeadLayoutButtonRow?. .FirstOrDefault(a => a.Text.Trim() == result.MessageText) // ?? SubHeadLayoutButtonRow?.FirstOrDefault(a => a.Text.Trim() == result.MessageText); @@ -257,172 +393,184 @@ namespace TelegramBotBase.Controls.Hybrid check: + switch (SelectedViewIndex) + { + case 0: - switch (SelectedViewIndex) - { - case 0: + //Remove button click message + if (DeleteReplyMessage) + { + await Device.DeleteMessage(result.MessageId); + } - //Remove button click message - if (DeleteReplyMessage) - await Device.DeleteMessage(result.MessageId); + if (match != null) + { + await OnButtonClicked(new ButtonClickedEventArgs(match.GetButtonMatch(result.MessageText), + index, match)); - if (match != null) + result.Handled = true; + return; + } + + if (result.MessageText == PreviousPageLabel) + { + if (CurrentPageIndex > 0) { - await OnButtonClicked(new ButtonClickedEventArgs(match.GetButtonMatch(result.MessageText), index, match)); - - result.Handled = true; - return; - } - - if (result.MessageText == PreviousPageLabel) - { - if (CurrentPageIndex > 0) - CurrentPageIndex--; - - Updated(); - result.Handled = true; - } - else if (result.MessageText == NextPageLabel) - { - if (CurrentPageIndex < PageCount - 1) - CurrentPageIndex++; - - Updated(); - result.Handled = true; - } - else if (EnableSearch) - { - if (result.MessageText.StartsWith("🔍")) - { - //Sent note about searching - if (SearchQuery == null) - { - await Device.Send(SearchLabel); - } - - SearchQuery = null; - Updated(); - result.Handled = true; - return; - } - - SearchQuery = result.MessageText; - - if (SearchQuery != null && SearchQuery != "") - { - CurrentPageIndex = 0; - Updated(); - result.Handled = true; - } - - } - else if (Tags != null) - { - if (result.MessageText == "📁") - { - //Remove button click message - if (DeletePreviousMessage) - await Device.DeleteMessage(result.MessageId); - - SelectedViewIndex = 1; - Updated(); - result.Handled = true; - } - } - - break; - case 1: - - //Remove button click message - if (DeleteReplyMessage) - await Device.DeleteMessage(result.MessageId); - - if (result.MessageText == BackLabel) - { - SelectedViewIndex = 0; - Updated(); - result.Handled = true; - return; - } - - if (result.MessageText == CheckAllLabel) - { - CheckAllTags(); - } - else if (result.MessageText == UncheckAllLabel) - { - UncheckAllTags(); - } - - var i = result.MessageText.LastIndexOf(" "); - if (i == -1) - i = result.MessageText.Length; - - var t = result.MessageText.Substring(0, i); - - if (SelectedTags.Contains(t)) - { - SelectedTags.Remove(t); - } - else - { - SelectedTags.Add(t); + CurrentPageIndex--; } Updated(); result.Handled = true; + } + else if (result.MessageText == NextPageLabel) + { + if (CurrentPageIndex < PageCount - 1) + { + CurrentPageIndex++; + } + + Updated(); + result.Handled = true; + } + else if (EnableSearch) + { + if (result.MessageText.StartsWith("🔍")) + { + //Sent note about searching + if (SearchQuery == null) + { + await Device.Send(SearchLabel); + } + + SearchQuery = null; + Updated(); + result.Handled = true; + return; + } + + SearchQuery = result.MessageText; + + if (SearchQuery != null && SearchQuery != "") + { + CurrentPageIndex = 0; + Updated(); + result.Handled = true; + } + } + else if (Tags != null) + { + if (result.MessageText == "📁") + { + //Remove button click message + if (DeletePreviousMessage) + { + await Device.DeleteMessage(result.MessageId); + } + + SelectedViewIndex = 1; + Updated(); + result.Handled = true; + } + } + + break; + case 1: + + //Remove button click message + if (DeleteReplyMessage) + { + await Device.DeleteMessage(result.MessageId); + } + + if (result.MessageText == BackLabel) + { + SelectedViewIndex = 0; + Updated(); + result.Handled = true; + return; + } + + if (result.MessageText == CheckAllLabel) + { + CheckAllTags(); + } + else if (result.MessageText == UncheckAllLabel) + { + UncheckAllTags(); + } + + var i = result.MessageText.LastIndexOf(" "); + if (i == -1) + { + i = result.MessageText.Length; + } + + var t = result.MessageText.Substring(0, i); + + if (SelectedTags.Contains(t)) + { + SelectedTags.Remove(t); + } + else + { + SelectedTags.Add(t); + } + + Updated(); + result.Handled = true; - break; - - } - - + break; + } + } + public override async Task Action(MessageResult result, string value = null) + { + if (result.Handled) + { + return; } - public override async Task Action(MessageResult result, string value = null) + if (!result.IsFirstHandler) { - if (result.Handled) - return; + return; + } - if (!result.IsFirstHandler) - return; + //Find clicked button depending on Text or Value (depending on markup type) + if (KeyboardType != EKeyboardType.InlineKeyBoard) + { + return; + } - //Find clicked button depending on Text or Value (depending on markup type) - if (KeyboardType != EKeyboardType.InlineKeyBoard) - return; + await result.ConfirmAction(ConfirmationText ?? ""); - await result.ConfirmAction(ConfirmationText ?? ""); + ButtonRow match = null; + var index = -1; - ButtonRow match = null; - var index = -1; + if (HeadLayoutButtonRow?.Matches(result.RawData, false) ?? false) + { + match = HeadLayoutButtonRow; + goto check; + } - if (HeadLayoutButtonRow?.Matches(result.RawData, false) ?? false) - { - match = HeadLayoutButtonRow; - goto check; - } + if (SubHeadLayoutButtonRow?.Matches(result.RawData, false) ?? false) + { + match = SubHeadLayoutButtonRow; + goto check; + } - if (SubHeadLayoutButtonRow?.Matches(result.RawData, false) ?? false) - { - match = SubHeadLayoutButtonRow; - goto check; - } - - if (TagsSubHeadLayoutButtonRow?.Matches(result.RawData) ?? false) - { - match = TagsSubHeadLayoutButtonRow; - goto check; - } - - var br = DataSource.FindRow(result.RawData, false); - if (br != null) - { - match = br.Item1; - index = br.Item2; - } + if (TagsSubHeadLayoutButtonRow?.Matches(result.RawData) ?? false) + { + match = TagsSubHeadLayoutButtonRow; + goto check; + } + var br = DataSource.FindRow(result.RawData, false); + if (br != null) + { + match = br.Item1; + index = br.Item2; + } //var bf = DataSource.ButtonForm; @@ -434,537 +582,439 @@ namespace TelegramBotBase.Controls.Hybrid //var index = bf.FindRowByButton(button); check: - if (match != null) - { - await OnButtonClicked(new ButtonClickedEventArgs(match.GetButtonMatch(result.RawData, false), index, match)); - - result.Handled = true; - return; - } - - switch (result.RawData) - { - case "$previous$": - - if (CurrentPageIndex > 0) - CurrentPageIndex--; - - Updated(); - - break; - - case "$next$": - - if (CurrentPageIndex < PageCount - 1) - CurrentPageIndex++; - - Updated(); - - break; - - case "$filter$": - - SelectedViewIndex = 1; - Updated(); - - break; - - case "$back$": - - SelectedViewIndex = 0; - Updated(); - - break; - - case "$checkall$": - - CheckAllTags(); - - break; - - case "$uncheckall$": - - UncheckAllTags(); - - break; - } + if (match != null) + { + await OnButtonClicked(new ButtonClickedEventArgs(match.GetButtonMatch(result.RawData, false), index, + match)); + result.Handled = true; + return; } - /// - /// This method checks of the amount of buttons - /// - private void CheckGrid() + switch (result.RawData) { - switch (_mEKeyboardType) - { - case EKeyboardType.InlineKeyBoard: + case "$previous$": - if (DataSource.RowCount > Constants.Telegram.MaxInlineKeyBoardRows && !EnablePaging) - { - throw new MaximumRowsReachedException { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxInlineKeyBoardRows }; - } - - if (DataSource.ColumnCount > Constants.Telegram.MaxInlineKeyBoardCols) - { - throw new MaximumColsException { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxInlineKeyBoardCols }; - } - - break; - - case EKeyboardType.ReplyKeyboard: - - if (DataSource.RowCount > Constants.Telegram.MaxReplyKeyboardRows && !EnablePaging) - { - throw new MaximumRowsReachedException { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxReplyKeyboardRows }; - } - - if (DataSource.ColumnCount > Constants.Telegram.MaxReplyKeyboardCols) - { - throw new MaximumColsException { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxReplyKeyboardCols }; - } - - break; - } - } - - public override async Task Render(MessageResult result) - { - if (!_renderNecessary) - return; - - //Check for rows and column limits - CheckGrid(); - - _renderNecessary = false; - - switch (SelectedViewIndex) - { - case 0: - - await RenderDataView(); - - break; - - case 1: - - - await RenderTagView(); - - - - break; - - } - - - - } - - - #region "Data View" - - private async Task RenderDataView() - { - Message m = null; - - var form = DataSource.PickItems(CurrentPageIndex * ItemRowsPerPage, ItemRowsPerPage, (EnableSearch ? SearchQuery : null)); - - //if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "") - //{ - // form = form.FilterDuplicate(this.SearchQuery, true); - //} - //else - //{ - // form = form.Duplicate(); - //} - - if (Tags != null && SelectedTags != null) - { - form = form.TagDuplicate(SelectedTags); - } - - if (EnablePaging) - { - IntegratePagingView(form); - } - - if (HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0) - { - form.InsertButtonRow(0, HeadLayoutButtonRow.ToArray()); - } - - if (SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0) - { - if (IsNavigationBarVisible) + if (CurrentPageIndex > 0) { - form.InsertButtonRow(2, SubHeadLayoutButtonRow.ToArray()); - } - else - { - form.InsertButtonRow(1, SubHeadLayoutButtonRow.ToArray()); - } - } - - switch (KeyboardType) - { - //Reply Keyboard could only be updated with a new keyboard. - case EKeyboardType.ReplyKeyboard: - - if (form.Count == 0) - { - if (MessageId != null) - { - await Device.HideReplyKeyboard(); - MessageId = null; - } - return; - } - - - var rkm = (ReplyKeyboardMarkup)form; - rkm.ResizeKeyboard = ResizeKeyboard; - rkm.OneTimeKeyboard = OneTimeKeyboard; - m = await Device.Send(Title, rkm, disableNotification: true, parseMode: MessageParseMode, markdownV2AutoEscape: false); - - //Prevent flicker of keyboard - if (DeletePreviousMessage && MessageId != null) - await Device.DeleteMessage(MessageId.Value); - - break; - - case EKeyboardType.InlineKeyBoard: - - - //Try to edit message if message id is available - //When the returned message is null then the message has been already deleted, resend it - if (MessageId != null) - { - m = await Device.Edit(MessageId.Value, Title, (InlineKeyboardMarkup)form); - if (m != null) - { - MessageId = m.MessageId; - return; - } - } - - //When no message id is available or it has been deleted due the use of AutoCleanForm re-render automatically - m = await Device.Send(Title, (InlineKeyboardMarkup)form, disableNotification: true, parseMode: MessageParseMode, markdownV2AutoEscape: false); - break; - } - - if (m != null) - { - MessageId = m.MessageId; - } - } - - private void IntegratePagingView(ButtonForm dataForm) - { - //No Items - if (dataForm.Rows == 0) - { - dataForm.AddButtonRow(new ButtonBase(NoItemsLabel, "$")); - } - - if (IsNavigationBarVisible) - { - //🔍 - var row = new ButtonRow(); - row.Add(new ButtonBase(PreviousPageLabel, "$previous$")); - row.Add(new ButtonBase(string.Format(Default.Language["ButtonGrid_CurrentPage"], CurrentPageIndex + 1, PageCount), "$site$")); - - if (Tags != null && Tags.Count > 0) - { - row.Add(new ButtonBase("📁", "$filter$")); + CurrentPageIndex--; } - row.Add(new ButtonBase(NextPageLabel, "$next$")); - - if (EnableSearch) - { - row.Insert(2, new ButtonBase("🔍 " + (SearchQuery ?? ""), "$search$")); - } - - dataForm.InsertButtonRow(0, row); - - dataForm.AddButtonRow(row); - } - } - - #endregion - - - #region "Tag View" - - - private async Task RenderTagView() - { - Message m = null; - var bf = new ButtonForm(); - - bf.AddButtonRow(BackLabel, "$back$"); - - if (EnableCheckAllTools) - { - TagsSubHeadLayoutButtonRow = new ButtonRow(new ButtonBase(CheckAllLabel, "$checkall$"), new ButtonBase(UncheckAllLabel, "$uncheckall$")); - bf.AddButtonRow(TagsSubHeadLayoutButtonRow); - } - - foreach (var t in Tags) - { - - var s = t; - - if (SelectedTags?.Contains(t) ?? false) - { - s += " ✅"; - } - - bf.AddButtonRow(s, t); - - } - - switch (KeyboardType) - { - //Reply Keyboard could only be updated with a new keyboard. - case EKeyboardType.ReplyKeyboard: - - if (bf.Count == 0) - { - if (MessageId != null) - { - await Device.HideReplyKeyboard(); - MessageId = null; - } - return; - } - - //if (bf.Count == 0) - // return; - - - var rkm = (ReplyKeyboardMarkup)bf; - rkm.ResizeKeyboard = ResizeKeyboard; - rkm.OneTimeKeyboard = OneTimeKeyboard; - m = await Device.Send("Choose category", rkm, disableNotification: true, parseMode: MessageParseMode, markdownV2AutoEscape: false); - - //Prevent flicker of keyboard - if (DeletePreviousMessage && MessageId != null) - await Device.DeleteMessage(MessageId.Value); - - break; - - case EKeyboardType.InlineKeyBoard: - - if (MessageId != null) - { - m = await Device.Edit(MessageId.Value, "Choose category", (InlineKeyboardMarkup)bf); - } - else - { - m = await Device.Send("Choose category", (InlineKeyboardMarkup)bf, disableNotification: true, parseMode: MessageParseMode, markdownV2AutoEscape: false); - } - - break; - } - - - - if (m != null) - MessageId = m.MessageId; - - } - - - #endregion - - - public bool PagingNecessary - { - get - { - if (KeyboardType == EKeyboardType.InlineKeyBoard && TotalRows > Constants.Telegram.MaxInlineKeyBoardRows) - { - return true; - } - - if (KeyboardType == EKeyboardType.ReplyKeyboard && TotalRows > Constants.Telegram.MaxReplyKeyboardRows) - { - return true; - } - - return false; - } - } - - public bool IsNavigationBarVisible - { - get - { - if (NavigationBarVisibility == ENavigationBarVisibility.always | (NavigationBarVisibility == ENavigationBarVisibility.auto && PagingNecessary)) - { - return true; - } - - return false; - } - } - - /// - /// Returns the maximum number of rows - /// - public int MaximumRow - { - get - { - return KeyboardType switch - { - EKeyboardType.InlineKeyBoard => Constants.Telegram.MaxInlineKeyBoardRows, - EKeyboardType.ReplyKeyboard => Constants.Telegram.MaxReplyKeyboardRows, - _ => 0 - }; - } - } - - /// - /// Returns the number of all rows (layout + navigation + content); - /// - public int TotalRows => LayoutRows + DataSource.RowCount; - - - /// - /// Contains the Number of Rows which are used by the layout. - /// - private int LayoutRows - { - get - { - var layoutRows = 0; - - if (NavigationBarVisibility == ENavigationBarVisibility.always | NavigationBarVisibility == ENavigationBarVisibility.auto) - layoutRows += 2; - - if (HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0) - layoutRows++; - - if (SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0) - layoutRows++; - - if (EnableCheckAllTools && SelectedViewIndex == 1) - { - layoutRows++; - } - - return layoutRows; - } - } - - /// - /// Returns the number of item rows per page. - /// - public int ItemRowsPerPage => MaximumRow - LayoutRows; - - public int PageCount - { - get - { - if (DataSource.RowCount == 0) - return 1; - - //var bf = this.DataSource.PickAllItems(this.EnableSearch ? this.SearchQuery : null); - - var max = DataSource.CalculateMax(EnableSearch ? SearchQuery : null); - - //if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "") - //{ - // bf = bf.FilterDuplicate(this.SearchQuery); - //} - - if (max == 0) - return 1; - - return (int)Math.Ceiling(max / (decimal)ItemRowsPerPage); - } - } - - public override Task Hidden(bool formClose) - { - //Prepare for opening Modal, and comming back - if (!formClose) - { Updated(); - } - else - { - //Remove event handler - Device.MessageDeleted -= Device_MessageDeleted; - } - return Task.CompletedTask; + break; + + case "$next$": + + if (CurrentPageIndex < PageCount - 1) + { + CurrentPageIndex++; + } + + Updated(); + + break; + + case "$filter$": + + SelectedViewIndex = 1; + Updated(); + + break; + + case "$back$": + + SelectedViewIndex = 0; + Updated(); + + break; + + case "$checkall$": + + CheckAllTags(); + + break; + + case "$uncheckall$": + + UncheckAllTags(); + + break; } + } - /// - /// Tells the control that it has been updated. - /// - public void Updated() + /// + /// This method checks of the amount of buttons + /// + private void CheckGrid() + { + switch (_mEKeyboardType) { - _renderNecessary = true; - } + case EKeyboardType.InlineKeyBoard: - public override async Task Cleanup() + if (DataSource.RowCount > Constants.Telegram.MaxInlineKeyBoardRows && !EnablePaging) + { + throw new MaximumRowsReachedException + { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxInlineKeyBoardRows }; + } + + if (DataSource.ColumnCount > Constants.Telegram.MaxInlineKeyBoardCols) + { + throw new MaximumColsException + { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxInlineKeyBoardCols }; + } + + break; + + case EKeyboardType.ReplyKeyboard: + + if (DataSource.RowCount > Constants.Telegram.MaxReplyKeyboardRows && !EnablePaging) + { + throw new MaximumRowsReachedException + { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxReplyKeyboardRows }; + } + + if (DataSource.ColumnCount > Constants.Telegram.MaxReplyKeyboardCols) + { + throw new MaximumColsException + { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxReplyKeyboardCols }; + } + + break; + } + } + + public override async Task Render(MessageResult result) + { + if (!_renderNecessary) { - if (MessageId == null) - return; - - switch (KeyboardType) - { - case EKeyboardType.InlineKeyBoard: - - await Device.DeleteMessage(MessageId.Value); - - MessageId = null; - - break; - case EKeyboardType.ReplyKeyboard: - - if (HideKeyboardOnCleanup) - { - await Device.HideReplyKeyboard(); - } - - MessageId = null; - - break; - } - + return; } + //Check for rows and column limits + CheckGrid(); - /// - /// Checks all tags for filtering. - /// - public void CheckAllTags() + _renderNecessary = false; + + switch (SelectedViewIndex) { - SelectedTags.Clear(); + case 0: - SelectedTags = Tags.Select(a => a).ToList(); + await RenderDataView(); - Updated(); + break; + case 1: + + + await RenderTagView(); + + + break; } - - /// - /// Unchecks all tags for filtering. - /// - public void UncheckAllTags() - { - SelectedTags.Clear(); - - Updated(); - } - } -} + #region "Tag View" + + private async Task RenderTagView() + { + Message m = null; + var bf = new ButtonForm(); + + bf.AddButtonRow(BackLabel, "$back$"); + + if (EnableCheckAllTools) + { + TagsSubHeadLayoutButtonRow = new ButtonRow(new ButtonBase(CheckAllLabel, "$checkall$"), + new ButtonBase(UncheckAllLabel, "$uncheckall$")); + bf.AddButtonRow(TagsSubHeadLayoutButtonRow); + } + + foreach (var t in Tags) + { + var s = t; + + if (SelectedTags?.Contains(t) ?? false) + { + s += " ✅"; + } + + bf.AddButtonRow(s, t); + } + + switch (KeyboardType) + { + //Reply Keyboard could only be updated with a new keyboard. + case EKeyboardType.ReplyKeyboard: + + if (bf.Count == 0) + { + if (MessageId != null) + { + await Device.HideReplyKeyboard(); + MessageId = null; + } + + return; + } + + //if (bf.Count == 0) + // return; + + + var rkm = (ReplyKeyboardMarkup)bf; + rkm.ResizeKeyboard = ResizeKeyboard; + rkm.OneTimeKeyboard = OneTimeKeyboard; + m = await Device.Send("Choose category", rkm, disableNotification: true, + parseMode: MessageParseMode, markdownV2AutoEscape: false); + + //Prevent flicker of keyboard + if (DeletePreviousMessage && MessageId != null) + { + await Device.DeleteMessage(MessageId.Value); + } + + break; + + case EKeyboardType.InlineKeyBoard: + + if (MessageId != null) + { + m = await Device.Edit(MessageId.Value, "Choose category", (InlineKeyboardMarkup)bf); + } + else + { + m = await Device.Send("Choose category", (InlineKeyboardMarkup)bf, disableNotification: true, + parseMode: MessageParseMode, markdownV2AutoEscape: false); + } + + break; + } + + + if (m != null) + { + MessageId = m.MessageId; + } + } + + #endregion + + public override Task Hidden(bool formClose) + { + //Prepare for opening Modal, and comming back + if (!formClose) + { + Updated(); + } + else + //Remove event handler + { + Device.MessageDeleted -= Device_MessageDeleted; + } + + return Task.CompletedTask; + } + + /// + /// Tells the control that it has been updated. + /// + public void Updated() + { + _renderNecessary = true; + } + + public override async Task Cleanup() + { + if (MessageId == null) + { + return; + } + + switch (KeyboardType) + { + case EKeyboardType.InlineKeyBoard: + + await Device.DeleteMessage(MessageId.Value); + + MessageId = null; + + break; + case EKeyboardType.ReplyKeyboard: + + if (HideKeyboardOnCleanup) + { + await Device.HideReplyKeyboard(); + } + + MessageId = null; + + break; + } + } + + + /// + /// Checks all tags for filtering. + /// + public void CheckAllTags() + { + SelectedTags.Clear(); + + SelectedTags = Tags.Select(a => a).ToList(); + + Updated(); + } + + /// + /// Unchecks all tags for filtering. + /// + public void UncheckAllTags() + { + SelectedTags.Clear(); + + Updated(); + } + + + #region "Data View" + + private async Task RenderDataView() + { + Message m = null; + + var form = DataSource.PickItems(CurrentPageIndex * ItemRowsPerPage, ItemRowsPerPage, + EnableSearch ? SearchQuery : null); + + //if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "") + //{ + // form = form.FilterDuplicate(this.SearchQuery, true); + //} + //else + //{ + // form = form.Duplicate(); + //} + + if (Tags != null && SelectedTags != null) + { + form = form.TagDuplicate(SelectedTags); + } + + if (EnablePaging) + { + IntegratePagingView(form); + } + + if (HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0) + { + form.InsertButtonRow(0, HeadLayoutButtonRow.ToArray()); + } + + if (SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0) + { + if (IsNavigationBarVisible) + { + form.InsertButtonRow(2, SubHeadLayoutButtonRow.ToArray()); + } + else + { + form.InsertButtonRow(1, SubHeadLayoutButtonRow.ToArray()); + } + } + + switch (KeyboardType) + { + //Reply Keyboard could only be updated with a new keyboard. + case EKeyboardType.ReplyKeyboard: + + if (form.Count == 0) + { + if (MessageId != null) + { + await Device.HideReplyKeyboard(); + MessageId = null; + } + + return; + } + + + var rkm = (ReplyKeyboardMarkup)form; + rkm.ResizeKeyboard = ResizeKeyboard; + rkm.OneTimeKeyboard = OneTimeKeyboard; + m = await Device.Send(Title, rkm, disableNotification: true, parseMode: MessageParseMode, + markdownV2AutoEscape: false); + + //Prevent flicker of keyboard + if (DeletePreviousMessage && MessageId != null) + { + await Device.DeleteMessage(MessageId.Value); + } + + break; + + case EKeyboardType.InlineKeyBoard: + + + //Try to edit message if message id is available + //When the returned message is null then the message has been already deleted, resend it + if (MessageId != null) + { + m = await Device.Edit(MessageId.Value, Title, (InlineKeyboardMarkup)form); + if (m != null) + { + MessageId = m.MessageId; + return; + } + } + + //When no message id is available or it has been deleted due the use of AutoCleanForm re-render automatically + m = await Device.Send(Title, (InlineKeyboardMarkup)form, disableNotification: true, + parseMode: MessageParseMode, markdownV2AutoEscape: false); + break; + } + + if (m != null) + { + MessageId = m.MessageId; + } + } + + private void IntegratePagingView(ButtonForm dataForm) + { + //No Items + if (dataForm.Rows == 0) + { + dataForm.AddButtonRow(new ButtonBase(NoItemsLabel, "$")); + } + + if (IsNavigationBarVisible) + { + //🔍 + var row = new ButtonRow(); + row.Add(new ButtonBase(PreviousPageLabel, "$previous$")); + row.Add(new ButtonBase( + string.Format(Default.Language["ButtonGrid_CurrentPage"], CurrentPageIndex + 1, PageCount), + "$site$")); + + if (Tags != null && Tags.Count > 0) + { + row.Add(new ButtonBase("📁", "$filter$")); + } + + row.Add(new ButtonBase(NextPageLabel, "$next$")); + + if (EnableSearch) + { + row.Insert(2, new ButtonBase("🔍 " + (SearchQuery ?? ""), "$search$")); + } + + dataForm.InsertButtonRow(0, row); + + dataForm.AddButtonRow(row); + } + } + + #endregion +} \ No newline at end of file diff --git a/TelegramBotBase/Controls/Inline/CalendarPicker.cs b/TelegramBotBase/Controls/Inline/CalendarPicker.cs index ccdd1db..4420cc1 100644 --- a/TelegramBotBase/Controls/Inline/CalendarPicker.cs +++ b/TelegramBotBase/Controls/Inline/CalendarPicker.cs @@ -10,254 +10,257 @@ using TelegramBotBase.Localizations; using static TelegramBotBase.Tools.Arrays; using static TelegramBotBase.Tools.Time; -namespace TelegramBotBase.Controls.Inline +namespace TelegramBotBase.Controls.Inline; + +public class CalendarPicker : ControlBase { - public class CalendarPicker : ControlBase + public CalendarPicker(CultureInfo culture) { + SelectedDate = DateTime.Today; + VisibleMonth = DateTime.Today; + FirstDayOfWeek = DayOfWeek.Monday; + Culture = culture; + PickerMode = EMonthPickerMode.day; + } - public DateTime SelectedDate { get; set; } + public CalendarPicker() : this(new CultureInfo("en-en")) + { + } - public DateTime VisibleMonth { get; set; } + public DateTime SelectedDate { get; set; } - public DayOfWeek FirstDayOfWeek { get; set; } + public DateTime VisibleMonth { get; set; } - public CultureInfo Culture { get; set; } + public DayOfWeek FirstDayOfWeek { get; set; } + + public CultureInfo Culture { get; set; } - private int? MessageId { get; set; } + private int? MessageId { get; set; } - public string Title { get; set; } = Default.Language["CalendarPicker_Title"]; + public string Title { get; set; } = Default.Language["CalendarPicker_Title"]; - public EMonthPickerMode PickerMode { get; set; } + public EMonthPickerMode PickerMode { get; set; } - public bool EnableDayView { get; set; } = true; + public bool EnableDayView { get; set; } = true; - public bool EnableMonthView { get; set; } = true; + public bool EnableMonthView { get; set; } = true; - public bool EnableYearView { get; set; } = true; + public bool EnableYearView { get; set; } = true; - public CalendarPicker(CultureInfo culture) + + public override async Task Action(MessageResult result, string value = null) + { + await result.ConfirmAction(); + + switch (result.RawData) { - SelectedDate = DateTime.Today; - VisibleMonth = DateTime.Today; - FirstDayOfWeek = DayOfWeek.Monday; - Culture = culture; - PickerMode = EMonthPickerMode.day; - } + case "$next$": - public CalendarPicker() : this(new CultureInfo("en-en")) { } + VisibleMonth = PickerMode switch + { + EMonthPickerMode.day => VisibleMonth.AddMonths(1), + EMonthPickerMode.month => VisibleMonth.AddYears(1), + EMonthPickerMode.year => VisibleMonth.AddYears(10), + _ => VisibleMonth + }; + break; + case "$prev$": + VisibleMonth = PickerMode switch + { + EMonthPickerMode.day => VisibleMonth.AddMonths(-1), + EMonthPickerMode.month => VisibleMonth.AddYears(-1), + EMonthPickerMode.year => VisibleMonth.AddYears(-10), + _ => VisibleMonth + }; + break; - public override async Task Action(MessageResult result, string value = null) - { - await result.ConfirmAction(); + case "$monthtitle$": - switch (result.RawData) - { - case "$next$": + if (EnableMonthView) + { + PickerMode = EMonthPickerMode.month; + } - VisibleMonth = PickerMode switch - { - EMonthPickerMode.day => VisibleMonth.AddMonths(1), - EMonthPickerMode.month => VisibleMonth.AddYears(1), - EMonthPickerMode.year => VisibleMonth.AddYears(10), - _ => VisibleMonth - }; + break; - break; - case "$prev$": + case "$yeartitle$": - VisibleMonth = PickerMode switch - { - EMonthPickerMode.day => VisibleMonth.AddMonths(-1), - EMonthPickerMode.month => VisibleMonth.AddYears(-1), - EMonthPickerMode.year => VisibleMonth.AddYears(-10), - _ => VisibleMonth - }; + if (EnableYearView) + { + PickerMode = EMonthPickerMode.year; + } - break; + break; + case "$yearstitle$": - case "$monthtitle$": + if (EnableMonthView) + { + PickerMode = EMonthPickerMode.month; + } - if (EnableMonthView) - { - PickerMode = EMonthPickerMode.month; - } + VisibleMonth = SelectedDate; - break; + break; - case "$yeartitle$": + default: - if (EnableYearView) - { - PickerMode = EMonthPickerMode.year; - } - - break; - case "$yearstitle$": - - if (EnableMonthView) - { - PickerMode = EMonthPickerMode.month; - } + var day = 0; + if (result.RawData.StartsWith("d-") && + TryParseDay(result.RawData.Split('-')[1], SelectedDate, out day)) + { + SelectedDate = new DateTime(VisibleMonth.Year, VisibleMonth.Month, day); + } + var month = 0; + if (result.RawData.StartsWith("m-") && TryParseMonth(result.RawData.Split('-')[1], out month)) + { + SelectedDate = new DateTime(VisibleMonth.Year, month, 1); VisibleMonth = SelectedDate; - break; - - default: - - var day = 0; - if (result.RawData.StartsWith("d-") && TryParseDay(result.RawData.Split('-')[1], SelectedDate, out day)) + if (EnableDayView) { - SelectedDate = new DateTime(VisibleMonth.Year, VisibleMonth.Month, day); + PickerMode = EMonthPickerMode.day; } + } - var month = 0; - if (result.RawData.StartsWith("m-") && TryParseMonth(result.RawData.Split('-')[1], out month)) + var year = 0; + if (result.RawData.StartsWith("y-") && TryParseYear(result.RawData.Split('-')[1], out year)) + { + SelectedDate = new DateTime(year, SelectedDate.Month, SelectedDate.Day); + VisibleMonth = SelectedDate; + + if (EnableMonthView) { - SelectedDate = new DateTime(VisibleMonth.Year, month, 1); - VisibleMonth = SelectedDate; - - if (EnableDayView) - { - PickerMode = EMonthPickerMode.day; - } + PickerMode = EMonthPickerMode.month; } + } - var year = 0; - if (result.RawData.StartsWith("y-") && TryParseYear(result.RawData.Split('-')[1], out year)) - { - SelectedDate = new DateTime(year, SelectedDate.Month, SelectedDate.Day); - VisibleMonth = SelectedDate; - - if (EnableMonthView) - { - PickerMode = EMonthPickerMode.month; - } - - } - - break; - } - - - + break; } - - - - public override async Task Render(MessageResult result) - { - - - - var bf = new ButtonForm(); - - switch (PickerMode) - { - case EMonthPickerMode.day: - - var month = VisibleMonth; - - var dayNamesNormal = Culture.DateTimeFormat.ShortestDayNames; - var dayNamesShifted = Shift(dayNamesNormal, (int)FirstDayOfWeek); - - bf.AddButtonRow(new ButtonBase(Default.Language["CalendarPicker_PreviousPage"], "$prev$"), new ButtonBase(Culture.DateTimeFormat.MonthNames[month.Month - 1] + " " + month.Year, "$monthtitle$"), new ButtonBase(Default.Language["CalendarPicker_NextPage"], "$next$")); - - bf.AddButtonRow(dayNamesShifted.Select(a => new ButtonBase(a, a)).ToList()); - - //First Day of month - var firstDay = new DateTime(month.Year, month.Month, 1); - - //Last Day of month - var lastDay = firstDay.LastDayOfMonth(); - - //Start of Week where first day of month is (left border) - var start = firstDay.StartOfWeek(FirstDayOfWeek); - - //End of week where last day of month is (right border) - var end = lastDay.EndOfWeek(FirstDayOfWeek); - - for (var i = 0; i <= ((end - start).Days / 7); i++) - { - var lst = new List(); - for (var id = 0; id < 7; id++) - { - var d = start.AddDays((i * 7) + id); - if (d < firstDay | d > lastDay) - { - lst.Add(new ButtonBase("-", "m-" + d.Day)); - continue; - } - - var day = d.Day.ToString(); - - if (d == DateTime.Today) - { - day = "(" + day + ")"; - } - - lst.Add(new ButtonBase((SelectedDate == d ? "[" + day + "]" : day), "d-" + d.Day)); - } - bf.AddButtonRow(lst); - } - - break; - - case EMonthPickerMode.month: - - bf.AddButtonRow(new ButtonBase(Default.Language["CalendarPicker_PreviousPage"], "$prev$"), new ButtonBase(VisibleMonth.Year.ToString("0000"), "$yeartitle$"), new ButtonBase(Default.Language["CalendarPicker_NextPage"], "$next$")); - - var months = Culture.DateTimeFormat.MonthNames; - - var buttons = months.Select((a, b) => new ButtonBase((b == SelectedDate.Month - 1 && SelectedDate.Year == VisibleMonth.Year ? "[ " + a + " ]" : a), "m-" + (b + 1))); - - bf.AddSplitted(buttons); - - break; - - case EMonthPickerMode.year: - - bf.AddButtonRow(new ButtonBase(Default.Language["CalendarPicker_PreviousPage"], "$prev$"), new ButtonBase("Year", "$yearstitle$"), new ButtonBase(Default.Language["CalendarPicker_NextPage"], "$next$")); - - var starti = Math.Floor(VisibleMonth.Year / 10f) * 10; - - for (var i = 0; i < 10; i++) - { - var m = starti + (i * 2); - bf.AddButtonRow(new ButtonBase((SelectedDate.Year == m ? "[ " + m + " ]" : m.ToString()), "y-" + m), new ButtonBase((SelectedDate.Year == (m + 1) ? "[ " + (m + 1) + " ]" : (m + 1).ToString()), "y-" + (m + 1))); - } - - break; - - } - - - if (MessageId != null) - { - var m = await Device.Edit(MessageId.Value, Title, bf); - } - else - { - var m = await Device.Send(Title, bf); - MessageId = m.MessageId; - } - } - - - - public override async Task Cleanup() - { - - if (MessageId != null) - { - await Device.DeleteMessage(MessageId.Value); - } - - } - } -} + + + public override async Task Render(MessageResult result) + { + var bf = new ButtonForm(); + + switch (PickerMode) + { + case EMonthPickerMode.day: + + var month = VisibleMonth; + + var dayNamesNormal = Culture.DateTimeFormat.ShortestDayNames; + var dayNamesShifted = Shift(dayNamesNormal, (int)FirstDayOfWeek); + + bf.AddButtonRow(new ButtonBase(Default.Language["CalendarPicker_PreviousPage"], "$prev$"), + new ButtonBase(Culture.DateTimeFormat.MonthNames[month.Month - 1] + " " + month.Year, + "$monthtitle$"), + new ButtonBase(Default.Language["CalendarPicker_NextPage"], "$next$")); + + bf.AddButtonRow(dayNamesShifted.Select(a => new ButtonBase(a, a)).ToList()); + + //First Day of month + var firstDay = new DateTime(month.Year, month.Month, 1); + + //Last Day of month + var lastDay = firstDay.LastDayOfMonth(); + + //Start of Week where first day of month is (left border) + var start = firstDay.StartOfWeek(FirstDayOfWeek); + + //End of week where last day of month is (right border) + var end = lastDay.EndOfWeek(FirstDayOfWeek); + + for (var i = 0; i <= (end - start).Days / 7; i++) + { + var lst = new List(); + for (var id = 0; id < 7; id++) + { + var d = start.AddDays(i * 7 + id); + if ((d < firstDay) | (d > lastDay)) + { + lst.Add(new ButtonBase("-", "m-" + d.Day)); + continue; + } + + var day = d.Day.ToString(); + + if (d == DateTime.Today) + { + day = "(" + day + ")"; + } + + lst.Add(new ButtonBase(SelectedDate == d ? "[" + day + "]" : day, "d-" + d.Day)); + } + + bf.AddButtonRow(lst); + } + + break; + + case EMonthPickerMode.month: + + bf.AddButtonRow(new ButtonBase(Default.Language["CalendarPicker_PreviousPage"], "$prev$"), + new ButtonBase(VisibleMonth.Year.ToString("0000"), "$yeartitle$"), + new ButtonBase(Default.Language["CalendarPicker_NextPage"], "$next$")); + + var months = Culture.DateTimeFormat.MonthNames; + + var buttons = months.Select((a, b) => + new ButtonBase( + b == SelectedDate.Month - 1 && + SelectedDate.Year == VisibleMonth.Year + ? "[ " + a + " ]" + : a, + "m-" + (b + 1))); + + bf.AddSplitted(buttons); + + break; + + case EMonthPickerMode.year: + + bf.AddButtonRow(new ButtonBase(Default.Language["CalendarPicker_PreviousPage"], "$prev$"), + new ButtonBase("Year", "$yearstitle$"), + new ButtonBase(Default.Language["CalendarPicker_NextPage"], "$next$")); + + var starti = Math.Floor(VisibleMonth.Year / 10f) * 10; + + for (var i = 0; i < 10; i++) + { + var m = starti + i * 2; + bf.AddButtonRow( + new ButtonBase(SelectedDate.Year == m ? "[ " + m + " ]" : m.ToString(), "y-" + m), + new ButtonBase(SelectedDate.Year == m + 1 ? "[ " + (m + 1) + " ]" : (m + 1).ToString(), + "y-" + (m + 1))); + } + + break; + } + + + if (MessageId != null) + { + var m = await Device.Edit(MessageId.Value, Title, bf); + } + else + { + var m = await Device.Send(Title, bf); + MessageId = m.MessageId; + } + } + + + public override async Task Cleanup() + { + if (MessageId != null) + { + await Device.DeleteMessage(MessageId.Value); + } + } +} \ No newline at end of file diff --git a/TelegramBotBase/Controls/Inline/MonthPicker.cs b/TelegramBotBase/Controls/Inline/MonthPicker.cs index a5032b1..d6b5fb1 100644 --- a/TelegramBotBase/Controls/Inline/MonthPicker.cs +++ b/TelegramBotBase/Controls/Inline/MonthPicker.cs @@ -1,18 +1,12 @@ using TelegramBotBase.Enums; -namespace TelegramBotBase.Controls.Inline +namespace TelegramBotBase.Controls.Inline; + +public class MonthPicker : CalendarPicker { - public class MonthPicker : CalendarPicker + public MonthPicker() { - - - - public MonthPicker() - { - PickerMode = EMonthPickerMode.month; - EnableDayView = false; - } - - + PickerMode = EMonthPickerMode.month; + EnableDayView = false; } -} +} \ No newline at end of file diff --git a/TelegramBotBase/Controls/Inline/MultiToggleButton.cs b/TelegramBotBase/Controls/Inline/MultiToggleButton.cs index fa8f159..488a5f1 100644 --- a/TelegramBotBase/Controls/Inline/MultiToggleButton.cs +++ b/TelegramBotBase/Controls/Inline/MultiToggleButton.cs @@ -6,152 +6,147 @@ using TelegramBotBase.Base; using TelegramBotBase.Form; using TelegramBotBase.Localizations; -namespace TelegramBotBase.Controls.Inline +namespace TelegramBotBase.Controls.Inline; + +public class MultiToggleButton : ControlBase { - public class MultiToggleButton : ControlBase + private static readonly object EvToggled = new(); + + private readonly EventHandlerList _events = new(); + + private bool _renderNecessary = true; + + + public MultiToggleButton() { - /// - /// This contains the selected icon. - /// - public string SelectedIcon { get; set; } = Default.Language["MultiToggleButton_SelectedIcon"]; + Options = new List(); + } - /// - /// This will appear on the ConfirmAction message (if not empty) - /// - public string ChangedString { get; set; } = Default.Language["MultiToggleButton_Changed"]; + /// + /// This contains the selected icon. + /// + public string SelectedIcon { get; set; } = Default.Language["MultiToggleButton_SelectedIcon"]; - /// - /// This holds the title of the control. - /// - public string Title { get; set; } = Default.Language["MultiToggleButton_Title"]; + /// + /// This will appear on the ConfirmAction message (if not empty) + /// + public string ChangedString { get; set; } = Default.Language["MultiToggleButton_Changed"]; - public int? MessageId { get; set; } + /// + /// This holds the title of the control. + /// + public string Title { get; set; } = Default.Language["MultiToggleButton_Title"]; - private bool _renderNecessary = true; + public int? MessageId { get; set; } - private static readonly object EvToggled = new object(); + /// + /// This will hold all options available. + /// + public List Options { get; set; } - private readonly EventHandlerList _events = new EventHandlerList(); + /// + /// This will set if an empty selection (null) is allowed. + /// + public bool AllowEmptySelection { get; set; } = true; - /// - /// This will hold all options available. - /// - public List Options { get; set; } + public ButtonBase SelectedOption { get; set; } - /// - /// This will set if an empty selection (null) is allowed. - /// - public bool AllowEmptySelection { get; set; } = true; + public event EventHandler Toggled + { + add => _events.AddHandler(EvToggled, value); + remove => _events.RemoveHandler(EvToggled, value); + } + public void OnToggled(EventArgs e) + { + (_events[EvToggled] as EventHandler)?.Invoke(this, e); + } - public MultiToggleButton() + public override async Task Action(MessageResult result, string value = null) + { + if (result.Handled) { - Options = new List(); + return; } - public event EventHandler Toggled + await result.ConfirmAction(ChangedString); + + switch (value ?? "unknown") { - add => _events.AddHandler(EvToggled, value); - remove => _events.RemoveHandler(EvToggled, value); - } + default: - public void OnToggled(EventArgs e) - { - (_events[EvToggled] as EventHandler)?.Invoke(this, e); - } + var s = value.Split('$'); - public override async Task Action(MessageResult result, string value = null) - { - if (result.Handled) - return; - - await result.ConfirmAction(ChangedString); - - switch (value ?? "unknown") - { - default: - - var s = value.Split('$'); - - if (s[0] == "check" && s.Length > 1) + if (s[0] == "check" && s.Length > 1) + { + var index = 0; + if (!int.TryParse(s[1], out index)) { - var index = 0; - if (!int.TryParse(s[1], out index)) - { - return; - } - - if(SelectedOption== null || SelectedOption != Options[index]) - { - SelectedOption = Options[index]; - OnToggled(EventArgs.Empty); - } - else if(AllowEmptySelection) - { - SelectedOption = null; - OnToggled(EventArgs.Empty); - } - - _renderNecessary = true; - return; } + if (SelectedOption == null || SelectedOption != Options[index]) + { + SelectedOption = Options[index]; + OnToggled(EventArgs.Empty); + } + else if (AllowEmptySelection) + { + SelectedOption = null; + OnToggled(EventArgs.Empty); + } - _renderNecessary = false; + _renderNecessary = true; - break; - - } - - result.Handled = true; - - } - - public override async Task Render(MessageResult result) - { - if (!_renderNecessary) - return; - - var bf = new ButtonForm(this); - - var lst = new List(); - foreach (var o in Options) - { - var index = Options.IndexOf(o); - if (o == SelectedOption) - { - lst.Add(new ButtonBase(SelectedIcon + " " + o.Text, "check$" + index)); - continue; + return; } - lst.Add(new ButtonBase(o.Text, "check$" + index)); - } - - bf.AddButtonRow(lst); - - if (MessageId != null) - { - var m = await Device.Edit(MessageId.Value, Title, bf); - } - else - { - var m = await Device.Send(Title, bf, disableNotification: true); - if (m != null) - { - MessageId = m.MessageId; - } - } - - _renderNecessary = false; + _renderNecessary = false; + break; } - public ButtonBase SelectedOption - { - get; set; - } - + result.Handled = true; } -} + + public override async Task Render(MessageResult result) + { + if (!_renderNecessary) + { + return; + } + + var bf = new ButtonForm(this); + + var lst = new List(); + foreach (var o in Options) + { + var index = Options.IndexOf(o); + if (o == SelectedOption) + { + lst.Add(new ButtonBase(SelectedIcon + " " + o.Text, "check$" + index)); + continue; + } + + lst.Add(new ButtonBase(o.Text, "check$" + index)); + } + + bf.AddButtonRow(lst); + + if (MessageId != null) + { + var m = await Device.Edit(MessageId.Value, Title, bf); + } + else + { + var m = await Device.Send(Title, bf, disableNotification: true); + if (m != null) + { + MessageId = m.MessageId; + } + } + + _renderNecessary = false; + } +} \ No newline at end of file diff --git a/TelegramBotBase/Controls/Inline/ProgressBar.cs b/TelegramBotBase/Controls/Inline/ProgressBar.cs index 2dde19a..ab2fc89 100644 --- a/TelegramBotBase/Controls/Inline/ProgressBar.cs +++ b/TelegramBotBase/Controls/Inline/ProgressBar.cs @@ -2,266 +2,255 @@ using System.Threading.Tasks; using TelegramBotBase.Base; -namespace TelegramBotBase.Controls.Inline +namespace TelegramBotBase.Controls.Inline; + +/// +/// A simple control for show and managing progress. +/// +public class ProgressBar : ControlBase { - /// - /// A simple control for show and managing progress. - /// - public class ProgressBar : ControlBase + public enum EProgressStyle { - public enum EProgressStyle - { - standard = 0, - squares = 1, - circles = 2, - lines = 3, - squaredLines = 4, - custom = 10 - } - - public EProgressStyle ProgressStyle - { - get => _mEStyle; - set - { - _mEStyle = value; - LoadStyle(); - } - } - - private EProgressStyle _mEStyle = EProgressStyle.standard; - - - public int Value - { - get => _mIValue; - set - { - if (value > Max) - { - return; - } - - if (_mIValue != value) - { - RenderNecessary = true; - } - _mIValue = value; - } - } - - private int _mIValue; - - public int Max - { - get => _mIMax; - set - { - if (_mIMax != value) - { - RenderNecessary = true; - } - _mIMax = value; - } - } - - private int _mIMax = 100; - - public int? MessageId { get; set; } - - private bool RenderNecessary { get; set; } - - public int Steps - { - get - { - return ProgressStyle switch - { - EProgressStyle.standard => 1, - EProgressStyle.squares => 10, - EProgressStyle.circles => 10, - EProgressStyle.lines => 5, - EProgressStyle.squaredLines => 5, - _ => 1 - }; - } - } - - /// - /// Filled block (reached percentage) - /// - public string BlockChar - { - get; set; - } - - /// - /// Unfilled block (not reached yet) - /// - public string EmptyBlockChar - { - get; set; - } - - /// - /// String at the beginning of the progress bar - /// - public string StartChar - { - get; set; - } - - /// - /// String at the end of the progress bar - /// - public string EndChar - { - get; set; - } - - public ProgressBar() - { - ProgressStyle = EProgressStyle.standard; - - Value = 0; - Max = 100; - - RenderNecessary = true; - } - - public ProgressBar(int value, int max, EProgressStyle style) - { - this.Value = value; - this.Max = max; - ProgressStyle = style; - - RenderNecessary = true; - } - - public override async Task Cleanup() - { - if (MessageId == null || MessageId == -1) - return; - - - await Device.DeleteMessage(MessageId.Value); - } - - public void LoadStyle() - { - StartChar = ""; - EndChar = ""; - - switch (ProgressStyle) - { - case EProgressStyle.circles: - - BlockChar = "⚫️ "; - EmptyBlockChar = "⚪️ "; - - break; - case EProgressStyle.squares: - - BlockChar = "⬛️ "; - EmptyBlockChar = "⬜️ "; - - break; - case EProgressStyle.lines: - - BlockChar = "█"; - EmptyBlockChar = "▁"; - - break; - case EProgressStyle.squaredLines: - - BlockChar = "▇"; - EmptyBlockChar = "—"; - - StartChar = "["; - EndChar = "]"; - - break; - case EProgressStyle.standard: - case EProgressStyle.custom: - - BlockChar = ""; - EmptyBlockChar = ""; - - break; - } - - } - - public override async Task Render(MessageResult result) - { - if (!RenderNecessary) - { - return; - } - - if (Device == null) - { - return; - } - - var message = ""; - var blocks = 0; - var maxBlocks = 0; - - switch (ProgressStyle) - { - case EProgressStyle.standard: - - message = Value.ToString("0") + "%"; - - break; - - case EProgressStyle.squares: - case EProgressStyle.circles: - case EProgressStyle.lines: - case EProgressStyle.squaredLines: - case EProgressStyle.custom: - - blocks = (int)Math.Floor((decimal)Value / Steps); - - maxBlocks = (Max / Steps); - - message += StartChar; - - for (var i = 0; i < blocks; i++) - { - message += BlockChar; - } - - for (var i = 0; i < (maxBlocks - blocks); i++) - { - message += EmptyBlockChar; - } - - message += EndChar; - - message += " " + Value.ToString("0") + "%"; - - break; - - default: - - return; - } - - if (MessageId == null) - { - var m = await Device.Send(message); - - MessageId = m.MessageId; - } - else - { - await Device.Edit(MessageId.Value, message); - } - - RenderNecessary = false; - } - + standard = 0, + squares = 1, + circles = 2, + lines = 3, + squaredLines = 4, + custom = 10 } -} + + private EProgressStyle _mEStyle = EProgressStyle.standard; + + private int _mIMax = 100; + + private int _mIValue; + + public ProgressBar() + { + ProgressStyle = EProgressStyle.standard; + + Value = 0; + Max = 100; + + RenderNecessary = true; + } + + public ProgressBar(int value, int max, EProgressStyle style) + { + Value = value; + Max = max; + ProgressStyle = style; + + RenderNecessary = true; + } + + public EProgressStyle ProgressStyle + { + get => _mEStyle; + set + { + _mEStyle = value; + LoadStyle(); + } + } + + + public int Value + { + get => _mIValue; + set + { + if (value > Max) + { + return; + } + + if (_mIValue != value) + { + RenderNecessary = true; + } + + _mIValue = value; + } + } + + public int Max + { + get => _mIMax; + set + { + if (_mIMax != value) + { + RenderNecessary = true; + } + + _mIMax = value; + } + } + + public int? MessageId { get; set; } + + private bool RenderNecessary { get; set; } + + public int Steps + { + get + { + return ProgressStyle switch + { + EProgressStyle.standard => 1, + EProgressStyle.squares => 10, + EProgressStyle.circles => 10, + EProgressStyle.lines => 5, + EProgressStyle.squaredLines => 5, + _ => 1 + }; + } + } + + /// + /// Filled block (reached percentage) + /// + public string BlockChar { get; set; } + + /// + /// Unfilled block (not reached yet) + /// + public string EmptyBlockChar { get; set; } + + /// + /// String at the beginning of the progress bar + /// + public string StartChar { get; set; } + + /// + /// String at the end of the progress bar + /// + public string EndChar { get; set; } + + public override async Task Cleanup() + { + if (MessageId == null || MessageId == -1) + { + return; + } + + + await Device.DeleteMessage(MessageId.Value); + } + + public void LoadStyle() + { + StartChar = ""; + EndChar = ""; + + switch (ProgressStyle) + { + case EProgressStyle.circles: + + BlockChar = "⚫️ "; + EmptyBlockChar = "⚪️ "; + + break; + case EProgressStyle.squares: + + BlockChar = "⬛️ "; + EmptyBlockChar = "⬜️ "; + + break; + case EProgressStyle.lines: + + BlockChar = "█"; + EmptyBlockChar = "▁"; + + break; + case EProgressStyle.squaredLines: + + BlockChar = "▇"; + EmptyBlockChar = "—"; + + StartChar = "["; + EndChar = "]"; + + break; + case EProgressStyle.standard: + case EProgressStyle.custom: + + BlockChar = ""; + EmptyBlockChar = ""; + + break; + } + } + + public override async Task Render(MessageResult result) + { + if (!RenderNecessary) + { + return; + } + + if (Device == null) + { + return; + } + + var message = ""; + var blocks = 0; + var maxBlocks = 0; + + switch (ProgressStyle) + { + case EProgressStyle.standard: + + message = Value.ToString("0") + "%"; + + break; + + case EProgressStyle.squares: + case EProgressStyle.circles: + case EProgressStyle.lines: + case EProgressStyle.squaredLines: + case EProgressStyle.custom: + + blocks = (int)Math.Floor((decimal)Value / Steps); + + maxBlocks = Max / Steps; + + message += StartChar; + + for (var i = 0; i < blocks; i++) + { + message += BlockChar; + } + + for (var i = 0; i < maxBlocks - blocks; i++) + { + message += EmptyBlockChar; + } + + message += EndChar; + + message += " " + Value.ToString("0") + "%"; + + break; + + default: + + return; + } + + if (MessageId == null) + { + var m = await Device.Send(message); + + MessageId = m.MessageId; + } + else + { + await Device.Edit(MessageId.Value, message); + } + + RenderNecessary = false; + } +} \ No newline at end of file diff --git a/TelegramBotBase/Controls/Inline/ToggleButton.cs b/TelegramBotBase/Controls/Inline/ToggleButton.cs index 8f27415..4c7811e 100644 --- a/TelegramBotBase/Controls/Inline/ToggleButton.cs +++ b/TelegramBotBase/Controls/Inline/ToggleButton.cs @@ -5,135 +5,133 @@ using TelegramBotBase.Base; using TelegramBotBase.Form; using TelegramBotBase.Localizations; -namespace TelegramBotBase.Controls.Inline +namespace TelegramBotBase.Controls.Inline; + +public class ToggleButton : ControlBase { - public class ToggleButton : ControlBase + private static readonly object EvToggled = new(); + + private readonly EventHandlerList _events = new(); + + private bool _renderNecessary = true; + + + public ToggleButton() { - - public string UncheckedIcon { get; set; } = Default.Language["ToggleButton_OffIcon"]; - - public string CheckedIcon { get; set; } = Default.Language["ToggleButton_OnIcon"]; - - public string CheckedString { get; set; } = Default.Language["ToggleButton_On"]; - - public string UncheckedString { get; set; } = Default.Language["ToggleButton_Off"]; - - public string ChangedString { get; set; } = Default.Language["ToggleButton_Changed"]; - - public string Title { get; set; } = Default.Language["ToggleButton_Title"]; - - public int? MessageId { get; set; } - - public bool Checked { get; set; } - - private bool _renderNecessary = true; - - private static readonly object EvToggled = new object(); - - private readonly EventHandlerList _events = new EventHandlerList(); - - - public ToggleButton() - { - - - } - - public ToggleButton(string checkedString, string uncheckedString) - { - this.CheckedString = checkedString; - this.UncheckedString = uncheckedString; - } - - public event EventHandler Toggled - { - add => _events.AddHandler(EvToggled, value); - remove => _events.RemoveHandler(EvToggled, value); - } - - public void OnToggled(EventArgs e) - { - (_events[EvToggled] as EventHandler)?.Invoke(this, e); - } - - public override async Task Action(MessageResult result, string value = null) - { - - if (result.Handled) - return; - - await result.ConfirmAction(ChangedString); - - switch (value ?? "unknown") - { - case "on": - - if (Checked) - return; - - _renderNecessary = true; - - Checked = true; - - OnToggled(EventArgs.Empty); - - break; - - case "off": - - if (!Checked) - return; - - _renderNecessary = true; - - Checked = false; - - OnToggled(EventArgs.Empty); - - break; - - default: - - _renderNecessary = false; - - break; - - } - - result.Handled = true; - - } - - public override async Task Render(MessageResult result) - { - if (!_renderNecessary) - return; - - var bf = new ButtonForm(this); - - var bOn = new ButtonBase((Checked ? CheckedIcon : UncheckedIcon) + " " + CheckedString, "on"); - - var bOff = new ButtonBase((!Checked ? CheckedIcon : UncheckedIcon) + " " + UncheckedString, "off"); - - bf.AddButtonRow(bOn, bOff); - - if (MessageId != null) - { - var m = await Device.Edit(MessageId.Value, Title, bf); - } - else - { - var m = await Device.Send(Title, bf, disableNotification: true); - if (m != null) - { - MessageId = m.MessageId; - } - } - - _renderNecessary = false; - - - } - } -} + + public ToggleButton(string checkedString, string uncheckedString) + { + CheckedString = checkedString; + UncheckedString = uncheckedString; + } + + public string UncheckedIcon { get; set; } = Default.Language["ToggleButton_OffIcon"]; + + public string CheckedIcon { get; set; } = Default.Language["ToggleButton_OnIcon"]; + + public string CheckedString { get; set; } = Default.Language["ToggleButton_On"]; + + public string UncheckedString { get; set; } = Default.Language["ToggleButton_Off"]; + + public string ChangedString { get; set; } = Default.Language["ToggleButton_Changed"]; + + public string Title { get; set; } = Default.Language["ToggleButton_Title"]; + + public int? MessageId { get; set; } + + public bool Checked { get; set; } + + public event EventHandler Toggled + { + add => _events.AddHandler(EvToggled, value); + remove => _events.RemoveHandler(EvToggled, value); + } + + public void OnToggled(EventArgs e) + { + (_events[EvToggled] as EventHandler)?.Invoke(this, e); + } + + public override async Task Action(MessageResult result, string value = null) + { + if (result.Handled) + { + return; + } + + await result.ConfirmAction(ChangedString); + + switch (value ?? "unknown") + { + case "on": + + if (Checked) + { + return; + } + + _renderNecessary = true; + + Checked = true; + + OnToggled(EventArgs.Empty); + + break; + + case "off": + + if (!Checked) + { + return; + } + + _renderNecessary = true; + + Checked = false; + + OnToggled(EventArgs.Empty); + + break; + + default: + + _renderNecessary = false; + + break; + } + + result.Handled = true; + } + + public override async Task Render(MessageResult result) + { + if (!_renderNecessary) + { + return; + } + + var bf = new ButtonForm(this); + + var bOn = new ButtonBase((Checked ? CheckedIcon : UncheckedIcon) + " " + CheckedString, "on"); + + var bOff = new ButtonBase((!Checked ? CheckedIcon : UncheckedIcon) + " " + UncheckedString, "off"); + + bf.AddButtonRow(bOn, bOff); + + if (MessageId != null) + { + var m = await Device.Edit(MessageId.Value, Title, bf); + } + else + { + var m = await Device.Send(Title, bf, disableNotification: true); + if (m != null) + { + MessageId = m.MessageId; + } + } + + _renderNecessary = false; + } +} \ No newline at end of file diff --git a/TelegramBotBase/Controls/Inline/TreeView.cs b/TelegramBotBase/Controls/Inline/TreeView.cs index e3b6612..1aee568 100644 --- a/TelegramBotBase/Controls/Inline/TreeView.cs +++ b/TelegramBotBase/Controls/Inline/TreeView.cs @@ -5,117 +5,117 @@ using TelegramBotBase.Base; using TelegramBotBase.Form; using TelegramBotBase.Localizations; -namespace TelegramBotBase.Controls.Inline +namespace TelegramBotBase.Controls.Inline; + +public class TreeView : ControlBase { - public class TreeView : ControlBase + public TreeView() { - public List Nodes { get; set; } + Nodes = new List(); + Title = Default.Language["TreeView_Title"]; + } - public TreeViewNode SelectedNode { get; set; } + public List Nodes { get; set; } - public TreeViewNode VisibleNode { get; set; } + public TreeViewNode SelectedNode { get; set; } - public string Title { get; set; } + public TreeViewNode VisibleNode { get; set; } - private int? MessageId { get; set; } + public string Title { get; set; } - public string MoveUpIcon { get; set; } = Default.Language["TreeView_LevelUp"]; + private int? MessageId { get; set; } - public TreeView() + public string MoveUpIcon { get; set; } = Default.Language["TreeView_LevelUp"]; + + + public override async Task Action(MessageResult result, string value = null) + { + await result.ConfirmAction(); + + if (result.Handled) { - Nodes = new List(); - Title = Default.Language["TreeView_Title"]; + return; } + var val = result.RawData; - public override async Task Action(MessageResult result, string value = null) + switch (val) { - await result.ConfirmAction(); + case "up": + case "parent": - if (result.Handled) - return; + VisibleNode = VisibleNode?.ParentNode; - var val = result.RawData; + result.Handled = true; - switch (val) - { - case "up": - case "parent": + break; + default: - VisibleNode = (VisibleNode?.ParentNode); + var n = VisibleNode != null + ? VisibleNode.FindNodeByValue(val) + : Nodes.FirstOrDefault(a => a.Value == val); - result.Handled = true; - - break; - default: - - var n = (VisibleNode != null ? VisibleNode.FindNodeByValue(val) : Nodes.FirstOrDefault(a => a.Value == val)); - - if (n == null) - return; - - - if (n.ChildNodes.Count > 0) - { - VisibleNode = n; - } - else - { - SelectedNode = (SelectedNode != n ? n : null); - } - - result.Handled = true; - - - break; - - } - - } - - - public override async Task Render(MessageResult result) - { - var startnode = VisibleNode; - - var nodes = (startnode?.ChildNodes ?? Nodes); - - var bf = new ButtonForm(); - - if (startnode != null) - { - bf.AddButtonRow(new ButtonBase(MoveUpIcon, "up"), new ButtonBase(startnode.Text, "parent")); - } - - foreach (var n in nodes) - { - var s = n.Text; - if (SelectedNode == n) + if (n == null) { - s = "[ " + s + " ]"; + return; } - bf.AddButtonRow(new ButtonBase(s, n.Value, n.Url)); - } + + if (n.ChildNodes.Count > 0) + { + VisibleNode = n; + } + else + { + SelectedNode = SelectedNode != n ? n : null; + } + + result.Handled = true; - - if (MessageId != null) - { - var m = await Device.Edit(MessageId.Value, Title, bf); - } - else - { - var m = await Device.Send(Title, bf); - MessageId = m.MessageId; - } + break; } - - public string GetPath() - { - return (VisibleNode?.GetPath() ?? "\\"); - } - - } -} + + + public override async Task Render(MessageResult result) + { + var startnode = VisibleNode; + + var nodes = startnode?.ChildNodes ?? Nodes; + + var bf = new ButtonForm(); + + if (startnode != null) + { + bf.AddButtonRow(new ButtonBase(MoveUpIcon, "up"), new ButtonBase(startnode.Text, "parent")); + } + + foreach (var n in nodes) + { + var s = n.Text; + if (SelectedNode == n) + { + s = "[ " + s + " ]"; + } + + bf.AddButtonRow(new ButtonBase(s, n.Value, n.Url)); + } + + + if (MessageId != null) + { + var m = await Device.Edit(MessageId.Value, Title, bf); + } + else + { + var m = await Device.Send(Title, bf); + MessageId = m.MessageId; + } + } + + public string GetPath() + { + return VisibleNode?.GetPath() ?? "\\"; + } +} \ No newline at end of file diff --git a/TelegramBotBase/Controls/Inline/TreeViewNode.cs b/TelegramBotBase/Controls/Inline/TreeViewNode.cs index 4219f49..b714bbd 100644 --- a/TelegramBotBase/Controls/Inline/TreeViewNode.cs +++ b/TelegramBotBase/Controls/Inline/TreeViewNode.cs @@ -1,62 +1,61 @@ using System.Collections.Generic; using System.Linq; -namespace TelegramBotBase.Controls.Inline +namespace TelegramBotBase.Controls.Inline; + +public class TreeViewNode { - public class TreeViewNode + public TreeViewNode(string text, string value) { - public string Text { get; set; } - - public string Value { get; set; } - - public string Url { get; set; } - - public List ChildNodes { get; set; } = new List(); - - public TreeViewNode ParentNode { get; set; } - - public TreeViewNode(string text, string value) - { - this.Text = text; - this.Value = value; - } - - public TreeViewNode(string text, string value, string url) : this(text, value) - { - this.Url = url; - } - - public TreeViewNode(string text, string value, params TreeViewNode[] childnodes) : this(text, value) - { - foreach(var c in childnodes) - { - AddNode(c); - } - } - - - public void AddNode(TreeViewNode node) - { - node.ParentNode = this; - ChildNodes.Add(node); - } - - public TreeViewNode FindNodeByValue(string value) - { - return ChildNodes.FirstOrDefault(a => a.Value == value); - } - - public string GetPath() - { - var s = "\\" + Value; - var p = this; - while (p.ParentNode != null) - { - s = "\\" + p.ParentNode.Value + s; - p = p.ParentNode; - } - return s; - } - + Text = text; + Value = value; } -} + + public TreeViewNode(string text, string value, string url) : this(text, value) + { + Url = url; + } + + public TreeViewNode(string text, string value, params TreeViewNode[] childnodes) : this(text, value) + { + foreach (var c in childnodes) + { + AddNode(c); + } + } + + public string Text { get; set; } + + public string Value { get; set; } + + public string Url { get; set; } + + public List ChildNodes { get; set; } = new(); + + public TreeViewNode ParentNode { get; set; } + + + public void AddNode(TreeViewNode node) + { + node.ParentNode = this; + ChildNodes.Add(node); + } + + public TreeViewNode FindNodeByValue(string value) + { + return ChildNodes.FirstOrDefault(a => a.Value == value); + } + + public string GetPath() + { + var s = "\\" + Value; + var p = this; + while (p.ParentNode != null) + { + s = "\\" + p.ParentNode.Value + s; + p = p.ParentNode; + } + + return s; + } +} \ No newline at end of file diff --git a/TelegramBotBase/DataSources/ButtonFormDataSource.cs b/TelegramBotBase/DataSources/ButtonFormDataSource.cs index 3b90ec8..c14b7e3 100644 --- a/TelegramBotBase/DataSources/ButtonFormDataSource.cs +++ b/TelegramBotBase/DataSources/ButtonFormDataSource.cs @@ -4,132 +4,134 @@ using TelegramBotBase.Controls.Hybrid; using TelegramBotBase.Form; using TelegramBotBase.Interfaces; -namespace TelegramBotBase.DataSources +namespace TelegramBotBase.DataSources; + +public class ButtonFormDataSource : IDataSource { - public class ButtonFormDataSource : IDataSource + private ButtonForm _buttonform; + + public ButtonFormDataSource() { - public virtual ButtonForm ButtonForm - { - get => _buttonform; - set => _buttonform = value; - } - - private ButtonForm _buttonform; - - public ButtonFormDataSource() - { - _buttonform = new ButtonForm(); - } - - public ButtonFormDataSource(ButtonForm bf) - { - _buttonform = bf; - } - - - /// - /// Returns the amount of rows exisiting. - /// - /// - public virtual int Count => ButtonForm.Count; - - - /// - /// Returns the amount of rows. - /// - public virtual int RowCount => ButtonForm.Rows; - - /// - /// Returns the maximum amount of columns. - /// - public virtual int ColumnCount => ButtonForm.Cols; - - /// - /// Returns the row with the specific index. - /// - /// - /// - public virtual ButtonRow ItemAt(int index) - { - return ButtonForm[index]; - } - - public virtual List ItemRange(int start, int count) - { - return ButtonForm.GetRange(start, count); - } - - public virtual List AllItems() - { - return ButtonForm.ToArray(); - } - - public virtual ButtonForm PickItems(int start, int count, string filter = null) - { - var bf = new ButtonForm(); - ButtonForm dataForm = null; - - if (filter == null) - { - dataForm = ButtonForm.Duplicate(); - } - else - { - dataForm = ButtonForm.FilterDuplicate(filter, true); - } - - for (var i = 0; i < count; i++) - { - var it = start + i; - - if (it > dataForm.Rows - 1) - break; - - bf.AddButtonRow(dataForm[it]); - } - - return bf; - } - - public virtual ButtonForm PickAllItems(string filter = null) - { - if (filter == null) - return ButtonForm.Duplicate(); - - - return ButtonForm.FilterDuplicate(filter, true); - } - - public virtual Tuple FindRow(string text, bool useText = true) - { - return ButtonForm.FindRow(text, useText); - } - - /// - /// Returns the maximum items of this data source. - /// - /// - /// - public virtual int CalculateMax(string filter = null) - { - return PickAllItems(filter).Rows; - } - - public virtual ButtonRow Render(object data) - { - return data as ButtonRow; - } - - - public static implicit operator ButtonFormDataSource(ButtonForm bf) - { - return new ButtonFormDataSource(bf); - } - - public static implicit operator ButtonForm(ButtonFormDataSource ds) - { - return ds.ButtonForm; - } - + _buttonform = new ButtonForm(); } -} + + public ButtonFormDataSource(ButtonForm bf) + { + _buttonform = bf; + } + + public virtual ButtonForm ButtonForm + { + get => _buttonform; + set => _buttonform = value; + } + + + /// + /// Returns the amount of rows. + /// + public virtual int RowCount => ButtonForm.Rows; + + /// + /// Returns the maximum amount of columns. + /// + public virtual int ColumnCount => ButtonForm.Cols; + + + /// + /// Returns the amount of rows exisiting. + /// + /// + public virtual int Count => ButtonForm.Count; + + /// + /// Returns the row with the specific index. + /// + /// + /// + public virtual ButtonRow ItemAt(int index) + { + return ButtonForm[index]; + } + + public virtual List ItemRange(int start, int count) + { + return ButtonForm.GetRange(start, count); + } + + public virtual List AllItems() + { + return ButtonForm.ToArray(); + } + + public virtual ButtonForm PickItems(int start, int count, string filter = null) + { + var bf = new ButtonForm(); + ButtonForm dataForm = null; + + if (filter == null) + { + dataForm = ButtonForm.Duplicate(); + } + else + { + dataForm = ButtonForm.FilterDuplicate(filter, true); + } + + for (var i = 0; i < count; i++) + { + var it = start + i; + + if (it > dataForm.Rows - 1) + { + break; + } + + bf.AddButtonRow(dataForm[it]); + } + + return bf; + } + + public virtual ButtonForm PickAllItems(string filter = null) + { + if (filter == null) + { + return ButtonForm.Duplicate(); + } + + + return ButtonForm.FilterDuplicate(filter, true); + } + + public virtual Tuple FindRow(string text, bool useText = true) + { + return ButtonForm.FindRow(text, useText); + } + + /// + /// Returns the maximum items of this data source. + /// + /// + /// + public virtual int CalculateMax(string filter = null) + { + return PickAllItems(filter).Rows; + } + + public virtual ButtonRow Render(object data) + { + return data as ButtonRow; + } + + + public static implicit operator ButtonFormDataSource(ButtonForm bf) + { + return new ButtonFormDataSource(bf); + } + + public static implicit operator ButtonForm(ButtonFormDataSource ds) + { + return ds.ButtonForm; + } +} \ No newline at end of file diff --git a/TelegramBotBase/DataSources/StaticDataSource.cs b/TelegramBotBase/DataSources/StaticDataSource.cs index 59e400e..2cf1d50 100644 --- a/TelegramBotBase/DataSources/StaticDataSource.cs +++ b/TelegramBotBase/DataSources/StaticDataSource.cs @@ -2,38 +2,36 @@ using System.Linq; using TelegramBotBase.Interfaces; -namespace TelegramBotBase.DataSources +namespace TelegramBotBase.DataSources; + +public class StaticDataSource : IDataSource { - public class StaticDataSource : IDataSource + public StaticDataSource() { - private List Data { get; set; } - - public StaticDataSource() - { - - } - - public StaticDataSource(List data) - { - Data = data; - } - - - public int Count => Data.Count; - - public T ItemAt(int index) - { - return Data[index]; - } - - public List ItemRange(int start, int count) - { - return Data.Skip(start).Take(count).ToList(); - } - - public List AllItems() - { - return Data; - } } -} + + public StaticDataSource(List data) + { + Data = data; + } + + private List Data { get; } + + + public int Count => Data.Count; + + public T ItemAt(int index) + { + return Data[index]; + } + + public List ItemRange(int start, int count) + { + return Data.Skip(start).Take(count).ToList(); + } + + public List AllItems() + { + return Data; + } +} \ No newline at end of file diff --git a/TelegramBotBase/Enums/eDeleteMode.cs b/TelegramBotBase/Enums/eDeleteMode.cs index b4d190a..4cd1421 100644 --- a/TelegramBotBase/Enums/eDeleteMode.cs +++ b/TelegramBotBase/Enums/eDeleteMode.cs @@ -1,18 +1,19 @@ -namespace TelegramBotBase.Enums +namespace TelegramBotBase.Enums; + +public enum EDeleteMode { - public enum EDeleteMode - { - /// - /// Don't delete any message. - /// - None = 0, - /// - /// Delete messages on every callback/action. - /// - OnEveryCall = 1, - /// - /// Delete on leaving this form. - /// - OnLeavingForm = 2 - } -} + /// + /// Don't delete any message. + /// + None = 0, + + /// + /// Delete messages on every callback/action. + /// + OnEveryCall = 1, + + /// + /// Delete on leaving this form. + /// + OnLeavingForm = 2 +} \ No newline at end of file diff --git a/TelegramBotBase/Enums/eDeleteSide.cs b/TelegramBotBase/Enums/eDeleteSide.cs index 1b91ea1..3c75443 100644 --- a/TelegramBotBase/Enums/eDeleteSide.cs +++ b/TelegramBotBase/Enums/eDeleteSide.cs @@ -1,18 +1,19 @@ -namespace TelegramBotBase.Enums +namespace TelegramBotBase.Enums; + +public enum EDeleteSide { - public enum EDeleteSide - { - /// - /// Delete only messages from this bot. - /// - BotOnly = 0, - /// - /// Delete only user messages. - /// - UserOnly = 1, - /// - /// Delete all messages in this context. - /// - Both = 2 - } -} + /// + /// Delete only messages from this bot. + /// + BotOnly = 0, + + /// + /// Delete only user messages. + /// + UserOnly = 1, + + /// + /// Delete all messages in this context. + /// + Both = 2 +} \ No newline at end of file diff --git a/TelegramBotBase/Enums/eKeyboardType.cs b/TelegramBotBase/Enums/eKeyboardType.cs index ed808a0..c4f2033 100644 --- a/TelegramBotBase/Enums/eKeyboardType.cs +++ b/TelegramBotBase/Enums/eKeyboardType.cs @@ -1,16 +1,14 @@ -namespace TelegramBotBase.Enums +namespace TelegramBotBase.Enums; + +public enum EKeyboardType { - public enum EKeyboardType - { - /// - /// Uses a ReplyKeyboardMarkup - /// - ReplyKeyboard = 0, + /// + /// Uses a ReplyKeyboardMarkup + /// + ReplyKeyboard = 0, - /// - /// Uses a InlineKeyboardMakup - /// - InlineKeyBoard = 1 - - } -} + /// + /// Uses a InlineKeyboardMakup + /// + InlineKeyBoard = 1 +} \ No newline at end of file diff --git a/TelegramBotBase/Enums/eMonthPickerMode.cs b/TelegramBotBase/Enums/eMonthPickerMode.cs index b5f318f..f61cd08 100644 --- a/TelegramBotBase/Enums/eMonthPickerMode.cs +++ b/TelegramBotBase/Enums/eMonthPickerMode.cs @@ -1,18 +1,19 @@ -namespace TelegramBotBase.Enums +namespace TelegramBotBase.Enums; + +public enum EMonthPickerMode { - public enum EMonthPickerMode - { - /// - /// Shows the calendar with day picker mode - /// - day = 0, - /// - /// Shows the calendar with month overview - /// - month = 1, - /// - /// Shows the calendar with year overview - /// - year = 2 - } -} + /// + /// Shows the calendar with day picker mode + /// + day = 0, + + /// + /// Shows the calendar with month overview + /// + month = 1, + + /// + /// Shows the calendar with year overview + /// + year = 2 +} \ No newline at end of file diff --git a/TelegramBotBase/Enums/eNavigationBarVisibility.cs b/TelegramBotBase/Enums/eNavigationBarVisibility.cs index 00b4d57..f9834c2 100644 --- a/TelegramBotBase/Enums/eNavigationBarVisibility.cs +++ b/TelegramBotBase/Enums/eNavigationBarVisibility.cs @@ -1,21 +1,19 @@ -namespace TelegramBotBase.Enums +namespace TelegramBotBase.Enums; + +public enum ENavigationBarVisibility { - public enum ENavigationBarVisibility - { - /// - /// Shows it depending on the amount of items. - /// - auto = 0, + /// + /// Shows it depending on the amount of items. + /// + auto = 0, - /// - /// Will not show it at any time. - /// - never = 1, + /// + /// Will not show it at any time. + /// + never = 1, - /// - /// Will show it at any time. - /// - always = 2 - - } -} + /// + /// Will show it at any time. + /// + always = 2 +} \ No newline at end of file diff --git a/TelegramBotBase/Enums/eSettings.cs b/TelegramBotBase/Enums/eSettings.cs index da63d21..cebc8f7 100644 --- a/TelegramBotBase/Enums/eSettings.cs +++ b/TelegramBotBase/Enums/eSettings.cs @@ -1,36 +1,34 @@ -namespace TelegramBotBase.Enums +namespace TelegramBotBase.Enums; + +public enum ESettings { - public enum ESettings - { - /// - /// How often could a form navigate to another (within one user action/call/message) - /// - NavigationMaximum = 1, + /// + /// How often could a form navigate to another (within one user action/call/message) + /// + NavigationMaximum = 1, - /// - /// Loggs all messages and sent them to the event handler - /// - LogAllMessages = 2, + /// + /// Loggs all messages and sent them to the event handler + /// + LogAllMessages = 2, - /// - /// Skips all messages during running (good for big delay updates) - /// - SkipAllMessages = 3, + /// + /// Skips all messages during running (good for big delay updates) + /// + SkipAllMessages = 3, - /// - /// Does stick to the console event handler and saves all sessions on exit. - /// - SaveSessionsOnConsoleExit = 4, + /// + /// Does stick to the console event handler and saves all sessions on exit. + /// + SaveSessionsOnConsoleExit = 4, - /// - /// Indicates the maximum number of times a request that received error - /// 429 will be sent again after a timeout until it receives code 200 or an error code not equal to 429. - /// - MaxNumberOfRetries = 5, - - } -} + /// + /// Indicates the maximum number of times a request that received error + /// 429 will be sent again after a timeout until it receives code 200 or an error code not equal to 429. + /// + MaxNumberOfRetries = 5 +} \ No newline at end of file diff --git a/TelegramBotBase/Exceptions/MaxLengthException.cs b/TelegramBotBase/Exceptions/MaxLengthException.cs index 86d811a..2e93214 100644 --- a/TelegramBotBase/Exceptions/MaxLengthException.cs +++ b/TelegramBotBase/Exceptions/MaxLengthException.cs @@ -1,13 +1,11 @@ using System; -namespace TelegramBotBase.Exceptions -{ - public class MaxLengthException : Exception - { - public MaxLengthException(int length) : base($"Your messages with a length of {length} is too long for telegram. Actually is {Constants.Telegram.MaxMessageLength} characters allowed. Please split it.") - { - - } +namespace TelegramBotBase.Exceptions; +public class MaxLengthException : Exception +{ + public MaxLengthException(int length) : base( + $"Your messages with a length of {length} is too long for telegram. Actually is {Constants.Telegram.MaxMessageLength} characters allowed. Please split it.") + { } -} +} \ No newline at end of file diff --git a/TelegramBotBase/Exceptions/MaximumColsException.cs b/TelegramBotBase/Exceptions/MaximumColsException.cs index 8ddf203..4209353 100644 --- a/TelegramBotBase/Exceptions/MaximumColsException.cs +++ b/TelegramBotBase/Exceptions/MaximumColsException.cs @@ -1,14 +1,14 @@ using System; -namespace TelegramBotBase.Exceptions +namespace TelegramBotBase.Exceptions; + +public class MaximumColsException : Exception { - public class MaximumColsException : Exception - { - public int Value { get; set; } + public int Value { get; set; } - public int Maximum { get; set; } + public int Maximum { get; set; } - public override string Message => $"You have exceeded the maximum of columns by {Value.ToString()} / {Maximum.ToString()}"; - } -} + public override string Message => + $"You have exceeded the maximum of columns by {Value.ToString()} / {Maximum.ToString()}"; +} \ No newline at end of file diff --git a/TelegramBotBase/Exceptions/MaximumRowsException.cs b/TelegramBotBase/Exceptions/MaximumRowsException.cs index 10f5140..be3ad7d 100644 --- a/TelegramBotBase/Exceptions/MaximumRowsException.cs +++ b/TelegramBotBase/Exceptions/MaximumRowsException.cs @@ -1,14 +1,14 @@ using System; -namespace TelegramBotBase.Exceptions +namespace TelegramBotBase.Exceptions; + +public class MaximumRowsReachedException : Exception { - public class MaximumRowsReachedException : Exception - { - public int Value { get; set; } + public int Value { get; set; } - public int Maximum { get; set; } + public int Maximum { get; set; } - public override string Message => $"You have exceeded the maximum of rows by {Value.ToString()} / {Maximum.ToString()}"; - } -} + public override string Message => + $"You have exceeded the maximum of rows by {Value.ToString()} / {Maximum.ToString()}"; +} \ No newline at end of file diff --git a/TelegramBotBase/Factories/DefaultStartFormFactory.cs b/TelegramBotBase/Factories/DefaultStartFormFactory.cs index 969d446..7ce2988 100644 --- a/TelegramBotBase/Factories/DefaultStartFormFactory.cs +++ b/TelegramBotBase/Factories/DefaultStartFormFactory.cs @@ -2,24 +2,25 @@ using TelegramBotBase.Form; using TelegramBotBase.Interfaces; -namespace TelegramBotBase.Factories +namespace TelegramBotBase.Factories; + +public class DefaultStartFormFactory : IStartFormFactory { - public class DefaultStartFormFactory : IStartFormFactory + private readonly Type _startFormClass; + + public DefaultStartFormFactory(Type startFormClass) { - private readonly Type _startFormClass; - - public DefaultStartFormFactory(Type startFormClass) + if (!typeof(FormBase).IsAssignableFrom(startFormClass)) { - if (!typeof(FormBase).IsAssignableFrom(startFormClass)) - throw new ArgumentException("startFormClass argument must be a FormBase type"); - - _startFormClass = startFormClass; + throw new ArgumentException("startFormClass argument must be a FormBase type"); } - - public FormBase CreateForm() - { - return _startFormClass.GetConstructor(new Type[] { })?.Invoke(new object[] { }) as FormBase; - } + _startFormClass = startFormClass; } -} + + + public FormBase CreateForm() + { + return _startFormClass.GetConstructor(new Type[] { })?.Invoke(new object[] { }) as FormBase; + } +} \ No newline at end of file diff --git a/TelegramBotBase/Factories/LambdaStartFormFactory.cs b/TelegramBotBase/Factories/LambdaStartFormFactory.cs index 563e03e..2ca4c5c 100644 --- a/TelegramBotBase/Factories/LambdaStartFormFactory.cs +++ b/TelegramBotBase/Factories/LambdaStartFormFactory.cs @@ -1,22 +1,21 @@ using TelegramBotBase.Form; using TelegramBotBase.Interfaces; -namespace TelegramBotBase.Factories +namespace TelegramBotBase.Factories; + +public class LambdaStartFormFactory : IStartFormFactory { - public class LambdaStartFormFactory : IStartFormFactory + public delegate FormBase CreateFormDelegate(); + + private readonly CreateFormDelegate _lambda; + + public LambdaStartFormFactory(CreateFormDelegate lambda) { - public delegate FormBase CreateFormDelegate(); - - private readonly CreateFormDelegate _lambda; - - public LambdaStartFormFactory(CreateFormDelegate lambda) - { - _lambda = lambda; - } - - public FormBase CreateForm() - { - return _lambda(); - } + _lambda = lambda; } -} + + public FormBase CreateForm() + { + return _lambda(); + } +} \ No newline at end of file diff --git a/TelegramBotBase/Factories/ServiceProviderStartFormFactory.cs b/TelegramBotBase/Factories/ServiceProviderStartFormFactory.cs index 4f2a0ef..4ee81db 100644 --- a/TelegramBotBase/Factories/ServiceProviderStartFormFactory.cs +++ b/TelegramBotBase/Factories/ServiceProviderStartFormFactory.cs @@ -3,33 +3,34 @@ using Microsoft.Extensions.DependencyInjection; using TelegramBotBase.Form; using TelegramBotBase.Interfaces; -namespace TelegramBotBase.Factories +namespace TelegramBotBase.Factories; + +public class ServiceProviderStartFormFactory : IStartFormFactory { - public class ServiceProviderStartFormFactory : IStartFormFactory + private readonly IServiceProvider _serviceProvider; + private readonly Type _startFormClass; + + public ServiceProviderStartFormFactory(Type startFormClass, IServiceProvider serviceProvider) { - private readonly Type _startFormClass; - private readonly IServiceProvider _serviceProvider; - - public ServiceProviderStartFormFactory(Type startFormClass, IServiceProvider serviceProvider) + if (!typeof(FormBase).IsAssignableFrom(startFormClass)) { - if (!typeof(FormBase).IsAssignableFrom(startFormClass)) - throw new ArgumentException("startFormClass argument must be a FormBase type"); - - _startFormClass = startFormClass; - _serviceProvider = serviceProvider; + throw new ArgumentException("startFormClass argument must be a FormBase type"); } - public FormBase CreateForm() - { - return (FormBase)ActivatorUtilities.CreateInstance(_serviceProvider, _startFormClass); - } + _startFormClass = startFormClass; + _serviceProvider = serviceProvider; } - public class ServiceProviderStartFormFactory : ServiceProviderStartFormFactory - where T : FormBase + public FormBase CreateForm() { - public ServiceProviderStartFormFactory(IServiceProvider serviceProvider) : base(typeof(T), serviceProvider) - { - } + return (FormBase)ActivatorUtilities.CreateInstance(_serviceProvider, _startFormClass); } } + +public class ServiceProviderStartFormFactory : ServiceProviderStartFormFactory + where T : FormBase +{ + public ServiceProviderStartFormFactory(IServiceProvider serviceProvider) : base(typeof(T), serviceProvider) + { + } +} \ No newline at end of file diff --git a/TelegramBotBase/Form/AlertDialog.cs b/TelegramBotBase/Form/AlertDialog.cs index fe7f472..74f4f1c 100644 --- a/TelegramBotBase/Form/AlertDialog.cs +++ b/TelegramBotBase/Form/AlertDialog.cs @@ -1,21 +1,18 @@ using TelegramBotBase.Attributes; -namespace TelegramBotBase.Form +namespace TelegramBotBase.Form; + +/// +/// A simple prompt dialog with one ok Button +/// +[IgnoreState] +public class AlertDialog : ConfirmDialog { - /// - /// A simple prompt dialog with one ok Button - /// - [IgnoreState] - public class AlertDialog : ConfirmDialog + public AlertDialog(string message, string buttonText) : base(message) { - public string ButtonText { get; set; } - - public AlertDialog(string message, string buttonText) : base(message) - { - Buttons.Add(new ButtonBase(buttonText, "ok")); - this.ButtonText = buttonText; - - } - + Buttons.Add(new ButtonBase(buttonText, "ok")); + ButtonText = buttonText; } -} + + public string ButtonText { get; set; } +} \ No newline at end of file diff --git a/TelegramBotBase/Form/ArrayPromptDialog.cs b/TelegramBotBase/Form/ArrayPromptDialog.cs index 4ce663c..7481563 100644 --- a/TelegramBotBase/Form/ArrayPromptDialog.cs +++ b/TelegramBotBase/Form/ArrayPromptDialog.cs @@ -1,113 +1,112 @@ using System; using System.Collections.Generic; -using System.ComponentModel; using System.Linq; using System.Threading.Tasks; using TelegramBotBase.Args; using TelegramBotBase.Attributes; using TelegramBotBase.Base; -namespace TelegramBotBase.Form +namespace TelegramBotBase.Form; + +/// +/// A prompt with a lot of buttons +/// +[IgnoreState] +public class ArrayPromptDialog : FormBase { - /// - /// A prompt with a lot of buttons - /// - [IgnoreState] - public class ArrayPromptDialog : FormBase + public ArrayPromptDialog() { - /// - /// The message the users sees. - /// - public string Message { get; set; } + } - /// - /// An additional optional value. - /// - public object Tag { get; set; } + public ArrayPromptDialog(string message) + { + Message = message; + } - public ButtonBase[][] Buttons { get; set; } + public ArrayPromptDialog(string message, params ButtonBase[][] buttons) + { + Message = message; + Buttons = buttons; + } - [Obsolete] - public Dictionary ButtonForms { get; set; } = new Dictionary(); + /// + /// The message the users sees. + /// + public string Message { get; set; } - private static object EvButtonClicked { get; } = new object(); + /// + /// An additional optional value. + /// + public object Tag { get; set; } - public ArrayPromptDialog() + public ButtonBase[][] Buttons { get; set; } + + [Obsolete] public Dictionary ButtonForms { get; set; } = new(); + + private static object EvButtonClicked { get; } = new(); + + public override async Task Action(MessageResult message) + { + var call = message.GetData(); + + message.Handled = true; + + if (!message.IsAction) { - + return; } - public ArrayPromptDialog(string message) + await message.ConfirmAction(); + + await message.DeleteMessage(); + + var buttons = Buttons.Aggregate((a, b) => a.Union(b).ToArray()).ToList(); + + if (call == null) { - this.Message = message; + return; } - public ArrayPromptDialog(string message, params ButtonBase[][] buttons) + var button = buttons.FirstOrDefault(a => a.Value == call.Value); + + if (button == null) { - this.Message = message; - this.Buttons = buttons; + return; } - public override async Task Action(MessageResult message) + OnButtonClicked(new ButtonClickedEventArgs(button) { Tag = Tag }); + + var fb = ButtonForms.ContainsKey(call.Value) ? ButtonForms[call.Value] : null; + + if (fb != null) { - var call = message.GetData(); - - message.Handled = true; - - if (!message.IsAction) - return; - - await message.ConfirmAction(); - - await message.DeleteMessage(); - - var buttons = Buttons.Aggregate((a, b) => a.Union(b).ToArray()).ToList(); - - if(call==null) - { - return; - } - - var button = buttons.FirstOrDefault(a => a.Value == call.Value); - - if (button == null) - { - return; - } - - OnButtonClicked(new ButtonClickedEventArgs(button) { Tag = Tag }); - - var fb = ButtonForms.ContainsKey(call.Value) ? ButtonForms[call.Value] : null; - - if (fb != null) - { - await NavigateTo(fb); - } - } - - - public override async Task Render(MessageResult message) - { - var btn = new ButtonForm(); - - foreach(var bl in Buttons) - { - btn.AddButtonRow(bl.Select(a => new ButtonBase(a.Text, CallbackData.Create("action", a.Value))).ToList()); - } - - await Device.Send(Message, btn); - } - - - public event EventHandler ButtonClicked - { - add => Events.AddHandler(EvButtonClicked, value); - remove => Events.RemoveHandler(EvButtonClicked, value); - } - - public void OnButtonClicked(ButtonClickedEventArgs e) - { - (Events[EvButtonClicked] as EventHandler)?.Invoke(this, e); + await NavigateTo(fb); } } + + + public override async Task Render(MessageResult message) + { + var btn = new ButtonForm(); + + foreach (var bl in Buttons) + { + btn.AddButtonRow( + bl.Select(a => new ButtonBase(a.Text, CallbackData.Create("action", a.Value))).ToList()); + } + + await Device.Send(Message, btn); + } + + + public event EventHandler ButtonClicked + { + add => Events.AddHandler(EvButtonClicked, value); + remove => Events.RemoveHandler(EvButtonClicked, value); + } + + public void OnButtonClicked(ButtonClickedEventArgs e) + { + (Events[EvButtonClicked] as EventHandler)?.Invoke(this, e); + } } diff --git a/TelegramBotBase/Form/AutoCleanForm.cs b/TelegramBotBase/Form/AutoCleanForm.cs index be2ff1e..d920488 100644 --- a/TelegramBotBase/Form/AutoCleanForm.cs +++ b/TelegramBotBase/Form/AutoCleanForm.cs @@ -11,135 +11,143 @@ using TelegramBotBase.Attributes; using TelegramBotBase.Base; using TelegramBotBase.Enums; -namespace TelegramBotBase.Form +namespace TelegramBotBase.Form; + +/// +/// A form which cleans up old messages sent within +/// +public class AutoCleanForm : FormBase { - /// - /// A form which cleans up old messages sent within - /// - public class AutoCleanForm : FormBase + public AutoCleanForm() { - [SaveState] - public List OldMessages { get; set; } + OldMessages = new List(); + DeleteMode = EDeleteMode.OnEveryCall; + DeleteSide = EDeleteSide.BotOnly; - [SaveState] - public EDeleteMode DeleteMode { get; set; } + Init += AutoCleanForm_Init; - [SaveState] - public EDeleteSide DeleteSide { get; set; } + Closed += AutoCleanForm_Closed; + } + [SaveState] public List OldMessages { get; set; } + [SaveState] public EDeleteMode DeleteMode { get; set; } - public AutoCleanForm() + [SaveState] public EDeleteSide DeleteSide { get; set; } + + private Task AutoCleanForm_Init(object sender, InitEventArgs e) + { + if (Device == null) { - OldMessages = new List(); - DeleteMode = EDeleteMode.OnEveryCall; - DeleteSide = EDeleteSide.BotOnly; - - Init += AutoCleanForm_Init; - - Closed += AutoCleanForm_Closed; - - } - - private Task AutoCleanForm_Init(object sender, InitEventArgs e) - { - if (Device == null) - return Task.CompletedTask; - - Device.MessageSent += Device_MessageSent; - - Device.MessageReceived += Device_MessageReceived; - - Device.MessageDeleted += Device_MessageDeleted; return Task.CompletedTask; } - private void Device_MessageDeleted(object sender, MessageDeletedEventArgs e) + Device.MessageSent += Device_MessageSent; + + Device.MessageReceived += Device_MessageReceived; + + Device.MessageDeleted += Device_MessageDeleted; + return Task.CompletedTask; + } + + private void Device_MessageDeleted(object sender, MessageDeletedEventArgs e) + { + if (OldMessages.Contains(e.MessageId)) { - if (OldMessages.Contains(e.MessageId)) - OldMessages.Remove(e.MessageId); + OldMessages.Remove(e.MessageId); + } + } + + private void Device_MessageReceived(object sender, MessageReceivedEventArgs e) + { + if (DeleteSide == EDeleteSide.BotOnly) + { + return; } - private void Device_MessageReceived(object sender, MessageReceivedEventArgs e) + OldMessages.Add(e.Message.MessageId); + } + + private Task Device_MessageSent(object sender, MessageSentEventArgs e) + { + if (DeleteSide == EDeleteSide.UserOnly) { - if (DeleteSide == EDeleteSide.BotOnly) - return; - - OldMessages.Add(e.Message.MessageId); - } - - private Task Device_MessageSent(object sender, MessageSentEventArgs e) - { - if (DeleteSide == EDeleteSide.UserOnly) - return Task.CompletedTask; - - OldMessages.Add(e.Message.MessageId); return Task.CompletedTask; } - public override async Task PreLoad(MessageResult message) - { - if (DeleteMode != EDeleteMode.OnEveryCall) - return; + OldMessages.Add(e.Message.MessageId); + return Task.CompletedTask; + } - await MessageCleanup(); + public override async Task PreLoad(MessageResult message) + { + if (DeleteMode != EDeleteMode.OnEveryCall) + { + return; } - /// - /// Adds a message to this of removable ones - /// - /// - public void AddMessage(Message m) + await MessageCleanup(); + } + + /// + /// Adds a message to this of removable ones + /// + /// + public void AddMessage(Message m) + { + OldMessages.Add(m.MessageId); + } + + + /// + /// Adds a message to this of removable ones + /// + /// + public void AddMessage(int messageId) + { + OldMessages.Add(messageId); + } + + /// + /// Keeps the message by removing it from the list + /// + /// + public void LeaveMessage(int id) + { + OldMessages.Remove(id); + } + + /// + /// Keeps the last sent message + /// + public void LeaveLastMessage() + { + if (OldMessages.Count == 0) { - OldMessages.Add(m.MessageId); + return; } + OldMessages.RemoveAt(OldMessages.Count - 1); + } - /// - /// Adds a message to this of removable ones - /// - /// - public void AddMessage(int messageId) + private Task AutoCleanForm_Closed(object sender, EventArgs e) + { + if (DeleteMode != EDeleteMode.OnLeavingForm) { - OldMessages.Add(messageId); - } - - /// - /// Keeps the message by removing it from the list - /// - /// - public void LeaveMessage(int id) - { - OldMessages.Remove(id); - } - - /// - /// Keeps the last sent message - /// - public void LeaveLastMessage() - { - if (OldMessages.Count == 0) - return; - - OldMessages.RemoveAt(OldMessages.Count - 1); - } - - private Task AutoCleanForm_Closed(object sender, EventArgs e) - { - if (DeleteMode != EDeleteMode.OnLeavingForm) - return Task.CompletedTask; - - MessageCleanup().Wait(); return Task.CompletedTask; } - /// - /// Cleans up all remembered messages. - /// - /// - public async Task MessageCleanup() - { - var oldMessages = OldMessages.AsEnumerable(); + MessageCleanup().Wait(); + return Task.CompletedTask; + } + + /// + /// Cleans up all remembered messages. + /// + /// + public async Task MessageCleanup() + { + var oldMessages = OldMessages.AsEnumerable(); #if !NETSTANDARD2_0 while (oldMessages.Any()) @@ -181,51 +189,51 @@ namespace TelegramBotBase.Form await retryAfterTask; } #else - while (oldMessages.Any()) + while (oldMessages.Any()) + { + using (var cts = new CancellationTokenSource()) { - using (var cts = new CancellationTokenSource()) + var deletedMessages = new ConcurrentBag(); + var parallelQuery = OldMessages.AsParallel() + .WithCancellation(cts.Token); + Task retryAfterTask = null; + try { - var deletedMessages = new ConcurrentBag(); - var parallelQuery = OldMessages.AsParallel() - .WithCancellation(cts.Token); - Task retryAfterTask = null; - try + parallelQuery.ForAll(i => { - parallelQuery.ForAll(i => + try { - try - { - Device.DeleteMessage(i).GetAwaiter().GetResult(); - deletedMessages.Add(i); - } - catch (ApiRequestException req) when (req.ErrorCode == 400) - { - deletedMessages.Add(i); - } - }); - } - catch (AggregateException ex) - { - cts.Cancel(); + Device.DeleteMessage(i).GetAwaiter().GetResult(); + deletedMessages.Add(i); + } + catch (ApiRequestException req) when (req.ErrorCode == 400) + { + deletedMessages.Add(i); + } + }); + } + catch (AggregateException ex) + { + cts.Cancel(); - var retryAfterSeconds = ex.InnerExceptions - .Where(e => e is ApiRequestException apiEx && apiEx.ErrorCode == 429) - .Max(e => ((ApiRequestException)e).Parameters.RetryAfter) ?? 0; - retryAfterTask = Task.Delay(retryAfterSeconds * 1000); - } + var retryAfterSeconds = ex.InnerExceptions + .Where(e => e is ApiRequestException apiEx && apiEx.ErrorCode == 429) + .Max(e => ((ApiRequestException)e).Parameters.RetryAfter) ?? 0; + retryAfterTask = Task.Delay(retryAfterSeconds * 1000); + } - //deletedMessages.AsParallel().ForAll(i => Device.OnMessageDeleted(new MessageDeletedEventArgs(i))); - - oldMessages = oldMessages.Where(x => !deletedMessages.Contains(x)); - if (retryAfterTask != null) - await retryAfterTask; + //deletedMessages.AsParallel().ForAll(i => Device.OnMessageDeleted(new MessageDeletedEventArgs(i))); + oldMessages = oldMessages.Where(x => !deletedMessages.Contains(x)); + if (retryAfterTask != null) + { + await retryAfterTask; } } + } #endif - OldMessages.Clear(); - } + OldMessages.Clear(); } -} +} \ No newline at end of file diff --git a/TelegramBotBase/Form/ButtonBase.cs b/TelegramBotBase/Form/ButtonBase.cs index a068774..c962dcb 100644 --- a/TelegramBotBase/Form/ButtonBase.cs +++ b/TelegramBotBase/Form/ButtonBase.cs @@ -1,66 +1,62 @@ using System.Diagnostics; using Telegram.Bot.Types.ReplyMarkups; -namespace TelegramBotBase.Form +namespace TelegramBotBase.Form; + +[DebuggerDisplay("{Text}, {Value}")] +/// +/// Base class for button handling +/// +public class ButtonBase { - [DebuggerDisplay("{Text}, {Value}")] - /// - /// Base class for button handling - /// - public class ButtonBase + public ButtonBase() { - public virtual string Text { get; set; } - - public string Value { get; set; } - - public string Url { get; set; } - - public ButtonBase() - { - - } - - public ButtonBase(string text, string value, string url = null) - { - this.Text = text; - this.Value = value; - this.Url = url; - } - - - /// - /// Returns an inline Button - /// - /// - /// - public virtual InlineKeyboardButton ToInlineButton(ButtonForm form) - { - var id = (form.DependencyControl != null ? form.DependencyControl.ControlId + "_" : ""); - if (Url == null) - { - return InlineKeyboardButton.WithCallbackData(Text, id + Value); - } - - var ikb = new InlineKeyboardButton(Text) - { - //ikb.Text = this.Text; - Url = Url - }; - - return ikb; - - } - - - /// - /// Returns a KeyBoardButton - /// - /// - /// - public virtual KeyboardButton ToKeyboardButton(ButtonForm form) - { - return new KeyboardButton(Text); - } - } -} + + public ButtonBase(string text, string value, string url = null) + { + Text = text; + Value = value; + Url = url; + } + + public virtual string Text { get; set; } + + public string Value { get; set; } + + public string Url { get; set; } + + + /// + /// Returns an inline Button + /// + /// + /// + public virtual InlineKeyboardButton ToInlineButton(ButtonForm form) + { + var id = form.DependencyControl != null ? form.DependencyControl.ControlId + "_" : ""; + if (Url == null) + { + return InlineKeyboardButton.WithCallbackData(Text, id + Value); + } + + var ikb = new InlineKeyboardButton(Text) + { + //ikb.Text = this.Text; + Url = Url + }; + + return ikb; + } + + + /// + /// Returns a KeyBoardButton + /// + /// + /// + public virtual KeyboardButton ToKeyboardButton(ButtonForm form) + { + return new KeyboardButton(Text); + } +} \ No newline at end of file diff --git a/TelegramBotBase/Form/ButtonForm.cs b/TelegramBotBase/Form/ButtonForm.cs index fea7fb9..9591ddf 100644 --- a/TelegramBotBase/Form/ButtonForm.cs +++ b/TelegramBotBase/Form/ButtonForm.cs @@ -5,321 +5,337 @@ using Telegram.Bot.Types.ReplyMarkups; using TelegramBotBase.Base; using TelegramBotBase.Controls.Hybrid; -namespace TelegramBotBase.Form +namespace TelegramBotBase.Form; + +/// +/// Base class for an buttons array +/// +public class ButtonForm { - /// - /// Base class for an buttons array - /// - public class ButtonForm + private readonly List _buttons = new(); + + public ButtonForm() { - private List _buttons = new List(); + } + + public ButtonForm(ControlBase control) + { + DependencyControl = control; + } - public IReplyMarkup Markup { get; set; } + public IReplyMarkup Markup { get; set; } - public ControlBase DependencyControl { get; set; } + public ControlBase DependencyControl { get; set; } - /// - /// Contains the number of rows. - /// - public int Rows => _buttons.Count; + /// + /// Contains the number of rows. + /// + public int Rows => _buttons.Count; - /// - /// Contains the highest number of columns in an row. - /// - public int Cols + /// + /// Contains the highest number of columns in an row. + /// + public int Cols + { + get { return _buttons.Select(a => a.Count).OrderByDescending(a => a).FirstOrDefault(); } + } + + + public ButtonRow this[int row] => _buttons[row]; + + public int Count + { + get { - get + if (_buttons.Count == 0) { - return _buttons.Select(a => a.Count).OrderByDescending(a => a).FirstOrDefault(); - } - } - - - public ButtonRow this[int row] => _buttons[row]; - - public ButtonForm() - { - - } - - public ButtonForm(ControlBase control) - { - DependencyControl = control; - } - - public void AddButtonRow(string text, string value, string url = null) - { - _buttons.Add(new List { new ButtonBase(text, value, url) }); - } - - //public void AddButtonRow(ButtonRow row) - //{ - // Buttons.Add(row.ToList()); - //} - - public void AddButtonRow(ButtonRow row) - { - _buttons.Add(row); - } - - public void AddButtonRow(params ButtonBase[] row) - { - AddButtonRow(row.ToList()); - } - - public void AddButtonRows(IEnumerable rows) - { - _buttons.AddRange(rows); - } - - public void InsertButtonRow(int index, IEnumerable row) - { - _buttons.Insert(index, row.ToList()); - } - - public void InsertButtonRow(int index, ButtonRow row) - { - _buttons.Insert(index, row); - } - - //public void InsertButtonRow(int index, params ButtonBase[] row) - //{ - // InsertButtonRow(index, row.ToList()); - //} - - public static T[][] SplitTo(IEnumerable items, int itemsPerRow = 2) - { - var splitted = default(T[][]); - - try - { - var t = items.Select((a, index) => new { a, index }) - .GroupBy(a => a.index / itemsPerRow) - .Select(a => a.Select(b => b.a).ToArray()).ToArray(); - - splitted = t; - } - catch - { - + return 0; } - return splitted; - } - - public int Count - { - get - { - if (_buttons.Count == 0) - return 0; - - return _buttons.Select(a => a.ToArray()).ToList().Aggregate((a, b) => a.Union(b).ToArray()).Length; - } - } - - /// - /// Add buttons splitted in the amount of columns (i.e. 2 per row...) - /// - /// - /// - public void AddSplitted(IEnumerable buttons, int buttonsPerRow = 2) - { - var sp = SplitTo(buttons, buttonsPerRow); - - foreach (var bl in sp) - { - AddButtonRow(bl); - } - } - - /// - /// Returns a range of rows from the buttons. - /// - /// - /// - /// - public List GetRange(int start, int count) - { - return _buttons.Skip(start).Take(count).ToList(); - } - - - public List ToList() - { - return _buttons.DefaultIfEmpty(new List()).Select(a => a.ToList()).Aggregate((a, b) => a.Union(b).ToList()); - } - - public InlineKeyboardButton[][] ToInlineButtonArray() - { - var ikb = _buttons.Select(a => a.ToArray().Select(b => b.ToInlineButton(this)).ToArray()).ToArray(); - - return ikb; - } - - public KeyboardButton[][] ToReplyButtonArray() - { - var ikb = _buttons.Select(a => a.ToArray().Select(b => b.ToKeyboardButton(this)).ToArray()).ToArray(); - - return ikb; - } - - public List ToArray() - { - return _buttons; - } - - public int FindRowByButton(ButtonBase button) - { - var row = _buttons.FirstOrDefault(a => a.ToArray().Count(b => b == button) > 0); - if (row == null) - return -1; - - return _buttons.IndexOf(row); - } - - public Tuple FindRow(string text, bool useText = true) - { - var r = _buttons.FirstOrDefault(a => a.Matches(text, useText)); - if (r == null) - return null; - - var i = _buttons.IndexOf(r); - return new Tuple(r, i); - } - - - /// - /// Returns the first Button with the given value. - /// - /// - /// - public ButtonBase GetButtonByValue(string value) - { - return ToList().Where(a => a.Value == value).FirstOrDefault(); - } - - public static implicit operator InlineKeyboardMarkup(ButtonForm form) - { - if (form == null) - return null; - - var ikm = new InlineKeyboardMarkup(form.ToInlineButtonArray()); - - return ikm; - } - - public static implicit operator ReplyKeyboardMarkup(ButtonForm form) - { - if (form == null) - return null; - - var ikm = new ReplyKeyboardMarkup(form.ToReplyButtonArray()); - - return ikm; - } - - /// - /// Creates a copy of this form. - /// - /// - public ButtonForm Duplicate() - { - var bf = new ButtonForm - { - Markup = Markup, - DependencyControl = DependencyControl - }; - - foreach (var b in _buttons) - { - var lst = new ButtonRow(); - foreach (var b2 in b) - { - lst.Add(b2); - } - bf._buttons.Add(lst); - } - - return bf; - } - - /// - /// Creates a copy of this form and filters by the parameter. - /// - /// - public ButtonForm FilterDuplicate(string filter, bool byRow = false) - { - var bf = new ButtonForm - { - Markup = Markup, - DependencyControl = DependencyControl - }; - - foreach (var b in _buttons) - { - var lst = new ButtonRow(); - foreach (var b2 in b) - { - if (b2.Text.IndexOf(filter, StringComparison.InvariantCultureIgnoreCase) == -1) - continue; - - //Copy full row, when at least one match has found. - if (byRow) - { - lst = b; - break; - } - - lst.Add(b2); - } - - if (lst.Count > 0) - bf._buttons.Add(lst); - } - - return bf; - } - - /// - /// Creates a copy of this form and filters by the parameter. - /// - /// - public ButtonForm TagDuplicate(List tags, bool byRow = false) - { - var bf = new ButtonForm - { - Markup = Markup, - DependencyControl = DependencyControl - }; - - foreach (var b in _buttons) - { - var lst = new ButtonRow(); - foreach (var b2 in b) - { - if (!(b2 is TagButtonBase tb)) - continue; - - if (!tags.Contains(tb.Tag)) - continue; - - //Copy full row, when at least one match has found. - if (byRow) - { - lst = b; - break; - } - - lst.Add(b2); - } - - if (lst.Count > 0) - bf._buttons.Add(lst); - } - - return bf; + return _buttons.Select(a => a.ToArray()).ToList().Aggregate((a, b) => a.Union(b).ToArray()).Length; } } -} + + public void AddButtonRow(string text, string value, string url = null) + { + _buttons.Add(new List { new(text, value, url) }); + } + + //public void AddButtonRow(ButtonRow row) + //{ + // Buttons.Add(row.ToList()); + //} + + public void AddButtonRow(ButtonRow row) + { + _buttons.Add(row); + } + + public void AddButtonRow(params ButtonBase[] row) + { + AddButtonRow(row.ToList()); + } + + public void AddButtonRows(IEnumerable rows) + { + _buttons.AddRange(rows); + } + + public void InsertButtonRow(int index, IEnumerable row) + { + _buttons.Insert(index, row.ToList()); + } + + public void InsertButtonRow(int index, ButtonRow row) + { + _buttons.Insert(index, row); + } + + //public void InsertButtonRow(int index, params ButtonBase[] row) + //{ + // InsertButtonRow(index, row.ToList()); + //} + + public static T[][] SplitTo(IEnumerable items, int itemsPerRow = 2) + { + var splitted = default(T[][]); + + try + { + var t = items.Select((a, index) => new { a, index }) + .GroupBy(a => a.index / itemsPerRow) + .Select(a => a.Select(b => b.a).ToArray()).ToArray(); + + splitted = t; + } + catch + { + } + + return splitted; + } + + /// + /// Add buttons splitted in the amount of columns (i.e. 2 per row...) + /// + /// + /// + public void AddSplitted(IEnumerable buttons, int buttonsPerRow = 2) + { + var sp = SplitTo(buttons, buttonsPerRow); + + foreach (var bl in sp) + { + AddButtonRow(bl); + } + } + + /// + /// Returns a range of rows from the buttons. + /// + /// + /// + /// + public List GetRange(int start, int count) + { + return _buttons.Skip(start).Take(count).ToList(); + } + + + public List ToList() + { + return _buttons.DefaultIfEmpty(new List()).Select(a => a.ToList()) + .Aggregate((a, b) => a.Union(b).ToList()); + } + + public InlineKeyboardButton[][] ToInlineButtonArray() + { + var ikb = _buttons.Select(a => a.ToArray().Select(b => b.ToInlineButton(this)).ToArray()).ToArray(); + + return ikb; + } + + public KeyboardButton[][] ToReplyButtonArray() + { + var ikb = _buttons.Select(a => a.ToArray().Select(b => b.ToKeyboardButton(this)).ToArray()).ToArray(); + + return ikb; + } + + public List ToArray() + { + return _buttons; + } + + public int FindRowByButton(ButtonBase button) + { + var row = _buttons.FirstOrDefault(a => a.ToArray().Count(b => b == button) > 0); + if (row == null) + { + return -1; + } + + return _buttons.IndexOf(row); + } + + public Tuple FindRow(string text, bool useText = true) + { + var r = _buttons.FirstOrDefault(a => a.Matches(text, useText)); + if (r == null) + { + return null; + } + + var i = _buttons.IndexOf(r); + return new Tuple(r, i); + } + + + /// + /// Returns the first Button with the given value. + /// + /// + /// + public ButtonBase GetButtonByValue(string value) + { + return ToList().Where(a => a.Value == value).FirstOrDefault(); + } + + public static implicit operator InlineKeyboardMarkup(ButtonForm form) + { + if (form == null) + { + return null; + } + + var ikm = new InlineKeyboardMarkup(form.ToInlineButtonArray()); + + return ikm; + } + + public static implicit operator ReplyKeyboardMarkup(ButtonForm form) + { + if (form == null) + { + return null; + } + + var ikm = new ReplyKeyboardMarkup(form.ToReplyButtonArray()); + + return ikm; + } + + /// + /// Creates a copy of this form. + /// + /// + public ButtonForm Duplicate() + { + var bf = new ButtonForm + { + Markup = Markup, + DependencyControl = DependencyControl + }; + + foreach (var b in _buttons) + { + var lst = new ButtonRow(); + foreach (var b2 in b) + { + lst.Add(b2); + } + + bf._buttons.Add(lst); + } + + return bf; + } + + /// + /// Creates a copy of this form and filters by the parameter. + /// + /// + public ButtonForm FilterDuplicate(string filter, bool byRow = false) + { + var bf = new ButtonForm + { + Markup = Markup, + DependencyControl = DependencyControl + }; + + foreach (var b in _buttons) + { + var lst = new ButtonRow(); + foreach (var b2 in b) + { + if (b2.Text.IndexOf(filter, StringComparison.InvariantCultureIgnoreCase) == -1) + { + continue; + } + + //Copy full row, when at least one match has found. + if (byRow) + { + lst = b; + break; + } + + lst.Add(b2); + } + + if (lst.Count > 0) + { + bf._buttons.Add(lst); + } + } + + return bf; + } + + /// + /// Creates a copy of this form and filters by the parameter. + /// + /// + public ButtonForm TagDuplicate(List tags, bool byRow = false) + { + var bf = new ButtonForm + { + Markup = Markup, + DependencyControl = DependencyControl + }; + + foreach (var b in _buttons) + { + var lst = new ButtonRow(); + foreach (var b2 in b) + { + if (!(b2 is TagButtonBase tb)) + { + continue; + } + + if (!tags.Contains(tb.Tag)) + { + continue; + } + + //Copy full row, when at least one match has found. + if (byRow) + { + lst = b; + break; + } + + lst.Add(b2); + } + + if (lst.Count > 0) + { + bf._buttons.Add(lst); + } + } + + return bf; + } +} \ No newline at end of file diff --git a/TelegramBotBase/Form/CallbackData.cs b/TelegramBotBase/Form/CallbackData.cs index 9cca33d..d1cf35c 100644 --- a/TelegramBotBase/Form/CallbackData.cs +++ b/TelegramBotBase/Form/CallbackData.cs @@ -1,76 +1,67 @@ using Newtonsoft.Json; -namespace TelegramBotBase.Form +namespace TelegramBotBase.Form; + +/// +/// Base class for serializing buttons and data +/// +public class CallbackData { - /// - /// Base class for serializing buttons and data - /// - public class CallbackData + public CallbackData() { - [JsonProperty("m")] - public string Method { get; set; } - - [JsonProperty("v")] - public string Value { get; set; } - - - public CallbackData() - { - - } - - public CallbackData(string method, string value) - { - Method = method; - Value = value; - } - - public static string Create(string method, string value) - { - return new CallbackData(method, value).Serialize(); - } - - /// - /// Serializes data to json string - /// - /// - public string Serialize() - { - var s = ""; - try - { - - s = JsonConvert.SerializeObject(this); - } - catch - { - - - } - return s; - } - - /// - /// Deserializes data from json string - /// - /// - /// - public static CallbackData Deserialize(string data) - { - CallbackData cd = null; - try - { - cd = JsonConvert.DeserializeObject(data); - - return cd; - } - catch - { - - } - - return null; - } - } -} + + public CallbackData(string method, string value) + { + Method = method; + Value = value; + } + + [JsonProperty("m")] public string Method { get; set; } + + [JsonProperty("v")] public string Value { get; set; } + + public static string Create(string method, string value) + { + return new CallbackData(method, value).Serialize(); + } + + /// + /// Serializes data to json string + /// + /// + public string Serialize() + { + var s = ""; + try + { + s = JsonConvert.SerializeObject(this); + } + catch + { + } + + return s; + } + + /// + /// Deserializes data from json string + /// + /// + /// + public static CallbackData Deserialize(string data) + { + CallbackData cd = null; + try + { + cd = JsonConvert.DeserializeObject(data); + + return cd; + } + catch + { + } + + return null; + } +} \ No newline at end of file diff --git a/TelegramBotBase/Form/ConfirmDialog.cs b/TelegramBotBase/Form/ConfirmDialog.cs index 0621fcb..ebb62c3 100644 --- a/TelegramBotBase/Form/ConfirmDialog.cs +++ b/TelegramBotBase/Form/ConfirmDialog.cs @@ -1,115 +1,119 @@ using System; using System.Collections.Generic; -using System.ComponentModel; using System.Linq; using System.Threading.Tasks; using TelegramBotBase.Args; using TelegramBotBase.Attributes; using TelegramBotBase.Base; -namespace TelegramBotBase.Form +namespace TelegramBotBase.Form; + +[IgnoreState] +public class ConfirmDialog : ModalDialog { - [IgnoreState] - public class ConfirmDialog : ModalDialog + public ConfirmDialog() { - /// - /// The message the users sees. - /// - public string Message { get; set; } - - /// - /// An additional optional value. - /// - public object Tag { get; set; } - - /// - /// Automatically close form on button click - /// - public bool AutoCloseOnClick { get; set; } = true; - - public List Buttons { get; set; } - - private static object EvButtonClicked { get; } = new object(); - - public ConfirmDialog() - { - - } - - public ConfirmDialog(string message) - { - this.Message = message; - Buttons = new List(); - } - - public ConfirmDialog(string message, params ButtonBase[] buttons) - { - this.Message = message; - this.Buttons = buttons.ToList(); - } - - /// - /// Adds one Button - /// - /// - public void AddButton(ButtonBase button) - { - Buttons.Add(button); - } - - public override async Task Action(MessageResult message) - { - if (message.Handled) - return; - - if (!message.IsFirstHandler) - return; - - var call = message.GetData(); - if (call == null) - return; - - message.Handled = true; - - await message.ConfirmAction(); - - await message.DeleteMessage(); - - var button = Buttons.FirstOrDefault(a => a.Value == call.Value); - - if (button == null) - { - return; - } - - OnButtonClicked(new ButtonClickedEventArgs(button) { Tag = Tag }); - - if (AutoCloseOnClick) - await CloseForm(); - } - - - public override async Task Render(MessageResult message) - { - var btn = new ButtonForm(); - - var buttons = Buttons.Select(a => new ButtonBase(a.Text, CallbackData.Create("action", a.Value))).ToList(); - btn.AddButtonRow(buttons); - - await Device.Send(Message, btn); - } - - - public event EventHandler ButtonClicked - { - add => Events.AddHandler(EvButtonClicked, value); - remove => Events.RemoveHandler(EvButtonClicked, value); - } - - public void OnButtonClicked(ButtonClickedEventArgs e) - { - (Events[EvButtonClicked] as EventHandler)?.Invoke(this, e); - } - } -} + + public ConfirmDialog(string message) + { + Message = message; + Buttons = new List(); + } + + public ConfirmDialog(string message, params ButtonBase[] buttons) + { + Message = message; + Buttons = buttons.ToList(); + } + + /// + /// The message the users sees. + /// + public string Message { get; set; } + + /// + /// An additional optional value. + /// + public object Tag { get; set; } + + /// + /// Automatically close form on button click + /// + public bool AutoCloseOnClick { get; set; } = true; + + public List Buttons { get; set; } + + private static object EvButtonClicked { get; } = new(); + + /// + /// Adds one Button + /// + /// + public void AddButton(ButtonBase button) + { + Buttons.Add(button); + } + + public override async Task Action(MessageResult message) + { + if (message.Handled) + { + return; + } + + if (!message.IsFirstHandler) + { + return; + } + + var call = message.GetData(); + if (call == null) + { + return; + } + + message.Handled = true; + + await message.ConfirmAction(); + + await message.DeleteMessage(); + + var button = Buttons.FirstOrDefault(a => a.Value == call.Value); + + if (button == null) + { + return; + } + + OnButtonClicked(new ButtonClickedEventArgs(button) { Tag = Tag }); + + if (AutoCloseOnClick) + { + await CloseForm(); + } + } + + + public override async Task Render(MessageResult message) + { + var btn = new ButtonForm(); + + var buttons = Buttons.Select(a => new ButtonBase(a.Text, CallbackData.Create("action", a.Value))).ToList(); + btn.AddButtonRow(buttons); + + await Device.Send(Message, btn); + } + + + public event EventHandler ButtonClicked + { + add => Events.AddHandler(EvButtonClicked, value); + remove => Events.RemoveHandler(EvButtonClicked, value); + } + + public void OnButtonClicked(ButtonClickedEventArgs e) + { + (Events[EvButtonClicked] as EventHandler)?.Invoke(this, e); + } +} \ No newline at end of file diff --git a/TelegramBotBase/Form/DynamicButton.cs b/TelegramBotBase/Form/DynamicButton.cs index 9dcc89b..129339d 100644 --- a/TelegramBotBase/Form/DynamicButton.cs +++ b/TelegramBotBase/Form/DynamicButton.cs @@ -1,33 +1,30 @@ using System; -namespace TelegramBotBase.Form +namespace TelegramBotBase.Form; + +public class DynamicButton : ButtonBase { - public class DynamicButton : ButtonBase + private readonly Func _getText; + + private string _mText = ""; + + public DynamicButton(string text, string value, string url = null) { - public override string Text - { - get => _getText?.Invoke() ?? _mText; - set => _mText = value; - } - - private string _mText = ""; - - private Func _getText; - - public DynamicButton(string text, string value, string url = null) - { - this.Text = text; - this.Value = value; - this.Url = url; - } - - public DynamicButton(Func getText, string value, string url = null) - { - this._getText = getText; - this.Value = value; - this.Url = url; - } - - + Text = text; + Value = value; + Url = url; } -} + + public DynamicButton(Func getText, string value, string url = null) + { + _getText = getText; + Value = value; + Url = url; + } + + public override string Text + { + get => _getText?.Invoke() ?? _mText; + set => _mText = value; + } +} \ No newline at end of file diff --git a/TelegramBotBase/Form/GroupForm.cs b/TelegramBotBase/Form/GroupForm.cs index 6134a43..14002f9 100644 --- a/TelegramBotBase/Form/GroupForm.cs +++ b/TelegramBotBase/Form/GroupForm.cs @@ -3,73 +3,73 @@ using Telegram.Bot.Types.Enums; using TelegramBotBase.Args; using TelegramBotBase.Base; -namespace TelegramBotBase.Form +namespace TelegramBotBase.Form; + +public class GroupForm : FormBase { - public class GroupForm : FormBase + public override async Task Load(MessageResult message) { - public override async Task Load(MessageResult message) + switch (message.MessageType) { - switch (message.MessageType) - { - case MessageType.ChatMembersAdded: + case MessageType.ChatMembersAdded: - await OnMemberChanges(new MemberChangeEventArgs(MessageType.ChatMembersAdded, message, message.Message.NewChatMembers)); + await OnMemberChanges(new MemberChangeEventArgs(MessageType.ChatMembersAdded, message, + message.Message.NewChatMembers)); - break; - case MessageType.ChatMemberLeft: + break; + case MessageType.ChatMemberLeft: - await OnMemberChanges(new MemberChangeEventArgs(MessageType.ChatMemberLeft, message, message.Message.LeftChatMember)); + await OnMemberChanges(new MemberChangeEventArgs(MessageType.ChatMemberLeft, message, + message.Message.LeftChatMember)); - break; + break; - case MessageType.ChatPhotoChanged: - case MessageType.ChatPhotoDeleted: - case MessageType.ChatTitleChanged: - case MessageType.MigratedFromGroup: - case MessageType.MigratedToSupergroup: - case MessageType.MessagePinned: - case MessageType.GroupCreated: - case MessageType.SupergroupCreated: - case MessageType.ChannelCreated: + case MessageType.ChatPhotoChanged: + case MessageType.ChatPhotoDeleted: + case MessageType.ChatTitleChanged: + case MessageType.MigratedFromGroup: + case MessageType.MigratedToSupergroup: + case MessageType.MessagePinned: + case MessageType.GroupCreated: + case MessageType.SupergroupCreated: + case MessageType.ChannelCreated: - await OnGroupChanged(new GroupChangedEventArgs(message.MessageType, message)); + await OnGroupChanged(new GroupChangedEventArgs(message.MessageType, message)); - break; + break; - default: + default: - await OnMessage(message); + await OnMessage(message); - break; - } - - } - - public override async Task Edited(MessageResult message) - { - await OnMessageEdit(message); - } - - public virtual Task OnMemberChanges(MemberChangeEventArgs e) - { - return Task.CompletedTask; - } - - - public virtual Task OnGroupChanged(GroupChangedEventArgs e) - { - return Task.CompletedTask; - } - - - public virtual Task OnMessage(MessageResult e) - { - return Task.CompletedTask; - } - - public virtual Task OnMessageEdit(MessageResult e) - { - return Task.CompletedTask; + break; } } -} + + public override async Task Edited(MessageResult message) + { + await OnMessageEdit(message); + } + + public virtual Task OnMemberChanges(MemberChangeEventArgs e) + { + return Task.CompletedTask; + } + + + public virtual Task OnGroupChanged(GroupChangedEventArgs e) + { + return Task.CompletedTask; + } + + + public virtual Task OnMessage(MessageResult e) + { + return Task.CompletedTask; + } + + public virtual Task OnMessageEdit(MessageResult e) + { + return Task.CompletedTask; + } +} \ No newline at end of file diff --git a/TelegramBotBase/Form/ModalDialog.cs b/TelegramBotBase/Form/ModalDialog.cs index 06d7b7b..06e2bbd 100644 --- a/TelegramBotBase/Form/ModalDialog.cs +++ b/TelegramBotBase/Form/ModalDialog.cs @@ -1,26 +1,25 @@ using System; using System.Threading.Tasks; -namespace TelegramBotBase.Form +namespace TelegramBotBase.Form; + +public class ModalDialog : FormBase { - public class ModalDialog : FormBase + /// + /// Contains the parent from where the modal dialog has been opened. + /// + public FormBase ParentForm { get; set; } + + /// + /// This is a modal only function and does everything to close this form. + /// + public async Task CloseForm() { - /// - /// Contains the parent from where the modal dialog has been opened. - /// - public FormBase ParentForm { get; set; } + await CloseControls(); - /// - /// This is a modal only function and does everything to close this form. - /// - public async Task CloseForm() - { - await CloseControls(); - - await OnClosed(EventArgs.Empty); + await OnClosed(EventArgs.Empty); - await ParentForm?.ReturnFromModal(this); - } + await ParentForm?.ReturnFromModal(this); } -} +} \ No newline at end of file diff --git a/TelegramBotBase/Form/Navigation/NavigationController.cs b/TelegramBotBase/Form/Navigation/NavigationController.cs index 94461ab..01931e8 100644 --- a/TelegramBotBase/Form/Navigation/NavigationController.cs +++ b/TelegramBotBase/Form/Navigation/NavigationController.cs @@ -10,348 +10,356 @@ using TelegramBotBase.Base; using TelegramBotBase.Interfaces; using TelegramBotBase.Tools; -namespace TelegramBotBase.Form.Navigation +namespace TelegramBotBase.Form.Navigation; + +[DebuggerDisplay("{Index+1} Forms")] +public class NavigationController : FormBase, IStateForm { - [DebuggerDisplay("{Index+1} Forms")] - public class NavigationController : FormBase, IStateForm + public NavigationController() { + History = new List(); + Index = -1; + ForceCleanupOnLastPop = true; - [SaveState] - private List History { get; set; } + Init += NavigationController_Init; + Opened += NavigationController_Opened; + Closed += NavigationController_Closed; + } - [SaveState] - public int Index { get; set; } + public NavigationController(FormBase startForm, params FormBase[] forms) : this() + { + Client = startForm.Client; + Device = startForm.Device; + startForm.NavigationController = this; - /// - /// Will replace the controller when poping a form to the root form. - /// - [SaveState] - public bool ForceCleanupOnLastPop { get; set; } + History.Add(startForm); + Index = 0; - public NavigationController() + if (forms.Length > 0) { - History = new List(); - Index = -1; - ForceCleanupOnLastPop = true; - - Init += NavigationController_Init; - Opened += NavigationController_Opened; - Closed += NavigationController_Closed; + History.AddRange(forms); + Index = History.Count - 1; } + } - public NavigationController(FormBase startForm, params FormBase[] forms) : this() - { - Client = startForm.Client; - Device = startForm.Device; - startForm.NavigationController = this; + [SaveState] private List History { get; } - History.Add(startForm); - Index = 0; + [SaveState] public int Index { get; set; } - if (forms.Length > 0) - { - History.AddRange(forms); - Index = History.Count - 1; - } - } + /// + /// Will replace the controller when poping a form to the root form. + /// + [SaveState] + public bool ForceCleanupOnLastPop { get; set; } - private async Task NavigationController_Init(object sender, InitEventArgs e) - { - if (CurrentForm == null) - return; - - await CurrentForm.OnInit(e); - } - - private async Task NavigationController_Opened(object sender, EventArgs e) - { - if (CurrentForm == null) - return; - - await CurrentForm.OnOpened(e); - } - - private async Task NavigationController_Closed(object sender, EventArgs e) - { - if (CurrentForm == null) - return; - - await CurrentForm.OnClosed(e); - } - - - - /// - /// Remove the current active form on the stack. - /// - /// - public virtual async Task PopAsync() + /// + /// Returns the current form from the stack. + /// + public FormBase CurrentForm + { + get { if (History.Count == 0) - return; - - var form = History[Index]; - - form.NavigationController = null; - History.Remove(form); - Index--; - - Device.FormSwitched = true; - - await form.OnClosed(EventArgs.Empty); - - //Leave NavigationController and move to the last one - if (ForceCleanupOnLastPop && History.Count == 1) { - var lastForm = History[0]; - lastForm.NavigationController = null; - await NavigateTo(lastForm); - return; + return null; } - if (History.Count > 0) - { - form = History[Index]; - await form.OnOpened(EventArgs.Empty); - } + return History[Index]; + } + } + + + public void LoadState(LoadStateEventArgs e) + { + if (e.Get("$controller.history.count") == null) + { + return; } - /// - /// Pop's through all forms back to the root form. - /// - /// - public virtual async Task PopToRootAsync() - { - while (Index > 0) - { - await PopAsync(); - } - } - /// - /// Pushing the given form to the stack and renders it. - /// - /// - /// - public virtual async Task PushAsync(FormBase form, params object[] args) + var historyCount = e.GetInt("$controller.history.count"); + + for (var i = 0; i < historyCount; i++) { - form.Client = Client; + var c = e.GetObject($"$controller.history[{i}]") as Dictionary; + + + var qname = e.Get($"$controller.history[{i}].type"); + + if (qname == null) + { + continue; + } + + var t = Type.GetType(qname); + if (t == null || !t.IsSubclassOf(typeof(FormBase))) + { + continue; + } + + //No default constructor, fallback + if (t.GetConstructor(new Type[] { })?.Invoke(new object[] { }) is not FormBase form) + { + continue; + } + + var properties = c.Where(a => a.Key.StartsWith("$")); + + var fields = form.GetType() + .GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) + .Where(a => a.GetCustomAttributes(typeof(SaveState), true).Length != 0).ToList(); + + foreach (var p in properties) + { + var f = fields.FirstOrDefault(a => a.Name == p.Key.Substring(1)); + if (f == null) + { + continue; + } + + try + { + if (f.PropertyType.IsEnum) + { + var ent = Enum.Parse(f.PropertyType, p.Value.ToString()); + + f.SetValue(form, ent); + + continue; + } + + + f.SetValue(form, p.Value); + } + catch (ArgumentException) + { + Conversion.CustomConversionChecks(form, p, f); + } + catch + { + } + } + form.Device = Device; + form.Client = Client; form.NavigationController = this; + form.OnInit(new InitEventArgs()); + History.Add(form); - Index++; + } + } - Device.FormSwitched = true; + public void SaveState(SaveStateEventArgs e) + { + e.Set("$controller.history.count", History.Count.ToString()); - if (Index < 2) - return; + var i = 0; + foreach (var form in History) + { + var fields = form.GetType() + .GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) + .Where(a => a.GetCustomAttributes(typeof(SaveState), true).Length != 0).ToList(); - await form.OnInit(new InitEventArgs(args)); + var dt = new Dictionary(); + foreach (var f in fields) + { + var val = f.GetValue(form); + dt.Add("$" + f.Name, val); + } + + e.Set($"$controller.history[{i}].type", form.GetType().AssemblyQualifiedName); + + e.SetObject($"$controller.history[{i}]", dt); + + i++; + } + } + + private async Task NavigationController_Init(object sender, InitEventArgs e) + { + if (CurrentForm == null) + { + return; + } + + await CurrentForm.OnInit(e); + } + + private async Task NavigationController_Opened(object sender, EventArgs e) + { + if (CurrentForm == null) + { + return; + } + + await CurrentForm.OnOpened(e); + } + + private async Task NavigationController_Closed(object sender, EventArgs e) + { + if (CurrentForm == null) + { + return; + } + + await CurrentForm.OnClosed(e); + } + + + /// + /// Remove the current active form on the stack. + /// + /// + public virtual async Task PopAsync() + { + if (History.Count == 0) + { + return; + } + + var form = History[Index]; + + form.NavigationController = null; + History.Remove(form); + Index--; + + Device.FormSwitched = true; + + await form.OnClosed(EventArgs.Empty); + + //Leave NavigationController and move to the last one + if (ForceCleanupOnLastPop && History.Count == 1) + { + var lastForm = History[0]; + lastForm.NavigationController = null; + await NavigateTo(lastForm); + return; + } + + if (History.Count > 0) + { + form = History[Index]; await form.OnOpened(EventArgs.Empty); } + } - /// - /// Pops the current form and pushes a new one. - /// Will help to remove forms so you can not navigate back to them. - /// - /// - /// - /// - public virtual async Task PushAndReplaceAsync(FormBase form, params object[] args) + /// + /// Pop's through all forms back to the root form. + /// + /// + public virtual async Task PopToRootAsync() + { + while (Index > 0) { await PopAsync(); - - await PushAsync(form, args); } - - /// - /// Returns the current form from the stack. - /// - public FormBase CurrentForm - { - get - { - if (History.Count == 0) - return null; - - return History[Index]; - } - } - - public List GetAllForms() - { - return History.ToList(); - } - - - public void LoadState(LoadStateEventArgs e) - { - if (e.Get("$controller.history.count") == null) - return; - - - var historyCount = e.GetInt("$controller.history.count"); - - for (var i = 0; i < historyCount; i++) - { - - var c = e.GetObject($"$controller.history[{i}]") as Dictionary; - - - - var qname = e.Get($"$controller.history[{i}].type"); - - if (qname == null) - continue; - - var t = Type.GetType(qname); - if (t == null || !t.IsSubclassOf(typeof(FormBase))) - { - continue; - } - - //No default constructor, fallback - if (t.GetConstructor(new Type[] { })?.Invoke(new object[] { }) is not FormBase form) - { - continue; - } - - var properties = c.Where(a => a.Key.StartsWith("$")); - - var fields = form.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(a => a.GetCustomAttributes(typeof(SaveState), true).Length != 0).ToList(); - - foreach (var p in properties) - { - var f = fields.FirstOrDefault(a => a.Name == p.Key.Substring(1)); - if (f == null) - continue; - - try - { - if (f.PropertyType.IsEnum) - { - var ent = Enum.Parse(f.PropertyType, p.Value.ToString()); - - f.SetValue(form, ent); - - continue; - } - - - f.SetValue(form, p.Value); - } - catch (ArgumentException) - { - - Conversion.CustomConversionChecks(form, p, f); - - } - catch - { - - } - } - - form.Device = Device; - form.Client = Client; - form.NavigationController = this; - - form.OnInit(new InitEventArgs()); - - History.Add(form); - } - - } - - public void SaveState(SaveStateEventArgs e) - { - e.Set("$controller.history.count", History.Count.ToString()); - - var i = 0; - foreach (var form in History) - { - var fields = form.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(a => a.GetCustomAttributes(typeof(SaveState), true).Length != 0).ToList(); - - var dt = new Dictionary(); - foreach (var f in fields) - { - var val = f.GetValue(form); - - dt.Add("$" + f.Name, val); - } - - e.Set($"$controller.history[{i}].type", form.GetType().AssemblyQualifiedName); - - e.SetObject($"$controller.history[{i}]", dt); - - i++; - } - } - - - #region "Methods passthrough" - - public override async Task NavigateTo(FormBase newForm, params object[] args) - { - await CurrentForm.NavigateTo(newForm, args); - } - - public override async Task LoadControls(MessageResult message) - { - await CurrentForm.LoadControls(message); - } - - public override async Task Load(MessageResult message) - { - await CurrentForm.Load(message); - } - - public override async Task ActionControls(MessageResult message) - { - await CurrentForm.ActionControls(message); - } - - public override async Task Action(MessageResult message) - { - await CurrentForm.Action(message); - } - - - - public override async Task Edited(MessageResult message) - { - await CurrentForm.Edited(message); - } - - public override async Task Render(MessageResult message) - { - await CurrentForm.Render(message); - } - - public override async Task RenderControls(MessageResult message) - { - await CurrentForm.RenderControls(message); - } - - public override async Task PreLoad(MessageResult message) - { - await CurrentForm.PreLoad(message); - } - - public override async Task ReturnFromModal(ModalDialog modal) - { - await CurrentForm.ReturnFromModal(modal); - } - - public override async Task SentData(DataResult message) - { - await CurrentForm.SentData(message); - } - - - #endregion - } + + /// + /// Pushing the given form to the stack and renders it. + /// + /// + /// + public virtual async Task PushAsync(FormBase form, params object[] args) + { + form.Client = Client; + form.Device = Device; + form.NavigationController = this; + + History.Add(form); + Index++; + + Device.FormSwitched = true; + + if (Index < 2) + { + return; + } + + await form.OnInit(new InitEventArgs(args)); + + await form.OnOpened(EventArgs.Empty); + } + + /// + /// Pops the current form and pushes a new one. + /// Will help to remove forms so you can not navigate back to them. + /// + /// + /// + /// + public virtual async Task PushAndReplaceAsync(FormBase form, params object[] args) + { + await PopAsync(); + + await PushAsync(form, args); + } + + public List GetAllForms() + { + return History.ToList(); + } + + + #region "Methods passthrough" + + public override async Task NavigateTo(FormBase newForm, params object[] args) + { + await CurrentForm.NavigateTo(newForm, args); + } + + public override async Task LoadControls(MessageResult message) + { + await CurrentForm.LoadControls(message); + } + + public override async Task Load(MessageResult message) + { + await CurrentForm.Load(message); + } + + public override async Task ActionControls(MessageResult message) + { + await CurrentForm.ActionControls(message); + } + + public override async Task Action(MessageResult message) + { + await CurrentForm.Action(message); + } + + + public override async Task Edited(MessageResult message) + { + await CurrentForm.Edited(message); + } + + public override async Task Render(MessageResult message) + { + await CurrentForm.Render(message); + } + + public override async Task RenderControls(MessageResult message) + { + await CurrentForm.RenderControls(message); + } + + public override async Task PreLoad(MessageResult message) + { + await CurrentForm.PreLoad(message); + } + + public override async Task ReturnFromModal(ModalDialog modal) + { + await CurrentForm.ReturnFromModal(modal); + } + + public override async Task SentData(DataResult message) + { + await CurrentForm.SentData(message); + } + + #endregion } diff --git a/TelegramBotBase/Form/PromptDialog.cs b/TelegramBotBase/Form/PromptDialog.cs index 61a28bf..a2d4c56 100644 --- a/TelegramBotBase/Form/PromptDialog.cs +++ b/TelegramBotBase/Form/PromptDialog.cs @@ -1,5 +1,4 @@ using System; -using System.ComponentModel; using System.Threading.Tasks; using Telegram.Bot.Types; using Telegram.Bot.Types.ReplyMarkups; @@ -8,108 +7,106 @@ using TelegramBotBase.Attributes; using TelegramBotBase.Base; using TelegramBotBase.Localizations; -namespace TelegramBotBase.Form +namespace TelegramBotBase.Form; + +[IgnoreState] +public class PromptDialog : ModalDialog { - [IgnoreState] - public class PromptDialog : ModalDialog + public PromptDialog() { - /// - /// The message the users sees. - /// - public string Message { get; set; } - - /// - /// The returned text value by the user. - /// - public string Value { get; set; } - - /// - /// An additional optional value. - /// - public object Tag { get; set; } - - private static object EvCompleted { get; } = new object(); - - public bool ShowBackButton { get; set; } = false; - - public string BackLabel { get; set; } = Default.Language["PromptDialog_Back"]; - - /// - /// Contains the RAW received message. - /// - public Message ReceivedMessage { get; set; } - - public PromptDialog() - { - - } - - public PromptDialog(string message) - { - this.Message = message; - } - - public override async Task Load(MessageResult message) - { - if (message.Handled) - return; - - if (!message.IsFirstHandler) - return; - - if (ShowBackButton && message.MessageText == BackLabel) - { - await CloseForm(); - - return; - } - - if (Value == null) - { - Value = message.MessageText; - - ReceivedMessage = message.Message; - } - - - } - - public override async Task Render(MessageResult message) - { - - if (Value == null) - { - if (ShowBackButton) - { - var bf = new ButtonForm(); - bf.AddButtonRow(new ButtonBase(BackLabel, "back")); - await Device.Send(Message, (ReplyMarkupBase)bf); - return; - } - - await Device.Send(Message); - return; - } - - - message.Handled = true; - - OnCompleted(new PromptDialogCompletedEventArgs { Tag = Tag, Value = Value }); - - await CloseForm(); - } - - - public event EventHandler Completed - { - add => Events.AddHandler(EvCompleted, value); - remove => Events.RemoveHandler(EvCompleted, value); - } - - public void OnCompleted(PromptDialogCompletedEventArgs e) - { - (Events[EvCompleted] as EventHandler)?.Invoke(this, e); - } - } -} + + public PromptDialog(string message) + { + Message = message; + } + + /// + /// The message the users sees. + /// + public string Message { get; set; } + + /// + /// The returned text value by the user. + /// + public string Value { get; set; } + + /// + /// An additional optional value. + /// + public object Tag { get; set; } + + private static object EvCompleted { get; } = new(); + + public bool ShowBackButton { get; set; } = false; + + public string BackLabel { get; set; } = Default.Language["PromptDialog_Back"]; + + /// + /// Contains the RAW received message. + /// + public Message ReceivedMessage { get; set; } + + public override async Task Load(MessageResult message) + { + if (message.Handled) + { + return; + } + + if (!message.IsFirstHandler) + { + return; + } + + if (ShowBackButton && message.MessageText == BackLabel) + { + await CloseForm(); + + return; + } + + if (Value == null) + { + Value = message.MessageText; + + ReceivedMessage = message.Message; + } + } + + public override async Task Render(MessageResult message) + { + if (Value == null) + { + if (ShowBackButton) + { + var bf = new ButtonForm(); + bf.AddButtonRow(new ButtonBase(BackLabel, "back")); + await Device.Send(Message, (ReplyMarkupBase)bf); + return; + } + + await Device.Send(Message); + return; + } + + + message.Handled = true; + + OnCompleted(new PromptDialogCompletedEventArgs { Tag = Tag, Value = Value }); + + await CloseForm(); + } + + + public event EventHandler Completed + { + add => Events.AddHandler(EvCompleted, value); + remove => Events.RemoveHandler(EvCompleted, value); + } + + public void OnCompleted(PromptDialogCompletedEventArgs e) + { + (Events[EvCompleted] as EventHandler)?.Invoke(this, e); + } +} \ No newline at end of file diff --git a/TelegramBotBase/Form/SplitterForm.cs b/TelegramBotBase/Form/SplitterForm.cs index bfb9818..4d8d668 100644 --- a/TelegramBotBase/Form/SplitterForm.cs +++ b/TelegramBotBase/Form/SplitterForm.cs @@ -2,95 +2,92 @@ using Telegram.Bot.Types.Enums; using TelegramBotBase.Base; -namespace TelegramBotBase.Form +namespace TelegramBotBase.Form; + +/// +/// This is used to split incomming requests depending on the chat type. +/// +public class SplitterForm : FormBase { - /// - /// This is used to split incomming requests depending on the chat type. - /// - public class SplitterForm : FormBase + private static object __evOpenSupergroup = new(); + private static object __evOpenGroup = new(); + private static object __evOpenChannel = new(); + private static object __evOpen = new(); + + + public override async Task Load(MessageResult message) { - - private static object __evOpenSupergroup = new object(); - private static object __evOpenGroup = new object(); - private static object __evOpenChannel = new object(); - private static object __evOpen = new object(); - - - public override async Task Load(MessageResult message) + if (message.Message.Chat.Type == ChatType.Channel) { + if (await OpenChannel(message)) + { + return; + } + } - if (message.Message.Chat.Type == ChatType.Channel) + if (message.Message.Chat.Type == ChatType.Supergroup) + { + if (await OpenSupergroup(message)) { - if (await OpenChannel(message)) - { - return; - } - } - if (message.Message.Chat.Type == ChatType.Supergroup) - { - if (await OpenSupergroup(message)) - { - return; - } - if (await OpenGroup(message)) - { - return; - } - } - if (message.Message.Chat.Type == ChatType.Group) - { - if (await OpenGroup(message)) - { - return; - } + return; } - await Open(message); + if (await OpenGroup(message)) + { + return; + } } - - public virtual Task OpenSupergroup(MessageResult e) + if (message.Message.Chat.Type == ChatType.Group) { - return Task.FromResult(false); - } - - public virtual Task OpenChannel(MessageResult e) - { - return Task.FromResult(false); - } - - public virtual Task Open(MessageResult e) - { - return Task.FromResult(false); - } - - public virtual Task OpenGroup(MessageResult e) - { - return Task.FromResult(false); - } - - - - - public override Task Action(MessageResult message) - { - return base.Action(message); - } - - public override Task PreLoad(MessageResult message) - { - return base.PreLoad(message); - } - - public override Task Render(MessageResult message) - { - return base.Render(message); - } - - public override Task SentData(DataResult message) - { - return base.SentData(message); + if (await OpenGroup(message)) + { + return; + } } + await Open(message); } -} + + + public virtual Task OpenSupergroup(MessageResult e) + { + return Task.FromResult(false); + } + + public virtual Task OpenChannel(MessageResult e) + { + return Task.FromResult(false); + } + + public virtual Task Open(MessageResult e) + { + return Task.FromResult(false); + } + + public virtual Task OpenGroup(MessageResult e) + { + return Task.FromResult(false); + } + + + public override Task Action(MessageResult message) + { + return base.Action(message); + } + + public override Task PreLoad(MessageResult message) + { + return base.PreLoad(message); + } + + public override Task Render(MessageResult message) + { + return base.Render(message); + } + + public override Task SentData(DataResult message) + { + return base.SentData(message); + } +} \ No newline at end of file diff --git a/TelegramBotBase/Form/TagButtonBase.cs b/TelegramBotBase/Form/TagButtonBase.cs index fd6f545..8a6cb9e 100644 --- a/TelegramBotBase/Form/TagButtonBase.cs +++ b/TelegramBotBase/Form/TagButtonBase.cs @@ -1,50 +1,46 @@ using Telegram.Bot.Types.ReplyMarkups; -namespace TelegramBotBase.Form +namespace TelegramBotBase.Form; + +/// +/// Base class for button handling +/// +public class TagButtonBase : ButtonBase { - /// - /// Base class for button handling - /// - public class TagButtonBase : ButtonBase + public TagButtonBase() { - public string Tag { get; set; } - - public TagButtonBase() - { - - } - - public TagButtonBase(string text, string value, string tag) - { - this.Text = text; - this.Value = value; - this.Tag = tag; - } - - - /// - /// Returns an inline Button - /// - /// - /// - public override InlineKeyboardButton ToInlineButton(ButtonForm form) - { - var id = (form.DependencyControl != null ? form.DependencyControl.ControlId + "_" : ""); - - return InlineKeyboardButton.WithCallbackData(Text, id + Value); - - } - - - /// - /// Returns a KeyBoardButton - /// - /// - /// - public override KeyboardButton ToKeyboardButton(ButtonForm form) - { - return new KeyboardButton(Text); - } - } -} + + public TagButtonBase(string text, string value, string tag) + { + Text = text; + Value = value; + Tag = tag; + } + + public string Tag { get; set; } + + + /// + /// Returns an inline Button + /// + /// + /// + public override InlineKeyboardButton ToInlineButton(ButtonForm form) + { + var id = form.DependencyControl != null ? form.DependencyControl.ControlId + "_" : ""; + + return InlineKeyboardButton.WithCallbackData(Text, id + Value); + } + + + /// + /// Returns a KeyBoardButton + /// + /// + /// + public override KeyboardButton ToKeyboardButton(ButtonForm form) + { + return new KeyboardButton(Text); + } +} \ No newline at end of file diff --git a/TelegramBotBase/Interfaces/IDataSource.cs b/TelegramBotBase/Interfaces/IDataSource.cs index 7934972..fe759ee 100644 --- a/TelegramBotBase/Interfaces/IDataSource.cs +++ b/TelegramBotBase/Interfaces/IDataSource.cs @@ -1,40 +1,36 @@ using System.Collections.Generic; -namespace TelegramBotBase.Interfaces +namespace TelegramBotBase.Interfaces; + +public interface IDataSource { - public interface IDataSource - { - - /// - /// Returns the amount of items within this source. - /// - /// - int Count { get; } + /// + /// Returns the amount of items within this source. + /// + /// + int Count { get; } - /// - /// Returns the item at the specific index. - /// - /// - /// - T ItemAt(int index); + /// + /// Returns the item at the specific index. + /// + /// + /// + T ItemAt(int index); - /// - /// Get all items from this source within this range. - /// - /// - /// - /// - List ItemRange(int start, int count); + /// + /// Get all items from this source within this range. + /// + /// + /// + /// + List ItemRange(int start, int count); - /// - /// Gets a list of all items of this datasource. - /// - /// - List AllItems(); - - - } -} + /// + /// Gets a list of all items of this datasource. + /// + /// + List AllItems(); +} \ No newline at end of file diff --git a/TelegramBotBase/Interfaces/IDeviceSession.cs b/TelegramBotBase/Interfaces/IDeviceSession.cs index 05ae969..8e0d95a 100644 --- a/TelegramBotBase/Interfaces/IDeviceSession.cs +++ b/TelegramBotBase/Interfaces/IDeviceSession.cs @@ -1,40 +1,38 @@ using System; using TelegramBotBase.Form; -namespace TelegramBotBase.Interfaces +namespace TelegramBotBase.Interfaces; + +internal interface IDeviceSession { - internal interface IDeviceSession - { - /// - /// Device or chat id - /// - long DeviceId { get; set; } + /// + /// Device or chat id + /// + long DeviceId { get; set; } - /// - /// Username of user or group - /// - string ChatTitle { get; set; } + /// + /// Username of user or group + /// + string ChatTitle { get; set; } - /// - /// When did any last action happend (message received or button clicked) - /// - DateTime LastAction { get; set; } + /// + /// When did any last action happend (message received or button clicked) + /// + DateTime LastAction { get; set; } - /// - /// Returns the form where the user/group is at the moment. - /// - FormBase ActiveForm { get; set; } + /// + /// Returns the form where the user/group is at the moment. + /// + FormBase ActiveForm { get; set; } - /// - /// Returns the previous shown form - /// - FormBase PreviousForm { get; set; } + /// + /// Returns the previous shown form + /// + FormBase PreviousForm { get; set; } - /// - /// contains if the form has been switched (navigated) - /// - bool FormSwitched { get; set; } - - } -} + /// + /// contains if the form has been switched (navigated) + /// + bool FormSwitched { get; set; } +} \ No newline at end of file diff --git a/TelegramBotBase/Interfaces/IMessageLoopFactory.cs b/TelegramBotBase/Interfaces/IMessageLoopFactory.cs index 937e37a..951b7fa 100644 --- a/TelegramBotBase/Interfaces/IMessageLoopFactory.cs +++ b/TelegramBotBase/Interfaces/IMessageLoopFactory.cs @@ -4,15 +4,11 @@ using TelegramBotBase.Args; using TelegramBotBase.Base; using TelegramBotBase.Sessions; -namespace TelegramBotBase.Interfaces +namespace TelegramBotBase.Interfaces; + +public interface IMessageLoopFactory { - public interface IMessageLoopFactory - { + Task MessageLoop(BotBase bot, DeviceSession session, UpdateResult ur, MessageResult e); - Task MessageLoop(BotBase bot, DeviceSession session, UpdateResult ur, MessageResult e); - - event EventHandler UnhandledCall; - - - } -} + event EventHandler UnhandledCall; +} \ No newline at end of file diff --git a/TelegramBotBase/Interfaces/IStartFormFactory.cs b/TelegramBotBase/Interfaces/IStartFormFactory.cs index e300928..28a2df2 100644 --- a/TelegramBotBase/Interfaces/IStartFormFactory.cs +++ b/TelegramBotBase/Interfaces/IStartFormFactory.cs @@ -1,9 +1,8 @@ using TelegramBotBase.Form; -namespace TelegramBotBase.Interfaces +namespace TelegramBotBase.Interfaces; + +public interface IStartFormFactory { - public interface IStartFormFactory - { - FormBase CreateForm(); - } -} + FormBase CreateForm(); +} \ No newline at end of file diff --git a/TelegramBotBase/Interfaces/IStateForm.cs b/TelegramBotBase/Interfaces/IStateForm.cs index f9346d7..7e42cc4 100644 --- a/TelegramBotBase/Interfaces/IStateForm.cs +++ b/TelegramBotBase/Interfaces/IStateForm.cs @@ -1,16 +1,13 @@ using TelegramBotBase.Args; -namespace TelegramBotBase.Interfaces +namespace TelegramBotBase.Interfaces; + +/// +/// Is used to save specific fields into a session state to survive restarts or unhandled exceptions and crashes. +/// +public interface IStateForm { - /// - /// Is used to save specific fields into a session state to survive restarts or unhandled exceptions and crashes. - /// - public interface IStateForm - { + void LoadState(LoadStateEventArgs e); - void LoadState(LoadStateEventArgs e); - - void SaveState(SaveStateEventArgs e); - - } -} + void SaveState(SaveStateEventArgs e); +} \ No newline at end of file diff --git a/TelegramBotBase/Interfaces/IStateMachine.cs b/TelegramBotBase/Interfaces/IStateMachine.cs index 2c9c656..221fc77 100644 --- a/TelegramBotBase/Interfaces/IStateMachine.cs +++ b/TelegramBotBase/Interfaces/IStateMachine.cs @@ -2,14 +2,13 @@ using TelegramBotBase.Args; using TelegramBotBase.Base; -namespace TelegramBotBase.Interfaces +namespace TelegramBotBase.Interfaces; + +public interface IStateMachine { - public interface IStateMachine - { - Type FallbackStateForm { get; } + Type FallbackStateForm { get; } - void SaveFormStates(SaveStatesEventArgs e); + void SaveFormStates(SaveStatesEventArgs e); - StateContainer LoadFormStates(); - } -} + StateContainer LoadFormStates(); +} \ No newline at end of file diff --git a/TelegramBotBase/Localizations/Default.cs b/TelegramBotBase/Localizations/Default.cs index 27fb412..0582b8a 100644 --- a/TelegramBotBase/Localizations/Default.cs +++ b/TelegramBotBase/Localizations/Default.cs @@ -1,10 +1,6 @@ -namespace TelegramBotBase.Localizations +namespace TelegramBotBase.Localizations; + +public static class Default { - public static class Default - { - - public static Localization Language = new English(); - - - } -} + public static Localization Language = new English(); +} \ No newline at end of file diff --git a/TelegramBotBase/Localizations/English.cs b/TelegramBotBase/Localizations/English.cs index 2ba5fed..fb5b948 100644 --- a/TelegramBotBase/Localizations/English.cs +++ b/TelegramBotBase/Localizations/English.cs @@ -1,37 +1,35 @@ -namespace TelegramBotBase.Localizations +namespace TelegramBotBase.Localizations; + +public class English : Localization { - public class English : Localization + public English() { - public English() - { - Values["Language"] = "English"; - Values["ButtonGrid_Title"] = "Menu"; - Values["ButtonGrid_NoItems"] = "There are no items."; - Values["ButtonGrid_PreviousPage"] = "◀️"; - Values["ButtonGrid_NextPage"] = "▶️"; - Values["ButtonGrid_CurrentPage"] = "Page {0} of {1}"; - Values["ButtonGrid_SearchFeature"] = "💡 Send a message to filter the list. Click the 🔍 to reset the filter."; - Values["ButtonGrid_Back"] = "Back"; - Values["ButtonGrid_CheckAll"] = "Check all"; - Values["ButtonGrid_UncheckAll"] = "Uncheck all"; - Values["CalendarPicker_Title"] = "Pick date"; - Values["CalendarPicker_PreviousPage"] = "◀️"; - Values["CalendarPicker_NextPage"] = "▶️"; - Values["TreeView_Title"] = "Select node"; - Values["TreeView_LevelUp"] = "🔼 level up"; - Values["ToggleButton_On"] = "On"; - Values["ToggleButton_Off"] = "Off"; - Values["ToggleButton_OnIcon"] = "⚫"; - Values["ToggleButton_OffIcon"] = "⚪"; - Values["ToggleButton_Title"] = "Toggle"; - Values["ToggleButton_Changed"] = "Choosen"; - Values["MultiToggleButton_SelectedIcon"] = "✅"; - Values["MultiToggleButton_Title"] = "Multi-Toggle"; - Values["MultiToggleButton_Changed"] = "Choosen"; - Values["PromptDialog_Back"] = "Back"; - Values["ToggleButton_Changed"] = "Setting changed"; - } - - + Values["Language"] = "English"; + Values["ButtonGrid_Title"] = "Menu"; + Values["ButtonGrid_NoItems"] = "There are no items."; + Values["ButtonGrid_PreviousPage"] = "◀️"; + Values["ButtonGrid_NextPage"] = "▶️"; + Values["ButtonGrid_CurrentPage"] = "Page {0} of {1}"; + Values["ButtonGrid_SearchFeature"] = + "💡 Send a message to filter the list. Click the 🔍 to reset the filter."; + Values["ButtonGrid_Back"] = "Back"; + Values["ButtonGrid_CheckAll"] = "Check all"; + Values["ButtonGrid_UncheckAll"] = "Uncheck all"; + Values["CalendarPicker_Title"] = "Pick date"; + Values["CalendarPicker_PreviousPage"] = "◀️"; + Values["CalendarPicker_NextPage"] = "▶️"; + Values["TreeView_Title"] = "Select node"; + Values["TreeView_LevelUp"] = "🔼 level up"; + Values["ToggleButton_On"] = "On"; + Values["ToggleButton_Off"] = "Off"; + Values["ToggleButton_OnIcon"] = "⚫"; + Values["ToggleButton_OffIcon"] = "⚪"; + Values["ToggleButton_Title"] = "Toggle"; + Values["ToggleButton_Changed"] = "Choosen"; + Values["MultiToggleButton_SelectedIcon"] = "✅"; + Values["MultiToggleButton_Title"] = "Multi-Toggle"; + Values["MultiToggleButton_Changed"] = "Choosen"; + Values["PromptDialog_Back"] = "Back"; + Values["ToggleButton_Changed"] = "Setting changed"; } -} +} \ No newline at end of file diff --git a/TelegramBotBase/Localizations/German.cs b/TelegramBotBase/Localizations/German.cs index d34240a..52afbf7 100644 --- a/TelegramBotBase/Localizations/German.cs +++ b/TelegramBotBase/Localizations/German.cs @@ -1,37 +1,35 @@ -namespace TelegramBotBase.Localizations +namespace TelegramBotBase.Localizations; + +public class German : Localization { - public class German : Localization + public German() { - public German() - { - Values["Language"] = "Deutsch (German)"; - Values["ButtonGrid_Title"] = "Menü"; - Values["ButtonGrid_NoItems"] = "Es sind keine Einträge vorhanden."; - Values["ButtonGrid_PreviousPage"] = "◀️"; - Values["ButtonGrid_NextPage"] = "▶️"; - Values["ButtonGrid_CurrentPage"] = "Seite {0} von {1}"; - Values["ButtonGrid_SearchFeature"] = "💡 Sende eine Nachricht um die Liste zu filtern. Klicke die 🔍 um den Filter zurückzusetzen."; - Values["ButtonGrid_Back"] = "Zurück"; - Values["ButtonGrid_CheckAll"] = "Alle auswählen"; - Values["ButtonGrid_UncheckAll"] = "Keine auswählen"; - Values["CalendarPicker_Title"] = "Datum auswählen"; - Values["CalendarPicker_PreviousPage"] = "◀️"; - Values["CalendarPicker_NextPage"] = "▶️"; - Values["TreeView_Title"] = "Knoten auswählen"; - Values["TreeView_LevelUp"] = "🔼 Stufe hoch"; - Values["ToggleButton_On"] = "An"; - Values["ToggleButton_Off"] = "Aus"; - Values["ToggleButton_OnIcon"] = "⚫"; - Values["ToggleButton_OffIcon"] = "⚪"; - Values["ToggleButton_Title"] = "Schalter"; - Values["ToggleButton_Changed"] = "Ausgewählt"; - Values["MultiToggleButton_SelectedIcon"] = "✅"; - Values["MultiToggleButton_Title"] = "Mehrfach-Schalter"; - Values["MultiToggleButton_Changed"] = "Ausgewählt"; - Values["PromptDialog_Back"] = "Zurück"; - Values["ToggleButton_Changed"] = "Einstellung geändert"; - } - - + Values["Language"] = "Deutsch (German)"; + Values["ButtonGrid_Title"] = "Menü"; + Values["ButtonGrid_NoItems"] = "Es sind keine Einträge vorhanden."; + Values["ButtonGrid_PreviousPage"] = "◀️"; + Values["ButtonGrid_NextPage"] = "▶️"; + Values["ButtonGrid_CurrentPage"] = "Seite {0} von {1}"; + Values["ButtonGrid_SearchFeature"] = + "💡 Sende eine Nachricht um die Liste zu filtern. Klicke die 🔍 um den Filter zurückzusetzen."; + Values["ButtonGrid_Back"] = "Zurück"; + Values["ButtonGrid_CheckAll"] = "Alle auswählen"; + Values["ButtonGrid_UncheckAll"] = "Keine auswählen"; + Values["CalendarPicker_Title"] = "Datum auswählen"; + Values["CalendarPicker_PreviousPage"] = "◀️"; + Values["CalendarPicker_NextPage"] = "▶️"; + Values["TreeView_Title"] = "Knoten auswählen"; + Values["TreeView_LevelUp"] = "🔼 Stufe hoch"; + Values["ToggleButton_On"] = "An"; + Values["ToggleButton_Off"] = "Aus"; + Values["ToggleButton_OnIcon"] = "⚫"; + Values["ToggleButton_OffIcon"] = "⚪"; + Values["ToggleButton_Title"] = "Schalter"; + Values["ToggleButton_Changed"] = "Ausgewählt"; + Values["MultiToggleButton_SelectedIcon"] = "✅"; + Values["MultiToggleButton_Title"] = "Mehrfach-Schalter"; + Values["MultiToggleButton_Changed"] = "Ausgewählt"; + Values["PromptDialog_Back"] = "Zurück"; + Values["ToggleButton_Changed"] = "Einstellung geändert"; } -} +} \ No newline at end of file diff --git a/TelegramBotBase/Localizations/Localization.cs b/TelegramBotBase/Localizations/Localization.cs index b34fb88..3efddff 100644 --- a/TelegramBotBase/Localizations/Localization.cs +++ b/TelegramBotBase/Localizations/Localization.cs @@ -1,12 +1,10 @@ using System.Collections.Generic; -namespace TelegramBotBase.Localizations +namespace TelegramBotBase.Localizations; + +public abstract class Localization { - public abstract class Localization - { - public Dictionary Values = new Dictionary(); - - public string this[string key] => Values[key]; - } -} + public Dictionary Values = new(); + public string this[string key] => Values[key]; +} \ No newline at end of file diff --git a/TelegramBotBase/Markdown/Generator.cs b/TelegramBotBase/Markdown/Generator.cs index 748f62d..333c6cf 100644 --- a/TelegramBotBase/Markdown/Generator.cs +++ b/TelegramBotBase/Markdown/Generator.cs @@ -1,159 +1,159 @@ using System.Linq; using Telegram.Bot.Types.Enums; -namespace TelegramBotBase.Markdown +namespace TelegramBotBase.Markdown; + +/// +/// https://core.telegram.org/bots/api#markdownv2-style +/// +public static class Generator { + public static ParseMode OutputMode { get; set; } = ParseMode.Markdown; + /// - /// https://core.telegram.org/bots/api#markdownv2-style + /// Generates a link with title in Markdown or HTML /// - public static class Generator + /// + /// + /// + /// + public static string Link(this string url, string title = null, string tooltip = null) { - public static ParseMode OutputMode { get; set; } = ParseMode.Markdown; - - /// - /// Generates a link with title in Markdown or HTML - /// - /// - /// - /// - /// - public static string Link(this string url, string title = null, string tooltip = null) + return OutputMode switch { - return OutputMode switch - { - ParseMode.Markdown => "[" + (title ?? url) + "](" + url + " " + (tooltip ?? "") + ")", - ParseMode.Html => $"{title ?? ""}", - _ => url - }; - } - - /// - /// Returns a Link to the User, title is optional. - /// - /// - /// - /// - public static string MentionUser(this int userId, string title = null) - { - return Link("tg://user?id=" + userId, title); - } - - /// - /// Returns a Link to the User, title is optional. - /// - /// - /// - /// - public static string MentionUser(this string username, string title = null) - { - return Link("tg://user?id=" + username, title); - } - - /// - /// Returns a bold text in Markdown or HTML - /// - /// - /// - public static string Bold(this string text) - { - return OutputMode switch - { - ParseMode.Markdown => "*" + text + "*", - ParseMode.Html => "" + text + "", - _ => text - }; - } - - /// - /// Returns a strike through in Markdown or HTML - /// - /// - /// - public static string Strikesthrough(this string text) - { - return OutputMode switch - { - ParseMode.Markdown => "~" + text + "~", - ParseMode.Html => "" + text + "", - _ => text - }; - } - - /// - /// Returns a italic text in Markdown or HTML - /// - /// - /// - public static string Italic(this string text) - { - return OutputMode switch - { - ParseMode.Markdown => "_" + text + "_", - ParseMode.Html => "" + text + "", - _ => text - }; - } - - /// - /// Returns a underline text in Markdown or HTML - /// - /// - /// - public static string Underline(this string text) - { - return OutputMode switch - { - ParseMode.Markdown => "__" + text + "__", - ParseMode.Html => "" + text + "", - _ => text - }; - } - - /// - /// Returns a monospace text in Markdown or HTML - /// - /// - /// - public static string Monospace(this string text) - { - return OutputMode switch - { - ParseMode.Markdown => "`" + text + "`", - ParseMode.Html => "" + text + "", - _ => text - }; - } - - /// - /// Returns a multi monospace text in Markdown or HTML - /// - /// - /// - public static string MultiMonospace(this string text) - { - return OutputMode switch - { - ParseMode.Markdown => "```" + text + "```", - ParseMode.Html => "
" + text + "
", - _ => text - }; - } - - /// - /// Escapes all characters as stated in the documentation: https://core.telegram.org/bots/api#markdownv2-style - /// - /// - /// - public static string MarkdownV2Escape(this string text, params char[] toKeep) - { - var toEscape = new[] { '_', '*', '[', ']', '(', ')', '~', '`', '>', '#', '+', '-', '=', '|', '{', '}', '.', '!' }; - - return text.EscapeAll(toEscape.Where(a => !toKeep.Contains(a)).Select(a => a.ToString()).ToArray()); - } - - public static string EscapeAll(this string seed, string[] chars, char escapeCharacter = '\\') - { - return chars.Aggregate(seed, (str, cItem) => str.Replace(cItem, escapeCharacter + cItem)); - } + ParseMode.Markdown => "[" + (title ?? url) + "](" + url + " " + (tooltip ?? "") + ")", + ParseMode.Html => $"
{title ?? ""}", + _ => url + }; } -} + + /// + /// Returns a Link to the User, title is optional. + /// + /// + /// + /// + public static string MentionUser(this int userId, string title = null) + { + return Link("tg://user?id=" + userId, title); + } + + /// + /// Returns a Link to the User, title is optional. + /// + /// + /// + /// + public static string MentionUser(this string username, string title = null) + { + return Link("tg://user?id=" + username, title); + } + + /// + /// Returns a bold text in Markdown or HTML + /// + /// + /// + public static string Bold(this string text) + { + return OutputMode switch + { + ParseMode.Markdown => "*" + text + "*", + ParseMode.Html => "" + text + "", + _ => text + }; + } + + /// + /// Returns a strike through in Markdown or HTML + /// + /// + /// + public static string Strikesthrough(this string text) + { + return OutputMode switch + { + ParseMode.Markdown => "~" + text + "~", + ParseMode.Html => "" + text + "", + _ => text + }; + } + + /// + /// Returns a italic text in Markdown or HTML + /// + /// + /// + public static string Italic(this string text) + { + return OutputMode switch + { + ParseMode.Markdown => "_" + text + "_", + ParseMode.Html => "" + text + "", + _ => text + }; + } + + /// + /// Returns a underline text in Markdown or HTML + /// + /// + /// + public static string Underline(this string text) + { + return OutputMode switch + { + ParseMode.Markdown => "__" + text + "__", + ParseMode.Html => "" + text + "", + _ => text + }; + } + + /// + /// Returns a monospace text in Markdown or HTML + /// + /// + /// + public static string Monospace(this string text) + { + return OutputMode switch + { + ParseMode.Markdown => "`" + text + "`", + ParseMode.Html => "" + text + "", + _ => text + }; + } + + /// + /// Returns a multi monospace text in Markdown or HTML + /// + /// + /// + public static string MultiMonospace(this string text) + { + return OutputMode switch + { + ParseMode.Markdown => "```" + text + "```", + ParseMode.Html => "
" + text + "
", + _ => text + }; + } + + /// + /// Escapes all characters as stated in the documentation: https://core.telegram.org/bots/api#markdownv2-style + /// + /// + /// + public static string MarkdownV2Escape(this string text, params char[] toKeep) + { + var toEscape = new[] + { '_', '*', '[', ']', '(', ')', '~', '`', '>', '#', '+', '-', '=', '|', '{', '}', '.', '!' }; + + return text.EscapeAll(toEscape.Where(a => !toKeep.Contains(a)).Select(a => a.ToString()).ToArray()); + } + + public static string EscapeAll(this string seed, string[] chars, char escapeCharacter = '\\') + { + return chars.Aggregate(seed, (str, cItem) => str.Replace(cItem, escapeCharacter + cItem)); + } +} \ No newline at end of file diff --git a/TelegramBotBase/MessageLoops/FormBaseMessageLoop.cs b/TelegramBotBase/MessageLoops/FormBaseMessageLoop.cs index bfd6d81..7a06466 100644 --- a/TelegramBotBase/MessageLoops/FormBaseMessageLoop.cs +++ b/TelegramBotBase/MessageLoops/FormBaseMessageLoop.cs @@ -7,116 +7,116 @@ using TelegramBotBase.Base; using TelegramBotBase.Interfaces; using TelegramBotBase.Sessions; -namespace TelegramBotBase.MessageLoops +namespace TelegramBotBase.MessageLoops; + +/// +/// Thats the default message loop which reacts to Message, EditMessage and CallbackQuery. +/// +public class FormBaseMessageLoop : IMessageLoopFactory { - /// - /// Thats the default message loop which reacts to Message, EditMessage and CallbackQuery. - /// - public class FormBaseMessageLoop : IMessageLoopFactory + private static readonly object EvUnhandledCall = new(); + + private readonly EventHandlerList _events = new(); + + public async Task MessageLoop(BotBase bot, DeviceSession session, UpdateResult ur, MessageResult mr) { - private static readonly object EvUnhandledCall = new object(); + var update = ur.RawData; - private readonly EventHandlerList _events = new EventHandlerList(); - public async Task MessageLoop(BotBase bot, DeviceSession session, UpdateResult ur, MessageResult mr) + if (update.Type != UpdateType.Message + && update.Type != UpdateType.EditedMessage + && update.Type != UpdateType.CallbackQuery) { - var update = ur.RawData; + return; + } + //Is this a bot command ? + if (mr.IsFirstHandler && mr.IsBotCommand && bot.IsKnownBotCommand(mr.BotCommand)) + { + var sce = new BotCommandEventArgs(mr.BotCommand, mr.BotCommandParameters, mr.Message, session.DeviceId, + session); + await bot.OnBotCommand(sce); - if (update.Type != UpdateType.Message - && update.Type != UpdateType.EditedMessage - && update.Type != UpdateType.CallbackQuery) + if (sce.Handled) { return; } + } - //Is this a bot command ? - if (mr.IsFirstHandler && mr.IsBotCommand && bot.IsKnownBotCommand(mr.BotCommand)) + mr.Device = session; + + var activeForm = session.ActiveForm; + + //Pre Loading Event + await activeForm.PreLoad(mr); + + //Send Load event to controls + await activeForm.LoadControls(mr); + + //Loading Event + await activeForm.Load(mr); + + + //Is Attachment ? (Photo, Audio, Video, Contact, Location, Document) (Ignore Callback Queries) + if (update.Type == UpdateType.Message) + { + if ((mr.MessageType == MessageType.Contact) + | (mr.MessageType == MessageType.Document) + | (mr.MessageType == MessageType.Location) + | (mr.MessageType == MessageType.Photo) + | (mr.MessageType == MessageType.Video) + | (mr.MessageType == MessageType.Audio)) { - var sce = new BotCommandEventArgs(mr.BotCommand, mr.BotCommandParameters, mr.Message, session.DeviceId, session); - await bot.OnBotCommand(sce); - - if (sce.Handled) - return; + await activeForm.SentData(new DataResult(ur)); } + } - mr.Device = session; + //Action Event + if (!session.FormSwitched && mr.IsAction) + { + //Send Action event to controls + await activeForm.ActionControls(mr); - var activeForm = session.ActiveForm; + //Send Action event to form itself + await activeForm.Action(mr); - //Pre Loading Event - await activeForm.PreLoad(mr); - - //Send Load event to controls - await activeForm.LoadControls(mr); - - //Loading Event - await activeForm.Load(mr); - - - //Is Attachment ? (Photo, Audio, Video, Contact, Location, Document) (Ignore Callback Queries) - if (update.Type == UpdateType.Message) + if (!mr.Handled) { - if (mr.MessageType == MessageType.Contact - | mr.MessageType == MessageType.Document - | mr.MessageType == MessageType.Location - | mr.MessageType == MessageType.Photo - | mr.MessageType == MessageType.Video - | mr.MessageType == MessageType.Audio) + var uhc = new UnhandledCallEventArgs(ur.Message.Text, mr.RawData, session.DeviceId, mr.MessageId, + ur.Message, session); + OnUnhandledCall(uhc); + + if (uhc.Handled) { - await activeForm.SentData(new DataResult(ur)); - } - } - - //Action Event - if (!session.FormSwitched && mr.IsAction) - { - //Send Action event to controls - await activeForm.ActionControls(mr); - - //Send Action event to form itself - await activeForm.Action(mr); - - if (!mr.Handled) - { - var uhc = new UnhandledCallEventArgs(ur.Message.Text, mr.RawData, session.DeviceId, mr.MessageId, ur.Message, session); - OnUnhandledCall(uhc); - - if (uhc.Handled) + mr.Handled = true; + if (!session.FormSwitched) { - mr.Handled = true; - if (!session.FormSwitched) - { - return; - } + return; } } - } - - if (!session.FormSwitched) - { - //Render Event - await activeForm.RenderControls(mr); - - await activeForm.Render(mr); - } - } - /// - /// Will be called if no form handeled this call - /// - public event EventHandler UnhandledCall + if (!session.FormSwitched) { - add => _events.AddHandler(EvUnhandledCall, value); - remove => _events.RemoveHandler(EvUnhandledCall, value); - } - - public void OnUnhandledCall(UnhandledCallEventArgs e) - { - (_events[EvUnhandledCall] as EventHandler)?.Invoke(this, e); + //Render Event + await activeForm.RenderControls(mr); + await activeForm.Render(mr); } } -} + + /// + /// Will be called if no form handeled this call + /// + public event EventHandler UnhandledCall + { + add => _events.AddHandler(EvUnhandledCall, value); + remove => _events.RemoveHandler(EvUnhandledCall, value); + } + + public void OnUnhandledCall(UnhandledCallEventArgs e) + { + (_events[EvUnhandledCall] as EventHandler)?.Invoke(this, e); + } +} \ No newline at end of file diff --git a/TelegramBotBase/MessageLoops/FullMessageLoop.cs b/TelegramBotBase/MessageLoops/FullMessageLoop.cs index 1277094..69c2105 100644 --- a/TelegramBotBase/MessageLoops/FullMessageLoop.cs +++ b/TelegramBotBase/MessageLoops/FullMessageLoop.cs @@ -7,109 +7,109 @@ using TelegramBotBase.Base; using TelegramBotBase.Interfaces; using TelegramBotBase.Sessions; -namespace TelegramBotBase.MessageLoops +namespace TelegramBotBase.MessageLoops; + +/// +/// This message loop reacts to all update types. +/// +public class FullMessageLoop : IMessageLoopFactory { - /// - /// This message loop reacts to all update types. - /// - public class FullMessageLoop : IMessageLoopFactory + private static readonly object EvUnhandledCall = new(); + + private readonly EventHandlerList _events = new(); + + public async Task MessageLoop(BotBase bot, DeviceSession session, UpdateResult ur, MessageResult mr) { - private static readonly object EvUnhandledCall = new object(); + var update = ur.RawData; - private readonly EventHandlerList _events = new EventHandlerList(); - public async Task MessageLoop(BotBase bot, DeviceSession session, UpdateResult ur, MessageResult mr) + //Is this a bot command ? + if (mr.IsFirstHandler && mr.IsBotCommand && bot.IsKnownBotCommand(mr.BotCommand)) { - var update = ur.RawData; + var sce = new BotCommandEventArgs(mr.BotCommand, mr.BotCommandParameters, mr.Message, session.DeviceId, + session); + await bot.OnBotCommand(sce); - - //Is this a bot command ? - if (mr.IsFirstHandler && mr.IsBotCommand && bot.IsKnownBotCommand(mr.BotCommand)) + if (sce.Handled) { - var sce = new BotCommandEventArgs(mr.BotCommand, mr.BotCommandParameters, mr.Message, session.DeviceId, session); - await bot.OnBotCommand(sce); - - if (sce.Handled) - return; + return; } + } - mr.Device = session; + mr.Device = session; - var activeForm = session.ActiveForm; + var activeForm = session.ActiveForm; - //Pre Loading Event - await activeForm.PreLoad(mr); + //Pre Loading Event + await activeForm.PreLoad(mr); - //Send Load event to controls - await activeForm.LoadControls(mr); + //Send Load event to controls + await activeForm.LoadControls(mr); - //Loading Event - await activeForm.Load(mr); + //Loading Event + await activeForm.Load(mr); - //Is Attachment ? (Photo, Audio, Video, Contact, Location, Document) (Ignore Callback Queries) - if (update.Type == UpdateType.Message) + //Is Attachment ? (Photo, Audio, Video, Contact, Location, Document) (Ignore Callback Queries) + if (update.Type == UpdateType.Message) + { + if ((mr.MessageType == MessageType.Contact) + | (mr.MessageType == MessageType.Document) + | (mr.MessageType == MessageType.Location) + | (mr.MessageType == MessageType.Photo) + | (mr.MessageType == MessageType.Video) + | (mr.MessageType == MessageType.Audio)) { - if (mr.MessageType == MessageType.Contact - | mr.MessageType == MessageType.Document - | mr.MessageType == MessageType.Location - | mr.MessageType == MessageType.Photo - | mr.MessageType == MessageType.Video - | mr.MessageType == MessageType.Audio) - { - await activeForm.SentData(new DataResult(ur)); - } + await activeForm.SentData(new DataResult(ur)); } + } - //Action Event - if (!session.FormSwitched && mr.IsAction) + //Action Event + if (!session.FormSwitched && mr.IsAction) + { + //Send Action event to controls + await activeForm.ActionControls(mr); + + //Send Action event to form itself + await activeForm.Action(mr); + + if (!mr.Handled) { - //Send Action event to controls - await activeForm.ActionControls(mr); + var uhc = new UnhandledCallEventArgs(ur.Message.Text, mr.RawData, session.DeviceId, mr.MessageId, + ur.Message, session); + OnUnhandledCall(uhc); - //Send Action event to form itself - await activeForm.Action(mr); - - if (!mr.Handled) + if (uhc.Handled) { - var uhc = new UnhandledCallEventArgs(ur.Message.Text, mr.RawData, session.DeviceId, mr.MessageId, ur.Message, session); - OnUnhandledCall(uhc); - - if (uhc.Handled) + mr.Handled = true; + if (!session.FormSwitched) { - mr.Handled = true; - if (!session.FormSwitched) - { - return; - } + return; } } - } - - if (!session.FormSwitched) - { - //Render Event - await activeForm.RenderControls(mr); - - await activeForm.Render(mr); - } - } - /// - /// Will be called if no form handeled this call - /// - public event EventHandler UnhandledCall + if (!session.FormSwitched) { - add => _events.AddHandler(EvUnhandledCall, value); - remove => _events.RemoveHandler(EvUnhandledCall, value); - } - - public void OnUnhandledCall(UnhandledCallEventArgs e) - { - (_events[EvUnhandledCall] as EventHandler)?.Invoke(this, e); + //Render Event + await activeForm.RenderControls(mr); + await activeForm.Render(mr); } } -} + + /// + /// Will be called if no form handeled this call + /// + public event EventHandler UnhandledCall + { + add => _events.AddHandler(EvUnhandledCall, value); + remove => _events.RemoveHandler(EvUnhandledCall, value); + } + + public void OnUnhandledCall(UnhandledCallEventArgs e) + { + (_events[EvUnhandledCall] as EventHandler)?.Invoke(this, e); + } +} \ No newline at end of file diff --git a/TelegramBotBase/MessageLoops/MinimalMessageLoop.cs b/TelegramBotBase/MessageLoops/MinimalMessageLoop.cs index 2483668..74b5c83 100644 --- a/TelegramBotBase/MessageLoops/MinimalMessageLoop.cs +++ b/TelegramBotBase/MessageLoops/MinimalMessageLoop.cs @@ -6,44 +6,41 @@ using TelegramBotBase.Base; using TelegramBotBase.Interfaces; using TelegramBotBase.Sessions; -namespace TelegramBotBase.MessageLoops +namespace TelegramBotBase.MessageLoops; + +/// +/// This is a minimal message loop which will react to all update types and just calling the Load method. +/// +public class MinimalMessageLoop : IMessageLoopFactory { - /// - /// This is a minimal message loop which will react to all update types and just calling the Load method. - /// - public class MinimalMessageLoop : IMessageLoopFactory + private static readonly object EvUnhandledCall = new(); + + private readonly EventHandlerList _events = new(); + + public async Task MessageLoop(BotBase bot, DeviceSession session, UpdateResult ur, MessageResult mr) { - private static readonly object EvUnhandledCall = new object(); - - private readonly EventHandlerList _events = new EventHandlerList(); - - public async Task MessageLoop(BotBase bot, DeviceSession session, UpdateResult ur, MessageResult mr) - { - var update = ur.RawData; + var update = ur.RawData; - mr.Device = session; + mr.Device = session; - var activeForm = session.ActiveForm; + var activeForm = session.ActiveForm; - //Loading Event - await activeForm.Load(mr); - - } - - /// - /// Will be called if no form handeled this call - /// - public event EventHandler UnhandledCall - { - add => _events.AddHandler(EvUnhandledCall, value); - remove => _events.RemoveHandler(EvUnhandledCall, value); - } - - public void OnUnhandledCall(UnhandledCallEventArgs e) - { - (_events[EvUnhandledCall] as EventHandler)?.Invoke(this, e); - - } + //Loading Event + await activeForm.Load(mr); } -} + + /// + /// Will be called if no form handeled this call + /// + public event EventHandler UnhandledCall + { + add => _events.AddHandler(EvUnhandledCall, value); + remove => _events.RemoveHandler(EvUnhandledCall, value); + } + + public void OnUnhandledCall(UnhandledCallEventArgs e) + { + (_events[EvUnhandledCall] as EventHandler)?.Invoke(this, e); + } +} \ No newline at end of file diff --git a/TelegramBotBase/Properties/AssemblyInfo.cs b/TelegramBotBase/Properties/AssemblyInfo.cs index 14bc370..7f6a35f 100644 --- a/TelegramBotBase/Properties/AssemblyInfo.cs +++ b/TelegramBotBase/Properties/AssemblyInfo.cs @@ -32,4 +32,4 @@ using System.Runtime.InteropServices; // übernehmen, indem Sie "*" eingeben: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("3.1.0.0")] -[assembly: AssemblyFileVersion("3.1.0.0")] +[assembly: AssemblyFileVersion("3.1.0.0")] \ No newline at end of file diff --git a/TelegramBotBase/SessionBase.cs b/TelegramBotBase/SessionBase.cs index 66ac76d..e7036cd 100644 --- a/TelegramBotBase/SessionBase.cs +++ b/TelegramBotBase/SessionBase.cs @@ -11,330 +11,338 @@ using TelegramBotBase.Interfaces; using TelegramBotBase.Sessions; using TelegramBotBase.Tools; -namespace TelegramBotBase +namespace TelegramBotBase; + +/// +/// Base class for managing all active sessions +/// +public class SessionBase { - /// - /// Base class for managing all active sessions - /// - public class SessionBase + public SessionBase() { - /// - /// The Basic message client. - /// - public MessageClient Client { get; set; } + SessionList = new Dictionary(); + } - /// - /// A list of all active sessions. - /// - public Dictionary SessionList { get; set; } + /// + /// The Basic message client. + /// + public MessageClient Client { get; set; } + + /// + /// A list of all active sessions. + /// + public Dictionary SessionList { get; set; } - /// - /// Reference to the Main BotBase instance for later use. - /// - public BotBase BotBase { get; set; } + /// + /// Reference to the Main BotBase instance for later use. + /// + public BotBase BotBase { get; set; } + /// + /// Get device session from Device/ChatId + /// + /// + /// + public DeviceSession this[long key] + { + get => SessionList[key]; + set => SessionList[key] = value; + } - public SessionBase() + /// + /// Get device session from Device/ChatId + /// + /// + /// + public DeviceSession GetSession(long deviceId) + { + var ds = SessionList.FirstOrDefault(a => a.Key == deviceId).Value ?? null; + return ds; + } + + /// + /// Start a new session + /// + /// + /// + /// + public async Task StartSession(long deviceId) + { + var start = BotBase.StartFormFactory.CreateForm(); + + start.Client = Client; + + var ds = new DeviceSession(deviceId, start); + + start.Device = ds; + await start.OnInit(new InitEventArgs()); + + await start.OnOpened(EventArgs.Empty); + + this[deviceId] = ds; + return ds; + } + + /// + /// End session + /// + /// + public void EndSession(long deviceId) + { + var d = this[deviceId]; + if (d != null) { - SessionList = new Dictionary(); + SessionList.Remove(deviceId); + } + } + + /// + /// Returns all active User Sessions. + /// + /// + public List GetUserSessions() + { + return SessionList.Where(a => a.Key > 0).Select(a => a.Value).ToList(); + } + + /// + /// Returns all active Group Sessions. + /// + /// + public List GetGroupSessions() + { + return SessionList.Where(a => a.Key < 0).Select(a => a.Value).ToList(); + } + + /// + /// Loads the previously saved states from the machine. + /// + public async void LoadSessionStates() + { + if (BotBase.StateMachine == null) + { + return; } - /// - /// Get device session from Device/ChatId - /// - /// - /// - public DeviceSession this[long key] + LoadSessionStates(BotBase.StateMachine); + } + + + /// + /// Loads the previously saved states from the machine. + /// + public async void LoadSessionStates(IStateMachine statemachine) + { + if (statemachine == null) { - get => SessionList[key]; - set => SessionList[key] = value; + throw new ArgumentNullException("StateMachine", + "No StateMachine defined. Please set one to property BotBase.StateMachine"); } - /// - /// Get device session from Device/ChatId - /// - /// - /// - public DeviceSession GetSession(long deviceId) + var container = statemachine.LoadFormStates(); + + foreach (var s in container.States) { - var ds = SessionList.FirstOrDefault(a => a.Key == deviceId).Value ?? null; - return ds; - } - - /// - /// Start a new session - /// - /// - /// - /// - public async Task StartSession(long deviceId) - { - var start = BotBase.StartFormFactory.CreateForm(); - - start.Client = Client; - - var ds = new DeviceSession(deviceId, start); - - start.Device = ds; - await start.OnInit(new InitEventArgs()); - - await start.OnOpened(EventArgs.Empty); - - this[deviceId] = ds; - return ds; - } - - /// - /// End session - /// - /// - public void EndSession(long deviceId) - { - var d = this[deviceId]; - if (d != null) + var t = Type.GetType(s.QualifiedName); + if (t == null || !t.IsSubclassOf(typeof(FormBase))) { - SessionList.Remove(deviceId); - - } - } - - /// - /// Returns all active User Sessions. - /// - /// - public List GetUserSessions() - { - return SessionList.Where(a => a.Key > 0).Select(a => a.Value).ToList(); - } - - /// - /// Returns all active Group Sessions. - /// - /// - public List GetGroupSessions() - { - return SessionList.Where(a => a.Key < 0).Select(a => a.Value).ToList(); - } - - /// - /// Loads the previously saved states from the machine. - /// - public async void LoadSessionStates() - { - if (BotBase.StateMachine == null) - { - return; + continue; } - LoadSessionStates(BotBase.StateMachine); - } - - - /// - /// Loads the previously saved states from the machine. - /// - public async void LoadSessionStates(IStateMachine statemachine) - { - if (statemachine == null) + //Key already existing + if (SessionList.ContainsKey(s.DeviceId)) { - throw new ArgumentNullException("StateMachine", "No StateMachine defined. Please set one to property BotBase.StateMachine"); + continue; } - var container = statemachine.LoadFormStates(); - - foreach (var s in container.States) + //No default constructor, fallback + if (!(t.GetConstructor(new Type[] { })?.Invoke(new object[] { }) is FormBase form)) { - var t = Type.GetType(s.QualifiedName); - if (t == null || !t.IsSubclassOf(typeof(FormBase))) + if (!statemachine.FallbackStateForm.IsSubclassOf(typeof(FormBase))) { continue; } - //Key already existing - if (SessionList.ContainsKey(s.DeviceId)) + form = + statemachine.FallbackStateForm.GetConstructor(new Type[] { }) + ?.Invoke(new object[] { }) as FormBase; + + //Fallback failed, due missing default constructor + if (form == null) + { continue; - - //No default constructor, fallback - if (!(t.GetConstructor(new Type[] { })?.Invoke(new object[] { }) is FormBase form)) - { - if (!statemachine.FallbackStateForm.IsSubclassOf(typeof(FormBase))) - continue; - - form = statemachine.FallbackStateForm.GetConstructor(new Type[] { })?.Invoke(new object[] { }) as FormBase; - - //Fallback failed, due missing default constructor - if (form == null) - continue; - } + } - if (s.Values != null && s.Values.Count > 0) + if (s.Values != null && s.Values.Count > 0) + { + var properties = s.Values.Where(a => a.Key.StartsWith("$")); + var fields = form.GetType() + .GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) + .Where(a => a.GetCustomAttributes(typeof(SaveState), true).Length != 0).ToList(); + + foreach (var p in properties) { - var properties = s.Values.Where(a => a.Key.StartsWith("$")); - var fields = form.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(a => a.GetCustomAttributes(typeof(SaveState), true).Length != 0).ToList(); - - foreach (var p in properties) + var f = fields.FirstOrDefault(a => a.Name == p.Key.Substring(1)); + if (f == null) { - var f = fields.FirstOrDefault(a => a.Name == p.Key.Substring(1)); - if (f == null) + continue; + } + + try + { + if (f.PropertyType.IsEnum) + { + var ent = Enum.Parse(f.PropertyType, p.Value.ToString()); + + f.SetValue(form, ent); + continue; - - try - { - if (f.PropertyType.IsEnum) - { - var ent = Enum.Parse(f.PropertyType, p.Value.ToString()); - - f.SetValue(form, ent); - - continue; - } - - - f.SetValue(form, p.Value); } - catch (ArgumentException) - { - Conversion.CustomConversionChecks(form, p, f); - } - catch - { - - } + f.SetValue(form, p.Value); + } + catch (ArgumentException) + { + Conversion.CustomConversionChecks(form, p, f); + } + catch + { } } + } - form.Client = Client; - var device = new DeviceSession(s.DeviceId, form) + form.Client = Client; + var device = new DeviceSession(s.DeviceId, form) + { + ChatTitle = s.ChatTitle + }; + + SessionList.Add(s.DeviceId, device); + + //Is Subclass of IStateForm + if (form is IStateForm iform) + { + var ls = new LoadStateEventArgs { - ChatTitle = s.ChatTitle + Values = s.Values + }; + iform.LoadState(ls); + } + + try + { + await form.OnInit(new InitEventArgs()); + + await form.OnOpened(EventArgs.Empty); + } + catch + { + //Skip on exception + SessionList.Remove(s.DeviceId); + } + } + } + + + /// + /// Saves all open states into the machine. + /// + public void SaveSessionStates(IStateMachine statemachine) + { + if (statemachine == null) + { + throw new ArgumentNullException("StateMachine", + "No StateMachine defined. Please set one to property BotBase.StateMachine"); + } + + var states = new List(); + + foreach (var s in SessionList) + { + if (s.Value == null) + { + continue; + } + + var form = s.Value.ActiveForm; + + try + { + var se = new StateEntry + { + DeviceId = s.Key, + ChatTitle = s.Value.GetChatTitle(), + FormUri = form.GetType().FullName, + QualifiedName = form.GetType().AssemblyQualifiedName }; - SessionList.Add(s.DeviceId, device); + //Skip classes where IgnoreState attribute is existing + if (form.GetType().GetCustomAttributes(typeof(IgnoreState), true).Length != 0) + { + //Skip this form, when there is no fallback state form + if (statemachine.FallbackStateForm == null) + { + continue; + } + + //Replace form by default State one. + se.FormUri = statemachine.FallbackStateForm.FullName; + se.QualifiedName = statemachine.FallbackStateForm.AssemblyQualifiedName; + } //Is Subclass of IStateForm if (form is IStateForm iform) { - var ls = new LoadStateEventArgs - { - Values = s.Values - }; - iform.LoadState(ls); + //Loading Session states + var ssea = new SaveStateEventArgs(); + iform.SaveState(ssea); + + se.Values = ssea.Values; } - try - { - await form.OnInit(new InitEventArgs()); + //Search for public properties with SaveState attribute + var fields = form.GetType() + .GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) + .Where(a => a.GetCustomAttributes(typeof(SaveState), true).Length != 0).ToList(); - await form.OnOpened(EventArgs.Empty); - } - catch + foreach (var f in fields) { - //Skip on exception - SessionList.Remove(s.DeviceId); + var val = f.GetValue(form); + + se.Values.Add("$" + f.Name, val); } + + states.Add(se); + } + catch + { + //Continue on error (skip this form) } - } - - - - /// - /// Saves all open states into the machine. - /// - public void SaveSessionStates(IStateMachine statemachine) + var sc = new StateContainer { - if (statemachine == null) - { - throw new ArgumentNullException("StateMachine", "No StateMachine defined. Please set one to property BotBase.StateMachine"); - } + States = states + }; - var states = new List(); + statemachine.SaveFormStates(new SaveStatesEventArgs(sc)); + } - foreach (var s in SessionList) - { - if (s.Value == null) - { - continue; - } - - var form = s.Value.ActiveForm; - - try - { - var se = new StateEntry - { - DeviceId = s.Key, - ChatTitle = s.Value.GetChatTitle(), - FormUri = form.GetType().FullName, - QualifiedName = form.GetType().AssemblyQualifiedName - }; - - //Skip classes where IgnoreState attribute is existing - if (form.GetType().GetCustomAttributes(typeof(IgnoreState), true).Length != 0) - { - //Skip this form, when there is no fallback state form - if (statemachine.FallbackStateForm == null) - { - continue; - } - - //Replace form by default State one. - se.FormUri = statemachine.FallbackStateForm.FullName; - se.QualifiedName = statemachine.FallbackStateForm.AssemblyQualifiedName; - } - - //Is Subclass of IStateForm - if (form is IStateForm iform) - { - //Loading Session states - var ssea = new SaveStateEventArgs(); - iform.SaveState(ssea); - - se.Values = ssea.Values; - } - - //Search for public properties with SaveState attribute - var fields = form.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(a => a.GetCustomAttributes(typeof(SaveState), true).Length != 0).ToList(); - - foreach (var f in fields) - { - var val = f.GetValue(form); - - se.Values.Add("$" + f.Name, val); - } - - states.Add(se); - } - catch - { - //Continue on error (skip this form) - } - } - - var sc = new StateContainer - { - States = states - }; - - statemachine.SaveFormStates(new SaveStatesEventArgs(sc)); - } - - /// - /// Saves all open states into the machine. - /// - public void SaveSessionStates() + /// + /// Saves all open states into the machine. + /// + public void SaveSessionStates() + { + if (BotBase.StateMachine == null) { - if (BotBase.StateMachine == null) - return; - - - SaveSessionStates(BotBase.StateMachine); + return; } + + + SaveSessionStates(BotBase.StateMachine); } } diff --git a/TelegramBotBase/Sessions/DeviceSession.cs b/TelegramBotBase/Sessions/DeviceSession.cs index 5c017c0..2ece87c 100644 --- a/TelegramBotBase/Sessions/DeviceSession.cs +++ b/TelegramBotBase/Sessions/DeviceSession.cs @@ -18,914 +18,978 @@ using TelegramBotBase.Form; using TelegramBotBase.Interfaces; using TelegramBotBase.Markdown; -namespace TelegramBotBase.Sessions +namespace TelegramBotBase.Sessions; + +/// +/// Base class for a device/chat session +/// +public class DeviceSession : IDeviceSession { - /// - /// Base class for a device/chat session - /// - public class DeviceSession : IDeviceSession + private static readonly object EvMessageSent = new(); + private static readonly object EvMessageReceived = new(); + private static readonly object EvMessageDeleted = new(); + + private readonly EventHandlerList _events = new(); + + public DeviceSession() { - /// - /// Device or chat id - /// - public long DeviceId { get; set; } + } - /// - /// Username of user or group - /// - public string ChatTitle { get; set; } + public DeviceSession(long deviceId) + { + DeviceId = deviceId; + } - /// - /// Returns the ChatTitle depending on groups/channels or users - /// - /// - public string GetChatTitle() + public DeviceSession(long deviceId, FormBase startForm) + { + DeviceId = deviceId; + ActiveForm = startForm; + ActiveForm.Device = this; + } + + /// + /// Returns the ID of the last received message. + /// + public int LastMessageId => LastMessage?.MessageId ?? -1; + + /// + /// Returns the last received message. + /// + public Message LastMessage { get; set; } + + public MessageClient Client => ActiveForm.Client; + + /// + /// Returns if the messages is posted within a group. + /// + public bool IsGroup => LastMessage != null && + (LastMessage.Chat.Type == ChatType.Group) | + (LastMessage.Chat.Type == ChatType.Supergroup); + + /// + /// Returns if the messages is posted within a channel. + /// + public bool IsChannel => LastMessage != null && LastMessage.Chat.Type == ChatType.Channel; + + #region "Static" + + /// + /// Indicates the maximum number of times a request that received error + /// 429 will be sent again after a timeout until it receives code 200 or an error code not equal to 429. + /// + public static uint MaxNumberOfRetries { get; set; } + + #endregion "Static" + + /// + /// Device or chat id + /// + public long DeviceId { get; set; } + + /// + /// Username of user or group + /// + public string ChatTitle { get; set; } + + /// + /// When did any last action happend (message received or button clicked) + /// + public DateTime LastAction { get; set; } + + /// + /// Returns the form where the user/group is at the moment. + /// + public FormBase ActiveForm { get; set; } + + /// + /// Returns the previous shown form + /// + public FormBase PreviousForm { get; set; } + + /// + /// contains if the form has been switched (navigated) + /// + public bool FormSwitched { get; set; } = false; + + /// + /// Returns the ChatTitle depending on groups/channels or users + /// + /// + public string GetChatTitle() + { + return LastMessage?.Chat.Title + ?? LastMessage?.Chat.Username + ?? LastMessage?.Chat.FirstName + ?? ChatTitle; + } + + + /// + /// Confirm incomming action (i.e. Button click) + /// + /// + /// + public async Task ConfirmAction(string callbackQueryId, string message = "", bool showAlert = false, + string urlToOpen = null) + { + try { - return LastMessage?.Chat.Title - ?? LastMessage?.Chat.Username - ?? LastMessage?.Chat.FirstName - ?? ChatTitle; + await Client.TelegramClient.AnswerCallbackQueryAsync(callbackQueryId, message, showAlert, urlToOpen); + } + catch + { + } + } + + /// + /// Edits the text message + /// + /// + /// + /// + /// + public async Task Edit(int messageId, string text, ButtonForm buttons = null, + ParseMode parseMode = ParseMode.Markdown) + { + InlineKeyboardMarkup markup = buttons; + + if (text.Length > Constants.Telegram.MaxMessageLength) + { + throw new MaxLengthException(text.Length); } - /// - /// When did any last action happend (message received or button clicked) - /// - public DateTime LastAction { get; set; } - - /// - /// Returns the form where the user/group is at the moment. - /// - public FormBase ActiveForm { get; set; } - - /// - /// Returns the previous shown form - /// - public FormBase PreviousForm { get; set; } - - /// - /// contains if the form has been switched (navigated) - /// - public bool FormSwitched { get; set; } = false; - - /// - /// Returns the ID of the last received message. - /// - public int LastMessageId => LastMessage?.MessageId ?? -1; - - /// - /// Returns the last received message. - /// - public Message LastMessage { get; set; } - - public MessageClient Client => ActiveForm.Client; - - /// - /// Returns if the messages is posted within a group. - /// - public bool IsGroup => LastMessage != null && (LastMessage.Chat.Type == ChatType.Group | LastMessage.Chat.Type == ChatType.Supergroup); - - /// - /// Returns if the messages is posted within a channel. - /// - public bool IsChannel => LastMessage != null && LastMessage.Chat.Type == ChatType.Channel; - - private readonly EventHandlerList _events = new EventHandlerList(); - - private static readonly object EvMessageSent = new object(); - private static readonly object EvMessageReceived = new object(); - private static readonly object EvMessageDeleted = new object(); - - public DeviceSession() + try { - + return await Api(a => + a.EditMessageTextAsync(DeviceId, messageId, text, parseMode, replyMarkup: markup)); } - - public DeviceSession(long deviceId) + catch { - this.DeviceId = deviceId; - } - - public DeviceSession(long deviceId, FormBase startForm) - { - this.DeviceId = deviceId; - ActiveForm = startForm; - ActiveForm.Device = this; } - /// - /// Confirm incomming action (i.e. Button click) - /// - /// - /// - public async Task ConfirmAction(string callbackQueryId, string message = "", bool showAlert = false, string urlToOpen = null) - { - try - { - await Client.TelegramClient.AnswerCallbackQueryAsync(callbackQueryId, message, showAlert, urlToOpen); - } - catch - { + return null; + } - } + /// + /// Edits the text message + /// + /// + /// + /// + /// + public async Task Edit(int messageId, string text, InlineKeyboardMarkup markup, + ParseMode parseMode = ParseMode.Markdown) + { + if (text.Length > Constants.Telegram.MaxMessageLength) + { + throw new MaxLengthException(text.Length); } - /// - /// Edits the text message - /// - /// - /// - /// - /// - public async Task Edit(int messageId, string text, ButtonForm buttons = null, ParseMode parseMode = ParseMode.Markdown) + try { - InlineKeyboardMarkup markup = buttons; - - if (text.Length > Constants.Telegram.MaxMessageLength) - { - throw new MaxLengthException(text.Length); - } - - try - { - return await Api(a => a.EditMessageTextAsync(DeviceId, messageId, text, parseMode, replyMarkup: markup)); - } - catch - { - - } + return await Api(a => + a.EditMessageTextAsync(DeviceId, messageId, text, parseMode, replyMarkup: markup)); + } + catch + { + } + return null; + } + + /// + /// Edits the text message + /// + /// + /// + /// + /// + public async Task Edit(Message message, ButtonForm buttons = null, + ParseMode parseMode = ParseMode.Markdown) + { + InlineKeyboardMarkup markup = buttons; + + if (message.Text.Length > Constants.Telegram.MaxMessageLength) + { + throw new MaxLengthException(message.Text.Length); + } + + try + { + return await Api(a => + a.EditMessageTextAsync(DeviceId, message.MessageId, message.Text, parseMode, + replyMarkup: markup)); + } + catch + { + } + + + return null; + } + + /// + /// Edits the reply keyboard markup (buttons) + /// + /// + /// + /// + public async Task EditReplyMarkup(int messageId, ButtonForm bf) + { + try + { + return await Api(a => a.EditMessageReplyMarkupAsync(DeviceId, messageId, bf)); + } + catch + { + } + + return null; + } + + /// + /// Sends a simple text message + /// + /// + /// + /// + /// + /// + public async Task Send(long deviceId, string text, ButtonForm buttons = null, int replyTo = 0, + bool disableNotification = false, ParseMode parseMode = ParseMode.Markdown, + bool markdownV2AutoEscape = true) + { + if (ActiveForm == null) + { return null; } - /// - /// Edits the text message - /// - /// - /// - /// - /// - public async Task Edit(int messageId, string text, InlineKeyboardMarkup markup, ParseMode parseMode = ParseMode.Markdown) + InlineKeyboardMarkup markup = buttons; + + if (text.Length > Constants.Telegram.MaxMessageLength) { - if (text.Length > Constants.Telegram.MaxMessageLength) - { - throw new MaxLengthException(text.Length); - } + throw new MaxLengthException(text.Length); + } - try - { - return await Api(a => a.EditMessageTextAsync(DeviceId, messageId, text, parseMode, replyMarkup: markup)); - } - catch - { + if (parseMode == ParseMode.MarkdownV2 && markdownV2AutoEscape) + { + text = text.MarkdownV2Escape(); + } - } + try + { + var t = Api(a => a.SendTextMessageAsync(deviceId, text, parseMode, replyToMessageId: replyTo, + replyMarkup: markup, disableNotification: disableNotification)); + var o = GetOrigin(new StackTrace()); + await OnMessageSent(new MessageSentEventArgs(await t, o)); + + return await t; + } + catch + { + return null; + } + } + + /// + /// Sends a simple text message + /// + /// + /// + /// + /// + /// + public async Task Send(string text, ButtonForm buttons = null, int replyTo = 0, + bool disableNotification = false, ParseMode parseMode = ParseMode.Markdown, + bool markdownV2AutoEscape = true) + { + return await Send(DeviceId, text, buttons, replyTo, disableNotification, parseMode, markdownV2AutoEscape); + } + + /// + /// Sends a simple text message + /// + /// + /// + /// + /// + /// + public async Task Send(string text, InlineKeyboardMarkup markup, int replyTo = 0, + bool disableNotification = false, ParseMode parseMode = ParseMode.Markdown, + bool markdownV2AutoEscape = true) + { + if (ActiveForm == null) + { return null; } - /// - /// Edits the text message - /// - /// - /// - /// - /// - public async Task Edit(Message message, ButtonForm buttons = null, ParseMode parseMode = ParseMode.Markdown) + if (text.Length > Constants.Telegram.MaxMessageLength) { - InlineKeyboardMarkup markup = buttons; + throw new MaxLengthException(text.Length); + } - if (message.Text.Length > Constants.Telegram.MaxMessageLength) - { - throw new MaxLengthException(message.Text.Length); - } + if (parseMode == ParseMode.MarkdownV2 && markdownV2AutoEscape) + { + text = text.MarkdownV2Escape(); + } - try - { - return await Api(a => a.EditMessageTextAsync(DeviceId, message.MessageId, message.Text, parseMode, replyMarkup: markup)); - } - catch - { + try + { + var t = Api(a => a.SendTextMessageAsync(DeviceId, text, parseMode, replyToMessageId: replyTo, + replyMarkup: markup, disableNotification: disableNotification)); - } + var o = GetOrigin(new StackTrace()); + await OnMessageSent(new MessageSentEventArgs(await t, o)); + return await t; + } + catch + { + return null; + } + } + /// + /// Sends a simple text message + /// + /// + /// + /// + /// + /// + public async Task Send(string text, ReplyMarkupBase markup, int replyTo = 0, + bool disableNotification = false, ParseMode parseMode = ParseMode.Markdown, + bool markdownV2AutoEscape = true) + { + if (ActiveForm == null) + { return null; } - /// - /// Edits the reply keyboard markup (buttons) - /// - /// - /// - /// - public async Task EditReplyMarkup(int messageId, ButtonForm bf) + if (text.Length > Constants.Telegram.MaxMessageLength) { + throw new MaxLengthException(text.Length); + } - try - { - return await Api(a => a.EditMessageReplyMarkupAsync(DeviceId, messageId, bf)); - } - catch - { + if (parseMode == ParseMode.MarkdownV2 && markdownV2AutoEscape) + { + text = text.MarkdownV2Escape(); + } - } + try + { + var t = Api(a => a.SendTextMessageAsync(DeviceId, text, parseMode, replyToMessageId: replyTo, + replyMarkup: markup, disableNotification: disableNotification)); + var o = GetOrigin(new StackTrace()); + await OnMessageSent(new MessageSentEventArgs(await t, o)); + + return await t; + } + catch + { + return null; + } + } + + /// + /// Sends an image + /// + /// + /// + /// + /// + /// + public async Task SendPhoto(InputOnlineFile file, string caption = null, ButtonForm buttons = null, + int replyTo = 0, bool disableNotification = false, + ParseMode parseMode = ParseMode.Markdown) + { + if (ActiveForm == null) + { return null; } - /// - /// Sends a simple text message - /// - /// - /// - /// - /// - /// - public async Task Send(long deviceId, string text, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false, ParseMode parseMode = ParseMode.Markdown, bool markdownV2AutoEscape = true) + InlineKeyboardMarkup markup = buttons; + + try { - if (ActiveForm == null) - return null; + var t = Api(a => a.SendPhotoAsync(DeviceId, file, caption, parseMode, replyToMessageId: replyTo, + replyMarkup: markup, disableNotification: disableNotification)); - InlineKeyboardMarkup markup = buttons; + var o = GetOrigin(new StackTrace()); + await OnMessageSent(new MessageSentEventArgs(await t, o)); - if (text.Length > Constants.Telegram.MaxMessageLength) - { - throw new MaxLengthException(text.Length); - } + return await t; + } + catch + { + return null; + } + } - if (parseMode == ParseMode.MarkdownV2 && markdownV2AutoEscape) - { - text = text.MarkdownV2Escape(); - } - - try - { - var t = Api(a => a.SendTextMessageAsync(deviceId, text, parseMode, replyToMessageId: replyTo, replyMarkup: markup, disableNotification: disableNotification)); - - var o = GetOrigin(new StackTrace()); - - await OnMessageSent(new MessageSentEventArgs(await t, o)); - - return await t; - } - catch - { - return null; - } + /// + /// Sends an video + /// + /// + /// + /// + /// + /// + public async Task SendVideo(InputOnlineFile file, string caption = null, ButtonForm buttons = null, + int replyTo = 0, bool disableNotification = false, + ParseMode parseMode = ParseMode.Markdown) + { + if (ActiveForm == null) + { + return null; } - /// - /// Sends a simple text message - /// - /// - /// - /// - /// - /// - public async Task Send(string text, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false, ParseMode parseMode = ParseMode.Markdown, bool markdownV2AutoEscape = true) + InlineKeyboardMarkup markup = buttons; + + try { - return await Send(DeviceId, text, buttons, replyTo, disableNotification, parseMode, markdownV2AutoEscape); + var t = Api(a => a.SendVideoAsync(DeviceId, file, caption: caption, parseMode: parseMode, + replyToMessageId: replyTo, replyMarkup: markup, + disableNotification: disableNotification)); + + var o = GetOrigin(new StackTrace()); + await OnMessageSent(new MessageSentEventArgs(await t, o)); + + return await t; + } + catch + { + return null; + } + } + + /// + /// Sends an video + /// + /// + /// + /// + /// + /// + public async Task SendVideo(string url, ButtonForm buttons = null, int replyTo = 0, + bool disableNotification = false, ParseMode parseMode = ParseMode.Markdown) + { + if (ActiveForm == null) + { + return null; } - /// - /// Sends a simple text message - /// - /// - /// - /// - /// - /// - public async Task Send(string text, InlineKeyboardMarkup markup, int replyTo = 0, bool disableNotification = false, ParseMode parseMode = ParseMode.Markdown, bool markdownV2AutoEscape = true) + InlineKeyboardMarkup markup = buttons; + + try { - if (ActiveForm == null) - return null; + var t = Api(a => a.SendVideoAsync(DeviceId, new InputOnlineFile(url), parseMode: parseMode, + replyToMessageId: replyTo, replyMarkup: markup, + disableNotification: disableNotification)); - if (text.Length > Constants.Telegram.MaxMessageLength) - { - throw new MaxLengthException(text.Length); - } + var o = GetOrigin(new StackTrace()); + await OnMessageSent(new MessageSentEventArgs(await t, o)); - if (parseMode == ParseMode.MarkdownV2 && markdownV2AutoEscape) - { - text = text.MarkdownV2Escape(); - } + return await t; + } + catch + { + return null; + } + } - try - { - var t = Api(a => a.SendTextMessageAsync(DeviceId, text, parseMode, replyToMessageId: replyTo, replyMarkup: markup, disableNotification: disableNotification)); - - var o = GetOrigin(new StackTrace()); - await OnMessageSent(new MessageSentEventArgs(await t, o)); - - return await t; - } - catch - { - return null; - } + /// + /// Sends an video + /// + /// + /// + /// + /// + /// + /// + public async Task SendVideo(string filename, byte[] video, ButtonForm buttons = null, int replyTo = 0, + bool disableNotification = false, ParseMode parseMode = ParseMode.Markdown) + { + if (ActiveForm == null) + { + return null; } - /// - /// Sends a simple text message - /// - /// - /// - /// - /// - /// - public async Task Send(string text, ReplyMarkupBase markup, int replyTo = 0, bool disableNotification = false, ParseMode parseMode = ParseMode.Markdown, bool markdownV2AutoEscape = true) + InlineKeyboardMarkup markup = buttons; + + try { - if (ActiveForm == null) - return null; - - if (text.Length > Constants.Telegram.MaxMessageLength) - { - throw new MaxLengthException(text.Length); - } - - if (parseMode == ParseMode.MarkdownV2 && markdownV2AutoEscape) - { - text = text.MarkdownV2Escape(); - } - - try - { - var t = Api(a => a.SendTextMessageAsync(DeviceId, text, parseMode, replyToMessageId: replyTo, replyMarkup: markup, disableNotification: disableNotification)); - - var o = GetOrigin(new StackTrace()); - await OnMessageSent(new MessageSentEventArgs(await t, o)); - - return await t; - } - catch - { - return null; - } - } - - /// - /// Sends an image - /// - /// - /// - /// - /// - /// - public async Task SendPhoto(InputOnlineFile file, string caption = null, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false, ParseMode parseMode = ParseMode.Markdown) - { - if (ActiveForm == null) - return null; - - InlineKeyboardMarkup markup = buttons; - - try - { - var t = Api(a => a.SendPhotoAsync(DeviceId, file, caption: caption, parseMode: parseMode, replyToMessageId: replyTo, replyMarkup: markup, disableNotification: disableNotification)); - - var o = GetOrigin(new StackTrace()); - await OnMessageSent(new MessageSentEventArgs(await t, o)); - - return await t; - } - catch - { - return null; - } - } - - /// - /// Sends an video - /// - /// - /// - /// - /// - /// - public async Task SendVideo(InputOnlineFile file, string caption = null, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false, ParseMode parseMode = ParseMode.Markdown) - { - if (ActiveForm == null) - return null; - - InlineKeyboardMarkup markup = buttons; - - try - { - var t = Api(a => a.SendVideoAsync(DeviceId, file, caption: caption, parseMode: parseMode, replyToMessageId: replyTo, replyMarkup: markup, disableNotification: disableNotification)); - - var o = GetOrigin(new StackTrace()); - await OnMessageSent(new MessageSentEventArgs(await t, o)); - - return await t; - } - catch - { - return null; - } - } - - /// - /// Sends an video - /// - /// - /// - /// - /// - /// - public async Task SendVideo(string url, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false, ParseMode parseMode = ParseMode.Markdown) - { - if (ActiveForm == null) - return null; - - InlineKeyboardMarkup markup = buttons; - - try - { - var t = Api(a => a.SendVideoAsync(DeviceId, new InputOnlineFile(url), parseMode: parseMode, replyToMessageId: replyTo, replyMarkup: markup, disableNotification: disableNotification)); - - var o = GetOrigin(new StackTrace()); - await OnMessageSent(new MessageSentEventArgs(await t, o)); - - return await t; - } - catch - { - return null; - } - } - - /// - /// Sends an video - /// - /// - /// - /// - /// - /// - /// - public async Task SendVideo(string filename, byte[] video, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false, ParseMode parseMode = ParseMode.Markdown) - { - if (ActiveForm == null) - return null; - - InlineKeyboardMarkup markup = buttons; - - try - { - var ms = new MemoryStream(video); - - var fts = new InputOnlineFile(ms, filename); - - var t = Api(a => a.SendVideoAsync(DeviceId, fts, parseMode: parseMode, replyToMessageId: replyTo, replyMarkup: markup, disableNotification: disableNotification)); - - var o = GetOrigin(new StackTrace()); - await OnMessageSent(new MessageSentEventArgs(await t, o)); - - return await t; - } - catch - { - return null; - } - } - - /// - /// Sends an local file as video - /// - /// - /// - /// - /// - /// - /// - public async Task SendLocalVideo(string filepath, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false, ParseMode parseMode = ParseMode.Markdown) - { - if (ActiveForm == null) - return null; - - InlineKeyboardMarkup markup = buttons; - - try - { - var fs = new FileStream(filepath, FileMode.Open); - - var filename = Path.GetFileName(filepath); - - var fts = new InputOnlineFile(fs, filename); - - var t = Api(a => a.SendVideoAsync(DeviceId, fts, parseMode: parseMode, replyToMessageId: replyTo, replyMarkup: markup, disableNotification: disableNotification)); - - var o = GetOrigin(new StackTrace()); - await OnMessageSent(new MessageSentEventArgs(await t, o)); - - return await t; - } - catch - { - return null; - } - } - - /// - /// Sends an document - /// - /// - /// - /// - /// - /// - /// - /// - public async Task SendDocument(string filename, byte[] document, string caption = "", ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false) - { - var ms = new MemoryStream(document); + var ms = new MemoryStream(video); var fts = new InputOnlineFile(ms, filename); - return await SendDocument(fts, caption, buttons, replyTo, disableNotification); + var t = Api(a => a.SendVideoAsync(DeviceId, fts, parseMode: parseMode, replyToMessageId: replyTo, + replyMarkup: markup, disableNotification: disableNotification)); + + var o = GetOrigin(new StackTrace()); + await OnMessageSent(new MessageSentEventArgs(await t, o)); + + return await t; } - - /// - /// Generates a Textfile from scratch with the specified encoding. (Default is UTF8) - /// - /// - /// - /// Default is UTF8 - /// - /// - /// - /// - /// - public async Task SendTextFile(string filename, string textcontent, Encoding encoding = null, string caption = "", ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false) + catch { - encoding = encoding ?? Encoding.UTF8; - - var ms = new MemoryStream(); - var sw = new StreamWriter(ms, encoding); - - sw.Write(textcontent); - sw.Flush(); - - var content = ms.ToArray(); - - return await SendDocument(filename, content, caption, buttons, replyTo, disableNotification); - } - - /// - /// Sends an document - /// - /// - /// - /// - /// - /// - /// - public async Task SendDocument(InputOnlineFile document, string caption = "", ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false) - { - InlineKeyboardMarkup markup = null; - if (buttons != null) - { - markup = buttons; - } - - try - { - var t = Api(a => a.SendDocumentAsync(DeviceId, document, caption, replyMarkup: markup, disableNotification: disableNotification, replyToMessageId: replyTo)); - - var o = GetOrigin(new StackTrace()); - await OnMessageSent(new MessageSentEventArgs(await t, o)); - - return await t; - } - catch - { - return null; - } - } - - /// - /// Set a chat action (showed to the user) - /// - /// - /// - public async Task SetAction(ChatAction action) - { - await Api(a => a.SendChatActionAsync(DeviceId, action)); - } - - /// - /// Requests the contact from the user. - /// - /// - /// - /// - /// - public async Task RequestContact(string buttonText = "Send your contact", string requestMessage = "Give me your phone number!", bool oneTimeOnly = true) - { - var rck = new ReplyKeyboardMarkup(KeyboardButton.WithRequestContact(buttonText)) - { - OneTimeKeyboard = oneTimeOnly - }; - return await Api(a => a.SendTextMessageAsync(DeviceId, requestMessage, replyMarkup: rck)); - } - - /// - /// Requests the location from the user. - /// - /// - /// - /// - /// - public async Task RequestLocation(string buttonText = "Send your location", string requestMessage = "Give me your location!", bool oneTimeOnly = true) - { - var rcl = new ReplyKeyboardMarkup(KeyboardButton.WithRequestLocation(buttonText)) - { - OneTimeKeyboard = oneTimeOnly - }; - return await Api(a => a.SendTextMessageAsync(DeviceId, requestMessage, replyMarkup: rcl)); - } - - public async Task HideReplyKeyboard(string closedMsg = "Closed", bool autoDeleteResponse = true) - { - try - { - var m = await Send(closedMsg, new ReplyKeyboardRemove()); - - if (autoDeleteResponse && m != null) - { - await DeleteMessage(m); - } - - return m; - } - catch - { - - } return null; } - - /// - /// Deletes a message - /// - /// - /// - public virtual async Task DeleteMessage(int messageId = -1) - { - - await Raw(a => a.DeleteMessageAsync(DeviceId, messageId)); - - OnMessageDeleted(new MessageDeletedEventArgs(messageId)); - - return true; - } - - /// - /// Deletes the given message - /// - /// - /// - public virtual async Task DeleteMessage(Message message) - { - return await DeleteMessage(message.MessageId); - } - - - public virtual async Task ChangeChatPermissions(ChatPermissions permissions) - { - try - { - await Api(a => a.SetChatPermissionsAsync(DeviceId, permissions)); - } - catch - { - - } - } - - private Type GetOrigin(StackTrace stackTrace) - { - for (var i = 0; i < stackTrace.FrameCount; i++) - { - var methodBase = stackTrace.GetFrame(i).GetMethod(); - - //Debug.WriteLine(methodBase.Name); - - if (methodBase.DeclaringType.IsSubclassOf(typeof(FormBase)) | methodBase.DeclaringType.IsSubclassOf(typeof(ControlBase))) - { - return methodBase.DeclaringType; - } - } - - return null; - } - - #region "Users" - - public virtual async Task RestrictUser(long userId, ChatPermissions permissions, DateTime until = default(DateTime)) - { - try - { - await Api(a => a.RestrictChatMemberAsync(DeviceId, userId, permissions, until)); - } - catch - { - - } - } - - public virtual async Task GetChatUser(long userId) - { - try - { - return await Api(a => a.GetChatMemberAsync(DeviceId, userId)); - } - catch - { - - } - return null; - } - - [Obsolete("User BanUser instead.")] - public virtual async Task KickUser(long userId, DateTime until = default(DateTime)) - { - try - { - await Api(a => a.BanChatMemberAsync(DeviceId, userId, until)); - } - catch - { - - } - } - - public virtual async Task BanUser(long userId, DateTime until = default(DateTime)) - { - try - { - await Api(a => a.BanChatMemberAsync(DeviceId, userId, until)); - } - catch - { - - } - } - - public virtual async Task UnbanUser(long userId) - { - try - { - await Api(a => a.UnbanChatMemberAsync(DeviceId, userId)); - } - catch - { - - } - } - - #endregion - - /// - /// Gives access to the original TelegramClient without any Exception catchings. - /// - /// - /// - /// - public T Raw(Func call) - { - return call(Client.TelegramClient); - } - - /// - /// This will call a function on the TelegramClient and automatically Retry if an limit has been exceeded. - /// - /// - /// - /// - public async Task Api(Func> call) - { - var numberOfTries = 0; - while (numberOfTries < MaxNumberOfRetries) - { - try - { - return await call(Client.TelegramClient); - } - catch (ApiRequestException ex) - { - if (ex.ErrorCode != 429) - throw; - - if (ex.Parameters != null && ex.Parameters.RetryAfter != null) - await Task.Delay(ex.Parameters.RetryAfter.Value * 1000); - - numberOfTries++; - } - } - return default(T); - } - - /// - /// This will call a function on the TelegramClient and automatically Retry if an limit has been exceeded. - /// - /// - /// - public async Task Api(Func call) - { - var numberOfTries = 0; - while (numberOfTries < MaxNumberOfRetries) - { - try - { - await call(Client.TelegramClient); - return; - } - catch (ApiRequestException ex) - { - if (ex.ErrorCode != 429) - throw; - - if (ex.Parameters != null && ex.Parameters.RetryAfter != null) - await Task.Delay(ex.Parameters.RetryAfter.Value * 1000); - - numberOfTries++; - } - } - } - - - #region "Events" - - /// - /// Eventhandler for sent messages - /// - public event Async.AsyncEventHandler MessageSent - { - add => _events.AddHandler(EvMessageSent, value); - remove => _events.RemoveHandler(EvMessageSent, value); - } - - - public async Task OnMessageSent(MessageSentEventArgs e) - { - if (e.Message == null) - return; - - var handler = _events[EvMessageSent]?.GetInvocationList().Cast>(); - if (handler == null) - return; - - foreach (var h in handler) - { - await h.InvokeAllAsync(this, e); - } - - //(this.__Events[__evMessageSent] as EventHandler)?.Invoke(this, e); - } - - /// - /// Eventhandler for received messages - /// - public event EventHandler MessageReceived - { - add => _events.AddHandler(EvMessageReceived, value); - remove => _events.RemoveHandler(EvMessageReceived, value); - } - - - public void OnMessageReceived(MessageReceivedEventArgs e) - { - (_events[EvMessageReceived] as EventHandler)?.Invoke(this, e); - } - - /// - /// Eventhandler for deleting messages - /// - public event EventHandler MessageDeleted - { - add => _events.AddHandler(EvMessageDeleted, value); - remove => _events.RemoveHandler(EvMessageDeleted, value); - } - - - public void OnMessageDeleted(MessageDeletedEventArgs e) - { - (_events[EvMessageDeleted] as EventHandler)?.Invoke(this, e); - } - - #endregion - - #region "Static" - - /// - /// Indicates the maximum number of times a request that received error - /// 429 will be sent again after a timeout until it receives code 200 or an error code not equal to 429. - /// - public static uint MaxNumberOfRetries { get; set; } - - #endregion "Static" } -} + + /// + /// Sends an local file as video + /// + /// + /// + /// + /// + /// + /// + public async Task SendLocalVideo(string filepath, ButtonForm buttons = null, int replyTo = 0, + bool disableNotification = false, + ParseMode parseMode = ParseMode.Markdown) + { + if (ActiveForm == null) + { + return null; + } + + InlineKeyboardMarkup markup = buttons; + + try + { + var fs = new FileStream(filepath, FileMode.Open); + + var filename = Path.GetFileName(filepath); + + var fts = new InputOnlineFile(fs, filename); + + var t = Api(a => a.SendVideoAsync(DeviceId, fts, parseMode: parseMode, replyToMessageId: replyTo, + replyMarkup: markup, disableNotification: disableNotification)); + + var o = GetOrigin(new StackTrace()); + await OnMessageSent(new MessageSentEventArgs(await t, o)); + + return await t; + } + catch + { + return null; + } + } + + /// + /// Sends an document + /// + /// + /// + /// + /// + /// + /// + /// + public async Task SendDocument(string filename, byte[] document, string caption = "", + ButtonForm buttons = null, int replyTo = 0, + bool disableNotification = false) + { + var ms = new MemoryStream(document); + + var fts = new InputOnlineFile(ms, filename); + + return await SendDocument(fts, caption, buttons, replyTo, disableNotification); + } + + /// + /// Generates a Textfile from scratch with the specified encoding. (Default is UTF8) + /// + /// + /// + /// Default is UTF8 + /// + /// + /// + /// + /// + public async Task SendTextFile(string filename, string textcontent, Encoding encoding = null, + string caption = "", ButtonForm buttons = null, int replyTo = 0, + bool disableNotification = false) + { + encoding = encoding ?? Encoding.UTF8; + + var ms = new MemoryStream(); + var sw = new StreamWriter(ms, encoding); + + sw.Write(textcontent); + sw.Flush(); + + var content = ms.ToArray(); + + return await SendDocument(filename, content, caption, buttons, replyTo, disableNotification); + } + + /// + /// Sends an document + /// + /// + /// + /// + /// + /// + /// + public async Task SendDocument(InputOnlineFile document, string caption = "", + ButtonForm buttons = null, int replyTo = 0, + bool disableNotification = false) + { + InlineKeyboardMarkup markup = null; + if (buttons != null) + { + markup = buttons; + } + + try + { + var t = Api(a => a.SendDocumentAsync(DeviceId, document, caption, replyMarkup: markup, + disableNotification: disableNotification, replyToMessageId: replyTo)); + + var o = GetOrigin(new StackTrace()); + await OnMessageSent(new MessageSentEventArgs(await t, o)); + + return await t; + } + catch + { + return null; + } + } + + /// + /// Set a chat action (showed to the user) + /// + /// + /// + public async Task SetAction(ChatAction action) + { + await Api(a => a.SendChatActionAsync(DeviceId, action)); + } + + /// + /// Requests the contact from the user. + /// + /// + /// + /// + /// + public async Task RequestContact(string buttonText = "Send your contact", + string requestMessage = "Give me your phone number!", + bool oneTimeOnly = true) + { + var rck = new ReplyKeyboardMarkup(KeyboardButton.WithRequestContact(buttonText)) + { + OneTimeKeyboard = oneTimeOnly + }; + return await Api(a => a.SendTextMessageAsync(DeviceId, requestMessage, replyMarkup: rck)); + } + + /// + /// Requests the location from the user. + /// + /// + /// + /// + /// + public async Task RequestLocation(string buttonText = "Send your location", + string requestMessage = "Give me your location!", + bool oneTimeOnly = true) + { + var rcl = new ReplyKeyboardMarkup(KeyboardButton.WithRequestLocation(buttonText)) + { + OneTimeKeyboard = oneTimeOnly + }; + return await Api(a => a.SendTextMessageAsync(DeviceId, requestMessage, replyMarkup: rcl)); + } + + public async Task HideReplyKeyboard(string closedMsg = "Closed", bool autoDeleteResponse = true) + { + try + { + var m = await Send(closedMsg, new ReplyKeyboardRemove()); + + if (autoDeleteResponse && m != null) + { + await DeleteMessage(m); + } + + return m; + } + catch + { + } + + return null; + } + + /// + /// Deletes a message + /// + /// + /// + public virtual async Task DeleteMessage(int messageId = -1) + { + await Raw(a => a.DeleteMessageAsync(DeviceId, messageId)); + + OnMessageDeleted(new MessageDeletedEventArgs(messageId)); + + return true; + } + + /// + /// Deletes the given message + /// + /// + /// + public virtual async Task DeleteMessage(Message message) + { + return await DeleteMessage(message.MessageId); + } + + + public virtual async Task ChangeChatPermissions(ChatPermissions permissions) + { + try + { + await Api(a => a.SetChatPermissionsAsync(DeviceId, permissions)); + } + catch + { + } + } + + private Type GetOrigin(StackTrace stackTrace) + { + for (var i = 0; i < stackTrace.FrameCount; i++) + { + var methodBase = stackTrace.GetFrame(i).GetMethod(); + + //Debug.WriteLine(methodBase.Name); + + if (methodBase.DeclaringType.IsSubclassOf(typeof(FormBase)) | + methodBase.DeclaringType.IsSubclassOf(typeof(ControlBase))) + { + return methodBase.DeclaringType; + } + } + + return null; + } + + /// + /// Gives access to the original TelegramClient without any Exception catchings. + /// + /// + /// + /// + public T Raw(Func call) + { + return call(Client.TelegramClient); + } + + /// + /// This will call a function on the TelegramClient and automatically Retry if an limit has been exceeded. + /// + /// + /// + /// + public async Task Api(Func> call) + { + var numberOfTries = 0; + while (numberOfTries < MaxNumberOfRetries) + { + try + { + return await call(Client.TelegramClient); + } + catch (ApiRequestException ex) + { + if (ex.ErrorCode != 429) + { + throw; + } + + if (ex.Parameters != null && ex.Parameters.RetryAfter != null) + { + await Task.Delay(ex.Parameters.RetryAfter.Value * 1000); + } + + numberOfTries++; + } + } + + return default; + } + + /// + /// This will call a function on the TelegramClient and automatically Retry if an limit has been exceeded. + /// + /// + /// + public async Task Api(Func call) + { + var numberOfTries = 0; + while (numberOfTries < MaxNumberOfRetries) + { + try + { + await call(Client.TelegramClient); + return; + } + catch (ApiRequestException ex) + { + if (ex.ErrorCode != 429) + { + throw; + } + + if (ex.Parameters != null && ex.Parameters.RetryAfter != null) + { + await Task.Delay(ex.Parameters.RetryAfter.Value * 1000); + } + + numberOfTries++; + } + } + } + + #region "Users" + + public virtual async Task RestrictUser(long userId, ChatPermissions permissions, DateTime until = default) + { + try + { + await Api(a => a.RestrictChatMemberAsync(DeviceId, userId, permissions, until)); + } + catch + { + } + } + + public virtual async Task GetChatUser(long userId) + { + try + { + return await Api(a => a.GetChatMemberAsync(DeviceId, userId)); + } + catch + { + } + + return null; + } + + [Obsolete("User BanUser instead.")] + public virtual async Task KickUser(long userId, DateTime until = default) + { + try + { + await Api(a => a.BanChatMemberAsync(DeviceId, userId, until)); + } + catch + { + } + } + + public virtual async Task BanUser(long userId, DateTime until = default) + { + try + { + await Api(a => a.BanChatMemberAsync(DeviceId, userId, until)); + } + catch + { + } + } + + public virtual async Task UnbanUser(long userId) + { + try + { + await Api(a => a.UnbanChatMemberAsync(DeviceId, userId)); + } + catch + { + } + } + + #endregion + + + #region "Events" + + /// + /// Eventhandler for sent messages + /// + public event Async.AsyncEventHandler MessageSent + { + add => _events.AddHandler(EvMessageSent, value); + remove => _events.RemoveHandler(EvMessageSent, value); + } + + + public async Task OnMessageSent(MessageSentEventArgs e) + { + if (e.Message == null) + { + return; + } + + var handler = _events[EvMessageSent]?.GetInvocationList() + .Cast>(); + if (handler == null) + { + return; + } + + foreach (var h in handler) + { + await h.InvokeAllAsync(this, e); + } + + //(this.__Events[__evMessageSent] as EventHandler)?.Invoke(this, e); + } + + /// + /// Eventhandler for received messages + /// + public event EventHandler MessageReceived + { + add => _events.AddHandler(EvMessageReceived, value); + remove => _events.RemoveHandler(EvMessageReceived, value); + } + + + public void OnMessageReceived(MessageReceivedEventArgs e) + { + (_events[EvMessageReceived] as EventHandler)?.Invoke(this, e); + } + + /// + /// Eventhandler for deleting messages + /// + public event EventHandler MessageDeleted + { + add => _events.AddHandler(EvMessageDeleted, value); + remove => _events.RemoveHandler(EvMessageDeleted, value); + } + + + public void OnMessageDeleted(MessageDeletedEventArgs e) + { + (_events[EvMessageDeleted] as EventHandler)?.Invoke(this, e); + } + + #endregion +} \ No newline at end of file diff --git a/TelegramBotBase/States/JSONStateMachine.cs b/TelegramBotBase/States/JSONStateMachine.cs index 944caf0..ada7fe4 100644 --- a/TelegramBotBase/States/JSONStateMachine.cs +++ b/TelegramBotBase/States/JSONStateMachine.cs @@ -6,87 +6,87 @@ using TelegramBotBase.Base; using TelegramBotBase.Form; using TelegramBotBase.Interfaces; -namespace TelegramBotBase.States +namespace TelegramBotBase.States; + +/// +/// Is used for all complex data types. Use if other default machines are not working. +/// +public class JsonStateMachine : IStateMachine { /// - /// Is used for all complex data types. Use if other default machines are not working. + /// Will initialize the state machine. /// - public class JsonStateMachine : IStateMachine + /// Path of the file and name where to save the session details. + /// + /// Type of Form which will be saved instead of Form which has + /// attribute declared. Needs to be subclass of + /// . + /// + /// Declares of the file could be overwritten. + public JsonStateMachine(string file, Type fallbackStateForm = null, bool overwrite = true) { - public string FilePath { get; set; } + FallbackStateForm = fallbackStateForm; - public bool Overwrite { get; set; } - - public Type FallbackStateForm { get; private set; } - - /// - /// Will initialize the state machine. - /// - /// Path of the file and name where to save the session details. - /// Type of Form which will be saved instead of Form which has attribute declared. Needs to be subclass of . - /// Declares of the file could be overwritten. - public JsonStateMachine(string file, Type fallbackStateForm = null, bool overwrite = true) + if (FallbackStateForm != null && !FallbackStateForm.IsSubclassOf(typeof(FormBase))) { - FallbackStateForm = fallbackStateForm; - - if (FallbackStateForm != null && !FallbackStateForm.IsSubclassOf(typeof(FormBase))) - { - throw new ArgumentException("FallbackStateForm is not a subclass of FormBase"); - } - - FilePath = file ?? throw new ArgumentNullException(nameof(file)); - Overwrite = overwrite; + throw new ArgumentException("FallbackStateForm is not a subclass of FormBase"); } - public StateContainer LoadFormStates() + FilePath = file ?? throw new ArgumentNullException(nameof(file)); + Overwrite = overwrite; + } + + public string FilePath { get; set; } + + public bool Overwrite { get; set; } + + public Type FallbackStateForm { get; } + + public StateContainer LoadFormStates() + { + try { - try + var content = File.ReadAllText(FilePath); + + var sc = JsonConvert.DeserializeObject(content, new JsonSerializerSettings { - var content = File.ReadAllText(FilePath); + TypeNameHandling = TypeNameHandling.All, + TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Simple + }); - var sc = JsonConvert.DeserializeObject(content, new JsonSerializerSettings - { - TypeNameHandling = TypeNameHandling.All, - TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Simple - }); - - return sc; - } - catch - { - - } - - return new StateContainer(); + return sc; + } + catch + { } - public void SaveFormStates(SaveStatesEventArgs e) + return new StateContainer(); + } + + public void SaveFormStates(SaveStatesEventArgs e) + { + if (File.Exists(FilePath)) { - if (File.Exists(FilePath)) + if (!Overwrite) { - if (!Overwrite) - { - throw new Exception("File exists already."); - } - - File.Delete(FilePath); + throw new Exception("File exists already."); } - try + File.Delete(FilePath); + } + + try + { + var content = JsonConvert.SerializeObject(e.States, Formatting.Indented, new JsonSerializerSettings { - var content = JsonConvert.SerializeObject(e.States, Formatting.Indented, new JsonSerializerSettings - { - TypeNameHandling = TypeNameHandling.All, - TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Simple - }); - - File.WriteAllText(FilePath, content); - } - catch - { - - } + TypeNameHandling = TypeNameHandling.All, + TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Simple + }); + File.WriteAllText(FilePath, content); + } + catch + { } } -} +} \ No newline at end of file diff --git a/TelegramBotBase/States/SimpleJSONStateMachine.cs b/TelegramBotBase/States/SimpleJSONStateMachine.cs index 5c84456..7e8fa58 100644 --- a/TelegramBotBase/States/SimpleJSONStateMachine.cs +++ b/TelegramBotBase/States/SimpleJSONStateMachine.cs @@ -6,79 +6,80 @@ using TelegramBotBase.Base; using TelegramBotBase.Form; using TelegramBotBase.Interfaces; -namespace TelegramBotBase.States +namespace TelegramBotBase.States; + +/// +/// Is used for simple object structures like classes, lists or basic datatypes without generics and other compiler +/// based data types. +/// +public class SimpleJsonStateMachine : IStateMachine { /// - /// Is used for simple object structures like classes, lists or basic datatypes without generics and other compiler based data types. + /// Will initialize the state machine. /// - public class SimpleJsonStateMachine : IStateMachine + /// Path of the file and name where to save the session details. + /// + /// Type of Form which will be saved instead of Form which has + /// attribute declared. Needs to be subclass of + /// . + /// + /// Declares of the file could be overwritten. + public SimpleJsonStateMachine(string file, Type fallbackStateForm = null, bool overwrite = true) { - public string FilePath { get; set; } + FallbackStateForm = fallbackStateForm; - public bool Overwrite { get; set; } - - public Type FallbackStateForm { get; private set; } - - /// - /// Will initialize the state machine. - /// - /// Path of the file and name where to save the session details. - /// Type of Form which will be saved instead of Form which has attribute declared. Needs to be subclass of . - /// Declares of the file could be overwritten. - public SimpleJsonStateMachine(string file, Type fallbackStateForm = null, bool overwrite = true) + if (FallbackStateForm != null && !FallbackStateForm.IsSubclassOf(typeof(FormBase))) { - FallbackStateForm = fallbackStateForm; - - if (FallbackStateForm != null && !FallbackStateForm.IsSubclassOf(typeof(FormBase))) - { - throw new ArgumentException("FallbackStateForm is not a subclass of FormBase"); - } - - FilePath = file ?? throw new ArgumentNullException(nameof(file)); - Overwrite = overwrite; + throw new ArgumentException("FallbackStateForm is not a subclass of FormBase"); } - public StateContainer LoadFormStates() + FilePath = file ?? throw new ArgumentNullException(nameof(file)); + Overwrite = overwrite; + } + + public string FilePath { get; set; } + + public bool Overwrite { get; set; } + + public Type FallbackStateForm { get; } + + public StateContainer LoadFormStates() + { + try { - try - { - var content = File.ReadAllText(FilePath); + var content = File.ReadAllText(FilePath); - var sc = JsonConvert.DeserializeObject(content); + var sc = JsonConvert.DeserializeObject(content); - return sc; - } - catch - { - - } - - return new StateContainer(); + return sc; + } + catch + { } - public void SaveFormStates(SaveStatesEventArgs e) + return new StateContainer(); + } + + public void SaveFormStates(SaveStatesEventArgs e) + { + if (File.Exists(FilePath)) { - if (File.Exists(FilePath)) + if (!Overwrite) { - if (!Overwrite) - { - throw new Exception("File exists already."); - } - - File.Delete(FilePath); + throw new Exception("File exists already."); } - try - { - var content = JsonConvert.SerializeObject(e.States, Formatting.Indented); + File.Delete(FilePath); + } - File.WriteAllText(FilePath, content); - } - catch - { - - } + try + { + var content = JsonConvert.SerializeObject(e.States, Formatting.Indented); + File.WriteAllText(FilePath, content); + } + catch + { } } -} +} \ No newline at end of file diff --git a/TelegramBotBase/States/XMLStateMachine.cs b/TelegramBotBase/States/XMLStateMachine.cs index b472d27..1a569eb 100644 --- a/TelegramBotBase/States/XMLStateMachine.cs +++ b/TelegramBotBase/States/XMLStateMachine.cs @@ -7,90 +7,89 @@ using TelegramBotBase.Base; using TelegramBotBase.Form; using TelegramBotBase.Interfaces; -namespace TelegramBotBase.States +namespace TelegramBotBase.States; + +public class XmlStateMachine : IStateMachine { - public class XmlStateMachine : IStateMachine + /// + /// Will initialize the state machine. + /// + /// Path of the file and name where to save the session details. + /// + /// Type of Form which will be saved instead of Form which has + /// attribute declared. Needs to be subclass of + /// . + /// + /// Declares of the file could be overwritten. + public XmlStateMachine(string file, Type fallbackStateForm = null, bool overwrite = true) { - public string FilePath { get; set; } + FallbackStateForm = fallbackStateForm; - public bool Overwrite { get; set; } - - public Type FallbackStateForm { get; private set; } - - /// - /// Will initialize the state machine. - /// - /// Path of the file and name where to save the session details. - /// Type of Form which will be saved instead of Form which has attribute declared. Needs to be subclass of . - /// Declares of the file could be overwritten. - public XmlStateMachine(string file, Type fallbackStateForm = null, bool overwrite = true) + if (FallbackStateForm != null && !FallbackStateForm.IsSubclassOf(typeof(FormBase))) { - FallbackStateForm = fallbackStateForm; - - if (FallbackStateForm != null && !FallbackStateForm.IsSubclassOf(typeof(FormBase))) - { - throw new ArgumentException("FallbackStateForm is not a subclass of FormBase"); - } - - FilePath = file ?? throw new ArgumentNullException(nameof(file)); - Overwrite = overwrite; + throw new ArgumentException("FallbackStateForm is not a subclass of FormBase"); } - public StateContainer LoadFormStates() - { - try - { - var serializer = new DataContractSerializer(typeof(StateContainer)); - - using (var reader = new StreamReader(FilePath)) - { - using (var xml = new XmlTextReader(reader)) - { - var sc = serializer.ReadObject(xml) as StateContainer; - return sc; - } - } - } - catch - { - - } - - return new StateContainer(); - } - - public void SaveFormStates(SaveStatesEventArgs e) - { - if (File.Exists(FilePath)) - { - if (!Overwrite) - { - throw new Exception("File exists already."); - } - - File.Delete(FilePath); - } - - try - { - var serializer = new DataContractSerializer(typeof(StateContainer)); - - using (var sw = new StreamWriter(FilePath)) - { - using (var writer = new XmlTextWriter(sw)) - { - writer.Formatting = Formatting.Indented; // indent the Xml so it’s human readable - serializer.WriteObject(writer, e.States); - writer.Flush(); - } - } - } - catch - { - - } - - } + FilePath = file ?? throw new ArgumentNullException(nameof(file)); + Overwrite = overwrite; } -} + public string FilePath { get; set; } + + public bool Overwrite { get; set; } + + public Type FallbackStateForm { get; } + + public StateContainer LoadFormStates() + { + try + { + var serializer = new DataContractSerializer(typeof(StateContainer)); + + using (var reader = new StreamReader(FilePath)) + { + using (var xml = new XmlTextReader(reader)) + { + var sc = serializer.ReadObject(xml) as StateContainer; + return sc; + } + } + } + catch + { + } + + return new StateContainer(); + } + + public void SaveFormStates(SaveStatesEventArgs e) + { + if (File.Exists(FilePath)) + { + if (!Overwrite) + { + throw new Exception("File exists already."); + } + + File.Delete(FilePath); + } + + try + { + var serializer = new DataContractSerializer(typeof(StateContainer)); + + using (var sw = new StreamWriter(FilePath)) + { + using (var writer = new XmlTextWriter(sw)) + { + writer.Formatting = Formatting.Indented; // indent the Xml so it’s human readable + serializer.WriteObject(writer, e.States); + writer.Flush(); + } + } + } + catch + { + } + } +} \ No newline at end of file diff --git a/TelegramBotBase/TelegramBotBase.csproj b/TelegramBotBase/TelegramBotBase.csproj index 4203025..3879e73 100644 --- a/TelegramBotBase/TelegramBotBase.csproj +++ b/TelegramBotBase/TelegramBotBase.csproj @@ -1,64 +1,64 @@  - - netstandard2.0;net5;netcoreapp3.1;net6 - 9 - false - False - true - https://github.com/MajMcCloud/TelegramBotFramework - https://github.com/MajMcCloud/TelegramBotFramework - - Dependency update. Removing .Net Framework target and replacing with .Net Standard 2.0 - Debug;Release; - MIT - false - false - true - true - true - snupkg - $(VersionPrefix) - portable - + + netstandard2.0;net5;netcoreapp3.1;net6 + 10 + false + False + true + https://github.com/MajMcCloud/TelegramBotFramework + https://github.com/MajMcCloud/TelegramBotFramework + - Dependency update. Removing .Net Framework target and replacing with .Net Standard 2.0 + Debug;Release; + MIT + false + false + true + true + true + snupkg + $(VersionPrefix) + portable + - - - - + + + + - - true - full - false - bin\Debug\ - TRACE;DEBUG - prompt - 4 - + + true + full + false + bin\Debug\ + TRACE;DEBUG + prompt + 4 + - - portable - true - bin\Release\ - TRACE - prompt - 4 - bin\Release\TelegramBotBase.xml - + + portable + true + bin\Release\ + TRACE + prompt + 4 + bin\Release\TelegramBotBase.xml + - - - - - + + + + + - - - - + + + + diff --git a/TelegramBotBase/TelegramBotBase.nuspec b/TelegramBotBase/TelegramBotBase.nuspec index 22df758..12c8077 100644 --- a/TelegramBotBase/TelegramBotBase.nuspec +++ b/TelegramBotBase/TelegramBotBase.nuspec @@ -1,27 +1,29 @@  - - TelegramBotBase - 2.1.0 - TelegramBotBase - TelegramBotBase - false - MIT - https://github.com/MajMcCloud/TelegramBotFramework - Package Description - - moving from .Net Framework 4.7.2 to .Net Standard 2.1 for the Library and .Net Core 3.0 for the test project! - - - - - - - - - - - - - - - \ No newline at end of file + + TelegramBotBase + 2.1.0 + TelegramBotBase + TelegramBotBase + false + MIT + https://github.com/MajMcCloud/TelegramBotFramework + Package Description + - moving from .Net Framework 4.7.2 to .Net Standard 2.1 for the Library and .Net Core 3.0 for the + test project! + + + + + + + + + + + + + + + +
diff --git a/TelegramBotBase/Tools/Arrays.cs b/TelegramBotBase/Tools/Arrays.cs index b3814b1..9ad3993 100644 --- a/TelegramBotBase/Tools/Arrays.cs +++ b/TelegramBotBase/Tools/Arrays.cs @@ -1,15 +1,14 @@ using System; -namespace TelegramBotBase.Tools +namespace TelegramBotBase.Tools; + +public static class Arrays { - public static class Arrays + public static T[] Shift(T[] array, int positions) { - public static T[] Shift(T[] array, int positions) - { - var copy = new T[array.Length]; - Array.Copy(array, 0, copy, array.Length - positions, positions); - Array.Copy(array, positions, copy, 0, array.Length - positions); - return copy; - } + var copy = new T[array.Length]; + Array.Copy(array, 0, copy, array.Length - positions, positions); + Array.Copy(array, positions, copy, 0, array.Length - positions); + return copy; } -} +} \ No newline at end of file diff --git a/TelegramBotBase/Tools/Console.cs b/TelegramBotBase/Tools/Console.cs index 7baa187..31af172 100644 --- a/TelegramBotBase/Tools/Console.cs +++ b/TelegramBotBase/Tools/Console.cs @@ -2,64 +2,63 @@ using System.Collections.Generic; using System.Runtime.InteropServices; -namespace TelegramBotBase.Tools +namespace TelegramBotBase.Tools; + +public static class Console { - public static class Console + private static EventHandler __handler; + + private static readonly List __actions = new(); + + static Console() { - [DllImport("Kernel32")] - private static extern bool SetConsoleCtrlHandler(EventHandler handler, bool add); - - private delegate bool EventHandler(CtrlType sig); - - private static EventHandler __handler; - - private static List __actions = new List(); - - private enum CtrlType - { - CtrlCEvent = 0, - CtrlBreakEvent = 1, - CtrlCloseEvent = 2, - CtrlLogoffEvent = 5, - CtrlShutdownEvent = 6 - } - - static Console() - { - - } - - public static void SetHandler(Action action) - { - __actions.Add(action); - - if (__handler != null) - return; - - __handler += Handler; - SetConsoleCtrlHandler(__handler, true); - } - - private static bool Handler(CtrlType sig) - { - switch (sig) - { - case CtrlType.CtrlCEvent: - case CtrlType.CtrlLogoffEvent: - case CtrlType.CtrlShutdownEvent: - case CtrlType.CtrlCloseEvent: - - foreach (var a in __actions) - { - a(); - } - - return false; - - default: - return false; - } - } - } -} + + [DllImport("Kernel32")] + private static extern bool SetConsoleCtrlHandler(EventHandler handler, bool add); + + public static void SetHandler(Action action) + { + __actions.Add(action); + + if (__handler != null) + { + return; + } + + __handler += Handler; + SetConsoleCtrlHandler(__handler, true); + } + + private static bool Handler(CtrlType sig) + { + switch (sig) + { + case CtrlType.CtrlCEvent: + case CtrlType.CtrlLogoffEvent: + case CtrlType.CtrlShutdownEvent: + case CtrlType.CtrlCloseEvent: + + foreach (var a in __actions) + { + a(); + } + + return false; + + default: + return false; + } + } + + private delegate bool EventHandler(CtrlType sig); + + private enum CtrlType + { + CtrlCEvent = 0, + CtrlBreakEvent = 1, + CtrlCloseEvent = 2, + CtrlLogoffEvent = 5, + CtrlShutdownEvent = 6 + } +} \ No newline at end of file diff --git a/TelegramBotBase/Tools/Conversion.cs b/TelegramBotBase/Tools/Conversion.cs index 9993cd5..00ffc47 100644 --- a/TelegramBotBase/Tools/Conversion.cs +++ b/TelegramBotBase/Tools/Conversion.cs @@ -2,34 +2,31 @@ using System.Reflection; using TelegramBotBase.Form; -namespace TelegramBotBase.Tools +namespace TelegramBotBase.Tools; + +public static class Conversion { - public static class Conversion + public static void CustomConversionChecks(FormBase form, KeyValuePair p, PropertyInfo f) { - public static void CustomConversionChecks(FormBase form, KeyValuePair p, PropertyInfo f) + //Newtonsoft Int64/Int32 converter issue + if (f.PropertyType == typeof(int)) { - //Newtonsoft Int64/Int32 converter issue - if (f.PropertyType == typeof(int)) + if (int.TryParse(p.Value.ToString(), out var i)) { - if (int.TryParse(p.Value.ToString(), out var i)) - { - f.SetValue(form, i); - } - return; + f.SetValue(form, i); } - //Newtonsoft Double/Decimal converter issue - if (f.PropertyType == typeof(decimal) | f.PropertyType == typeof(decimal?)) - { - decimal d = 0; - if (decimal.TryParse(p.Value.ToString(), out d)) - { - f.SetValue(form, d); - } - } - - + return; } + //Newtonsoft Double/Decimal converter issue + if ((f.PropertyType == typeof(decimal)) | (f.PropertyType == typeof(decimal?))) + { + decimal d = 0; + if (decimal.TryParse(p.Value.ToString(), out d)) + { + f.SetValue(form, d); + } + } } -} +} \ No newline at end of file diff --git a/TelegramBotBase/Tools/Time.cs b/TelegramBotBase/Tools/Time.cs index f11733b..28d73c4 100644 --- a/TelegramBotBase/Tools/Time.cs +++ b/TelegramBotBase/Tools/Time.cs @@ -1,47 +1,48 @@ using System; -namespace TelegramBotBase.Tools +namespace TelegramBotBase.Tools; + +public static class Time { - public static class Time + public static bool TryParseDay(string src, DateTime currentDate, out int resultDay) { - public static bool TryParseDay(string src, DateTime currentDate, out int resultDay) - { - return int.TryParse(src, out resultDay) && resultDay >= 1 && resultDay <= DateTime.DaysInMonth(currentDate.Year, currentDate.Month); - } - - public static bool TryParseMonth(string src, out int resultMonth) - { - return int.TryParse(src, out resultMonth) && resultMonth >= 1 && resultMonth <= 12; - } - - public static bool TryParseYear(string src, out int resultYear) - { - return int.TryParse(src, out resultYear) && resultYear >= 0 && resultYear <= DateTime.MaxValue.Year; - } - - public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek) - { - var diff = dt.DayOfWeek - startOfWeek; - if (diff < 0) - { - diff += 7; - } - return dt.AddDays(-1 * diff).Date; - } - - public static DateTime EndOfWeek(this DateTime dt, DayOfWeek startOfWeek) - { - return StartOfWeek(dt, startOfWeek).AddDays(6); - } - - public static DateTime FirstDayOfMonth(this DateTime date) - { - return new DateTime(date.Year, date.Month, 1); - } - - public static DateTime LastDayOfMonth(this DateTime date) - { - return FirstDayOfMonth(date).AddMonths(1).AddDays(-1); - } + return int.TryParse(src, out resultDay) && resultDay >= 1 && + resultDay <= DateTime.DaysInMonth(currentDate.Year, currentDate.Month); } -} + + public static bool TryParseMonth(string src, out int resultMonth) + { + return int.TryParse(src, out resultMonth) && resultMonth >= 1 && resultMonth <= 12; + } + + public static bool TryParseYear(string src, out int resultYear) + { + return int.TryParse(src, out resultYear) && resultYear >= 0 && resultYear <= DateTime.MaxValue.Year; + } + + public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek) + { + var diff = dt.DayOfWeek - startOfWeek; + if (diff < 0) + { + diff += 7; + } + + return dt.AddDays(-1 * diff).Date; + } + + public static DateTime EndOfWeek(this DateTime dt, DayOfWeek startOfWeek) + { + return StartOfWeek(dt, startOfWeek).AddDays(6); + } + + public static DateTime FirstDayOfMonth(this DateTime date) + { + return new DateTime(date.Year, date.Month, 1); + } + + public static DateTime LastDayOfMonth(this DateTime date) + { + return FirstDayOfMonth(date).AddMonths(1).AddDays(-1); + } +} \ No newline at end of file