From c518ab7c428ea4c6078a6b3bfbb5866d79a365b9 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sun, 14 Feb 2021 13:03:21 +0100 Subject: [PATCH 001/304] Working in providers --- src/Navigator.Abstractions/{ => Old}/IAction.cs | 0 .../{ => Old}/IActionLauncher.cs | 0 src/Navigator.Abstractions/{ => Old}/IBotClient.cs | 0 .../{ => Old}/INavigatorContext.cs | 0 .../{ => Old}/INavigatorContextBuilder.cs | 0 .../{ => Old}/INavigatorContextExtensionProvider.cs | 0 .../{ => Old}/INavigatorMiddleware.cs | 0 .../{ => Old}/INavigatorNotification.cs | 0 .../{ => Old}/INotificationLauncher.cs | 0 .../NavigatorProviderConfigurationExtension.cs | 7 +++++++ .../NavigatorTelegramProviderOptions.cs | 7 +++++++ .../NavigatorTelegramProviderOptionsExtensions.cs | 7 +++++++ ...NavigatorBuilder.cs => NavigatorConfiguration.cs} | 12 ++++++++---- src/Navigator/{ => Old}/ActionLauncher.cs | 0 src/Navigator/{ => Old}/BotClient.cs | 0 .../{ => Old}/EndpointRouteBuilderExtensions.cs | 0 .../Hosted/SetTelegramBotWebHookHostedService.cs | 0 src/Navigator/{ => Old}/NavigatorContext.cs | 0 src/Navigator/{ => Old}/NavigatorContextBuilder.cs | 0 src/Navigator/{ => Old}/NavigatorMiddleware.cs | 0 .../NavigatorOptionsCollectionExtensions.cs | 0 .../{ => Old}/Notification/NavigatorNotification.cs | 0 src/Navigator/{ => Old}/NotificationLauncher.cs | 0 23 files changed, 29 insertions(+), 4 deletions(-) rename src/Navigator.Abstractions/{ => Old}/IAction.cs (100%) rename src/Navigator.Abstractions/{ => Old}/IActionLauncher.cs (100%) rename src/Navigator.Abstractions/{ => Old}/IBotClient.cs (100%) rename src/Navigator.Abstractions/{ => Old}/INavigatorContext.cs (100%) rename src/Navigator.Abstractions/{ => Old}/INavigatorContextBuilder.cs (100%) rename src/Navigator.Abstractions/{ => Old}/INavigatorContextExtensionProvider.cs (100%) rename src/Navigator.Abstractions/{ => Old}/INavigatorMiddleware.cs (100%) rename src/Navigator.Abstractions/{ => Old}/INavigatorNotification.cs (100%) rename src/Navigator.Abstractions/{ => Old}/INotificationLauncher.cs (100%) create mode 100644 src/Navigator.Provider.Telegram/NavigatorProviderConfigurationExtension.cs create mode 100644 src/Navigator.Provider.Telegram/NavigatorTelegramProviderOptions.cs create mode 100644 src/Navigator.Provider.Telegram/NavigatorTelegramProviderOptionsExtensions.cs rename src/Navigator/{NavigatorBuilder.cs => NavigatorConfiguration.cs} (86%) rename src/Navigator/{ => Old}/ActionLauncher.cs (100%) rename src/Navigator/{ => Old}/BotClient.cs (100%) rename src/Navigator/{ => Old}/EndpointRouteBuilderExtensions.cs (100%) rename src/Navigator/{ => Old}/Hosted/SetTelegramBotWebHookHostedService.cs (100%) rename src/Navigator/{ => Old}/NavigatorContext.cs (100%) rename src/Navigator/{ => Old}/NavigatorContextBuilder.cs (100%) rename src/Navigator/{ => Old}/NavigatorMiddleware.cs (100%) rename src/Navigator/{ => Old}/NavigatorOptionsCollectionExtensions.cs (100%) rename src/Navigator/{ => Old}/Notification/NavigatorNotification.cs (100%) rename src/Navigator/{ => Old}/NotificationLauncher.cs (100%) diff --git a/src/Navigator.Abstractions/IAction.cs b/src/Navigator.Abstractions/Old/IAction.cs similarity index 100% rename from src/Navigator.Abstractions/IAction.cs rename to src/Navigator.Abstractions/Old/IAction.cs diff --git a/src/Navigator.Abstractions/IActionLauncher.cs b/src/Navigator.Abstractions/Old/IActionLauncher.cs similarity index 100% rename from src/Navigator.Abstractions/IActionLauncher.cs rename to src/Navigator.Abstractions/Old/IActionLauncher.cs diff --git a/src/Navigator.Abstractions/IBotClient.cs b/src/Navigator.Abstractions/Old/IBotClient.cs similarity index 100% rename from src/Navigator.Abstractions/IBotClient.cs rename to src/Navigator.Abstractions/Old/IBotClient.cs diff --git a/src/Navigator.Abstractions/INavigatorContext.cs b/src/Navigator.Abstractions/Old/INavigatorContext.cs similarity index 100% rename from src/Navigator.Abstractions/INavigatorContext.cs rename to src/Navigator.Abstractions/Old/INavigatorContext.cs diff --git a/src/Navigator.Abstractions/INavigatorContextBuilder.cs b/src/Navigator.Abstractions/Old/INavigatorContextBuilder.cs similarity index 100% rename from src/Navigator.Abstractions/INavigatorContextBuilder.cs rename to src/Navigator.Abstractions/Old/INavigatorContextBuilder.cs diff --git a/src/Navigator.Abstractions/INavigatorContextExtensionProvider.cs b/src/Navigator.Abstractions/Old/INavigatorContextExtensionProvider.cs similarity index 100% rename from src/Navigator.Abstractions/INavigatorContextExtensionProvider.cs rename to src/Navigator.Abstractions/Old/INavigatorContextExtensionProvider.cs diff --git a/src/Navigator.Abstractions/INavigatorMiddleware.cs b/src/Navigator.Abstractions/Old/INavigatorMiddleware.cs similarity index 100% rename from src/Navigator.Abstractions/INavigatorMiddleware.cs rename to src/Navigator.Abstractions/Old/INavigatorMiddleware.cs diff --git a/src/Navigator.Abstractions/INavigatorNotification.cs b/src/Navigator.Abstractions/Old/INavigatorNotification.cs similarity index 100% rename from src/Navigator.Abstractions/INavigatorNotification.cs rename to src/Navigator.Abstractions/Old/INavigatorNotification.cs diff --git a/src/Navigator.Abstractions/INotificationLauncher.cs b/src/Navigator.Abstractions/Old/INotificationLauncher.cs similarity index 100% rename from src/Navigator.Abstractions/INotificationLauncher.cs rename to src/Navigator.Abstractions/Old/INotificationLauncher.cs diff --git a/src/Navigator.Provider.Telegram/NavigatorProviderConfigurationExtension.cs b/src/Navigator.Provider.Telegram/NavigatorProviderConfigurationExtension.cs new file mode 100644 index 0000000..9dd5149 --- /dev/null +++ b/src/Navigator.Provider.Telegram/NavigatorProviderConfigurationExtension.cs @@ -0,0 +1,7 @@ +namespace Navigator.Provider.Telegram +{ + public class NavigatorProviderConfigurationExtension + { + + } +} \ No newline at end of file diff --git a/src/Navigator.Provider.Telegram/NavigatorTelegramProviderOptions.cs b/src/Navigator.Provider.Telegram/NavigatorTelegramProviderOptions.cs new file mode 100644 index 0000000..5dbc8ba --- /dev/null +++ b/src/Navigator.Provider.Telegram/NavigatorTelegramProviderOptions.cs @@ -0,0 +1,7 @@ +namespace Navigator.Provider.Telegram +{ + public class NavigatorTelegramProviderOptions + { + + } +} \ No newline at end of file diff --git a/src/Navigator.Provider.Telegram/NavigatorTelegramProviderOptionsExtensions.cs b/src/Navigator.Provider.Telegram/NavigatorTelegramProviderOptionsExtensions.cs new file mode 100644 index 0000000..8ad70d3 --- /dev/null +++ b/src/Navigator.Provider.Telegram/NavigatorTelegramProviderOptionsExtensions.cs @@ -0,0 +1,7 @@ +namespace Navigator.Provider.Telegram +{ + public class NavigatorTelegramProviderOptionsExtensions + { + + } +} \ No newline at end of file diff --git a/src/Navigator/NavigatorBuilder.cs b/src/Navigator/NavigatorConfiguration.cs similarity index 86% rename from src/Navigator/NavigatorBuilder.cs rename to src/Navigator/NavigatorConfiguration.cs index 7b4463c..7dec197 100644 --- a/src/Navigator/NavigatorBuilder.cs +++ b/src/Navigator/NavigatorConfiguration.cs @@ -1,9 +1,6 @@ using System; -using System.Collections.Generic; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; -using Navigator.Abstractions; -using Scrutor; namespace Navigator { @@ -12,6 +9,8 @@ namespace Navigator /// public class NavigatorBuilder { + public NavigatorProviderConfiguration WithProvider { get; protected set; } + /// /// Gets the that are being used. /// @@ -43,10 +42,15 @@ public NavigatorBuilder(Action options, IServiceCollection ser services.AddSingleton(Options); } + public void RegisterOrReplaceOptions() { - Services.Replace(ServiceDescriptor.Singleton(Options)); + Services.Replace(ServiceDescriptor.Singleton(Options)); } } + + public class NavigatorProviderConfiguration + { + } } \ No newline at end of file diff --git a/src/Navigator/ActionLauncher.cs b/src/Navigator/Old/ActionLauncher.cs similarity index 100% rename from src/Navigator/ActionLauncher.cs rename to src/Navigator/Old/ActionLauncher.cs diff --git a/src/Navigator/BotClient.cs b/src/Navigator/Old/BotClient.cs similarity index 100% rename from src/Navigator/BotClient.cs rename to src/Navigator/Old/BotClient.cs diff --git a/src/Navigator/EndpointRouteBuilderExtensions.cs b/src/Navigator/Old/EndpointRouteBuilderExtensions.cs similarity index 100% rename from src/Navigator/EndpointRouteBuilderExtensions.cs rename to src/Navigator/Old/EndpointRouteBuilderExtensions.cs diff --git a/src/Navigator/Hosted/SetTelegramBotWebHookHostedService.cs b/src/Navigator/Old/Hosted/SetTelegramBotWebHookHostedService.cs similarity index 100% rename from src/Navigator/Hosted/SetTelegramBotWebHookHostedService.cs rename to src/Navigator/Old/Hosted/SetTelegramBotWebHookHostedService.cs diff --git a/src/Navigator/NavigatorContext.cs b/src/Navigator/Old/NavigatorContext.cs similarity index 100% rename from src/Navigator/NavigatorContext.cs rename to src/Navigator/Old/NavigatorContext.cs diff --git a/src/Navigator/NavigatorContextBuilder.cs b/src/Navigator/Old/NavigatorContextBuilder.cs similarity index 100% rename from src/Navigator/NavigatorContextBuilder.cs rename to src/Navigator/Old/NavigatorContextBuilder.cs diff --git a/src/Navigator/NavigatorMiddleware.cs b/src/Navigator/Old/NavigatorMiddleware.cs similarity index 100% rename from src/Navigator/NavigatorMiddleware.cs rename to src/Navigator/Old/NavigatorMiddleware.cs diff --git a/src/Navigator/NavigatorOptionsCollectionExtensions.cs b/src/Navigator/Old/NavigatorOptionsCollectionExtensions.cs similarity index 100% rename from src/Navigator/NavigatorOptionsCollectionExtensions.cs rename to src/Navigator/Old/NavigatorOptionsCollectionExtensions.cs diff --git a/src/Navigator/Notification/NavigatorNotification.cs b/src/Navigator/Old/Notification/NavigatorNotification.cs similarity index 100% rename from src/Navigator/Notification/NavigatorNotification.cs rename to src/Navigator/Old/Notification/NavigatorNotification.cs diff --git a/src/Navigator/NotificationLauncher.cs b/src/Navigator/Old/NotificationLauncher.cs similarity index 100% rename from src/Navigator/NotificationLauncher.cs rename to src/Navigator/Old/NotificationLauncher.cs From 1762427e977420f4bf5369e426e60942952764be Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sun, 14 Feb 2021 13:04:09 +0100 Subject: [PATCH 002/304] More work on the telegram provider --- .../Navigator.Provider.Telegram.csproj | 16 +++++ ...NavigatorProviderConfigurationExtension.cs | 15 ++++- .../NavigatorTelegramProviderOptions.cs | 2 +- ...igatorTelegramProviderOptionsExtensions.cs | 58 ++++++++++++++++++- src/Navigator.sln | 10 ++++ src/Navigator/NavigatorConfiguration.cs | 21 ++++++- src/Navigator/NavigatorOptions.cs | 26 ++++++++- .../NavigatorServiceCollectionExtensions.cs | 4 +- .../NavigatorOptionsCollectionExtensions.cs | 54 +---------------- 9 files changed, 142 insertions(+), 64 deletions(-) create mode 100644 src/Navigator.Provider.Telegram/Navigator.Provider.Telegram.csproj diff --git a/src/Navigator.Provider.Telegram/Navigator.Provider.Telegram.csproj b/src/Navigator.Provider.Telegram/Navigator.Provider.Telegram.csproj new file mode 100644 index 0000000..a59f094 --- /dev/null +++ b/src/Navigator.Provider.Telegram/Navigator.Provider.Telegram.csproj @@ -0,0 +1,16 @@ + + + + net5.0 + enable + + + + + + + + + + + diff --git a/src/Navigator.Provider.Telegram/NavigatorProviderConfigurationExtension.cs b/src/Navigator.Provider.Telegram/NavigatorProviderConfigurationExtension.cs index 9dd5149..d5e7d73 100644 --- a/src/Navigator.Provider.Telegram/NavigatorProviderConfigurationExtension.cs +++ b/src/Navigator.Provider.Telegram/NavigatorProviderConfigurationExtension.cs @@ -1,7 +1,18 @@ +using System; + namespace Navigator.Provider.Telegram { - public class NavigatorProviderConfigurationExtension + public static class NavigatorProviderConfigurationExtension { - + public static NavigatorConfiguration Telegram(this NavigatorProviderConfiguration providerConfiguration, + Action options) + { + var telegramProviderOptions = new NavigatorTelegramProviderOptions(); + options.Invoke(telegramProviderOptions); + + return providerConfiguration.Provider( + optionsAction => optionsAction.Import(optionsAction.RetrieveAllOptions()), + null); + } } } \ No newline at end of file diff --git a/src/Navigator.Provider.Telegram/NavigatorTelegramProviderOptions.cs b/src/Navigator.Provider.Telegram/NavigatorTelegramProviderOptions.cs index 5dbc8ba..97bf0e8 100644 --- a/src/Navigator.Provider.Telegram/NavigatorTelegramProviderOptions.cs +++ b/src/Navigator.Provider.Telegram/NavigatorTelegramProviderOptions.cs @@ -1,6 +1,6 @@ namespace Navigator.Provider.Telegram { - public class NavigatorTelegramProviderOptions + public class NavigatorTelegramProviderOptions : NavigatorOptions { } diff --git a/src/Navigator.Provider.Telegram/NavigatorTelegramProviderOptionsExtensions.cs b/src/Navigator.Provider.Telegram/NavigatorTelegramProviderOptionsExtensions.cs index 8ad70d3..8d1cd7f 100644 --- a/src/Navigator.Provider.Telegram/NavigatorTelegramProviderOptionsExtensions.cs +++ b/src/Navigator.Provider.Telegram/NavigatorTelegramProviderOptionsExtensions.cs @@ -1,7 +1,63 @@ +using MihaZupan.TelegramBotClients.RateLimitedClient; + namespace Navigator.Provider.Telegram { - public class NavigatorTelegramProviderOptionsExtensions + public static class NavigatorTelegramProviderOptionsExtensions { + #region SchedulerSettings + + private const string SchedulerSettingsKey = "_navigator.options.scheduler_settings"; + + public static void SetSchedulerSettings(this NavigatorTelegramProviderOptions navigatorOptions, SchedulerSettings schedulerSettings) + { + navigatorOptions.TryRegisterOption(SchedulerSettingsKey, schedulerSettings); + } + + public static SchedulerSettings GetSchedulerSettingsOrDefault(this INavigatorOptions navigatorOptions) + { + return navigatorOptions.RetrieveOption(SchedulerSettingsKey) ?? SchedulerSettings.Default; + } + + #endregion + #region TelegramToken + + private const string TelegramTokenKey = "_navigator.options.telegram_token"; + + public static void SetTelegramToken(this NavigatorOptions navigatorOptions, string telegramToken) + { + navigatorOptions.TryRegisterOption(TelegramTokenKey, telegramToken); + + } + + public static string? GetTelegramToken(this NavigatorOptions navigatorOptions) + { + return navigatorOptions.RetrieveOption(TelegramTokenKey); + } + + #endregion + + #region WebHookEndpoint + + private const string WebHookEndpointKey = "_navigator.options.webhook_endpoint"; + + public static void SetWebHookEndpoint(this NavigatorOptions navigatorOptions, string webHookEndpoint) + { + navigatorOptions.TryRegisterOption(WebHookEndpointKey, webHookEndpoint); + } + + public static string GetWebHookEndpointOrDefault(this NavigatorOptions navigatorOptions) + { + var webHookEndpoint = navigatorOptions.RetrieveOption(WebHookEndpointKey); + + if (webHookEndpoint is null) + { + navigatorOptions.SetWebHookEndpoint($"bot/{Guid.NewGuid()}"); + } + + return navigatorOptions.RetrieveOption(WebHookEndpointKey)!; + } + + #endregion } } \ No newline at end of file diff --git a/src/Navigator.sln b/src/Navigator.sln index 76befef..becb85f 100644 --- a/src/Navigator.sln +++ b/src/Navigator.sln @@ -34,6 +34,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Navigator.Extensions.Shipya EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Navigator.Extensions.Shipyard.Abstractions", "Navigator.Extensions.Shipyard.Abstractions\Navigator.Extensions.Shipyard.Abstractions.csproj", "{294C1716-C054-4585-B66E-C79D155AE684}" EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Providers", "Providers", "{DAA22477-BB29-475C-AD2C-905F81B4AD8E}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Navigator.Provider.Telegram", "Navigator.Provider.Telegram\Navigator.Provider.Telegram.csproj", "{8E0F6DCA-FAA4-4FA8-B9E0-75E9DC0F3573}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -80,6 +84,10 @@ Global {294C1716-C054-4585-B66E-C79D155AE684}.Debug|Any CPU.Build.0 = Debug|Any CPU {294C1716-C054-4585-B66E-C79D155AE684}.Release|Any CPU.ActiveCfg = Release|Any CPU {294C1716-C054-4585-B66E-C79D155AE684}.Release|Any CPU.Build.0 = Release|Any CPU + {8E0F6DCA-FAA4-4FA8-B9E0-75E9DC0F3573}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8E0F6DCA-FAA4-4FA8-B9E0-75E9DC0F3573}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8E0F6DCA-FAA4-4FA8-B9E0-75E9DC0F3573}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8E0F6DCA-FAA4-4FA8-B9E0-75E9DC0F3573}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(NestedProjects) = preSolution {7E8F867E-70E1-4C5B-AE65-A2C6822BFD6E} = {6D6A8E40-8C40-49AA-BEAD-B046D43F511A} @@ -97,5 +105,7 @@ Global {E2FF61C3-F081-40C8-9CC3-BBE1F81543F6} = {F178DCF2-AD03-44C8-AF8F-95C60664DD10} {90E6A9A5-BD73-4C9D-97A3-FA8021D16921} = {E2FF61C3-F081-40C8-9CC3-BBE1F81543F6} {294C1716-C054-4585-B66E-C79D155AE684} = {E2FF61C3-F081-40C8-9CC3-BBE1F81543F6} + {DAA22477-BB29-475C-AD2C-905F81B4AD8E} = {895808DE-1CA6-406C-924A-7E43F293CF7D} + {8E0F6DCA-FAA4-4FA8-B9E0-75E9DC0F3573} = {DAA22477-BB29-475C-AD2C-905F81B4AD8E} EndGlobalSection EndGlobal diff --git a/src/Navigator/NavigatorConfiguration.cs b/src/Navigator/NavigatorConfiguration.cs index 7dec197..9cf6fe7 100644 --- a/src/Navigator/NavigatorConfiguration.cs +++ b/src/Navigator/NavigatorConfiguration.cs @@ -7,7 +7,7 @@ namespace Navigator /// /// Helper functions for configuring navigator services. /// - public class NavigatorBuilder + public class NavigatorConfiguration { public NavigatorProviderConfiguration WithProvider { get; protected set; } @@ -28,12 +28,12 @@ public class NavigatorBuilder public IServiceCollection Services { get; private set; } /// - /// Creates a new instance of . + /// Creates a new instance of . /// /// The to use. /// The to attach to. - public NavigatorBuilder(Action options, IServiceCollection services) + public NavigatorConfiguration(Action options, IServiceCollection services) { Options = new NavigatorOptions(); options.Invoke(Options); @@ -52,5 +52,20 @@ public void RegisterOrReplaceOptions() public class NavigatorProviderConfiguration { + private readonly NavigatorConfiguration _navigatorConfiguration; + + public NavigatorProviderConfiguration(NavigatorConfiguration navigatorConfiguration) + { + _navigatorConfiguration = navigatorConfiguration; + } + + public NavigatorConfiguration Provider(Action? optionsAction, Action? servicesAction) + { + optionsAction?.Invoke(_navigatorConfiguration.Options); + + servicesAction?.Invoke(_navigatorConfiguration.Services); + + return _navigatorConfiguration; + } } } \ No newline at end of file diff --git a/src/Navigator/NavigatorOptions.cs b/src/Navigator/NavigatorOptions.cs index 4591fc8..7402039 100644 --- a/src/Navigator/NavigatorOptions.cs +++ b/src/Navigator/NavigatorOptions.cs @@ -1,12 +1,11 @@ using System.Collections.Generic; -using Navigator.Abstractions; namespace Navigator { /// /// Represents all the options you can use to configure the navigator framework. /// - public class NavigatorOptions : INavigatorOptions + public class NavigatorOptions { private readonly Dictionary _options; @@ -36,5 +35,28 @@ public bool ForceRegisterOption(string key, object option) return default; } + + public Dictionary RetrieveAllOptions() + { + return _options; + } + + public void Import(Dictionary options, bool overwrite = false) + { + if (overwrite) + { + foreach (var (key, option) in options) + { + ForceRegisterOption(key, option); + } + + return; + } + + foreach (var (key, option) in options) + { + TryRegisterOption(key, option); + } + } } } \ No newline at end of file diff --git a/src/Navigator/NavigatorServiceCollectionExtensions.cs b/src/Navigator/NavigatorServiceCollectionExtensions.cs index fd69b17..205d311 100644 --- a/src/Navigator/NavigatorServiceCollectionExtensions.cs +++ b/src/Navigator/NavigatorServiceCollectionExtensions.cs @@ -8,14 +8,14 @@ namespace Navigator { public static class NavigatorServiceCollectionExtensions { - public static NavigatorBuilder AddNavigator(this IServiceCollection services, Action options) + public static NavigatorConfiguration AddNavigator(this IServiceCollection services, Action options) { if (options == null) { throw new ArgumentNullException(nameof(options), "Navigator options are required for navigator framework to work."); } - var navigatorBuilder = new NavigatorBuilder(options, services); + var navigatorBuilder = new NavigatorConfiguration(options, services); services.AddSingleton(); diff --git a/src/Navigator/Old/NavigatorOptionsCollectionExtensions.cs b/src/Navigator/Old/NavigatorOptionsCollectionExtensions.cs index dbf9c17..86e945a 100644 --- a/src/Navigator/Old/NavigatorOptionsCollectionExtensions.cs +++ b/src/Navigator/Old/NavigatorOptionsCollectionExtensions.cs @@ -10,38 +10,7 @@ namespace Navigator /// public static class NavigatorOptionsCollectionExtensions { - #region SchedulerSettings - - private const string SchedulerSettingsKey = "_navigator.options.scheduler_settings"; - - public static void SetSchedulerSettings(this NavigatorOptions navigatorOptions, SchedulerSettings schedulerSettings) - { - navigatorOptions.TryRegisterOption(SchedulerSettingsKey, schedulerSettings); - } - - public static SchedulerSettings GetSchedulerSettingsOrDefault(this NavigatorOptions navigatorOptions) - { - return navigatorOptions.RetrieveOption(SchedulerSettingsKey) ?? SchedulerSettings.Default; - } - - #endregion - - #region TelegramToken - - private const string TelegramTokenKey = "_navigator.options.telegram_token"; - - public static void SetTelegramToken(this NavigatorOptions navigatorOptions, string telegramToken) - { - navigatorOptions.TryRegisterOption(TelegramTokenKey, telegramToken); - - } - - public static string? GetTelegramToken(this NavigatorOptions navigatorOptions) - { - return navigatorOptions.RetrieveOption(TelegramTokenKey); - } - - #endregion + #region WebHookBaseUrl @@ -60,28 +29,7 @@ public static void SetWebHookBaseUrl(this NavigatorOptions navigatorOptions, str #endregion - #region WebHookEndpoint - - private const string WebHookEndpointKey = "_navigator.options.webhook_endpoint"; - - public static void SetWebHookEndpoint(this NavigatorOptions navigatorOptions, string webHookEndpoint) - { - navigatorOptions.TryRegisterOption(WebHookEndpointKey, webHookEndpoint); - } - public static string GetWebHookEndpointOrDefault(this NavigatorOptions navigatorOptions) - { - var webHookEndpoint = navigatorOptions.RetrieveOption(WebHookEndpointKey); - - if (webHookEndpoint is null) - { - navigatorOptions.SetWebHookEndpoint($"bot/{Guid.NewGuid()}"); - } - - return navigatorOptions.RetrieveOption(WebHookEndpointKey)!; - } - - #endregion #region MultipleActions From dba4a6b26bc8511ed0a881fea5c384b8ebbdc5ca Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sun, 14 Feb 2021 13:05:42 +0100 Subject: [PATCH 003/304] Updated INavigatorOptions --- .../INavigatorOptions.cs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) rename src/{Navigator.Abstractions => Navigator}/INavigatorOptions.cs (58%) diff --git a/src/Navigator.Abstractions/INavigatorOptions.cs b/src/Navigator/INavigatorOptions.cs similarity index 58% rename from src/Navigator.Abstractions/INavigatorOptions.cs rename to src/Navigator/INavigatorOptions.cs index 12da1af..1b14468 100644 --- a/src/Navigator.Abstractions/INavigatorOptions.cs +++ b/src/Navigator/INavigatorOptions.cs @@ -1,4 +1,6 @@ -namespace Navigator.Abstractions +using System.Collections.Generic; + +namespace Navigator { /// /// @@ -8,5 +10,7 @@ public interface INavigatorOptions bool TryRegisterOption(string key, object option); bool ForceRegisterOption(string key, object option); TType? RetrieveOption(string key); + Dictionary RetrieveAllOptions(); + void Import(Dictionary options, bool overwrite = false); } } \ No newline at end of file From a71ce04051e1e5b4f1b5cb4639793adeaf5e810e Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sun, 14 Feb 2021 13:11:45 +0100 Subject: [PATCH 004/304] Updated static method for options --- .../NavigatorTelegramProviderOptionsExtensions.cs | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/Navigator.Provider.Telegram/NavigatorTelegramProviderOptionsExtensions.cs b/src/Navigator.Provider.Telegram/NavigatorTelegramProviderOptionsExtensions.cs index 8d1cd7f..06e6089 100644 --- a/src/Navigator.Provider.Telegram/NavigatorTelegramProviderOptionsExtensions.cs +++ b/src/Navigator.Provider.Telegram/NavigatorTelegramProviderOptionsExtensions.cs @@ -1,3 +1,4 @@ +using System; using MihaZupan.TelegramBotClients.RateLimitedClient; namespace Navigator.Provider.Telegram @@ -24,13 +25,13 @@ public static SchedulerSettings GetSchedulerSettingsOrDefault(this INavigatorOpt private const string TelegramTokenKey = "_navigator.options.telegram_token"; - public static void SetTelegramToken(this NavigatorOptions navigatorOptions, string telegramToken) + public static void SetTelegramToken(this NavigatorTelegramProviderOptions navigatorOptions, string telegramToken) { navigatorOptions.TryRegisterOption(TelegramTokenKey, telegramToken); } - public static string? GetTelegramToken(this NavigatorOptions navigatorOptions) + public static string? GetTelegramToken(this INavigatorOptions navigatorOptions) { return navigatorOptions.RetrieveOption(TelegramTokenKey); } @@ -41,18 +42,18 @@ public static void SetTelegramToken(this NavigatorOptions navigatorOptions, stri private const string WebHookEndpointKey = "_navigator.options.webhook_endpoint"; - public static void SetWebHookEndpoint(this NavigatorOptions navigatorOptions, string webHookEndpoint) + public static void SetWebHookEndpoint(this NavigatorTelegramProviderOptions navigatorOptions, string webHookEndpoint) { navigatorOptions.TryRegisterOption(WebHookEndpointKey, webHookEndpoint); } - public static string GetWebHookEndpointOrDefault(this NavigatorOptions navigatorOptions) + public static string GetWebHookEndpointOrDefault(this INavigatorOptions navigatorOptions) { var webHookEndpoint = navigatorOptions.RetrieveOption(WebHookEndpointKey); if (webHookEndpoint is null) { - navigatorOptions.SetWebHookEndpoint($"bot/{Guid.NewGuid()}"); + navigatorOptions.TryRegisterOption(WebHookEndpointKey,$"bot/{Guid.NewGuid()}"); } return navigatorOptions.RetrieveOption(WebHookEndpointKey)!; From dd0db5ffadf457225309b8f2d2ec57426d4f440d Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sun, 14 Feb 2021 13:18:21 +0100 Subject: [PATCH 005/304] Added interface to NavigatorOptions --- src/Navigator/NavigatorOptions.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Navigator/NavigatorOptions.cs b/src/Navigator/NavigatorOptions.cs index 7402039..8c1dce5 100644 --- a/src/Navigator/NavigatorOptions.cs +++ b/src/Navigator/NavigatorOptions.cs @@ -5,7 +5,7 @@ namespace Navigator /// /// Represents all the options you can use to configure the navigator framework. /// - public class NavigatorOptions + public class NavigatorOptions : INavigatorOptions { private readonly Dictionary _options; From 0fd777279ee731d386aca94f8c5a7e1178978119 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sun, 14 Feb 2021 13:20:45 +0100 Subject: [PATCH 006/304] Moved hosted service to provider package --- .../Hosted/SetTelegramBotWebHookHostedService.cs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) rename src/{Navigator/Old => Navigator.Provider.Telegram}/Hosted/SetTelegramBotWebHookHostedService.cs (95%) diff --git a/src/Navigator/Old/Hosted/SetTelegramBotWebHookHostedService.cs b/src/Navigator.Provider.Telegram/Hosted/SetTelegramBotWebHookHostedService.cs similarity index 95% rename from src/Navigator/Old/Hosted/SetTelegramBotWebHookHostedService.cs rename to src/Navigator.Provider.Telegram/Hosted/SetTelegramBotWebHookHostedService.cs index 56634ed..d54799b 100644 --- a/src/Navigator/Old/Hosted/SetTelegramBotWebHookHostedService.cs +++ b/src/Navigator.Provider.Telegram/Hosted/SetTelegramBotWebHookHostedService.cs @@ -4,13 +4,12 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Options; using Navigator.Abstractions; -namespace Navigator.Hosted +namespace Navigator.Provider.Telegram.Hosted { /// - /// WebHook service for Navigator. + /// WebHook service for navigator's telegram provider. /// public class SetTelegramBotWebHookHostedService : BackgroundService { From 452f6f60322ed867fc83024e9790c6ec7c5836e6 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sun, 14 Feb 2021 13:47:13 +0100 Subject: [PATCH 007/304] Created NavigatorProviderConfiguration --- .../NavigatorProviderConfiguration.cs | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 src/Navigator/Provider/NavigatorProviderConfiguration.cs diff --git a/src/Navigator/Provider/NavigatorProviderConfiguration.cs b/src/Navigator/Provider/NavigatorProviderConfiguration.cs new file mode 100644 index 0000000..879fa60 --- /dev/null +++ b/src/Navigator/Provider/NavigatorProviderConfiguration.cs @@ -0,0 +1,37 @@ +using System; +using Microsoft.Extensions.DependencyInjection; + +namespace Navigator.Provider +{ + /// + /// Provides a entry point for configuring new providers for Navigator. + /// + public class NavigatorProviderConfiguration + { + private readonly NavigatorConfiguration _navigatorConfiguration; + + /// + /// Default constructor for . + /// + /// + public NavigatorProviderConfiguration(NavigatorConfiguration navigatorConfiguration) + { + _navigatorConfiguration = navigatorConfiguration; + } + + /// + /// Configure a new provider using this method. + /// + /// + /// + /// + public NavigatorConfiguration Provider(Action? optionsAction, Action? servicesAction) + { + optionsAction?.Invoke(_navigatorConfiguration.Options); + + servicesAction?.Invoke(_navigatorConfiguration.Services); + + return _navigatorConfiguration; + } + } +} \ No newline at end of file From ae7cda3b7b185e6595b98b59e5173d828bd6ace0 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sun, 14 Feb 2021 13:47:45 +0100 Subject: [PATCH 008/304] Moved back EndpointRouteBuilderExtensions --- src/Navigator/{Old => }/EndpointRouteBuilderExtensions.cs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) rename src/Navigator/{Old => }/EndpointRouteBuilderExtensions.cs (82%) diff --git a/src/Navigator/Old/EndpointRouteBuilderExtensions.cs b/src/Navigator/EndpointRouteBuilderExtensions.cs similarity index 82% rename from src/Navigator/Old/EndpointRouteBuilderExtensions.cs rename to src/Navigator/EndpointRouteBuilderExtensions.cs index 2bb80e4..ba67af4 100644 --- a/src/Navigator/Old/EndpointRouteBuilderExtensions.cs +++ b/src/Navigator/EndpointRouteBuilderExtensions.cs @@ -10,14 +10,18 @@ namespace Navigator { public static class EndpointRouteBuilderExtensions { - public static void MapNavigator(this IEndpointRouteBuilder endpointRouteBuilder) + public static NavigatorRouteConfiguration MapNavigator(this IEndpointRouteBuilder endpointRouteBuilder) { using var scope = endpointRouteBuilder.ServiceProvider.CreateScope(); var options = scope.ServiceProvider.GetRequiredService(); endpointRouteBuilder.MapPost(options.GetWebHookEndpointOrDefault(), ProcessTelegramUpdate); + + return new NavigatorRouteConfiguration(endpointRouteBuilder); } + + public static private static async Task ProcessTelegramUpdate(HttpContext context) { From 9ab31aedf322d1c131d50b2c14908d043926dd73 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sun, 14 Feb 2021 13:48:21 +0100 Subject: [PATCH 009/304] Updated NavigatorConfiguration to include Provider --- src/Navigator/NavigatorConfiguration.cs | 24 ++++-------------------- 1 file changed, 4 insertions(+), 20 deletions(-) diff --git a/src/Navigator/NavigatorConfiguration.cs b/src/Navigator/NavigatorConfiguration.cs index 9cf6fe7..c513d52 100644 --- a/src/Navigator/NavigatorConfiguration.cs +++ b/src/Navigator/NavigatorConfiguration.cs @@ -1,6 +1,7 @@ using System; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; +using Navigator.Provider; namespace Navigator { @@ -9,7 +10,7 @@ namespace Navigator /// public class NavigatorConfiguration { - public NavigatorProviderConfiguration WithProvider { get; protected set; } + public NavigatorProviderConfiguration WithProvider { get; internal set; } /// /// Gets the that are being used. @@ -41,6 +42,8 @@ public NavigatorConfiguration(Action options, IServiceCollecti Services = services; services.AddSingleton(Options); + + WithProvider = new NavigatorProviderConfiguration(this); } @@ -49,23 +52,4 @@ public void RegisterOrReplaceOptions() Services.Replace(ServiceDescriptor.Singleton(Options)); } } - - public class NavigatorProviderConfiguration - { - private readonly NavigatorConfiguration _navigatorConfiguration; - - public NavigatorProviderConfiguration(NavigatorConfiguration navigatorConfiguration) - { - _navigatorConfiguration = navigatorConfiguration; - } - - public NavigatorConfiguration Provider(Action? optionsAction, Action? servicesAction) - { - optionsAction?.Invoke(_navigatorConfiguration.Options); - - servicesAction?.Invoke(_navigatorConfiguration.Services); - - return _navigatorConfiguration; - } - } } \ No newline at end of file From 557a20101b033fe0bbe75538a43cfed5fba3d111 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sun, 14 Feb 2021 13:48:37 +0100 Subject: [PATCH 010/304] Started work on NavigatorRouteConfiguration --- src/Navigator/NavigatorRouteConfiguration.cs | 20 +++++++++++++ .../NavigatorRouteProviderConfiguration.cs | 29 +++++++++++++++++++ 2 files changed, 49 insertions(+) create mode 100644 src/Navigator/NavigatorRouteConfiguration.cs create mode 100644 src/Navigator/Provider/NavigatorRouteProviderConfiguration.cs diff --git a/src/Navigator/NavigatorRouteConfiguration.cs b/src/Navigator/NavigatorRouteConfiguration.cs new file mode 100644 index 0000000..04cd285 --- /dev/null +++ b/src/Navigator/NavigatorRouteConfiguration.cs @@ -0,0 +1,20 @@ +using Microsoft.AspNetCore.Routing; +using Navigator.Provider; + +namespace Navigator +{ + public class NavigatorRouteConfiguration + { + private readonly IEndpointRouteBuilder _endpointRouteBuilder; + + public NavigatorRouteProviderConfiguration ForProvider { get; set; } + + public NavigatorRouteConfiguration(IEndpointRouteBuilder endpointRouteBuilder) + { + _endpointRouteBuilder = endpointRouteBuilder; + + ForProvider = new NavigatorRouteProviderConfiguration(this); + } + + } +} \ No newline at end of file diff --git a/src/Navigator/Provider/NavigatorRouteProviderConfiguration.cs b/src/Navigator/Provider/NavigatorRouteProviderConfiguration.cs new file mode 100644 index 0000000..ebd7069 --- /dev/null +++ b/src/Navigator/Provider/NavigatorRouteProviderConfiguration.cs @@ -0,0 +1,29 @@ +using Microsoft.Extensions.DependencyInjection; + +namespace Navigator.Provider +{ + public class NavigatorRouteProviderConfiguration + { + private readonly NavigatorRouteConfiguration _navigatorRouteConfiguration; + + public NavigatorRouteProviderConfiguration(NavigatorRouteConfiguration navigatorRouteConfiguration) + { + _navigatorRouteConfiguration = navigatorRouteConfiguration; + } + + /// + /// Configure a new provider using this method. + /// + /// + /// + /// + public NavigatorRouteConfiguration Provider() + { + optionsAction?.Invoke(_navigatorConfiguration.Options); + + servicesAction?.Invoke(_navigatorConfiguration.Services); + + return _navigatorConfiguration; + } + } +} \ No newline at end of file From 7f812384823f2587d41126ef306d20aef54aaca2 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sun, 14 Feb 2021 13:49:09 +0100 Subject: [PATCH 011/304] fixed small typo --- .../NavigatorProviderConfigurationExtension.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Navigator.Provider.Telegram/NavigatorProviderConfigurationExtension.cs b/src/Navigator.Provider.Telegram/NavigatorProviderConfigurationExtension.cs index d5e7d73..b9b0f50 100644 --- a/src/Navigator.Provider.Telegram/NavigatorProviderConfigurationExtension.cs +++ b/src/Navigator.Provider.Telegram/NavigatorProviderConfigurationExtension.cs @@ -2,7 +2,7 @@ namespace Navigator.Provider.Telegram { - public static class NavigatorProviderConfigurationExtension + public static class NavigatorProviderConfigurationExtensions { public static NavigatorConfiguration Telegram(this NavigatorProviderConfiguration providerConfiguration, Action options) From 9ce9bee6b10957bec3b0dc974c1fe5b39f684c92 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sun, 14 Feb 2021 13:49:18 +0100 Subject: [PATCH 012/304] Renamed class --- ...eCollectionExtensions.cs => ServiceCollectionExtensions.cs} | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) rename src/Navigator/{NavigatorServiceCollectionExtensions.cs => ServiceCollectionExtensions.cs} (94%) diff --git a/src/Navigator/NavigatorServiceCollectionExtensions.cs b/src/Navigator/ServiceCollectionExtensions.cs similarity index 94% rename from src/Navigator/NavigatorServiceCollectionExtensions.cs rename to src/Navigator/ServiceCollectionExtensions.cs index 205d311..1629f32 100644 --- a/src/Navigator/NavigatorServiceCollectionExtensions.cs +++ b/src/Navigator/ServiceCollectionExtensions.cs @@ -1,12 +1,11 @@ using System; using Microsoft.Extensions.DependencyInjection; using Navigator.Abstractions; -using Navigator.Hosted; using Scrutor; namespace Navigator { - public static class NavigatorServiceCollectionExtensions + public static class ServiceCollectionExtensions { public static NavigatorConfiguration AddNavigator(this IServiceCollection services, Action options) { From 261c648d01b083c5446a45fc8ee487ea18dc6d35 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sun, 14 Feb 2021 13:49:31 +0100 Subject: [PATCH 013/304] Created NavigatorRouteProviderConfigurationExtensions in telegram provider --- .../NavigatorRouteProviderConfigurationExtensions.cs | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 src/Navigator.Provider.Telegram/NavigatorRouteProviderConfigurationExtensions.cs diff --git a/src/Navigator.Provider.Telegram/NavigatorRouteProviderConfigurationExtensions.cs b/src/Navigator.Provider.Telegram/NavigatorRouteProviderConfigurationExtensions.cs new file mode 100644 index 0000000..1071a74 --- /dev/null +++ b/src/Navigator.Provider.Telegram/NavigatorRouteProviderConfigurationExtensions.cs @@ -0,0 +1,7 @@ +namespace Navigator.Provider.Telegram +{ + public class NavigatorRouteProviderConfigurationExtensions + { + + } +} \ No newline at end of file From a96f8fd90381e0f970ea9a4f7fb29d69ab719132 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sun, 14 Feb 2021 13:54:39 +0100 Subject: [PATCH 014/304] updated setters --- src/Navigator/NavigatorConfiguration.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Navigator/NavigatorConfiguration.cs b/src/Navigator/NavigatorConfiguration.cs index c513d52..13d101d 100644 --- a/src/Navigator/NavigatorConfiguration.cs +++ b/src/Navigator/NavigatorConfiguration.cs @@ -18,7 +18,7 @@ public class NavigatorConfiguration /// /// The /// - public NavigatorOptions Options { get; private set; } + public NavigatorOptions Options { get; internal set; } /// /// Gets the services are attached to. @@ -26,7 +26,7 @@ public class NavigatorConfiguration /// /// The services are attached to. /// - public IServiceCollection Services { get; private set; } + public IServiceCollection Services { get; internal set; } /// /// Creates a new instance of . From 12e01ce0c7d7043bc4cb06d7aefee3733f2280a2 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sun, 14 Feb 2021 13:54:59 +0100 Subject: [PATCH 015/304] More work on route configuration --- src/Navigator/NavigatorRouteConfiguration.cs | 4 ++-- .../NavigatorRouteProviderConfiguration.cs | 18 ++++++------------ 2 files changed, 8 insertions(+), 14 deletions(-) diff --git a/src/Navigator/NavigatorRouteConfiguration.cs b/src/Navigator/NavigatorRouteConfiguration.cs index 04cd285..4d6b616 100644 --- a/src/Navigator/NavigatorRouteConfiguration.cs +++ b/src/Navigator/NavigatorRouteConfiguration.cs @@ -5,13 +5,13 @@ namespace Navigator { public class NavigatorRouteConfiguration { - private readonly IEndpointRouteBuilder _endpointRouteBuilder; + public IEndpointRouteBuilder EndpointRouteBuilder { get; internal set; } public NavigatorRouteProviderConfiguration ForProvider { get; set; } public NavigatorRouteConfiguration(IEndpointRouteBuilder endpointRouteBuilder) { - _endpointRouteBuilder = endpointRouteBuilder; + EndpointRouteBuilder = endpointRouteBuilder; ForProvider = new NavigatorRouteProviderConfiguration(this); } diff --git a/src/Navigator/Provider/NavigatorRouteProviderConfiguration.cs b/src/Navigator/Provider/NavigatorRouteProviderConfiguration.cs index ebd7069..ec6d7c9 100644 --- a/src/Navigator/Provider/NavigatorRouteProviderConfiguration.cs +++ b/src/Navigator/Provider/NavigatorRouteProviderConfiguration.cs @@ -1,3 +1,5 @@ +using System; +using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.DependencyInjection; namespace Navigator.Provider @@ -10,20 +12,12 @@ public NavigatorRouteProviderConfiguration(NavigatorRouteConfiguration navigator { _navigatorRouteConfiguration = navigatorRouteConfiguration; } - - /// - /// Configure a new provider using this method. - /// - /// - /// - /// - public NavigatorRouteConfiguration Provider() + + public NavigatorRouteConfiguration Provider(Action routeActions) { - optionsAction?.Invoke(_navigatorConfiguration.Options); - - servicesAction?.Invoke(_navigatorConfiguration.Services); + routeActions.Invoke(_navigatorRouteConfiguration.EndpointRouteBuilder); - return _navigatorConfiguration; + return _navigatorRouteConfiguration; } } } \ No newline at end of file From a323316316e4f3b70208bf628531dac7069e94be Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sun, 14 Feb 2021 13:59:51 +0100 Subject: [PATCH 016/304] Moved telegram endpoint building to provider --- ...torRouteProviderConfigurationExtensions.cs | 30 ++++++++++++++++++- .../EndpointRouteBuilderExtensions.cs | 20 ------------- 2 files changed, 29 insertions(+), 21 deletions(-) diff --git a/src/Navigator.Provider.Telegram/NavigatorRouteProviderConfigurationExtensions.cs b/src/Navigator.Provider.Telegram/NavigatorRouteProviderConfigurationExtensions.cs index 1071a74..09686bc 100644 --- a/src/Navigator.Provider.Telegram/NavigatorRouteProviderConfigurationExtensions.cs +++ b/src/Navigator.Provider.Telegram/NavigatorRouteProviderConfigurationExtensions.cs @@ -1,7 +1,35 @@ +using System.Threading.Tasks; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using Navigator.Abstractions; + namespace Navigator.Provider.Telegram { - public class NavigatorRouteProviderConfigurationExtensions + public static class NavigatorRouteProviderConfigurationExtensions { + public static NavigatorRouteConfiguration Telegram(this NavigatorRouteProviderConfiguration routeProviderConfiguration) + { + return routeProviderConfiguration.Provider(builder => + { + using var scope = builder.ServiceProvider.CreateScope(); + + var options = scope.ServiceProvider.GetRequiredService(); + + builder.MapPost(options.GetWebHookEndpointOrDefault(), ProcessTelegramUpdate); + }); + } + private static async Task ProcessTelegramUpdate(HttpContext context) + { + context.Response.StatusCode = 200; + + if (context.Request.ContentType == "application/json") + { + var navigatorMiddleware = context.RequestServices.GetRequiredService(); + + await navigatorMiddleware.Handle(context.Request); + } + } } } \ No newline at end of file diff --git a/src/Navigator/EndpointRouteBuilderExtensions.cs b/src/Navigator/EndpointRouteBuilderExtensions.cs index ba67af4..9d81d42 100644 --- a/src/Navigator/EndpointRouteBuilderExtensions.cs +++ b/src/Navigator/EndpointRouteBuilderExtensions.cs @@ -12,27 +12,7 @@ public static class EndpointRouteBuilderExtensions { public static NavigatorRouteConfiguration MapNavigator(this IEndpointRouteBuilder endpointRouteBuilder) { - using var scope = endpointRouteBuilder.ServiceProvider.CreateScope(); - - var options = scope.ServiceProvider.GetRequiredService(); - - endpointRouteBuilder.MapPost(options.GetWebHookEndpointOrDefault(), ProcessTelegramUpdate); - return new NavigatorRouteConfiguration(endpointRouteBuilder); } - - public static - - private static async Task ProcessTelegramUpdate(HttpContext context) - { - context.Response.StatusCode = 200; - - if (context.Request.ContentType == "application/json") - { - var navigatorMiddleware = context.RequestServices.GetRequiredService(); - - await navigatorMiddleware.Handle(context.Request); - } - } } } \ No newline at end of file From 77315af4f419d6fe51f2a09320af01610375709c Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sun, 14 Feb 2021 14:17:47 +0100 Subject: [PATCH 017/304] Cleaned endpoint route builder --- src/Navigator/EndpointRouteBuilderExtensions.cs | 13 ++++++------- src/Navigator/NavigatorRouteConfiguration.cs | 3 +-- 2 files changed, 7 insertions(+), 9 deletions(-) diff --git a/src/Navigator/EndpointRouteBuilderExtensions.cs b/src/Navigator/EndpointRouteBuilderExtensions.cs index 9d81d42..3a65240 100644 --- a/src/Navigator/EndpointRouteBuilderExtensions.cs +++ b/src/Navigator/EndpointRouteBuilderExtensions.cs @@ -1,18 +1,17 @@ -using System.Threading.Tasks; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Routing; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Options; -using Navigator.Abstractions; namespace Navigator { public static class EndpointRouteBuilderExtensions { + /// + /// Configure navigator's provider's endpoints. + /// + /// + /// public static NavigatorRouteConfiguration MapNavigator(this IEndpointRouteBuilder endpointRouteBuilder) { - return new NavigatorRouteConfiguration(endpointRouteBuilder); + return new(endpointRouteBuilder); } } } \ No newline at end of file diff --git a/src/Navigator/NavigatorRouteConfiguration.cs b/src/Navigator/NavigatorRouteConfiguration.cs index 4d6b616..6a17241 100644 --- a/src/Navigator/NavigatorRouteConfiguration.cs +++ b/src/Navigator/NavigatorRouteConfiguration.cs @@ -7,7 +7,7 @@ public class NavigatorRouteConfiguration { public IEndpointRouteBuilder EndpointRouteBuilder { get; internal set; } - public NavigatorRouteProviderConfiguration ForProvider { get; set; } + public NavigatorRouteProviderConfiguration ForProvider { get; internal set; } public NavigatorRouteConfiguration(IEndpointRouteBuilder endpointRouteBuilder) { @@ -15,6 +15,5 @@ public NavigatorRouteConfiguration(IEndpointRouteBuilder endpointRouteBuilder) ForProvider = new NavigatorRouteProviderConfiguration(this); } - } } \ No newline at end of file From 22d76c6d8d2de75a1274547570cc6abefaeb9919 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sun, 14 Feb 2021 14:18:52 +0100 Subject: [PATCH 018/304] Moved bot client to provider --- src/Navigator.Abstractions/Old/IBotClient.cs | 8 -------- .../NavigatorTelegramClient.cs | 13 +++++++++++++ src/Navigator/INavigatorClient.cs | 7 +++++++ src/Navigator/Old/BotClient.cs | 16 ---------------- 4 files changed, 20 insertions(+), 24 deletions(-) delete mode 100644 src/Navigator.Abstractions/Old/IBotClient.cs create mode 100644 src/Navigator.Provider.Telegram/NavigatorTelegramClient.cs create mode 100644 src/Navigator/INavigatorClient.cs delete mode 100644 src/Navigator/Old/BotClient.cs diff --git a/src/Navigator.Abstractions/Old/IBotClient.cs b/src/Navigator.Abstractions/Old/IBotClient.cs deleted file mode 100644 index bdd0817..0000000 --- a/src/Navigator.Abstractions/Old/IBotClient.cs +++ /dev/null @@ -1,8 +0,0 @@ -using Telegram.Bot; - -namespace Navigator.Abstractions -{ - public interface IBotClient : ITelegramBotClient - { - } -} \ No newline at end of file diff --git a/src/Navigator.Provider.Telegram/NavigatorTelegramClient.cs b/src/Navigator.Provider.Telegram/NavigatorTelegramClient.cs new file mode 100644 index 0000000..4a0c1ea --- /dev/null +++ b/src/Navigator.Provider.Telegram/NavigatorTelegramClient.cs @@ -0,0 +1,13 @@ +using System.Net.Http; +using MihaZupan.TelegramBotClients; + +namespace Navigator.Provider.Telegram +{ + public class NavigatorTelegramClient : RateLimitedTelegramBotClient, INavigatorClient + { + public NavigatorTelegramClient(NavigatorOptions options) + : base(options.GetTelegramToken(), (HttpClient) default!, options.GetSchedulerSettingsOrDefault()) + { + } + } +} \ No newline at end of file diff --git a/src/Navigator/INavigatorClient.cs b/src/Navigator/INavigatorClient.cs new file mode 100644 index 0000000..f2b96b7 --- /dev/null +++ b/src/Navigator/INavigatorClient.cs @@ -0,0 +1,7 @@ +namespace Navigator +{ + public interface INavigatorClient + { + + } +} \ No newline at end of file diff --git a/src/Navigator/Old/BotClient.cs b/src/Navigator/Old/BotClient.cs deleted file mode 100644 index 65dce5b..0000000 --- a/src/Navigator/Old/BotClient.cs +++ /dev/null @@ -1,16 +0,0 @@ -using System.Net.Http; -using Microsoft.Extensions.Options; -using MihaZupan.TelegramBotClients; -using Navigator.Abstractions; - -namespace Navigator -{ - /// - public class BotClient : RateLimitedTelegramBotClient, IBotClient - { - /// - public BotClient(NavigatorOptions options) : base(options.GetTelegramToken(), (HttpClient) default!, options.GetSchedulerSettingsOrDefault()) - { - } - } -} \ No newline at end of file From dff368e03c1879ed5a7986819e2e8e4c85ffcf4f Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sun, 14 Feb 2021 14:28:55 +0100 Subject: [PATCH 019/304] Moved provider services to provider --- .../Hosted/SetTelegramBotWebHookHostedService.cs | 6 +++--- .../Navigator.Provider.Telegram.csproj | 2 +- .../NavigatorProviderConfigurationExtension.cs | 13 +++++++++++-- src/Navigator/ServiceCollectionExtensions.cs | 3 --- 4 files changed, 15 insertions(+), 9 deletions(-) diff --git a/src/Navigator.Provider.Telegram/Hosted/SetTelegramBotWebHookHostedService.cs b/src/Navigator.Provider.Telegram/Hosted/SetTelegramBotWebHookHostedService.cs index d54799b..758f380 100644 --- a/src/Navigator.Provider.Telegram/Hosted/SetTelegramBotWebHookHostedService.cs +++ b/src/Navigator.Provider.Telegram/Hosted/SetTelegramBotWebHookHostedService.cs @@ -46,11 +46,11 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken) using var scope = _serviceScopeFactory.CreateScope(); - var botClient = scope.ServiceProvider.GetRequiredService(); + var navigatorClient = scope.ServiceProvider.GetRequiredService(); - await botClient.SetWebhookAsync(_webHookUrl, cancellationToken: stoppingToken); + await navigatorClient.SetWebhookAsync(_webHookUrl, cancellationToken: stoppingToken); - var me = await botClient.GetMeAsync(stoppingToken); + var me = await navigatorClient.GetMeAsync(stoppingToken); _logger.LogInformation($"Telegram Bot Client is receiving updates for bot: @{me.Username} at the url: {_webHookUrl}"); } diff --git a/src/Navigator.Provider.Telegram/Navigator.Provider.Telegram.csproj b/src/Navigator.Provider.Telegram/Navigator.Provider.Telegram.csproj index a59f094..d45fcd2 100644 --- a/src/Navigator.Provider.Telegram/Navigator.Provider.Telegram.csproj +++ b/src/Navigator.Provider.Telegram/Navigator.Provider.Telegram.csproj @@ -4,7 +4,7 @@ net5.0 enable - + diff --git a/src/Navigator.Provider.Telegram/NavigatorProviderConfigurationExtension.cs b/src/Navigator.Provider.Telegram/NavigatorProviderConfigurationExtension.cs index b9b0f50..695f6a3 100644 --- a/src/Navigator.Provider.Telegram/NavigatorProviderConfigurationExtension.cs +++ b/src/Navigator.Provider.Telegram/NavigatorProviderConfigurationExtension.cs @@ -1,4 +1,6 @@ using System; +using Microsoft.Extensions.DependencyInjection; +using Navigator.Provider.Telegram.Hosted; namespace Navigator.Provider.Telegram { @@ -11,8 +13,15 @@ public static NavigatorConfiguration Telegram(this NavigatorProviderConfiguratio options.Invoke(telegramProviderOptions); return providerConfiguration.Provider( - optionsAction => optionsAction.Import(optionsAction.RetrieveAllOptions()), - null); + optionsAction => optionsAction.Import(optionsAction.RetrieveAllOptions()), + services => + { + services.AddSingleton(); + services.AddSingleton(sp => sp.GetRequiredService()); + + services.AddHostedService(); + + }); } } } \ No newline at end of file diff --git a/src/Navigator/ServiceCollectionExtensions.cs b/src/Navigator/ServiceCollectionExtensions.cs index 1629f32..7e42720 100644 --- a/src/Navigator/ServiceCollectionExtensions.cs +++ b/src/Navigator/ServiceCollectionExtensions.cs @@ -16,9 +16,6 @@ public static NavigatorConfiguration AddNavigator(this IServiceCollection servic var navigatorBuilder = new NavigatorConfiguration(options, services); - services.AddSingleton(); - - services.AddHostedService(); services.AddScoped(); services.AddScoped(); services.AddScoped(); From b5272d46f90407e36cce3ad59550f904efbcc8b6 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sun, 14 Feb 2021 14:48:49 +0100 Subject: [PATCH 020/304] Moved Options extensions --- .../{Old => }/NavigatorOptionsCollectionExtensions.cs | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) rename src/Navigator/{Old => }/NavigatorOptionsCollectionExtensions.cs (98%) diff --git a/src/Navigator/Old/NavigatorOptionsCollectionExtensions.cs b/src/Navigator/NavigatorOptionsCollectionExtensions.cs similarity index 98% rename from src/Navigator/Old/NavigatorOptionsCollectionExtensions.cs rename to src/Navigator/NavigatorOptionsCollectionExtensions.cs index 86e945a..3074ed2 100644 --- a/src/Navigator/Old/NavigatorOptionsCollectionExtensions.cs +++ b/src/Navigator/NavigatorOptionsCollectionExtensions.cs @@ -6,12 +6,10 @@ namespace Navigator { /// - /// + /// Navigator Configuration Options. /// public static class NavigatorOptionsCollectionExtensions { - - #region WebHookBaseUrl private const string WebHookBaseUrlKey = "_navigator.options.webhook_base_url"; @@ -29,8 +27,6 @@ public static void SetWebHookBaseUrl(this NavigatorOptions navigatorOptions, str #endregion - - #region MultipleActions private const string MultipleActionsKey = "_navigator.options.multiple_actions"; From 3d8d20f56ae1a5f1b2b9da852f6dbba721649624 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sun, 14 Feb 2021 14:49:40 +0100 Subject: [PATCH 021/304] Moved INavigatorContext yo base package --- .../Old => Navigator}/INavigatorContext.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename src/{Navigator.Abstractions/Old => Navigator}/INavigatorContext.cs (90%) diff --git a/src/Navigator.Abstractions/Old/INavigatorContext.cs b/src/Navigator/INavigatorContext.cs similarity index 90% rename from src/Navigator.Abstractions/Old/INavigatorContext.cs rename to src/Navigator/INavigatorContext.cs index 44f1898..97ca33e 100644 --- a/src/Navigator.Abstractions/Old/INavigatorContext.cs +++ b/src/Navigator/INavigatorContext.cs @@ -7,7 +7,7 @@ namespace Navigator.Abstractions public interface INavigatorContext { Dictionary Items { get; } - public IBotClient Client { get; } + public INavigatorClient Client { get; } public User BotProfile { get; } public Update Update { get; } From 207c11a6db1af399998e92087a926e4434ff453d Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sun, 14 Feb 2021 14:51:22 +0100 Subject: [PATCH 022/304] Updated logic in NavigatorProviderConfiguration --- src/Navigator/Provider/NavigatorProviderConfiguration.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/Navigator/Provider/NavigatorProviderConfiguration.cs b/src/Navigator/Provider/NavigatorProviderConfiguration.cs index 879fa60..77ceb9b 100644 --- a/src/Navigator/Provider/NavigatorProviderConfiguration.cs +++ b/src/Navigator/Provider/NavigatorProviderConfiguration.cs @@ -28,9 +28,11 @@ public NavigatorProviderConfiguration(NavigatorConfiguration navigatorConfigurat public NavigatorConfiguration Provider(Action? optionsAction, Action? servicesAction) { optionsAction?.Invoke(_navigatorConfiguration.Options); - + servicesAction?.Invoke(_navigatorConfiguration.Services); + _navigatorConfiguration.RegisterOrReplaceOptions(); + return _navigatorConfiguration; } } From f8b07cf1c19732caca1aef698e1f1bc5e935f7a4 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sun, 14 Feb 2021 14:51:57 +0100 Subject: [PATCH 023/304] IBotClient => NavigatorTelegramClient --- .../Hosted/SetTelegramBotWebHookHostedService.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Navigator.Provider.Telegram/Hosted/SetTelegramBotWebHookHostedService.cs b/src/Navigator.Provider.Telegram/Hosted/SetTelegramBotWebHookHostedService.cs index 758f380..2f383de 100644 --- a/src/Navigator.Provider.Telegram/Hosted/SetTelegramBotWebHookHostedService.cs +++ b/src/Navigator.Provider.Telegram/Hosted/SetTelegramBotWebHookHostedService.cs @@ -46,7 +46,7 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken) using var scope = _serviceScopeFactory.CreateScope(); - var navigatorClient = scope.ServiceProvider.GetRequiredService(); + var navigatorClient = scope.ServiceProvider.GetRequiredService(); await navigatorClient.SetWebhookAsync(_webHookUrl, cancellationToken: stoppingToken); From 3b47624dd3c7f96a4afe59ab075e61bad1747bc5 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sun, 14 Feb 2021 14:53:57 +0100 Subject: [PATCH 024/304] Adjusted some namespaces --- .../Hosted/SetTelegramBotWebHookHostedService.cs | 1 + .../NavigatorProviderConfigurationExtension.cs | 2 ++ .../NavigatorRouteProviderConfigurationExtensions.cs | 2 ++ src/Navigator.Provider.Telegram/NavigatorTelegramClient.cs | 1 + .../NavigatorTelegramProviderOptions.cs | 2 ++ .../NavigatorTelegramProviderOptionsExtensions.cs | 1 + src/Navigator.Samples.Echo/Startup.cs | 1 + .../{ => Configuration}/EndpointRouteBuilderExtensions.cs | 2 +- src/Navigator/{ => Configuration}/INavigatorOptions.cs | 2 +- .../{ => Configuration}/NavigatorConfiguration.cs | 4 ++-- src/Navigator/{ => Configuration}/NavigatorOptions.cs | 2 +- .../NavigatorOptionsCollectionExtensions.cs | 4 +--- .../{ => Configuration}/NavigatorRouteConfiguration.cs | 4 ++-- .../Provider/NavigatorProviderConfiguration.cs | 2 +- .../Provider/NavigatorRouteProviderConfiguration.cs | 3 +-- src/Navigator/INavigatorContext.cs | 2 +- src/Navigator/Old/ActionLauncher.cs | 4 ++-- src/Navigator/Old/NavigatorContext.cs | 7 +++---- src/Navigator/Old/NavigatorContextBuilder.cs | 2 +- src/Navigator/Old/NavigatorMiddleware.cs | 2 +- src/Navigator/Old/Notification/NavigatorNotification.cs | 2 +- src/Navigator/Old/NotificationLauncher.cs | 4 ++-- src/Navigator/ServiceCollectionExtensions.cs | 2 ++ 23 files changed, 33 insertions(+), 25 deletions(-) rename src/Navigator/{ => Configuration}/EndpointRouteBuilderExtensions.cs (93%) rename src/Navigator/{ => Configuration}/INavigatorOptions.cs (92%) rename src/Navigator/{ => Configuration}/NavigatorConfiguration.cs (96%) rename src/Navigator/{ => Configuration}/NavigatorOptions.cs (97%) rename src/Navigator/{ => Configuration}/NavigatorOptionsCollectionExtensions.cs (96%) rename src/Navigator/{ => Configuration}/NavigatorRouteConfiguration.cs (87%) rename src/Navigator/{ => Configuration}/Provider/NavigatorProviderConfiguration.cs (96%) rename src/Navigator/{ => Configuration}/Provider/NavigatorRouteProviderConfiguration.cs (89%) diff --git a/src/Navigator.Provider.Telegram/Hosted/SetTelegramBotWebHookHostedService.cs b/src/Navigator.Provider.Telegram/Hosted/SetTelegramBotWebHookHostedService.cs index 2f383de..0b9cb13 100644 --- a/src/Navigator.Provider.Telegram/Hosted/SetTelegramBotWebHookHostedService.cs +++ b/src/Navigator.Provider.Telegram/Hosted/SetTelegramBotWebHookHostedService.cs @@ -5,6 +5,7 @@ using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Navigator.Abstractions; +using Navigator.Configuration; namespace Navigator.Provider.Telegram.Hosted { diff --git a/src/Navigator.Provider.Telegram/NavigatorProviderConfigurationExtension.cs b/src/Navigator.Provider.Telegram/NavigatorProviderConfigurationExtension.cs index 695f6a3..68ec99c 100644 --- a/src/Navigator.Provider.Telegram/NavigatorProviderConfigurationExtension.cs +++ b/src/Navigator.Provider.Telegram/NavigatorProviderConfigurationExtension.cs @@ -1,5 +1,7 @@ using System; using Microsoft.Extensions.DependencyInjection; +using Navigator.Configuration; +using Navigator.Configuration.Provider; using Navigator.Provider.Telegram.Hosted; namespace Navigator.Provider.Telegram diff --git a/src/Navigator.Provider.Telegram/NavigatorRouteProviderConfigurationExtensions.cs b/src/Navigator.Provider.Telegram/NavigatorRouteProviderConfigurationExtensions.cs index 09686bc..6968df0 100644 --- a/src/Navigator.Provider.Telegram/NavigatorRouteProviderConfigurationExtensions.cs +++ b/src/Navigator.Provider.Telegram/NavigatorRouteProviderConfigurationExtensions.cs @@ -3,6 +3,8 @@ using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Navigator.Abstractions; +using Navigator.Configuration; +using Navigator.Configuration.Provider; namespace Navigator.Provider.Telegram { diff --git a/src/Navigator.Provider.Telegram/NavigatorTelegramClient.cs b/src/Navigator.Provider.Telegram/NavigatorTelegramClient.cs index 4a0c1ea..0b945c1 100644 --- a/src/Navigator.Provider.Telegram/NavigatorTelegramClient.cs +++ b/src/Navigator.Provider.Telegram/NavigatorTelegramClient.cs @@ -1,5 +1,6 @@ using System.Net.Http; using MihaZupan.TelegramBotClients; +using Navigator.Configuration; namespace Navigator.Provider.Telegram { diff --git a/src/Navigator.Provider.Telegram/NavigatorTelegramProviderOptions.cs b/src/Navigator.Provider.Telegram/NavigatorTelegramProviderOptions.cs index 97bf0e8..f326bd3 100644 --- a/src/Navigator.Provider.Telegram/NavigatorTelegramProviderOptions.cs +++ b/src/Navigator.Provider.Telegram/NavigatorTelegramProviderOptions.cs @@ -1,3 +1,5 @@ +using Navigator.Configuration; + namespace Navigator.Provider.Telegram { public class NavigatorTelegramProviderOptions : NavigatorOptions diff --git a/src/Navigator.Provider.Telegram/NavigatorTelegramProviderOptionsExtensions.cs b/src/Navigator.Provider.Telegram/NavigatorTelegramProviderOptionsExtensions.cs index 06e6089..b66546f 100644 --- a/src/Navigator.Provider.Telegram/NavigatorTelegramProviderOptionsExtensions.cs +++ b/src/Navigator.Provider.Telegram/NavigatorTelegramProviderOptionsExtensions.cs @@ -1,5 +1,6 @@ using System; using MihaZupan.TelegramBotClients.RateLimitedClient; +using Navigator.Configuration; namespace Navigator.Provider.Telegram { diff --git a/src/Navigator.Samples.Echo/Startup.cs b/src/Navigator.Samples.Echo/Startup.cs index efa9d69..0515201 100644 --- a/src/Navigator.Samples.Echo/Startup.cs +++ b/src/Navigator.Samples.Echo/Startup.cs @@ -5,6 +5,7 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; +using Navigator.Configuration; using Navigator.Extensions.Shipyard; using Navigator.Extensions.Store; using Navigator.Samples.Echo.Entity; diff --git a/src/Navigator/EndpointRouteBuilderExtensions.cs b/src/Navigator/Configuration/EndpointRouteBuilderExtensions.cs similarity index 93% rename from src/Navigator/EndpointRouteBuilderExtensions.cs rename to src/Navigator/Configuration/EndpointRouteBuilderExtensions.cs index 3a65240..f3ff5a6 100644 --- a/src/Navigator/EndpointRouteBuilderExtensions.cs +++ b/src/Navigator/Configuration/EndpointRouteBuilderExtensions.cs @@ -1,6 +1,6 @@ using Microsoft.AspNetCore.Routing; -namespace Navigator +namespace Navigator.Configuration { public static class EndpointRouteBuilderExtensions { diff --git a/src/Navigator/INavigatorOptions.cs b/src/Navigator/Configuration/INavigatorOptions.cs similarity index 92% rename from src/Navigator/INavigatorOptions.cs rename to src/Navigator/Configuration/INavigatorOptions.cs index 1b14468..0392d1a 100644 --- a/src/Navigator/INavigatorOptions.cs +++ b/src/Navigator/Configuration/INavigatorOptions.cs @@ -1,6 +1,6 @@ using System.Collections.Generic; -namespace Navigator +namespace Navigator.Configuration { /// /// diff --git a/src/Navigator/NavigatorConfiguration.cs b/src/Navigator/Configuration/NavigatorConfiguration.cs similarity index 96% rename from src/Navigator/NavigatorConfiguration.cs rename to src/Navigator/Configuration/NavigatorConfiguration.cs index 13d101d..944c005 100644 --- a/src/Navigator/NavigatorConfiguration.cs +++ b/src/Navigator/Configuration/NavigatorConfiguration.cs @@ -1,9 +1,9 @@ using System; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; -using Navigator.Provider; +using Navigator.Configuration.Provider; -namespace Navigator +namespace Navigator.Configuration { /// /// Helper functions for configuring navigator services. diff --git a/src/Navigator/NavigatorOptions.cs b/src/Navigator/Configuration/NavigatorOptions.cs similarity index 97% rename from src/Navigator/NavigatorOptions.cs rename to src/Navigator/Configuration/NavigatorOptions.cs index 8c1dce5..9e21b5e 100644 --- a/src/Navigator/NavigatorOptions.cs +++ b/src/Navigator/Configuration/NavigatorOptions.cs @@ -1,6 +1,6 @@ using System.Collections.Generic; -namespace Navigator +namespace Navigator.Configuration { /// /// Represents all the options you can use to configure the navigator framework. diff --git a/src/Navigator/NavigatorOptionsCollectionExtensions.cs b/src/Navigator/Configuration/NavigatorOptionsCollectionExtensions.cs similarity index 96% rename from src/Navigator/NavigatorOptionsCollectionExtensions.cs rename to src/Navigator/Configuration/NavigatorOptionsCollectionExtensions.cs index 3074ed2..3d6b38e 100644 --- a/src/Navigator/NavigatorOptionsCollectionExtensions.cs +++ b/src/Navigator/Configuration/NavigatorOptionsCollectionExtensions.cs @@ -1,9 +1,7 @@ -using System; using System.Collections.Generic; using System.Reflection; -using MihaZupan.TelegramBotClients.RateLimitedClient; -namespace Navigator +namespace Navigator.Configuration { /// /// Navigator Configuration Options. diff --git a/src/Navigator/NavigatorRouteConfiguration.cs b/src/Navigator/Configuration/NavigatorRouteConfiguration.cs similarity index 87% rename from src/Navigator/NavigatorRouteConfiguration.cs rename to src/Navigator/Configuration/NavigatorRouteConfiguration.cs index 6a17241..aa1f393 100644 --- a/src/Navigator/NavigatorRouteConfiguration.cs +++ b/src/Navigator/Configuration/NavigatorRouteConfiguration.cs @@ -1,7 +1,7 @@ using Microsoft.AspNetCore.Routing; -using Navigator.Provider; +using Navigator.Configuration.Provider; -namespace Navigator +namespace Navigator.Configuration { public class NavigatorRouteConfiguration { diff --git a/src/Navigator/Provider/NavigatorProviderConfiguration.cs b/src/Navigator/Configuration/Provider/NavigatorProviderConfiguration.cs similarity index 96% rename from src/Navigator/Provider/NavigatorProviderConfiguration.cs rename to src/Navigator/Configuration/Provider/NavigatorProviderConfiguration.cs index 77ceb9b..2da30ee 100644 --- a/src/Navigator/Provider/NavigatorProviderConfiguration.cs +++ b/src/Navigator/Configuration/Provider/NavigatorProviderConfiguration.cs @@ -1,7 +1,7 @@ using System; using Microsoft.Extensions.DependencyInjection; -namespace Navigator.Provider +namespace Navigator.Configuration.Provider { /// /// Provides a entry point for configuring new providers for Navigator. diff --git a/src/Navigator/Provider/NavigatorRouteProviderConfiguration.cs b/src/Navigator/Configuration/Provider/NavigatorRouteProviderConfiguration.cs similarity index 89% rename from src/Navigator/Provider/NavigatorRouteProviderConfiguration.cs rename to src/Navigator/Configuration/Provider/NavigatorRouteProviderConfiguration.cs index ec6d7c9..a355559 100644 --- a/src/Navigator/Provider/NavigatorRouteProviderConfiguration.cs +++ b/src/Navigator/Configuration/Provider/NavigatorRouteProviderConfiguration.cs @@ -1,8 +1,7 @@ using System; using Microsoft.AspNetCore.Routing; -using Microsoft.Extensions.DependencyInjection; -namespace Navigator.Provider +namespace Navigator.Configuration.Provider { public class NavigatorRouteProviderConfiguration { diff --git a/src/Navigator/INavigatorContext.cs b/src/Navigator/INavigatorContext.cs index 97ca33e..a5a1108 100644 --- a/src/Navigator/INavigatorContext.cs +++ b/src/Navigator/INavigatorContext.cs @@ -2,7 +2,7 @@ using System.Threading.Tasks; using Telegram.Bot.Types; -namespace Navigator.Abstractions +namespace Navigator { public interface INavigatorContext { diff --git a/src/Navigator/Old/ActionLauncher.cs b/src/Navigator/Old/ActionLauncher.cs index afa99f3..e341c13 100644 --- a/src/Navigator/Old/ActionLauncher.cs +++ b/src/Navigator/Old/ActionLauncher.cs @@ -4,12 +4,12 @@ using System.Threading.Tasks; using MediatR; using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Options; using Navigator.Abstractions; +using Navigator.Configuration; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; -namespace Navigator +namespace Navigator.Old { public class ActionLauncher : IActionLauncher { diff --git a/src/Navigator/Old/NavigatorContext.cs b/src/Navigator/Old/NavigatorContext.cs index eba72fc..3e7bb58 100644 --- a/src/Navigator/Old/NavigatorContext.cs +++ b/src/Navigator/Old/NavigatorContext.cs @@ -1,10 +1,9 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Threading.Tasks; -using Navigator.Abstractions; using Telegram.Bot.Types; -namespace Navigator +namespace Navigator.Old { /// /// Default implementation of INavigatorContext. @@ -17,7 +16,7 @@ public class NavigatorContext : INavigatorContext protected IDictionary Extensions { get; set; } = null!; /// - public IBotClient Client { get; } + public INavigatorClient Client { get; } /// public Dictionary Items { get; } @@ -32,7 +31,7 @@ public class NavigatorContext : INavigatorContext /// Default constructor. /// /// - public NavigatorContext(IBotClient client) + public NavigatorContext(INavigatorClient client) { Client = client; Items = new Dictionary(); diff --git a/src/Navigator/Old/NavigatorContextBuilder.cs b/src/Navigator/Old/NavigatorContextBuilder.cs index 958503a..1326b40 100644 --- a/src/Navigator/Old/NavigatorContextBuilder.cs +++ b/src/Navigator/Old/NavigatorContextBuilder.cs @@ -5,7 +5,7 @@ using Navigator.Abstractions; using Telegram.Bot.Types; -namespace Navigator +namespace Navigator.Old { public class NavigatorContextBuilder : INavigatorContextBuilder { diff --git a/src/Navigator/Old/NavigatorMiddleware.cs b/src/Navigator/Old/NavigatorMiddleware.cs index ffa77eb..848326b 100644 --- a/src/Navigator/Old/NavigatorMiddleware.cs +++ b/src/Navigator/Old/NavigatorMiddleware.cs @@ -6,7 +6,7 @@ using Newtonsoft.Json; using Telegram.Bot.Types; -namespace Navigator +namespace Navigator.Old { /// /// diff --git a/src/Navigator/Old/Notification/NavigatorNotification.cs b/src/Navigator/Old/Notification/NavigatorNotification.cs index 7a9d29d..f479c55 100644 --- a/src/Navigator/Old/Notification/NavigatorNotification.cs +++ b/src/Navigator/Old/Notification/NavigatorNotification.cs @@ -3,7 +3,7 @@ using Telegram.Bot.Types; using Telegram.Bot.Types.Payments; -namespace Navigator.Notification +namespace Navigator.Old.Notification { public abstract class NavigatorNotification : INavigatorNotification { diff --git a/src/Navigator/Old/NotificationLauncher.cs b/src/Navigator/Old/NotificationLauncher.cs index d4503fd..28f76f1 100644 --- a/src/Navigator/Old/NotificationLauncher.cs +++ b/src/Navigator/Old/NotificationLauncher.cs @@ -2,10 +2,10 @@ using MediatR; using Microsoft.Extensions.Logging; using Navigator.Abstractions; -using Navigator.Notification; +using Navigator.Old.Notification; using Telegram.Bot.Types.Enums; -namespace Navigator +namespace Navigator.Old { public class NotificationLauncher : INotificationLauncher { diff --git a/src/Navigator/ServiceCollectionExtensions.cs b/src/Navigator/ServiceCollectionExtensions.cs index 7e42720..b5a75b5 100644 --- a/src/Navigator/ServiceCollectionExtensions.cs +++ b/src/Navigator/ServiceCollectionExtensions.cs @@ -1,6 +1,8 @@ using System; using Microsoft.Extensions.DependencyInjection; using Navigator.Abstractions; +using Navigator.Configuration; +using Navigator.Old; using Scrutor; namespace Navigator From 42377815ec28bb4cd688280f5420eeece37e8632 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sun, 14 Feb 2021 14:56:22 +0100 Subject: [PATCH 025/304] Updated navigator options --- src/Navigator/Configuration/INavigatorOptions.cs | 4 ++-- src/Navigator/Configuration/NavigatorOptions.cs | 8 +++----- 2 files changed, 5 insertions(+), 7 deletions(-) diff --git a/src/Navigator/Configuration/INavigatorOptions.cs b/src/Navigator/Configuration/INavigatorOptions.cs index 0392d1a..b056a37 100644 --- a/src/Navigator/Configuration/INavigatorOptions.cs +++ b/src/Navigator/Configuration/INavigatorOptions.cs @@ -3,12 +3,12 @@ namespace Navigator.Configuration { /// - /// + /// Represents all the options you can use to configure Navigator. /// public interface INavigatorOptions { bool TryRegisterOption(string key, object option); - bool ForceRegisterOption(string key, object option); + void ForceRegisterOption(string key, object option); TType? RetrieveOption(string key); Dictionary RetrieveAllOptions(); void Import(Dictionary options, bool overwrite = false); diff --git a/src/Navigator/Configuration/NavigatorOptions.cs b/src/Navigator/Configuration/NavigatorOptions.cs index 9e21b5e..ff58728 100644 --- a/src/Navigator/Configuration/NavigatorOptions.cs +++ b/src/Navigator/Configuration/NavigatorOptions.cs @@ -2,9 +2,7 @@ namespace Navigator.Configuration { - /// - /// Represents all the options you can use to configure the navigator framework. - /// + /// public class NavigatorOptions : INavigatorOptions { private readonly Dictionary _options; @@ -19,11 +17,11 @@ public bool TryRegisterOption(string key, object option) return _options.TryAdd(key, option); } - public bool ForceRegisterOption(string key, object option) + public void ForceRegisterOption(string key, object option) { _options.Remove(key); - return TryRegisterOption(key, option); + TryRegisterOption(key, option); } public TType? RetrieveOption(string key) From a78b6e87fd33981734df846358e1bbbf2d27d607 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sun, 14 Feb 2021 15:39:32 +0100 Subject: [PATCH 026/304] Started working in Discord Provider --- .../SetDiscordShardedSocketHostedService.cs | 93 +++++++++++++++++++ .../Navigator.Provider.Discord.csproj | 16 ++++ src/Navigator.sln | 7 ++ 3 files changed, 116 insertions(+) create mode 100644 src/Navigator.Provider.Discord/Hosted/SetDiscordShardedSocketHostedService.cs create mode 100644 src/Navigator.Provider.Discord/Navigator.Provider.Discord.csproj diff --git a/src/Navigator.Provider.Discord/Hosted/SetDiscordShardedSocketHostedService.cs b/src/Navigator.Provider.Discord/Hosted/SetDiscordShardedSocketHostedService.cs new file mode 100644 index 0000000..a990055 --- /dev/null +++ b/src/Navigator.Provider.Discord/Hosted/SetDiscordShardedSocketHostedService.cs @@ -0,0 +1,93 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using Discord; +using Discord.WebSocket; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using Navigator.Abstractions; +using Navigator.Configuration; + +namespace Navigator.Provider.Telegram.Hosted +{ + /// + /// WebHook service for navigator's telegram provider. + /// + public class SetDiscordShardedSocketHostedService : BackgroundService + { + private readonly ILogger _logger; + private readonly IServiceScopeFactory _serviceScopeFactory; + private readonly NavigatorOptions _navigatorOptions; + + /// + /// Default constructor. + /// + /// + /// + /// + /// + public SetDiscordShardedSocketHostedService(ILogger logger, IServiceScopeFactory serviceScopeFactory, + NavigatorOptions navigatorOptions) + { + _logger = logger; + _serviceScopeFactory = serviceScopeFactory; + _navigatorOptions = navigatorOptions; + } + + /// + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + + using var scope = _serviceScopeFactory.CreateScope(); + + var navigatorClient = scope.ServiceProvider.GetRequiredService(); + + navigatorClient.ShardReady += ReadyAsync; + navigatorClient.Log += LogAsync; + + await navigatorClient.LoginAsync(TokenType.Bot, _navigatorOptions.GetDiscordToken()); + await navigatorClient.StartAsync(); + + var me = await navigatorClient.CurrentUser; + + _logger.LogInformation($"Navigator Discord Client is receiving updates for bot: @{me.Username}"); + } + + private Task ReadyAsync(DiscordSocketClient shard) + { + _logger.LogInformation("Navigator Discord Shard Number {ShardId} is connected and ready!", shard.ShardId); + return Task.CompletedTask; + } + + private Task LogAsync(LogMessage log) + { + switch (log.Severity) + { + case LogSeverity.Critical: + _logger.LogCritical(log.Exception, "Message: {Message} Source: {Source}", log.Message, log.Source); + break; + case LogSeverity.Error: + _logger.LogError(log.Exception, "Message: {Message} Source: {Source}", log.Message, log.Source); + break; + case LogSeverity.Warning: + _logger.LogWarning(log.Exception, "Message: {Message} Source: {Source}", log.Message, log.Source); + break; + case LogSeverity.Info: + _logger.LogInformation("Message: {Message} Source: {Source}", log.Message, log.Source); + break; + case LogSeverity.Verbose: + _logger.LogTrace("Message: {Message} Source: {Source}", log.Message, log.Source); + break; + case LogSeverity.Debug: + _logger.LogDebug("Message: {Message} Source: {Source}", log.Message, log.Source); + break; + default: + _logger.LogInformation("Message: {Message} Source: {Source}", log.Message, log.Source); + break; + } + + return Task.CompletedTask; + } + } +} \ No newline at end of file diff --git a/src/Navigator.Provider.Discord/Navigator.Provider.Discord.csproj b/src/Navigator.Provider.Discord/Navigator.Provider.Discord.csproj new file mode 100644 index 0000000..b848986 --- /dev/null +++ b/src/Navigator.Provider.Discord/Navigator.Provider.Discord.csproj @@ -0,0 +1,16 @@ + + + + net5.0 + + + + + + + + + + + + diff --git a/src/Navigator.sln b/src/Navigator.sln index becb85f..33a2579 100644 --- a/src/Navigator.sln +++ b/src/Navigator.sln @@ -38,6 +38,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Providers", "Providers", "{ EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Navigator.Provider.Telegram", "Navigator.Provider.Telegram\Navigator.Provider.Telegram.csproj", "{8E0F6DCA-FAA4-4FA8-B9E0-75E9DC0F3573}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Navigator.Provider.Discord", "Navigator.Provider.Discord\Navigator.Provider.Discord.csproj", "{54039A52-DB2D-4428-A8D0-F998CA50B079}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -88,6 +90,10 @@ Global {8E0F6DCA-FAA4-4FA8-B9E0-75E9DC0F3573}.Debug|Any CPU.Build.0 = Debug|Any CPU {8E0F6DCA-FAA4-4FA8-B9E0-75E9DC0F3573}.Release|Any CPU.ActiveCfg = Release|Any CPU {8E0F6DCA-FAA4-4FA8-B9E0-75E9DC0F3573}.Release|Any CPU.Build.0 = Release|Any CPU + {54039A52-DB2D-4428-A8D0-F998CA50B079}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {54039A52-DB2D-4428-A8D0-F998CA50B079}.Debug|Any CPU.Build.0 = Debug|Any CPU + {54039A52-DB2D-4428-A8D0-F998CA50B079}.Release|Any CPU.ActiveCfg = Release|Any CPU + {54039A52-DB2D-4428-A8D0-F998CA50B079}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(NestedProjects) = preSolution {7E8F867E-70E1-4C5B-AE65-A2C6822BFD6E} = {6D6A8E40-8C40-49AA-BEAD-B046D43F511A} @@ -107,5 +113,6 @@ Global {294C1716-C054-4585-B66E-C79D155AE684} = {E2FF61C3-F081-40C8-9CC3-BBE1F81543F6} {DAA22477-BB29-475C-AD2C-905F81B4AD8E} = {895808DE-1CA6-406C-924A-7E43F293CF7D} {8E0F6DCA-FAA4-4FA8-B9E0-75E9DC0F3573} = {DAA22477-BB29-475C-AD2C-905F81B4AD8E} + {54039A52-DB2D-4428-A8D0-F998CA50B079} = {DAA22477-BB29-475C-AD2C-905F81B4AD8E} EndGlobalSection EndGlobal From b89286e98d2f679a5fb3aa7cbf3165f6a8de026b Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sun, 14 Feb 2021 15:45:34 +0100 Subject: [PATCH 027/304] Added discord options --- .../Navigator.Provider.Discord.csproj | 1 + .../NavigatorTelegramProviderOptions.cs | 9 ++++ ...igatorTelegramProviderOptionsExtensions.cs | 49 +++++++++++++++++++ 3 files changed, 59 insertions(+) create mode 100644 src/Navigator.Provider.Discord/NavigatorTelegramProviderOptions.cs create mode 100644 src/Navigator.Provider.Discord/NavigatorTelegramProviderOptionsExtensions.cs diff --git a/src/Navigator.Provider.Discord/Navigator.Provider.Discord.csproj b/src/Navigator.Provider.Discord/Navigator.Provider.Discord.csproj index b848986..874e3c7 100644 --- a/src/Navigator.Provider.Discord/Navigator.Provider.Discord.csproj +++ b/src/Navigator.Provider.Discord/Navigator.Provider.Discord.csproj @@ -2,6 +2,7 @@ net5.0 + enable diff --git a/src/Navigator.Provider.Discord/NavigatorTelegramProviderOptions.cs b/src/Navigator.Provider.Discord/NavigatorTelegramProviderOptions.cs new file mode 100644 index 0000000..5fbf80f --- /dev/null +++ b/src/Navigator.Provider.Discord/NavigatorTelegramProviderOptions.cs @@ -0,0 +1,9 @@ +using Navigator.Configuration; + +namespace Navigator.Provider.Discord +{ + public class NavigatorDiscordProviderOptions : NavigatorOptions + { + + } +} \ No newline at end of file diff --git a/src/Navigator.Provider.Discord/NavigatorTelegramProviderOptionsExtensions.cs b/src/Navigator.Provider.Discord/NavigatorTelegramProviderOptionsExtensions.cs new file mode 100644 index 0000000..b514541 --- /dev/null +++ b/src/Navigator.Provider.Discord/NavigatorTelegramProviderOptionsExtensions.cs @@ -0,0 +1,49 @@ +using System; +using MihaZupan.TelegramBotClients.RateLimitedClient; +using Navigator.Configuration; + +namespace Navigator.Provider.Discord +{ + public static class NavigatorTelegramProviderOptionsExtensions + { + #region DiscordToken + + private const string DiscordTokenKey = "_navigator.options.discord.discord_token"; + + public static void SetDiscordToken(this NavigatorDiscordProviderOptions navigatorOptions, string telegramToken) + { + navigatorOptions.TryRegisterOption(DiscordTokenKey, telegramToken); + + } + + public static string? GetDiscordToken(this INavigatorOptions navigatorOptions) + { + return navigatorOptions.RetrieveOption(DiscordTokenKey); + } + + #endregion + + #region Shards + + private const string TotalShardsKey = "_navigator.options.webhook_endpoint"; + + public static void SetTotalShards(this NavigatorDiscordProviderOptions navigatorOptions, int totalShards) + { + navigatorOptions.TryRegisterOption(TotalShardsKey, totalShards); + } + + public static int GetTotalShardsOrDefault(this INavigatorOptions navigatorOptions) + { + var totalShards = navigatorOptions.RetrieveOption(TotalShardsKey); + + if (totalShards is null) + { + navigatorOptions.TryRegisterOption(TotalShardsKey, 1); + } + + return navigatorOptions.RetrieveOption(TotalShardsKey)!; + } + + #endregion + } +} \ No newline at end of file From bf80635fda9372d18f1d7f30913ac9ba54c08418 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sun, 14 Feb 2021 15:45:45 +0100 Subject: [PATCH 028/304] Updated discord hosted service --- .../Hosted/SetDiscordShardedSocketHostedService.cs | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/src/Navigator.Provider.Discord/Hosted/SetDiscordShardedSocketHostedService.cs b/src/Navigator.Provider.Discord/Hosted/SetDiscordShardedSocketHostedService.cs index a990055..f161189 100644 --- a/src/Navigator.Provider.Discord/Hosted/SetDiscordShardedSocketHostedService.cs +++ b/src/Navigator.Provider.Discord/Hosted/SetDiscordShardedSocketHostedService.cs @@ -8,6 +8,7 @@ using Microsoft.Extensions.Logging; using Navigator.Abstractions; using Navigator.Configuration; +using Navigator.Provider.Discord; namespace Navigator.Provider.Telegram.Hosted { @@ -49,14 +50,21 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken) await navigatorClient.LoginAsync(TokenType.Bot, _navigatorOptions.GetDiscordToken()); await navigatorClient.StartAsync(); - var me = await navigatorClient.CurrentUser; + var me = navigatorClient.CurrentUser; - _logger.LogInformation($"Navigator Discord Client is receiving updates for bot: @{me.Username}"); + if (me is not null) + { + _logger.LogInformation($"Navigator Discord Client is receiving updates for bot: @{me.Username}"); + } + else + { + _logger.LogError("Unhandled error starting navigator discord client"); + } } private Task ReadyAsync(DiscordSocketClient shard) { - _logger.LogInformation("Navigator Discord Shard Number {ShardId} is connected and ready!", shard.ShardId); + _logger.LogInformation("Navigator Discord Shard Number {ShardId} is connected and ready", shard.ShardId); return Task.CompletedTask; } From e4c1b49c8926f0f6ed5045f400037bf72696136d Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sun, 14 Feb 2021 15:46:05 +0100 Subject: [PATCH 029/304] Linted --- .../Hosted/SetDiscordShardedSocketHostedService.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/Navigator.Provider.Discord/Hosted/SetDiscordShardedSocketHostedService.cs b/src/Navigator.Provider.Discord/Hosted/SetDiscordShardedSocketHostedService.cs index f161189..2cea1df 100644 --- a/src/Navigator.Provider.Discord/Hosted/SetDiscordShardedSocketHostedService.cs +++ b/src/Navigator.Provider.Discord/Hosted/SetDiscordShardedSocketHostedService.cs @@ -39,7 +39,6 @@ public SetDiscordShardedSocketHostedService(ILogger protected override async Task ExecuteAsync(CancellationToken stoppingToken) { - using var scope = _serviceScopeFactory.CreateScope(); var navigatorClient = scope.ServiceProvider.GetRequiredService(); From 0b018add98d418d5f0bfc9bb1ed4510dc61c3031 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sun, 14 Feb 2021 18:07:34 +0100 Subject: [PATCH 030/304] Upgraded Discord client and configuration --- .../SetDiscordShardedSocketHostedService.cs | 43 +------------ .../NavigatorDiscordClient.cs | 61 +++++++++++++++++++ ...NavigatorProviderConfigurationExtension.cs | 28 +++++++++ 3 files changed, 91 insertions(+), 41 deletions(-) create mode 100644 src/Navigator.Provider.Discord/NavigatorDiscordClient.cs create mode 100644 src/Navigator.Provider.Discord/NavigatorProviderConfigurationExtension.cs diff --git a/src/Navigator.Provider.Discord/Hosted/SetDiscordShardedSocketHostedService.cs b/src/Navigator.Provider.Discord/Hosted/SetDiscordShardedSocketHostedService.cs index 2cea1df..8cd62ad 100644 --- a/src/Navigator.Provider.Discord/Hosted/SetDiscordShardedSocketHostedService.cs +++ b/src/Navigator.Provider.Discord/Hosted/SetDiscordShardedSocketHostedService.cs @@ -41,10 +41,7 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken) { using var scope = _serviceScopeFactory.CreateScope(); - var navigatorClient = scope.ServiceProvider.GetRequiredService(); - - navigatorClient.ShardReady += ReadyAsync; - navigatorClient.Log += LogAsync; + var navigatorClient = scope.ServiceProvider.GetRequiredService(); await navigatorClient.LoginAsync(TokenType.Bot, _navigatorOptions.GetDiscordToken()); await navigatorClient.StartAsync(); @@ -57,44 +54,8 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken) } else { - _logger.LogError("Unhandled error starting navigator discord client"); + _logger.LogCritical("Unhandled error starting navigator discord client"); } } - - private Task ReadyAsync(DiscordSocketClient shard) - { - _logger.LogInformation("Navigator Discord Shard Number {ShardId} is connected and ready", shard.ShardId); - return Task.CompletedTask; - } - - private Task LogAsync(LogMessage log) - { - switch (log.Severity) - { - case LogSeverity.Critical: - _logger.LogCritical(log.Exception, "Message: {Message} Source: {Source}", log.Message, log.Source); - break; - case LogSeverity.Error: - _logger.LogError(log.Exception, "Message: {Message} Source: {Source}", log.Message, log.Source); - break; - case LogSeverity.Warning: - _logger.LogWarning(log.Exception, "Message: {Message} Source: {Source}", log.Message, log.Source); - break; - case LogSeverity.Info: - _logger.LogInformation("Message: {Message} Source: {Source}", log.Message, log.Source); - break; - case LogSeverity.Verbose: - _logger.LogTrace("Message: {Message} Source: {Source}", log.Message, log.Source); - break; - case LogSeverity.Debug: - _logger.LogDebug("Message: {Message} Source: {Source}", log.Message, log.Source); - break; - default: - _logger.LogInformation("Message: {Message} Source: {Source}", log.Message, log.Source); - break; - } - - return Task.CompletedTask; - } } } \ No newline at end of file diff --git a/src/Navigator.Provider.Discord/NavigatorDiscordClient.cs b/src/Navigator.Provider.Discord/NavigatorDiscordClient.cs new file mode 100644 index 0000000..b256338 --- /dev/null +++ b/src/Navigator.Provider.Discord/NavigatorDiscordClient.cs @@ -0,0 +1,61 @@ +using System.Threading.Tasks; +using Discord; +using Discord.WebSocket; +using Microsoft.Extensions.Logging; +using Navigator.Configuration; + +namespace Navigator.Provider.Discord +{ + public class NavigatorDiscordClient : DiscordShardedClient, INavigatorClient + { + private readonly ILogger _logger; + + public NavigatorDiscordClient(INavigatorOptions options, ILogger logger) + : base(new DiscordSocketConfig + { + TotalShards = options.GetTotalShardsOrDefault() + }) + { + _logger = logger; + + ShardReady += ReadyAsync; + Log += LogAsync; + } + + private Task ReadyAsync(DiscordSocketClient shard) + { + _logger.LogInformation("Navigator Discord Shard Number {ShardId} is connected and ready", shard.ShardId); + return Task.CompletedTask; + } + + private Task LogAsync(LogMessage log) + { + switch (log.Severity) + { + case LogSeverity.Critical: + _logger.LogCritical(log.Exception, "Message: {Message} Source: {Source}", log.Message, log.Source); + break; + case LogSeverity.Error: + _logger.LogError(log.Exception, "Message: {Message} Source: {Source}", log.Message, log.Source); + break; + case LogSeverity.Warning: + _logger.LogWarning(log.Exception, "Message: {Message} Source: {Source}", log.Message, log.Source); + break; + case LogSeverity.Info: + _logger.LogInformation("Message: {Message} Source: {Source}", log.Message, log.Source); + break; + case LogSeverity.Verbose: + _logger.LogTrace("Message: {Message} Source: {Source}", log.Message, log.Source); + break; + case LogSeverity.Debug: + _logger.LogDebug("Message: {Message} Source: {Source}", log.Message, log.Source); + break; + default: + _logger.LogInformation("Message: {Message} Source: {Source}", log.Message, log.Source); + break; + } + + return Task.CompletedTask; + } + } +} \ No newline at end of file diff --git a/src/Navigator.Provider.Discord/NavigatorProviderConfigurationExtension.cs b/src/Navigator.Provider.Discord/NavigatorProviderConfigurationExtension.cs new file mode 100644 index 0000000..e98a7c9 --- /dev/null +++ b/src/Navigator.Provider.Discord/NavigatorProviderConfigurationExtension.cs @@ -0,0 +1,28 @@ +using System; +using Microsoft.Extensions.DependencyInjection; +using Navigator.Configuration; +using Navigator.Configuration.Provider; +using Navigator.Provider.Telegram.Hosted; + +namespace Navigator.Provider.Discord +{ + public static class NavigatorProviderConfigurationExtensions + { + public static NavigatorConfiguration Discord(this NavigatorProviderConfiguration providerConfiguration, + Action options) + { + var discordProviderOptions = new NavigatorDiscordProviderOptions(); + options.Invoke(discordProviderOptions); + + return providerConfiguration.Provider( + optionsAction => optionsAction.Import(optionsAction.RetrieveAllOptions()), + services => + { + services.AddSingleton(); + services.AddSingleton(sp => sp.GetRequiredService()); + + services.AddHostedService(); + }); + } + } +} \ No newline at end of file From c160a774f71767265d818c89f04ebb4f13549723 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sun, 14 Feb 2021 18:14:43 +0100 Subject: [PATCH 031/304] Updated option keys --- .../NavigatorTelegramProviderOptionsExtensions.cs | 2 +- .../NavigatorTelegramProviderOptionsExtensions.cs | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/Navigator.Provider.Discord/NavigatorTelegramProviderOptionsExtensions.cs b/src/Navigator.Provider.Discord/NavigatorTelegramProviderOptionsExtensions.cs index b514541..cd79098 100644 --- a/src/Navigator.Provider.Discord/NavigatorTelegramProviderOptionsExtensions.cs +++ b/src/Navigator.Provider.Discord/NavigatorTelegramProviderOptionsExtensions.cs @@ -25,7 +25,7 @@ public static void SetDiscordToken(this NavigatorDiscordProviderOptions navigato #region Shards - private const string TotalShardsKey = "_navigator.options.webhook_endpoint"; + private const string TotalShardsKey = "_navigator.options.discord.total_shards"; public static void SetTotalShards(this NavigatorDiscordProviderOptions navigatorOptions, int totalShards) { diff --git a/src/Navigator.Provider.Telegram/NavigatorTelegramProviderOptionsExtensions.cs b/src/Navigator.Provider.Telegram/NavigatorTelegramProviderOptionsExtensions.cs index b66546f..faffbd5 100644 --- a/src/Navigator.Provider.Telegram/NavigatorTelegramProviderOptionsExtensions.cs +++ b/src/Navigator.Provider.Telegram/NavigatorTelegramProviderOptionsExtensions.cs @@ -8,7 +8,7 @@ public static class NavigatorTelegramProviderOptionsExtensions { #region SchedulerSettings - private const string SchedulerSettingsKey = "_navigator.options.scheduler_settings"; + private const string SchedulerSettingsKey = "_navigator.options.telegram.scheduler_settings"; public static void SetSchedulerSettings(this NavigatorTelegramProviderOptions navigatorOptions, SchedulerSettings schedulerSettings) { @@ -24,7 +24,7 @@ public static SchedulerSettings GetSchedulerSettingsOrDefault(this INavigatorOpt #region TelegramToken - private const string TelegramTokenKey = "_navigator.options.telegram_token"; + private const string TelegramTokenKey = "_navigator.options.telegram.telegram_token"; public static void SetTelegramToken(this NavigatorTelegramProviderOptions navigatorOptions, string telegramToken) { @@ -41,7 +41,7 @@ public static void SetTelegramToken(this NavigatorTelegramProviderOptions naviga #region WebHookEndpoint - private const string WebHookEndpointKey = "_navigator.options.webhook_endpoint"; + private const string WebHookEndpointKey = "_navigator.options.telegram.webhook_endpoint"; public static void SetWebHookEndpoint(this NavigatorTelegramProviderOptions navigatorOptions, string webHookEndpoint) { From 3d17a06cce4a3254f5663f78afe7fcc64b8ecb1b Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sun, 14 Feb 2021 19:27:11 +0100 Subject: [PATCH 032/304] Added BotUser model --- src/Navigator/Entities/BotUser.cs | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 src/Navigator/Entities/BotUser.cs diff --git a/src/Navigator/Entities/BotUser.cs b/src/Navigator/Entities/BotUser.cs new file mode 100644 index 0000000..cd2313e --- /dev/null +++ b/src/Navigator/Entities/BotUser.cs @@ -0,0 +1,8 @@ +namespace Navigator.Entities +{ + public class BotUser + { + public string Id { get; init; } + public string Username { get; init; } + } +} \ No newline at end of file From a99aa832a85e861683d0d0f2c594de1bcb5d1b0c Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sun, 14 Feb 2021 19:28:02 +0100 Subject: [PATCH 033/304] Added new method to INavigatorClient --- src/Navigator/INavigatorClient.cs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/src/Navigator/INavigatorClient.cs b/src/Navigator/INavigatorClient.cs index f2b96b7..d584de9 100644 --- a/src/Navigator/INavigatorClient.cs +++ b/src/Navigator/INavigatorClient.cs @@ -1,7 +1,16 @@ +using System.Threading; +using System.Threading.Tasks; +using Navigator.Entities; + namespace Navigator { public interface INavigatorClient { - + /// + /// Retrieves the bot user information. + /// + /// + /// + Task GetBotUser(CancellationToken cancellationToken = default); } } \ No newline at end of file From d4f016c7b4a3cf4e20a024a6458b338cc6867951 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sun, 14 Feb 2021 19:28:20 +0100 Subject: [PATCH 034/304] Implemented GetBotUser on Discord provider --- .../NavigatorDiscordClient.cs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/Navigator.Provider.Discord/NavigatorDiscordClient.cs b/src/Navigator.Provider.Discord/NavigatorDiscordClient.cs index b256338..2337923 100644 --- a/src/Navigator.Provider.Discord/NavigatorDiscordClient.cs +++ b/src/Navigator.Provider.Discord/NavigatorDiscordClient.cs @@ -1,8 +1,10 @@ +using System.Threading; using System.Threading.Tasks; using Discord; using Discord.WebSocket; using Microsoft.Extensions.Logging; using Navigator.Configuration; +using Navigator.Entities; namespace Navigator.Provider.Discord { @@ -57,5 +59,14 @@ private Task LogAsync(LogMessage log) return Task.CompletedTask; } + + public Task GetBotUser(CancellationToken cancellationToken = default) + { + return Task.FromResult(new BotUser + { + Id = CurrentUser.Id.ToString(), + Username = CurrentUser.Username + }); + } } } \ No newline at end of file From 8f0ed78f3c91788ac100dd501caaf87272b991dd Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sun, 14 Feb 2021 19:28:34 +0100 Subject: [PATCH 035/304] Implemented GetBotUser on Telegram provider --- .../NavigatorTelegramClient.cs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/src/Navigator.Provider.Telegram/NavigatorTelegramClient.cs b/src/Navigator.Provider.Telegram/NavigatorTelegramClient.cs index 0b945c1..01f1089 100644 --- a/src/Navigator.Provider.Telegram/NavigatorTelegramClient.cs +++ b/src/Navigator.Provider.Telegram/NavigatorTelegramClient.cs @@ -1,6 +1,9 @@ using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; using MihaZupan.TelegramBotClients; using Navigator.Configuration; +using Navigator.Entities; namespace Navigator.Provider.Telegram { @@ -10,5 +13,16 @@ public NavigatorTelegramClient(NavigatorOptions options) : base(options.GetTelegramToken(), (HttpClient) default!, options.GetSchedulerSettingsOrDefault()) { } + + public async Task GetBotUser(CancellationToken cancellationToken = default) + { + var bot = await GetMeAsync(cancellationToken); + + return new BotUser + { + Id = bot.Id.ToString(), + Username = bot.Username + }; + } } } \ No newline at end of file From 7881aa3bf1d8eeee4a55607589034d310705ed0e Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sun, 14 Feb 2021 19:28:51 +0100 Subject: [PATCH 036/304] Updated NavigatorContext interface --- src/Navigator/INavigatorContext.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Navigator/INavigatorContext.cs b/src/Navigator/INavigatorContext.cs index a5a1108..ed255af 100644 --- a/src/Navigator/INavigatorContext.cs +++ b/src/Navigator/INavigatorContext.cs @@ -1,5 +1,6 @@ using System.Collections.Generic; using System.Threading.Tasks; +using Navigator.Entities; using Telegram.Bot.Types; namespace Navigator @@ -8,7 +9,7 @@ public interface INavigatorContext { Dictionary Items { get; } public INavigatorClient Client { get; } - public User BotProfile { get; } + public BotUser BotProfile { get; } public Update Update { get; } Task Init(Update update, Dictionary extensions); From 7b671af5a0d2aea1ecd8d47f8ae80a2c95aad83d Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sun, 14 Feb 2021 19:29:08 +0100 Subject: [PATCH 037/304] Moved NavigatorContext back to package and updated methods. --- src/Navigator/{Old => }/NavigatorContext.cs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) rename src/Navigator/{Old => }/NavigatorContext.cs (88%) diff --git a/src/Navigator/Old/NavigatorContext.cs b/src/Navigator/NavigatorContext.cs similarity index 88% rename from src/Navigator/Old/NavigatorContext.cs rename to src/Navigator/NavigatorContext.cs index 3e7bb58..8642552 100644 --- a/src/Navigator/Old/NavigatorContext.cs +++ b/src/Navigator/NavigatorContext.cs @@ -1,12 +1,13 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Threading.Tasks; +using Navigator.Entities; using Telegram.Bot.Types; namespace Navigator.Old { /// - /// Default implementation of INavigatorContext. + /// Navigator Context present in all actions. /// public class NavigatorContext : INavigatorContext { @@ -22,7 +23,7 @@ public class NavigatorContext : INavigatorContext public Dictionary Items { get; } /// - public User BotProfile { get; protected set; } = null!; + public BotUser BotProfile { get; protected set; } = null!; /// public Update Update { get; protected set; } = null!; @@ -41,7 +42,7 @@ public NavigatorContext(INavigatorClient client) public async Task Init(Update update, Dictionary extensions) { Update = update; - BotProfile = await Client.GetMeAsync(); + BotProfile = await Client.GetBotUser(); Extensions = new ReadOnlyDictionary(extensions); } @@ -58,7 +59,7 @@ public async Task Init(Update update, Dictionary extensions) return throwIfNotFound ? throw new KeyNotFoundException($"{typeof(TExtension).Name} was not found.") - : (TExtension) default; + : default; } } } \ No newline at end of file From f4fbc1246e960b175803ca841863ccc1da6abd3c Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sun, 14 Feb 2021 19:35:16 +0100 Subject: [PATCH 038/304] Started updating example --- .../Navigator.Samples.Echo.csproj | 1 + src/Navigator.Samples.Echo/Startup.cs | 37 ++++++++++--------- 2 files changed, 21 insertions(+), 17 deletions(-) diff --git a/src/Navigator.Samples.Echo/Navigator.Samples.Echo.csproj b/src/Navigator.Samples.Echo/Navigator.Samples.Echo.csproj index 1d88af2..86d88dc 100644 --- a/src/Navigator.Samples.Echo/Navigator.Samples.Echo.csproj +++ b/src/Navigator.Samples.Echo/Navigator.Samples.Echo.csproj @@ -17,6 +17,7 @@ + diff --git a/src/Navigator.Samples.Echo/Startup.cs b/src/Navigator.Samples.Echo/Startup.cs index 0515201..1380660 100644 --- a/src/Navigator.Samples.Echo/Startup.cs +++ b/src/Navigator.Samples.Echo/Startup.cs @@ -8,6 +8,7 @@ using Navigator.Configuration; using Navigator.Extensions.Shipyard; using Navigator.Extensions.Store; +using Navigator.Provider.Telegram; using Navigator.Samples.Echo.Entity; using Navigator.Samples.Echo.Persistence; @@ -31,24 +32,25 @@ public void ConfigureServices(IServiceCollection services) services.AddApiVersioning(); - services.AddNavigator( - options => - { - options.SetTelegramToken(Configuration["BOT_TOKEN"]); - options.SetWebHookBaseUrl(Configuration["BASE_WEBHOOK_URL"]); - options.RegisterActionsFromAssemblies(typeof(Startup).Assembly); - } - ).AddNavigatorStore( - builder => - { - builder.UseSqlite(Configuration.GetConnectionString("DefaultConnection"), - b => b.MigrationsAssembly("Navigator.Samples.Echo")); - }, - options => { options.SetUserMapper(); } - ).AddShipyard(options => + services.AddNavigator(options => { - options.SetShipyardApiKey(Configuration["SHIPYARD_API_KEY"]); + options.SetWebHookBaseUrl(Configuration["BASE_WEBHOOK_URL"]); + options.RegisterActionsFromAssemblies(typeof(Startup).Assembly); + }).WithProvider.Telegram(options => + { + options.SetTelegramToken(Configuration["BOT_TOKEN"]); }); + // ).AddNavigatorStore( + // builder => + // { + // builder.UseSqlite(Configuration.GetConnectionString("DefaultConnection"), + // b => b.MigrationsAssembly("Navigator.Samples.Echo")); + // }, + // options => { options.SetUserMapper(); } + // ).AddShipyard(options => + // { + // options.SetShipyardApiKey(Configuration["SHIPYARD_API_KEY"]); + // }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. @@ -70,7 +72,8 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env) app.UseEndpoints(endpoints => { endpoints.MapControllers(); - endpoints.MapNavigator(); + endpoints.MapNavigator() + .ForProvider.Telegram(); }); } } From a0ea3956bcedf8533564523a98268b8fb39521b3 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sun, 14 Feb 2021 19:39:26 +0100 Subject: [PATCH 039/304] Moved NavigatorContext to new namespace --- src/Navigator.Samples.Echo/Actions/EchoAction.cs | 1 + src/Navigator.Samples.Echo/Actions/EchoActionHandler.cs | 1 + src/Navigator/{ => Context}/INavigatorContext.cs | 2 +- src/Navigator/{ => Context}/NavigatorContext.cs | 2 +- src/Navigator/Old/ActionLauncher.cs | 1 + src/Navigator/Old/NavigatorContextBuilder.cs | 1 + src/Navigator/Old/NotificationLauncher.cs | 1 + src/Navigator/ServiceCollectionExtensions.cs | 1 + 8 files changed, 8 insertions(+), 2 deletions(-) rename src/Navigator/{ => Context}/INavigatorContext.cs (94%) rename src/Navigator/{ => Context}/NavigatorContext.cs (98%) diff --git a/src/Navigator.Samples.Echo/Actions/EchoAction.cs b/src/Navigator.Samples.Echo/Actions/EchoAction.cs index 7b6456e..2343f3e 100644 --- a/src/Navigator.Samples.Echo/Actions/EchoAction.cs +++ b/src/Navigator.Samples.Echo/Actions/EchoAction.cs @@ -1,4 +1,5 @@ using Navigator.Abstractions; +using Navigator.Context; using Navigator.Extensions.Actions; namespace Navigator.Samples.Echo.Actions diff --git a/src/Navigator.Samples.Echo/Actions/EchoActionHandler.cs b/src/Navigator.Samples.Echo/Actions/EchoActionHandler.cs index 0bdd8dc..769f59a 100644 --- a/src/Navigator.Samples.Echo/Actions/EchoActionHandler.cs +++ b/src/Navigator.Samples.Echo/Actions/EchoActionHandler.cs @@ -3,6 +3,7 @@ using MediatR; using Navigator.Abstractions; using Navigator.Abstractions.Extensions; +using Navigator.Context; using Navigator.Extensions.Actions; using Navigator.Extensions.Store.Abstractions.Extensions; using Navigator.Samples.Echo.Entity; diff --git a/src/Navigator/INavigatorContext.cs b/src/Navigator/Context/INavigatorContext.cs similarity index 94% rename from src/Navigator/INavigatorContext.cs rename to src/Navigator/Context/INavigatorContext.cs index ed255af..092c396 100644 --- a/src/Navigator/INavigatorContext.cs +++ b/src/Navigator/Context/INavigatorContext.cs @@ -3,7 +3,7 @@ using Navigator.Entities; using Telegram.Bot.Types; -namespace Navigator +namespace Navigator.Context { public interface INavigatorContext { diff --git a/src/Navigator/NavigatorContext.cs b/src/Navigator/Context/NavigatorContext.cs similarity index 98% rename from src/Navigator/NavigatorContext.cs rename to src/Navigator/Context/NavigatorContext.cs index 8642552..8326587 100644 --- a/src/Navigator/NavigatorContext.cs +++ b/src/Navigator/Context/NavigatorContext.cs @@ -4,7 +4,7 @@ using Navigator.Entities; using Telegram.Bot.Types; -namespace Navigator.Old +namespace Navigator.Context { /// /// Navigator Context present in all actions. diff --git a/src/Navigator/Old/ActionLauncher.cs b/src/Navigator/Old/ActionLauncher.cs index e341c13..d7f04f7 100644 --- a/src/Navigator/Old/ActionLauncher.cs +++ b/src/Navigator/Old/ActionLauncher.cs @@ -6,6 +6,7 @@ using Microsoft.Extensions.Logging; using Navigator.Abstractions; using Navigator.Configuration; +using Navigator.Context; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; diff --git a/src/Navigator/Old/NavigatorContextBuilder.cs b/src/Navigator/Old/NavigatorContextBuilder.cs index 1326b40..ca7db5b 100644 --- a/src/Navigator/Old/NavigatorContextBuilder.cs +++ b/src/Navigator/Old/NavigatorContextBuilder.cs @@ -3,6 +3,7 @@ using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Navigator.Abstractions; +using Navigator.Context; using Telegram.Bot.Types; namespace Navigator.Old diff --git a/src/Navigator/Old/NotificationLauncher.cs b/src/Navigator/Old/NotificationLauncher.cs index 28f76f1..e712528 100644 --- a/src/Navigator/Old/NotificationLauncher.cs +++ b/src/Navigator/Old/NotificationLauncher.cs @@ -2,6 +2,7 @@ using MediatR; using Microsoft.Extensions.Logging; using Navigator.Abstractions; +using Navigator.Context; using Navigator.Old.Notification; using Telegram.Bot.Types.Enums; diff --git a/src/Navigator/ServiceCollectionExtensions.cs b/src/Navigator/ServiceCollectionExtensions.cs index b5a75b5..5e793b4 100644 --- a/src/Navigator/ServiceCollectionExtensions.cs +++ b/src/Navigator/ServiceCollectionExtensions.cs @@ -2,6 +2,7 @@ using Microsoft.Extensions.DependencyInjection; using Navigator.Abstractions; using Navigator.Configuration; +using Navigator.Context; using Navigator.Old; using Scrutor; From 3da281914049551c2ba66d79b9a90ecb0d5929b5 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 15 Feb 2021 09:31:28 +0100 Subject: [PATCH 040/304] Corrected name --- ...nsions.cs => NavigatorDiscordProviderOptionsExtensions.cs} | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) rename src/Navigator.Provider.Discord/{NavigatorTelegramProviderOptionsExtensions.cs => NavigatorDiscordProviderOptionsExtensions.cs} (91%) diff --git a/src/Navigator.Provider.Discord/NavigatorTelegramProviderOptionsExtensions.cs b/src/Navigator.Provider.Discord/NavigatorDiscordProviderOptionsExtensions.cs similarity index 91% rename from src/Navigator.Provider.Discord/NavigatorTelegramProviderOptionsExtensions.cs rename to src/Navigator.Provider.Discord/NavigatorDiscordProviderOptionsExtensions.cs index cd79098..26d77d7 100644 --- a/src/Navigator.Provider.Discord/NavigatorTelegramProviderOptionsExtensions.cs +++ b/src/Navigator.Provider.Discord/NavigatorDiscordProviderOptionsExtensions.cs @@ -1,10 +1,8 @@ -using System; -using MihaZupan.TelegramBotClients.RateLimitedClient; using Navigator.Configuration; namespace Navigator.Provider.Discord { - public static class NavigatorTelegramProviderOptionsExtensions + public static class NavigatorDiscordProviderOptionsExtensions { #region DiscordToken From 39829140100c45e1586760200baae3a8745e9788 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 15 Feb 2021 09:32:56 +0100 Subject: [PATCH 041/304] Erased navigator context interface --- src/Navigator/Context/INavigatorContext.cs | 18 ------------------ 1 file changed, 18 deletions(-) delete mode 100644 src/Navigator/Context/INavigatorContext.cs diff --git a/src/Navigator/Context/INavigatorContext.cs b/src/Navigator/Context/INavigatorContext.cs deleted file mode 100644 index 092c396..0000000 --- a/src/Navigator/Context/INavigatorContext.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System.Collections.Generic; -using System.Threading.Tasks; -using Navigator.Entities; -using Telegram.Bot.Types; - -namespace Navigator.Context -{ - public interface INavigatorContext - { - Dictionary Items { get; } - public INavigatorClient Client { get; } - public BotUser BotProfile { get; } - public Update Update { get; } - - Task Init(Update update, Dictionary extensions); - TExtension? Get(string extensionKey, bool throwIfNotFound = false); - } -} \ No newline at end of file From 2aadc4ebd2a6ce5c5b4c9fdda5f1fe17d612bac2 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 15 Feb 2021 09:33:05 +0100 Subject: [PATCH 042/304] Updated NavigatorContext --- src/Navigator/Context/NavigatorContext.cs | 26 ++++++----------------- 1 file changed, 7 insertions(+), 19 deletions(-) diff --git a/src/Navigator/Context/NavigatorContext.cs b/src/Navigator/Context/NavigatorContext.cs index 8326587..cc6eae1 100644 --- a/src/Navigator/Context/NavigatorContext.cs +++ b/src/Navigator/Context/NavigatorContext.cs @@ -9,39 +9,27 @@ namespace Navigator.Context /// /// Navigator Context present in all actions. /// - public class NavigatorContext : INavigatorContext + public class NavigatorContext { - /// - /// Extensions. - /// - protected IDictionary Extensions { get; set; } = null!; - - /// - public INavigatorClient Client { get; } - - /// + public readonly IDictionary Extensions; + public readonly INavigatorClient Client; public Dictionary Items { get; } /// - public BotUser BotProfile { get; protected set; } = null!; - - /// - public Update Update { get; protected set; } = null!; + public BotUser BotProfile { get; private set; } = null!; /// /// Default constructor. /// - /// - public NavigatorContext(INavigatorClient client) + public NavigatorContext(INavigatorClient ) { - Client = client; Items = new Dictionary(); } /// - public async Task Init(Update update, Dictionary extensions) + public async Task Init(INavigatorClient client, Dictionary extensions) { - Update = update; + Client = client; BotProfile = await Client.GetBotUser(); Extensions = new ReadOnlyDictionary(extensions); } From 93922832b65ca73c224ce41bef4416da00764ed7 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 15 Feb 2021 09:34:07 +0100 Subject: [PATCH 043/304] Route Provider configuration update --- ...torRouteProviderConfigurationExtensions.cs | 35 +++++++++++++++++-- 1 file changed, 32 insertions(+), 3 deletions(-) diff --git a/src/Navigator.Provider.Telegram/NavigatorRouteProviderConfigurationExtensions.cs b/src/Navigator.Provider.Telegram/NavigatorRouteProviderConfigurationExtensions.cs index 6968df0..dcb209a 100644 --- a/src/Navigator.Provider.Telegram/NavigatorRouteProviderConfigurationExtensions.cs +++ b/src/Navigator.Provider.Telegram/NavigatorRouteProviderConfigurationExtensions.cs @@ -1,3 +1,4 @@ +using System.IO; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; @@ -5,6 +6,8 @@ using Navigator.Abstractions; using Navigator.Configuration; using Navigator.Configuration.Provider; +using Newtonsoft.Json; +using Telegram.Bot.Types; namespace Navigator.Provider.Telegram { @@ -26,11 +29,37 @@ private static async Task ProcessTelegramUpdate(HttpContext context) { context.Response.StatusCode = 200; - if (context.Request.ContentType == "application/json") + if (context.Request.ContentType != "application/json") { - var navigatorMiddleware = context.RequestServices.GetRequiredService(); + return; + } + + var telegramUpdate = await ParseTelegramUpdate(context.Request.Body); - await navigatorMiddleware.Handle(context.Request); + if (telegramUpdate is null) + { + return; + } + + using var scope = context.RequestServices.CreateScope(); + + var navigatorMiddleware = context.RequestServices.GetRequiredService(); + + await navigatorMiddleware.Handle(context.Request); + } + + private static async Task ParseTelegramUpdate(Stream stream) + { + try + { + var reader = new StreamReader(stream); + var update = JsonConvert.DeserializeObject(await reader.ReadToEndAsync()); + + return update.Id == default ? default : update; + } + catch + { + return default; } } } From 76ef786f6b9961ef360d382f960e3a018536eeec Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 15 Feb 2021 14:48:27 +0100 Subject: [PATCH 044/304] More work on filling navigation contexte --- src/Navigator/Context/INavigatorContextAccessor.cs | 8 ++++++++ src/Navigator/Context/INavigatorContextBuilder.cs | 7 +++++++ src/Navigator/Context/NavigatorContext.cs | 3 ++- 3 files changed, 17 insertions(+), 1 deletion(-) create mode 100644 src/Navigator/Context/INavigatorContextAccessor.cs create mode 100644 src/Navigator/Context/INavigatorContextBuilder.cs diff --git a/src/Navigator/Context/INavigatorContextAccessor.cs b/src/Navigator/Context/INavigatorContextAccessor.cs new file mode 100644 index 0000000..e59d94b --- /dev/null +++ b/src/Navigator/Context/INavigatorContextAccessor.cs @@ -0,0 +1,8 @@ +namespace Navigator.Context +{ + public interface INavigatorContextAccessor + { + NavigatorContext NavigatorContext { get; set; } + + } +} \ No newline at end of file diff --git a/src/Navigator/Context/INavigatorContextBuilder.cs b/src/Navigator/Context/INavigatorContextBuilder.cs new file mode 100644 index 0000000..a123559 --- /dev/null +++ b/src/Navigator/Context/INavigatorContextBuilder.cs @@ -0,0 +1,7 @@ +namespace Navigator.Context +{ + public class INavigatorContextBuilder + { + + } +} \ No newline at end of file diff --git a/src/Navigator/Context/NavigatorContext.cs b/src/Navigator/Context/NavigatorContext.cs index cc6eae1..c4aef74 100644 --- a/src/Navigator/Context/NavigatorContext.cs +++ b/src/Navigator/Context/NavigatorContext.cs @@ -1,6 +1,7 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Threading.Tasks; +using Microsoft.AspNetCore.Http; using Navigator.Entities; using Telegram.Bot.Types; @@ -21,7 +22,7 @@ public class NavigatorContext /// /// Default constructor. /// - public NavigatorContext(INavigatorClient ) + public NavigatorContext(IHttpContextAccessor) { Items = new Dictionary(); } From 0cc565202739241ce0053d9bd33081ea02f3a86f Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 15 Feb 2021 14:48:46 +0100 Subject: [PATCH 045/304] Temperorary Action --- src/Navigator/Actions/Action.cs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 src/Navigator/Actions/Action.cs diff --git a/src/Navigator/Actions/Action.cs b/src/Navigator/Actions/Action.cs new file mode 100644 index 0000000..a6bdc7a --- /dev/null +++ b/src/Navigator/Actions/Action.cs @@ -0,0 +1,15 @@ +using MediatR; +using Navigator.Context; + +namespace Navigator.Actions +{ + public abstract class Action : IRequest + { + protected readonly NavigatorContext NavigatorContext; + + public Action(INavigatorContextAccessor navigatorContextAccessor) + { + NavigatorContext = navigatorContextAccessor.NavigatorContext; + } + } +} \ No newline at end of file From 488e03e3b102f62ba50c807fea11ee4d315dda25 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 15 Feb 2021 14:51:39 +0100 Subject: [PATCH 046/304] Added IProvider --- src/Navigator/IProvider.cs | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 src/Navigator/IProvider.cs diff --git a/src/Navigator/IProvider.cs b/src/Navigator/IProvider.cs new file mode 100644 index 0000000..3ed8049 --- /dev/null +++ b/src/Navigator/IProvider.cs @@ -0,0 +1,7 @@ +namespace Navigator +{ + public interface IProvider + { + + } +} \ No newline at end of file From ad9fde2a3bd11e82e80a19e75eaa153cc6648876 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 15 Feb 2021 14:52:22 +0100 Subject: [PATCH 047/304] Added provider implementation in each package --- src/Navigator.Provider.Discord/DiscordProvider.cs | 7 +++++++ src/Navigator.Provider.Telegram/TelegramProvider.cs | 7 +++++++ 2 files changed, 14 insertions(+) create mode 100644 src/Navigator.Provider.Discord/DiscordProvider.cs create mode 100644 src/Navigator.Provider.Telegram/TelegramProvider.cs diff --git a/src/Navigator.Provider.Discord/DiscordProvider.cs b/src/Navigator.Provider.Discord/DiscordProvider.cs new file mode 100644 index 0000000..ad34086 --- /dev/null +++ b/src/Navigator.Provider.Discord/DiscordProvider.cs @@ -0,0 +1,7 @@ +namespace Navigator.Provider.Discord +{ + public class DiscordProvider : IProvider + { + + } +} \ No newline at end of file diff --git a/src/Navigator.Provider.Telegram/TelegramProvider.cs b/src/Navigator.Provider.Telegram/TelegramProvider.cs new file mode 100644 index 0000000..0a9630a --- /dev/null +++ b/src/Navigator.Provider.Telegram/TelegramProvider.cs @@ -0,0 +1,7 @@ +namespace Navigator.Provider.Telegram +{ + public class TelegramProvider : IProvider + { + + } +} \ No newline at end of file From e63320f866e41e9c73c1098b7dec51d29cd42368 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 15 Feb 2021 16:34:58 +0100 Subject: [PATCH 048/304] Added IUser --- src/Navigator/Entities/BotUser.cs | 2 +- src/Navigator/Entities/IUser.cs | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) create mode 100644 src/Navigator/Entities/IUser.cs diff --git a/src/Navigator/Entities/BotUser.cs b/src/Navigator/Entities/BotUser.cs index cd2313e..e603313 100644 --- a/src/Navigator/Entities/BotUser.cs +++ b/src/Navigator/Entities/BotUser.cs @@ -1,6 +1,6 @@ namespace Navigator.Entities { - public class BotUser + public class BotUser : IUser { public string Id { get; init; } public string Username { get; init; } diff --git a/src/Navigator/Entities/IUser.cs b/src/Navigator/Entities/IUser.cs new file mode 100644 index 0000000..309ba66 --- /dev/null +++ b/src/Navigator/Entities/IUser.cs @@ -0,0 +1,18 @@ +namespace Navigator.Entities +{ + /// + /// User + /// + public interface IUser + { + /// + /// Id of the user. + /// + string Id { get; init; } + + /// + /// Username of the user, if any. + /// + string? Username { get; init; } + } +} \ No newline at end of file From a1145564284be65d759cb95835d421489a2f04fa Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 15 Feb 2021 17:32:41 +0100 Subject: [PATCH 049/304] Erased old stuff --- .../Navigator.Abstractions.csproj | 1 - .../Old/INavigatorContextBuilder.cs | 10 ---------- 2 files changed, 11 deletions(-) delete mode 100644 src/Navigator.Abstractions/Old/INavigatorContextBuilder.cs diff --git a/src/Navigator.Abstractions/Navigator.Abstractions.csproj b/src/Navigator.Abstractions/Navigator.Abstractions.csproj index ceb2d9c..907994d 100644 --- a/src/Navigator.Abstractions/Navigator.Abstractions.csproj +++ b/src/Navigator.Abstractions/Navigator.Abstractions.csproj @@ -25,7 +25,6 @@ - diff --git a/src/Navigator.Abstractions/Old/INavigatorContextBuilder.cs b/src/Navigator.Abstractions/Old/INavigatorContextBuilder.cs deleted file mode 100644 index 6bf1369..0000000 --- a/src/Navigator.Abstractions/Old/INavigatorContextBuilder.cs +++ /dev/null @@ -1,10 +0,0 @@ -using System.Threading.Tasks; -using Telegram.Bot.Types; - -namespace Navigator.Abstractions -{ - public interface INavigatorContextBuilder - { - Task Build(Update update); - } -} \ No newline at end of file From bb60f87f59d063bf5eaf3a8b955f5feca2e000b4 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 15 Feb 2021 17:33:03 +0100 Subject: [PATCH 050/304] Renamed method in NavigatorClient interface --- src/Navigator.Provider.Discord/NavigatorDiscordClient.cs | 2 +- src/Navigator.Provider.Telegram/NavigatorTelegramClient.cs | 2 +- src/Navigator/INavigatorClient.cs | 4 +++- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/src/Navigator.Provider.Discord/NavigatorDiscordClient.cs b/src/Navigator.Provider.Discord/NavigatorDiscordClient.cs index 2337923..eb80f7a 100644 --- a/src/Navigator.Provider.Discord/NavigatorDiscordClient.cs +++ b/src/Navigator.Provider.Discord/NavigatorDiscordClient.cs @@ -60,7 +60,7 @@ private Task LogAsync(LogMessage log) return Task.CompletedTask; } - public Task GetBotUser(CancellationToken cancellationToken = default) + public Task GetProfile(CancellationToken cancellationToken = default) { return Task.FromResult(new BotUser { diff --git a/src/Navigator.Provider.Telegram/NavigatorTelegramClient.cs b/src/Navigator.Provider.Telegram/NavigatorTelegramClient.cs index 01f1089..e45745a 100644 --- a/src/Navigator.Provider.Telegram/NavigatorTelegramClient.cs +++ b/src/Navigator.Provider.Telegram/NavigatorTelegramClient.cs @@ -14,7 +14,7 @@ public NavigatorTelegramClient(NavigatorOptions options) { } - public async Task GetBotUser(CancellationToken cancellationToken = default) + public async Task GetProfile(CancellationToken cancellationToken = default) { var bot = await GetMeAsync(cancellationToken); diff --git a/src/Navigator/INavigatorClient.cs b/src/Navigator/INavigatorClient.cs index d584de9..92c20fd 100644 --- a/src/Navigator/INavigatorClient.cs +++ b/src/Navigator/INavigatorClient.cs @@ -11,6 +11,8 @@ public interface INavigatorClient /// /// /// - Task GetBotUser(CancellationToken cancellationToken = default); + Task GetProfile(CancellationToken cancellationToken = default); + + IProvider Handles(); } } \ No newline at end of file From 8d2bc2f19de801aa2443db0ae79f004018124324 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 15 Feb 2021 17:33:22 +0100 Subject: [PATCH 051/304] More work on NavigatorContext --- .../Context/INavigatorContextBuilder.cs | 7 +++++-- src/Navigator/Context/NavigatorContext.cs | 20 ++++++++----------- 2 files changed, 13 insertions(+), 14 deletions(-) diff --git a/src/Navigator/Context/INavigatorContextBuilder.cs b/src/Navigator/Context/INavigatorContextBuilder.cs index a123559..90064a7 100644 --- a/src/Navigator/Context/INavigatorContextBuilder.cs +++ b/src/Navigator/Context/INavigatorContextBuilder.cs @@ -1,7 +1,10 @@ +using System.Threading.Tasks; +using Navigator.Entities; + namespace Navigator.Context { - public class INavigatorContextBuilder + public interface INavigatorContextBuilder { - + Task Build(IProvider provider, IUser from, IConversation conversation); } } \ No newline at end of file diff --git a/src/Navigator/Context/NavigatorContext.cs b/src/Navigator/Context/NavigatorContext.cs index c4aef74..a1d7c67 100644 --- a/src/Navigator/Context/NavigatorContext.cs +++ b/src/Navigator/Context/NavigatorContext.cs @@ -12,27 +12,23 @@ namespace Navigator.Context /// public class NavigatorContext { - public readonly IDictionary Extensions; + /// + /// + /// public readonly INavigatorClient Client; + public readonly IDictionary Extensions; public Dictionary Items { get; } - /// - public BotUser BotProfile { get; private set; } = null!; + public readonly BotUser BotProfile { get; } /// /// Default constructor. /// - public NavigatorContext(IHttpContextAccessor) - { - Items = new Dictionary(); - } - - /// - public async Task Init(INavigatorClient client, Dictionary extensions) + public NavigatorContext(INavigatorClient client) { Client = client; - BotProfile = await Client.GetBotUser(); - Extensions = new ReadOnlyDictionary(extensions); + BotProfile = client.GetProfile(); + Items = new Dictionary(); } /// From c727b31229c0dde405c019e997836f49e1a1acf4 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 15 Feb 2021 17:56:45 +0100 Subject: [PATCH 052/304] Added ContextFactory and updated flow of building a context --- .../Context/INavigatorContextBuilder.cs | 5 +- .../Context/INavigatorContextFactory.cs | 7 +++ src/Navigator/Context/NavigatorContext.cs | 35 +++++-------- .../Context/NavigatorContextBuilder.cs | 50 +++++++++++++++++++ src/Navigator/Entities/IConversation.cs | 16 ++++++ src/Navigator/INavigatorClient.cs | 2 +- 6 files changed, 91 insertions(+), 24 deletions(-) create mode 100644 src/Navigator/Context/INavigatorContextFactory.cs create mode 100644 src/Navigator/Context/NavigatorContextBuilder.cs create mode 100644 src/Navigator/Entities/IConversation.cs diff --git a/src/Navigator/Context/INavigatorContextBuilder.cs b/src/Navigator/Context/INavigatorContextBuilder.cs index 90064a7..68eacab 100644 --- a/src/Navigator/Context/INavigatorContextBuilder.cs +++ b/src/Navigator/Context/INavigatorContextBuilder.cs @@ -5,6 +5,9 @@ namespace Navigator.Context { public interface INavigatorContextBuilder { - Task Build(IProvider provider, IUser from, IConversation conversation); + INavigatorContextBuilder ForProvider(IProvider provider); + INavigatorContextBuilder From(IUser user); + + Task Retrieve(); } } \ No newline at end of file diff --git a/src/Navigator/Context/INavigatorContextFactory.cs b/src/Navigator/Context/INavigatorContextFactory.cs new file mode 100644 index 0000000..2444b94 --- /dev/null +++ b/src/Navigator/Context/INavigatorContextFactory.cs @@ -0,0 +1,7 @@ +namespace Navigator.Context +{ + public interface INavigatorContextFactory + { + INavigatorContextBuilder Supply(); + } +} \ No newline at end of file diff --git a/src/Navigator/Context/NavigatorContext.cs b/src/Navigator/Context/NavigatorContext.cs index a1d7c67..542670e 100644 --- a/src/Navigator/Context/NavigatorContext.cs +++ b/src/Navigator/Context/NavigatorContext.cs @@ -16,35 +16,26 @@ public class NavigatorContext /// /// public readonly INavigatorClient Client; - public readonly IDictionary Extensions; - public Dictionary Items { get; } - public readonly BotUser BotProfile { get; } + /// + /// + /// + public readonly BotUser BotProfile; /// - /// Default constructor. + /// /// - public NavigatorContext(INavigatorClient client) + public readonly Dictionary Items; + + /// + /// Builds a new Navigator Context. + /// + public NavigatorContext(INavigatorClient client, BotUser botProfile) { Client = client; - BotProfile = client.GetProfile(); + BotProfile = botProfile; + Items = new Dictionary(); } - - /// - public TExtension? Get(string extensionKey, bool throwIfNotFound = false) - { - if (Extensions.TryGetValue(extensionKey, out var extension)) - { - if (extension is TExtension castedExtension) - { - return castedExtension; - } - } - - return throwIfNotFound - ? throw new KeyNotFoundException($"{typeof(TExtension).Name} was not found.") - : default; - } } } \ No newline at end of file diff --git a/src/Navigator/Context/NavigatorContextBuilder.cs b/src/Navigator/Context/NavigatorContextBuilder.cs new file mode 100644 index 0000000..13a9801 --- /dev/null +++ b/src/Navigator/Context/NavigatorContextBuilder.cs @@ -0,0 +1,50 @@ +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using Navigator.Entities; + +namespace Navigator.Context +{ + public class NavigatorContextBuilder : INavigatorContextBuilder + { + private readonly ILogger _logger; + private readonly IEnumerable _navigatorClients; + private readonly NavigatorContextBuilderOptions _options; + + public NavigatorContextBuilder(ILogger logger, IEnumerable navigatorClients) + { + _logger = logger; + _navigatorClients = navigatorClients; + _options = new NavigatorContextBuilderOptions(); + } + + public INavigatorContextBuilder ForProvider(IProvider provider) + { + _options.Provider = provider; + + return this; + } + + public INavigatorContextBuilder From(IUser user) + { + _options.From = user; + + return this; + } + + public async Task Retrieve() + { + var client = _navigatorClients.First(navigatorClient => navigatorClient.Provider().GetType() == _options.Provider.GetType()); + var context = new NavigatorContext(client, await client.GetProfile()); + + throw new System.NotImplementedException(); + } + + private class NavigatorContextBuilderOptions + { + public IProvider Provider { get; set; } + public IUser From { get; set; } + } + } +} \ No newline at end of file diff --git a/src/Navigator/Entities/IConversation.cs b/src/Navigator/Entities/IConversation.cs new file mode 100644 index 0000000..b411140 --- /dev/null +++ b/src/Navigator/Entities/IConversation.cs @@ -0,0 +1,16 @@ +using System.Collections.Generic; + +namespace Navigator.Entities +{ + public interface IConversation + { + IUser User { get; init; } + IChat Chat { get; init; } + } + + public interface IChat + { + string Id { get; init; } + string Title { get; init; } + } +} \ No newline at end of file diff --git a/src/Navigator/INavigatorClient.cs b/src/Navigator/INavigatorClient.cs index 92c20fd..5c9f8ba 100644 --- a/src/Navigator/INavigatorClient.cs +++ b/src/Navigator/INavigatorClient.cs @@ -13,6 +13,6 @@ public interface INavigatorClient /// Task GetProfile(CancellationToken cancellationToken = default); - IProvider Handles(); + IProvider Provider(); } } \ No newline at end of file From a252df7b7902afccda000f2037c1d3c1df3a459d Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 15 Feb 2021 18:19:57 +0100 Subject: [PATCH 053/304] Extracted inteface from NavigatorContext --- src/Navigator/Context/INavigatorContext.cs | 23 ++++++++++++++++++++++ src/Navigator/Context/NavigatorContext.cs | 12 ++++------- 2 files changed, 27 insertions(+), 8 deletions(-) create mode 100644 src/Navigator/Context/INavigatorContext.cs diff --git a/src/Navigator/Context/INavigatorContext.cs b/src/Navigator/Context/INavigatorContext.cs new file mode 100644 index 0000000..b159017 --- /dev/null +++ b/src/Navigator/Context/INavigatorContext.cs @@ -0,0 +1,23 @@ +using System.Collections.Generic; +using Navigator.Entities; + +namespace Navigator.Context +{ + public interface INavigatorContext + { + /// + /// + /// + INavigatorClient Client { get; } + + /// + /// + /// + BotUser BotProfile { get; } + + /// + /// + /// + Dictionary Items { get; } + } +} \ No newline at end of file diff --git a/src/Navigator/Context/NavigatorContext.cs b/src/Navigator/Context/NavigatorContext.cs index 542670e..4fcb3d4 100644 --- a/src/Navigator/Context/NavigatorContext.cs +++ b/src/Navigator/Context/NavigatorContext.cs @@ -1,31 +1,27 @@ using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Http; using Navigator.Entities; -using Telegram.Bot.Types; namespace Navigator.Context { /// /// Navigator Context present in all actions. /// - public class NavigatorContext + public class NavigatorContext : INavigatorContext { /// /// /// - public readonly INavigatorClient Client; + public INavigatorClient Client { get; } /// /// /// - public readonly BotUser BotProfile; + public BotUser BotProfile { get; } /// /// /// - public readonly Dictionary Items; + public Dictionary Items { get; } /// /// Builds a new Navigator Context. From ac24b9171fd018e0e87533c4b033f7c91f4beefd Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 15 Feb 2021 18:20:46 +0100 Subject: [PATCH 054/304] Updated INavigatorContextAccessor Now uses the interface for NavigatorContext instead of the specific type. --- src/Navigator/Context/INavigatorContextAccessor.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/Navigator/Context/INavigatorContextAccessor.cs b/src/Navigator/Context/INavigatorContextAccessor.cs index e59d94b..6b1f332 100644 --- a/src/Navigator/Context/INavigatorContextAccessor.cs +++ b/src/Navigator/Context/INavigatorContextAccessor.cs @@ -2,7 +2,6 @@ namespace Navigator.Context { public interface INavigatorContextAccessor { - NavigatorContext NavigatorContext { get; set; } - + INavigatorContext NavigatorContext { get; } } } \ No newline at end of file From 34309ab052ed4f43769e30a7e9f60ab36cabe2cc Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 15 Feb 2021 18:20:59 +0100 Subject: [PATCH 055/304] Renamed method in INavigatorContextBuilder --- src/Navigator/Context/INavigatorContextBuilder.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Navigator/Context/INavigatorContextBuilder.cs b/src/Navigator/Context/INavigatorContextBuilder.cs index 68eacab..5a6c15f 100644 --- a/src/Navigator/Context/INavigatorContextBuilder.cs +++ b/src/Navigator/Context/INavigatorContextBuilder.cs @@ -8,6 +8,6 @@ public interface INavigatorContextBuilder INavigatorContextBuilder ForProvider(IProvider provider); INavigatorContextBuilder From(IUser user); - Task Retrieve(); + Task Build(); } } \ No newline at end of file From 3219fd651a58ab2fd11ef82431e44ef044764161 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 15 Feb 2021 18:21:19 +0100 Subject: [PATCH 056/304] Applied rename of method in NavigatorContextBuilder --- src/Navigator/Context/NavigatorContextBuilder.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Navigator/Context/NavigatorContextBuilder.cs b/src/Navigator/Context/NavigatorContextBuilder.cs index 13a9801..a67fcd2 100644 --- a/src/Navigator/Context/NavigatorContextBuilder.cs +++ b/src/Navigator/Context/NavigatorContextBuilder.cs @@ -33,12 +33,12 @@ public INavigatorContextBuilder From(IUser user) return this; } - public async Task Retrieve() + public async Task Build() { var client = _navigatorClients.First(navigatorClient => navigatorClient.Provider().GetType() == _options.Provider.GetType()); var context = new NavigatorContext(client, await client.GetProfile()); - throw new System.NotImplementedException(); + return context; } private class NavigatorContextBuilderOptions From d866570c196cc2f5bb629bc8e8250b0d5e84892b Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 15 Feb 2021 18:21:34 +0100 Subject: [PATCH 057/304] Updated INavigatorContextFactory methods --- src/Navigator/Context/INavigatorContextFactory.cs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/Navigator/Context/INavigatorContextFactory.cs b/src/Navigator/Context/INavigatorContextFactory.cs index 2444b94..83dc483 100644 --- a/src/Navigator/Context/INavigatorContextFactory.cs +++ b/src/Navigator/Context/INavigatorContextFactory.cs @@ -1,7 +1,12 @@ +using System; +using System.Threading.Tasks; + namespace Navigator.Context { public interface INavigatorContextFactory { - INavigatorContextBuilder Supply(); + Task Supply(Action action); + + INavigatorContext Retrieve(); } } \ No newline at end of file From 22032867aeb05b8512be1999ed080b5da302342e Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 15 Feb 2021 18:21:53 +0100 Subject: [PATCH 058/304] Barebones version of NavigatorContextAccessor --- src/Navigator/Context/NavigatorContextAccessor.cs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 src/Navigator/Context/NavigatorContextAccessor.cs diff --git a/src/Navigator/Context/NavigatorContextAccessor.cs b/src/Navigator/Context/NavigatorContextAccessor.cs new file mode 100644 index 0000000..fa9d13d --- /dev/null +++ b/src/Navigator/Context/NavigatorContextAccessor.cs @@ -0,0 +1,14 @@ +namespace Navigator.Context +{ + public class NavigatorContextAccessor : INavigatorContextAccessor + { + private readonly INavigatorContextFactory _navigatorContextFactory; + + public NavigatorContextAccessor(INavigatorContextFactory navigatorContextFactory) + { + _navigatorContextFactory = navigatorContextFactory; + } + + public INavigatorContext NavigatorContext { get; } + } +} \ No newline at end of file From c9ae6911cdabd92082f35107cbaf29720cce7135 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 15 Feb 2021 18:22:06 +0100 Subject: [PATCH 059/304] First iteration of NavigatorContextFactory --- .../Context/NavigatorContextFactory.cs | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 src/Navigator/Context/NavigatorContextFactory.cs diff --git a/src/Navigator/Context/NavigatorContextFactory.cs b/src/Navigator/Context/NavigatorContextFactory.cs new file mode 100644 index 0000000..6d8c7be --- /dev/null +++ b/src/Navigator/Context/NavigatorContextFactory.cs @@ -0,0 +1,42 @@ +using System; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; + +namespace Navigator.Context +{ + public class NavigatorContextFactory : INavigatorContextFactory + { + private readonly ILogger _logger; + private readonly INavigatorContextBuilder _navigatorContextBuilder; + private INavigatorContext NavigatorContext { get; set; } + + public NavigatorContextFactory(ILogger logger, INavigatorContextBuilder navigatorContextBuilder) + { + _logger = logger; + _navigatorContextBuilder = navigatorContextBuilder; + } + + public async Task Supply(Action action) + { + + action.Invoke(_navigatorContextBuilder); + + try + { + _logger.LogTrace("Building a new NavigatorContext"); + + NavigatorContext = await _navigatorContextBuilder.Build(); + } + catch (Exception e) + { + _logger.LogError(e, "Unhandled exception building NavigatorContext"); + throw; + } + } + + public INavigatorContext Retrieve() + { + return NavigatorContext ?? throw new NullReferenceException(); + } + } +} \ No newline at end of file From 7a5c3c7766880277535c7923544a8d64cce64072 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 15 Feb 2021 22:25:58 +0100 Subject: [PATCH 060/304] Updated name of method in INavigatorClient --- src/Navigator/Context/NavigatorContextBuilder.cs | 2 +- src/Navigator/INavigatorClient.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Navigator/Context/NavigatorContextBuilder.cs b/src/Navigator/Context/NavigatorContextBuilder.cs index a67fcd2..15a872b 100644 --- a/src/Navigator/Context/NavigatorContextBuilder.cs +++ b/src/Navigator/Context/NavigatorContextBuilder.cs @@ -35,7 +35,7 @@ public INavigatorContextBuilder From(IUser user) public async Task Build() { - var client = _navigatorClients.First(navigatorClient => navigatorClient.Provider().GetType() == _options.Provider.GetType()); + var client = _navigatorClients.First(navigatorClient => navigatorClient.IsClientFor().GetType() == _options.Provider.GetType()); var context = new NavigatorContext(client, await client.GetProfile()); return context; diff --git a/src/Navigator/INavigatorClient.cs b/src/Navigator/INavigatorClient.cs index 5c9f8ba..aa8ea93 100644 --- a/src/Navigator/INavigatorClient.cs +++ b/src/Navigator/INavigatorClient.cs @@ -13,6 +13,6 @@ public interface INavigatorClient /// Task GetProfile(CancellationToken cancellationToken = default); - IProvider Provider(); + IProvider IsClientFor(); } } \ No newline at end of file From f0fd6026835971a4ae8feb0d8cecba9798e4d8fc Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 15 Feb 2021 22:27:18 +0100 Subject: [PATCH 061/304] Renamed provider projects --- .../DiscordProvider.cs | 2 +- .../Hosted/SetDiscordShardedSocketHostedService.cs | 2 +- .../Navigator.Providers.Discord.csproj} | 0 .../NavigatorDiscordClient.cs | 2 +- .../NavigatorDiscordProviderOptionsExtensions.cs | 2 +- .../NavigatorProviderConfigurationExtension.cs | 2 +- .../NavigatorTelegramProviderOptions.cs | 2 +- .../Hosted/SetTelegramBotWebHookHostedService.cs | 2 +- .../Navigator.Providers.Telegram.csproj} | 0 .../NavigatorProviderConfigurationExtension.cs | 4 ++-- .../NavigatorRouteProviderConfigurationExtensions.cs | 2 +- .../NavigatorTelegramClient.cs | 2 +- .../NavigatorTelegramProviderOptions.cs | 2 +- .../NavigatorTelegramProviderOptionsExtensions.cs | 2 +- .../TelegramProvider.cs | 2 +- src/Navigator.Samples.Echo/Navigator.Samples.Echo.csproj | 2 +- src/Navigator.sln | 4 ++-- 17 files changed, 17 insertions(+), 17 deletions(-) rename src/{Navigator.Provider.Discord => Navigator.Providers.Discord}/DiscordProvider.cs (64%) rename src/{Navigator.Provider.Discord => Navigator.Providers.Discord}/Hosted/SetDiscordShardedSocketHostedService.cs (98%) rename src/{Navigator.Provider.Discord/Navigator.Provider.Discord.csproj => Navigator.Providers.Discord/Navigator.Providers.Discord.csproj} (100%) rename src/{Navigator.Provider.Discord => Navigator.Providers.Discord}/NavigatorDiscordClient.cs (98%) rename src/{Navigator.Provider.Discord => Navigator.Providers.Discord}/NavigatorDiscordProviderOptionsExtensions.cs (97%) rename src/{Navigator.Provider.Discord => Navigator.Providers.Discord}/NavigatorProviderConfigurationExtension.cs (96%) rename src/{Navigator.Provider.Discord => Navigator.Providers.Discord}/NavigatorTelegramProviderOptions.cs (76%) rename src/{Navigator.Provider.Telegram => Navigator.Providers.Telegram}/Hosted/SetTelegramBotWebHookHostedService.cs (98%) rename src/{Navigator.Provider.Telegram/Navigator.Provider.Telegram.csproj => Navigator.Providers.Telegram/Navigator.Providers.Telegram.csproj} (100%) rename src/{Navigator.Provider.Telegram => Navigator.Providers.Telegram}/NavigatorProviderConfigurationExtension.cs (92%) rename src/{Navigator.Provider.Telegram => Navigator.Providers.Telegram}/NavigatorRouteProviderConfigurationExtensions.cs (98%) rename src/{Navigator.Provider.Telegram => Navigator.Providers.Telegram}/NavigatorTelegramClient.cs (95%) rename src/{Navigator.Provider.Telegram => Navigator.Providers.Telegram}/NavigatorTelegramProviderOptions.cs (76%) rename src/{Navigator.Provider.Telegram => Navigator.Providers.Telegram}/NavigatorTelegramProviderOptionsExtensions.cs (98%) rename src/{Navigator.Provider.Telegram => Navigator.Providers.Telegram}/TelegramProvider.cs (64%) diff --git a/src/Navigator.Provider.Discord/DiscordProvider.cs b/src/Navigator.Providers.Discord/DiscordProvider.cs similarity index 64% rename from src/Navigator.Provider.Discord/DiscordProvider.cs rename to src/Navigator.Providers.Discord/DiscordProvider.cs index ad34086..67ddf6b 100644 --- a/src/Navigator.Provider.Discord/DiscordProvider.cs +++ b/src/Navigator.Providers.Discord/DiscordProvider.cs @@ -1,4 +1,4 @@ -namespace Navigator.Provider.Discord +namespace Navigator.Providers.Discord { public class DiscordProvider : IProvider { diff --git a/src/Navigator.Provider.Discord/Hosted/SetDiscordShardedSocketHostedService.cs b/src/Navigator.Providers.Discord/Hosted/SetDiscordShardedSocketHostedService.cs similarity index 98% rename from src/Navigator.Provider.Discord/Hosted/SetDiscordShardedSocketHostedService.cs rename to src/Navigator.Providers.Discord/Hosted/SetDiscordShardedSocketHostedService.cs index 8cd62ad..430e41a 100644 --- a/src/Navigator.Provider.Discord/Hosted/SetDiscordShardedSocketHostedService.cs +++ b/src/Navigator.Providers.Discord/Hosted/SetDiscordShardedSocketHostedService.cs @@ -8,7 +8,7 @@ using Microsoft.Extensions.Logging; using Navigator.Abstractions; using Navigator.Configuration; -using Navigator.Provider.Discord; +using Navigator.Providers.Discord; namespace Navigator.Provider.Telegram.Hosted { diff --git a/src/Navigator.Provider.Discord/Navigator.Provider.Discord.csproj b/src/Navigator.Providers.Discord/Navigator.Providers.Discord.csproj similarity index 100% rename from src/Navigator.Provider.Discord/Navigator.Provider.Discord.csproj rename to src/Navigator.Providers.Discord/Navigator.Providers.Discord.csproj diff --git a/src/Navigator.Provider.Discord/NavigatorDiscordClient.cs b/src/Navigator.Providers.Discord/NavigatorDiscordClient.cs similarity index 98% rename from src/Navigator.Provider.Discord/NavigatorDiscordClient.cs rename to src/Navigator.Providers.Discord/NavigatorDiscordClient.cs index eb80f7a..951d121 100644 --- a/src/Navigator.Provider.Discord/NavigatorDiscordClient.cs +++ b/src/Navigator.Providers.Discord/NavigatorDiscordClient.cs @@ -6,7 +6,7 @@ using Navigator.Configuration; using Navigator.Entities; -namespace Navigator.Provider.Discord +namespace Navigator.Providers.Discord { public class NavigatorDiscordClient : DiscordShardedClient, INavigatorClient { diff --git a/src/Navigator.Provider.Discord/NavigatorDiscordProviderOptionsExtensions.cs b/src/Navigator.Providers.Discord/NavigatorDiscordProviderOptionsExtensions.cs similarity index 97% rename from src/Navigator.Provider.Discord/NavigatorDiscordProviderOptionsExtensions.cs rename to src/Navigator.Providers.Discord/NavigatorDiscordProviderOptionsExtensions.cs index 26d77d7..c0ee25f 100644 --- a/src/Navigator.Provider.Discord/NavigatorDiscordProviderOptionsExtensions.cs +++ b/src/Navigator.Providers.Discord/NavigatorDiscordProviderOptionsExtensions.cs @@ -1,6 +1,6 @@ using Navigator.Configuration; -namespace Navigator.Provider.Discord +namespace Navigator.Providers.Discord { public static class NavigatorDiscordProviderOptionsExtensions { diff --git a/src/Navigator.Provider.Discord/NavigatorProviderConfigurationExtension.cs b/src/Navigator.Providers.Discord/NavigatorProviderConfigurationExtension.cs similarity index 96% rename from src/Navigator.Provider.Discord/NavigatorProviderConfigurationExtension.cs rename to src/Navigator.Providers.Discord/NavigatorProviderConfigurationExtension.cs index e98a7c9..fcb55c4 100644 --- a/src/Navigator.Provider.Discord/NavigatorProviderConfigurationExtension.cs +++ b/src/Navigator.Providers.Discord/NavigatorProviderConfigurationExtension.cs @@ -4,7 +4,7 @@ using Navigator.Configuration.Provider; using Navigator.Provider.Telegram.Hosted; -namespace Navigator.Provider.Discord +namespace Navigator.Providers.Discord { public static class NavigatorProviderConfigurationExtensions { diff --git a/src/Navigator.Provider.Discord/NavigatorTelegramProviderOptions.cs b/src/Navigator.Providers.Discord/NavigatorTelegramProviderOptions.cs similarity index 76% rename from src/Navigator.Provider.Discord/NavigatorTelegramProviderOptions.cs rename to src/Navigator.Providers.Discord/NavigatorTelegramProviderOptions.cs index 5fbf80f..a2c1c13 100644 --- a/src/Navigator.Provider.Discord/NavigatorTelegramProviderOptions.cs +++ b/src/Navigator.Providers.Discord/NavigatorTelegramProviderOptions.cs @@ -1,6 +1,6 @@ using Navigator.Configuration; -namespace Navigator.Provider.Discord +namespace Navigator.Providers.Discord { public class NavigatorDiscordProviderOptions : NavigatorOptions { diff --git a/src/Navigator.Provider.Telegram/Hosted/SetTelegramBotWebHookHostedService.cs b/src/Navigator.Providers.Telegram/Hosted/SetTelegramBotWebHookHostedService.cs similarity index 98% rename from src/Navigator.Provider.Telegram/Hosted/SetTelegramBotWebHookHostedService.cs rename to src/Navigator.Providers.Telegram/Hosted/SetTelegramBotWebHookHostedService.cs index 0b9cb13..95dd2bc 100644 --- a/src/Navigator.Provider.Telegram/Hosted/SetTelegramBotWebHookHostedService.cs +++ b/src/Navigator.Providers.Telegram/Hosted/SetTelegramBotWebHookHostedService.cs @@ -7,7 +7,7 @@ using Navigator.Abstractions; using Navigator.Configuration; -namespace Navigator.Provider.Telegram.Hosted +namespace Navigator.Providers.Telegram.Hosted { /// /// WebHook service for navigator's telegram provider. diff --git a/src/Navigator.Provider.Telegram/Navigator.Provider.Telegram.csproj b/src/Navigator.Providers.Telegram/Navigator.Providers.Telegram.csproj similarity index 100% rename from src/Navigator.Provider.Telegram/Navigator.Provider.Telegram.csproj rename to src/Navigator.Providers.Telegram/Navigator.Providers.Telegram.csproj diff --git a/src/Navigator.Provider.Telegram/NavigatorProviderConfigurationExtension.cs b/src/Navigator.Providers.Telegram/NavigatorProviderConfigurationExtension.cs similarity index 92% rename from src/Navigator.Provider.Telegram/NavigatorProviderConfigurationExtension.cs rename to src/Navigator.Providers.Telegram/NavigatorProviderConfigurationExtension.cs index 68ec99c..eb43428 100644 --- a/src/Navigator.Provider.Telegram/NavigatorProviderConfigurationExtension.cs +++ b/src/Navigator.Providers.Telegram/NavigatorProviderConfigurationExtension.cs @@ -2,9 +2,9 @@ using Microsoft.Extensions.DependencyInjection; using Navigator.Configuration; using Navigator.Configuration.Provider; -using Navigator.Provider.Telegram.Hosted; +using Navigator.Providers.Telegram.Hosted; -namespace Navigator.Provider.Telegram +namespace Navigator.Providers.Telegram { public static class NavigatorProviderConfigurationExtensions { diff --git a/src/Navigator.Provider.Telegram/NavigatorRouteProviderConfigurationExtensions.cs b/src/Navigator.Providers.Telegram/NavigatorRouteProviderConfigurationExtensions.cs similarity index 98% rename from src/Navigator.Provider.Telegram/NavigatorRouteProviderConfigurationExtensions.cs rename to src/Navigator.Providers.Telegram/NavigatorRouteProviderConfigurationExtensions.cs index dcb209a..f1fa827 100644 --- a/src/Navigator.Provider.Telegram/NavigatorRouteProviderConfigurationExtensions.cs +++ b/src/Navigator.Providers.Telegram/NavigatorRouteProviderConfigurationExtensions.cs @@ -9,7 +9,7 @@ using Newtonsoft.Json; using Telegram.Bot.Types; -namespace Navigator.Provider.Telegram +namespace Navigator.Providers.Telegram { public static class NavigatorRouteProviderConfigurationExtensions { diff --git a/src/Navigator.Provider.Telegram/NavigatorTelegramClient.cs b/src/Navigator.Providers.Telegram/NavigatorTelegramClient.cs similarity index 95% rename from src/Navigator.Provider.Telegram/NavigatorTelegramClient.cs rename to src/Navigator.Providers.Telegram/NavigatorTelegramClient.cs index e45745a..eb69269 100644 --- a/src/Navigator.Provider.Telegram/NavigatorTelegramClient.cs +++ b/src/Navigator.Providers.Telegram/NavigatorTelegramClient.cs @@ -5,7 +5,7 @@ using Navigator.Configuration; using Navigator.Entities; -namespace Navigator.Provider.Telegram +namespace Navigator.Providers.Telegram { public class NavigatorTelegramClient : RateLimitedTelegramBotClient, INavigatorClient { diff --git a/src/Navigator.Provider.Telegram/NavigatorTelegramProviderOptions.cs b/src/Navigator.Providers.Telegram/NavigatorTelegramProviderOptions.cs similarity index 76% rename from src/Navigator.Provider.Telegram/NavigatorTelegramProviderOptions.cs rename to src/Navigator.Providers.Telegram/NavigatorTelegramProviderOptions.cs index f326bd3..bbcf8c2 100644 --- a/src/Navigator.Provider.Telegram/NavigatorTelegramProviderOptions.cs +++ b/src/Navigator.Providers.Telegram/NavigatorTelegramProviderOptions.cs @@ -1,6 +1,6 @@ using Navigator.Configuration; -namespace Navigator.Provider.Telegram +namespace Navigator.Providers.Telegram { public class NavigatorTelegramProviderOptions : NavigatorOptions { diff --git a/src/Navigator.Provider.Telegram/NavigatorTelegramProviderOptionsExtensions.cs b/src/Navigator.Providers.Telegram/NavigatorTelegramProviderOptionsExtensions.cs similarity index 98% rename from src/Navigator.Provider.Telegram/NavigatorTelegramProviderOptionsExtensions.cs rename to src/Navigator.Providers.Telegram/NavigatorTelegramProviderOptionsExtensions.cs index faffbd5..d02258c 100644 --- a/src/Navigator.Provider.Telegram/NavigatorTelegramProviderOptionsExtensions.cs +++ b/src/Navigator.Providers.Telegram/NavigatorTelegramProviderOptionsExtensions.cs @@ -2,7 +2,7 @@ using MihaZupan.TelegramBotClients.RateLimitedClient; using Navigator.Configuration; -namespace Navigator.Provider.Telegram +namespace Navigator.Providers.Telegram { public static class NavigatorTelegramProviderOptionsExtensions { diff --git a/src/Navigator.Provider.Telegram/TelegramProvider.cs b/src/Navigator.Providers.Telegram/TelegramProvider.cs similarity index 64% rename from src/Navigator.Provider.Telegram/TelegramProvider.cs rename to src/Navigator.Providers.Telegram/TelegramProvider.cs index 0a9630a..4e99620 100644 --- a/src/Navigator.Provider.Telegram/TelegramProvider.cs +++ b/src/Navigator.Providers.Telegram/TelegramProvider.cs @@ -1,4 +1,4 @@ -namespace Navigator.Provider.Telegram +namespace Navigator.Providers.Telegram { public class TelegramProvider : IProvider { diff --git a/src/Navigator.Samples.Echo/Navigator.Samples.Echo.csproj b/src/Navigator.Samples.Echo/Navigator.Samples.Echo.csproj index 86d88dc..f4b9a66 100644 --- a/src/Navigator.Samples.Echo/Navigator.Samples.Echo.csproj +++ b/src/Navigator.Samples.Echo/Navigator.Samples.Echo.csproj @@ -17,7 +17,7 @@ - + diff --git a/src/Navigator.sln b/src/Navigator.sln index 33a2579..649f740 100644 --- a/src/Navigator.sln +++ b/src/Navigator.sln @@ -36,9 +36,9 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Navigator.Extensions.Shipya EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Providers", "Providers", "{DAA22477-BB29-475C-AD2C-905F81B4AD8E}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Navigator.Provider.Telegram", "Navigator.Provider.Telegram\Navigator.Provider.Telegram.csproj", "{8E0F6DCA-FAA4-4FA8-B9E0-75E9DC0F3573}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Navigator.Providers.Telegram", "Navigator.Providers.Telegram\Navigator.Providers.Telegram.csproj", "{8E0F6DCA-FAA4-4FA8-B9E0-75E9DC0F3573}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Navigator.Provider.Discord", "Navigator.Provider.Discord\Navigator.Provider.Discord.csproj", "{54039A52-DB2D-4428-A8D0-F998CA50B079}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Navigator.Providers.Discord", "Navigator.Providers.Discord\Navigator.Providers.Discord.csproj", "{54039A52-DB2D-4428-A8D0-F998CA50B079}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution From 56907c51fd7f8489c85c7c48f02151ae4b6998c6 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 15 Feb 2021 22:46:21 +0100 Subject: [PATCH 062/304] Added Provider fluent selector --- src/Navigator/Provider.cs | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 src/Navigator/Provider.cs diff --git a/src/Navigator/Provider.cs b/src/Navigator/Provider.cs new file mode 100644 index 0000000..26696f8 --- /dev/null +++ b/src/Navigator/Provider.cs @@ -0,0 +1,10 @@ +namespace Navigator +{ + public static class Provider + { + public static TProvider For() where TProvider : IProvider, new() + { + return new(); + } + } +} \ No newline at end of file From 60f66276485685f30e8996e73a110ae6b943f5d2 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 15 Feb 2021 22:47:09 +0100 Subject: [PATCH 063/304] Implemented IsClientFor in providers. This may need a new name. --- src/Navigator.Providers.Discord/NavigatorDiscordClient.cs | 5 +++++ .../NavigatorTelegramClient.cs | 7 ++++++- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/src/Navigator.Providers.Discord/NavigatorDiscordClient.cs b/src/Navigator.Providers.Discord/NavigatorDiscordClient.cs index 951d121..937483c 100644 --- a/src/Navigator.Providers.Discord/NavigatorDiscordClient.cs +++ b/src/Navigator.Providers.Discord/NavigatorDiscordClient.cs @@ -68,5 +68,10 @@ public Task GetProfile(CancellationToken cancellationToken = default) Username = CurrentUser.Username }); } + + public IProvider IsClientFor() + { + return Provider.For(); + } } } \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/NavigatorTelegramClient.cs b/src/Navigator.Providers.Telegram/NavigatorTelegramClient.cs index eb69269..0cf77c3 100644 --- a/src/Navigator.Providers.Telegram/NavigatorTelegramClient.cs +++ b/src/Navigator.Providers.Telegram/NavigatorTelegramClient.cs @@ -9,7 +9,7 @@ namespace Navigator.Providers.Telegram { public class NavigatorTelegramClient : RateLimitedTelegramBotClient, INavigatorClient { - public NavigatorTelegramClient(NavigatorOptions options) + public NavigatorTelegramClient(INavigatorOptions options) : base(options.GetTelegramToken(), (HttpClient) default!, options.GetSchedulerSettingsOrDefault()) { } @@ -24,5 +24,10 @@ public async Task GetProfile(CancellationToken cancellationToken = defa Username = bot.Username }; } + + public IProvider IsClientFor() + { + return Provider.For(); + } } } \ No newline at end of file From fff3f3ebdfbcba37569364c904f59ae58f27be11 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 15 Feb 2021 22:47:23 +0100 Subject: [PATCH 064/304] Corrected namespaces --- .../Hosted/SetDiscordShardedSocketHostedService.cs | 5 +---- .../NavigatorProviderConfigurationExtension.cs | 2 +- 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/src/Navigator.Providers.Discord/Hosted/SetDiscordShardedSocketHostedService.cs b/src/Navigator.Providers.Discord/Hosted/SetDiscordShardedSocketHostedService.cs index 430e41a..e729a4a 100644 --- a/src/Navigator.Providers.Discord/Hosted/SetDiscordShardedSocketHostedService.cs +++ b/src/Navigator.Providers.Discord/Hosted/SetDiscordShardedSocketHostedService.cs @@ -2,15 +2,12 @@ using System.Threading; using System.Threading.Tasks; using Discord; -using Discord.WebSocket; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; -using Navigator.Abstractions; using Navigator.Configuration; -using Navigator.Providers.Discord; -namespace Navigator.Provider.Telegram.Hosted +namespace Navigator.Providers.Discord.Hosted { /// /// WebHook service for navigator's telegram provider. diff --git a/src/Navigator.Providers.Discord/NavigatorProviderConfigurationExtension.cs b/src/Navigator.Providers.Discord/NavigatorProviderConfigurationExtension.cs index fcb55c4..81951c7 100644 --- a/src/Navigator.Providers.Discord/NavigatorProviderConfigurationExtension.cs +++ b/src/Navigator.Providers.Discord/NavigatorProviderConfigurationExtension.cs @@ -2,7 +2,7 @@ using Microsoft.Extensions.DependencyInjection; using Navigator.Configuration; using Navigator.Configuration.Provider; -using Navigator.Provider.Telegram.Hosted; +using Navigator.Providers.Discord.Hosted; namespace Navigator.Providers.Discord { From 2e88a7af9e02aa58c2eca294d2da552c1b25a0b8 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 15 Feb 2021 22:47:49 +0100 Subject: [PATCH 065/304] Created extension method to get a client out of a list --- .../NavigatorClientCollectionExtensions.cs | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 src/Navigator/NavigatorClientCollectionExtensions.cs diff --git a/src/Navigator/NavigatorClientCollectionExtensions.cs b/src/Navigator/NavigatorClientCollectionExtensions.cs new file mode 100644 index 0000000..b9827a5 --- /dev/null +++ b/src/Navigator/NavigatorClientCollectionExtensions.cs @@ -0,0 +1,13 @@ +using System.Collections.Generic; +using System.Linq; + +namespace Navigator +{ + public static class NavigatorClientCollectionExtensions + { + public static INavigatorClient? GetClientFor(this IEnumerable clients, IProvider? provider) + { + return clients.FirstOrDefault(client => client.IsClientFor().GetType() == provider?.GetType()); + } + } +} \ No newline at end of file From 123d1ab9bb76cb3794ab62dd697195800857e477 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 15 Feb 2021 22:48:13 +0100 Subject: [PATCH 066/304] Improved Build method in NavigatorContextBuilder --- src/Navigator/Context/NavigatorContextBuilder.cs | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/src/Navigator/Context/NavigatorContextBuilder.cs b/src/Navigator/Context/NavigatorContextBuilder.cs index 15a872b..f0d7325 100644 --- a/src/Navigator/Context/NavigatorContextBuilder.cs +++ b/src/Navigator/Context/NavigatorContextBuilder.cs @@ -1,3 +1,4 @@ +using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; @@ -35,7 +36,15 @@ public INavigatorContextBuilder From(IUser user) public async Task Build() { - var client = _navigatorClients.First(navigatorClient => navigatorClient.IsClientFor().GetType() == _options.Provider.GetType()); + var client = _navigatorClients.GetClientFor(_options.Provider); + + if (client is null) + { + _logger.LogError("No client found for provider: {@Provider}", _options.Provider); + //TODO: make NavigatorException + throw new Exception($"No client found for provider: {_options.Provider}"); + } + var context = new NavigatorContext(client, await client.GetProfile()); return context; @@ -43,8 +52,8 @@ public async Task Build() private class NavigatorContextBuilderOptions { - public IProvider Provider { get; set; } - public IUser From { get; set; } + public IProvider? Provider { get; set; } + public IUser? From { get; set; } } } } \ No newline at end of file From 24f342ecf59763ad72a09a34e035e3e6e0e2809a Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 15 Feb 2021 22:48:26 +0100 Subject: [PATCH 067/304] Corrected import on example project --- src/Navigator.Samples.Echo/Startup.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Navigator.Samples.Echo/Startup.cs b/src/Navigator.Samples.Echo/Startup.cs index 1380660..2a07458 100644 --- a/src/Navigator.Samples.Echo/Startup.cs +++ b/src/Navigator.Samples.Echo/Startup.cs @@ -8,7 +8,7 @@ using Navigator.Configuration; using Navigator.Extensions.Shipyard; using Navigator.Extensions.Store; -using Navigator.Provider.Telegram; +using Navigator.Providers.Telegram; using Navigator.Samples.Echo.Entity; using Navigator.Samples.Echo.Persistence; From 5e1d7d2c98b3b31538d560ca488bc7aa553d9cb7 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 16 Feb 2021 17:22:11 +0100 Subject: [PATCH 068/304] Separated Builder and BuilderOptions --- src/Navigator/Context/INavigatorContextBuilder.cs | 6 ++---- .../Context/INavigatorContextBuilderOptions.cs | 12 ++++++++++++ 2 files changed, 14 insertions(+), 4 deletions(-) create mode 100644 src/Navigator/Context/INavigatorContextBuilderOptions.cs diff --git a/src/Navigator/Context/INavigatorContextBuilder.cs b/src/Navigator/Context/INavigatorContextBuilder.cs index 5a6c15f..9096072 100644 --- a/src/Navigator/Context/INavigatorContextBuilder.cs +++ b/src/Navigator/Context/INavigatorContextBuilder.cs @@ -1,3 +1,4 @@ +using System; using System.Threading.Tasks; using Navigator.Entities; @@ -5,9 +6,6 @@ namespace Navigator.Context { public interface INavigatorContextBuilder { - INavigatorContextBuilder ForProvider(IProvider provider); - INavigatorContextBuilder From(IUser user); - - Task Build(); + Task Build(Action configurationAction); } } \ No newline at end of file diff --git a/src/Navigator/Context/INavigatorContextBuilderOptions.cs b/src/Navigator/Context/INavigatorContextBuilderOptions.cs new file mode 100644 index 0000000..cc3b75c --- /dev/null +++ b/src/Navigator/Context/INavigatorContextBuilderOptions.cs @@ -0,0 +1,12 @@ +using System.Collections.Generic; + +namespace Navigator.Context +{ + public interface INavigatorContextBuilderOptions + { + bool TryRegisterOption(string key, object option); + void ForceRegisterOption(string key, object option); + TType? RetrieveOption(string key); + Dictionary RetrieveAllOptions(); + } +} \ No newline at end of file From d5a4cfbba520d9ec1278cfd8190c556a8ac0926a Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 16 Feb 2021 17:23:50 +0100 Subject: [PATCH 069/304] Updated Factory method --- src/Navigator/Context/INavigatorContextFactory.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Navigator/Context/INavigatorContextFactory.cs b/src/Navigator/Context/INavigatorContextFactory.cs index 83dc483..b75e4dd 100644 --- a/src/Navigator/Context/INavigatorContextFactory.cs +++ b/src/Navigator/Context/INavigatorContextFactory.cs @@ -5,7 +5,7 @@ namespace Navigator.Context { public interface INavigatorContextFactory { - Task Supply(Action action); + Task Supply(Action action); INavigatorContext Retrieve(); } From dd2df14cce2c7b5fa00b1e4877a41f977fd95065 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 16 Feb 2021 17:24:18 +0100 Subject: [PATCH 070/304] Updated implementations to match interfaces --- .../Context/NavigatorContextBuilder.cs | 33 ++++----------- .../Context/NavigatorContextBuilderOptions.cs | 42 +++++++++++++++++++ ...avigatorContextBuilderOptionsExtensions.cs | 24 +++++++++++ .../Context/NavigatorContextFactory.cs | 7 +--- 4 files changed, 77 insertions(+), 29 deletions(-) create mode 100644 src/Navigator/Context/NavigatorContextBuilderOptions.cs create mode 100644 src/Navigator/Context/NavigatorContextBuilderOptionsExtensions.cs diff --git a/src/Navigator/Context/NavigatorContextBuilder.cs b/src/Navigator/Context/NavigatorContextBuilder.cs index f0d7325..cfcfc2f 100644 --- a/src/Navigator/Context/NavigatorContextBuilder.cs +++ b/src/Navigator/Context/NavigatorContextBuilder.cs @@ -11,8 +11,9 @@ public class NavigatorContextBuilder : INavigatorContextBuilder { private readonly ILogger _logger; private readonly IEnumerable _navigatorClients; - private readonly NavigatorContextBuilderOptions _options; + private readonly INavigatorContextBuilderOptions _options; + public NavigatorContextBuilder(ILogger logger, IEnumerable navigatorClients) { _logger = logger; @@ -20,40 +21,24 @@ public NavigatorContextBuilder(ILogger logger, IEnumera _options = new NavigatorContextBuilderOptions(); } - public INavigatorContextBuilder ForProvider(IProvider provider) - { - _options.Provider = provider; - - return this; - } + - public INavigatorContextBuilder From(IUser user) + public async Task Build(Action optionsAction) { - _options.From = user; - - return this; - } - - public async Task Build() - { - var client = _navigatorClients.GetClientFor(_options.Provider); + optionsAction.Invoke(_options); + + var client = _navigatorClients.GetClientFor(_options.GetProvider()); if (client is null) { - _logger.LogError("No client found for provider: {@Provider}", _options.Provider); + _logger.LogError("No client found for provider: {@Provider}", _options.GetProvider()); //TODO: make NavigatorException - throw new Exception($"No client found for provider: {_options.Provider}"); + throw new Exception($"No client found for provider: {_options.GetProvider()?.Name}"); } var context = new NavigatorContext(client, await client.GetProfile()); return context; } - - private class NavigatorContextBuilderOptions - { - public IProvider? Provider { get; set; } - public IUser? From { get; set; } - } } } \ No newline at end of file diff --git a/src/Navigator/Context/NavigatorContextBuilderOptions.cs b/src/Navigator/Context/NavigatorContextBuilderOptions.cs new file mode 100644 index 0000000..a4ddcd3 --- /dev/null +++ b/src/Navigator/Context/NavigatorContextBuilderOptions.cs @@ -0,0 +1,42 @@ +using System.Collections.Generic; +using Navigator.Entities; + +namespace Navigator.Context +{ + public class NavigatorContextBuilderOptions : INavigatorContextBuilderOptions + { + private readonly Dictionary _options; + + public NavigatorContextBuilderOptions() + { + _options = new Dictionary(); + } + + public bool TryRegisterOption(string key, object option) + { + return _options.TryAdd(key, option); + } + + public void ForceRegisterOption(string key, object option) + { + _options.Remove(key); + + TryRegisterOption(key, option); + } + + public TType? RetrieveOption(string key) + { + if (_options.TryGetValue(key, out var option)) + { + return (TType) option; + } + + return default; + } + + public Dictionary RetrieveAllOptions() + { + return _options; + } + } +} \ No newline at end of file diff --git a/src/Navigator/Context/NavigatorContextBuilderOptionsExtensions.cs b/src/Navigator/Context/NavigatorContextBuilderOptionsExtensions.cs new file mode 100644 index 0000000..b872c6f --- /dev/null +++ b/src/Navigator/Context/NavigatorContextBuilderOptionsExtensions.cs @@ -0,0 +1,24 @@ +using System; + +namespace Navigator.Context +{ + public static class NavigatorContextBuilderOptionsExtensions + { + #region Provider + + private const string ProviderKey = "_navigator.context.options.provider"; + + public static void Provider(this NavigatorContextBuilderOptions contextBuilderOptions) where TProvider : IProvider, new() + { + contextBuilderOptions.TryRegisterOption(ProviderKey, typeof(TProvider)); + + } + + public static Type? GetProvider(this INavigatorContextBuilderOptions contextBuilderOptions) + { + return contextBuilderOptions.RetrieveOption(ProviderKey); + } + + #endregion + } +} \ No newline at end of file diff --git a/src/Navigator/Context/NavigatorContextFactory.cs b/src/Navigator/Context/NavigatorContextFactory.cs index 6d8c7be..3e8d513 100644 --- a/src/Navigator/Context/NavigatorContextFactory.cs +++ b/src/Navigator/Context/NavigatorContextFactory.cs @@ -16,16 +16,13 @@ public NavigatorContextFactory(ILogger logger, INavigat _navigatorContextBuilder = navigatorContextBuilder; } - public async Task Supply(Action action) + public async Task Supply(Action action) { - - action.Invoke(_navigatorContextBuilder); - try { _logger.LogTrace("Building a new NavigatorContext"); - NavigatorContext = await _navigatorContextBuilder.Build(); + NavigatorContext = await _navigatorContextBuilder.Build(action); } catch (Exception e) { From 25b1bf24dcec9e5559abda42a3073f35e12609bf Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 16 Feb 2021 17:24:29 +0100 Subject: [PATCH 071/304] Updated extension method to find correct client --- src/Navigator/NavigatorClientCollectionExtensions.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/Navigator/NavigatorClientCollectionExtensions.cs b/src/Navigator/NavigatorClientCollectionExtensions.cs index b9827a5..e7ba8a1 100644 --- a/src/Navigator/NavigatorClientCollectionExtensions.cs +++ b/src/Navigator/NavigatorClientCollectionExtensions.cs @@ -1,3 +1,4 @@ +using System; using System.Collections.Generic; using System.Linq; @@ -5,9 +6,9 @@ namespace Navigator { public static class NavigatorClientCollectionExtensions { - public static INavigatorClient? GetClientFor(this IEnumerable clients, IProvider? provider) + public static INavigatorClient? GetClientFor(this IEnumerable clients, Type? provider) { - return clients.FirstOrDefault(client => client.IsClientFor().GetType() == provider?.GetType()); + return clients.FirstOrDefault(client => client.IsClientFor().GetType() == provider); } } } \ No newline at end of file From 325b512b8325aeb6d10d63963de435cd9c518bb5 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 16 Feb 2021 18:17:33 +0100 Subject: [PATCH 072/304] Deleted old code --- .../Old/INavigatorContextExtensionProvider.cs | 11 ----------- 1 file changed, 11 deletions(-) delete mode 100644 src/Navigator.Abstractions/Old/INavigatorContextExtensionProvider.cs diff --git a/src/Navigator.Abstractions/Old/INavigatorContextExtensionProvider.cs b/src/Navigator.Abstractions/Old/INavigatorContextExtensionProvider.cs deleted file mode 100644 index 78d09d9..0000000 --- a/src/Navigator.Abstractions/Old/INavigatorContextExtensionProvider.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System.Threading.Tasks; -using Telegram.Bot.Types; - -namespace Navigator.Abstractions -{ - public interface INavigatorContextExtensionProvider - { - int Order => 1000; - Task<(string?, object?)> Process(Update update); - } -} \ No newline at end of file From 6839ee65f395d00a804b186b1d218e3976d074a7 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 16 Feb 2021 18:17:59 +0100 Subject: [PATCH 073/304] More work on NavigatorContextExtensions --- .../Context/Extensions/INavigatorContextExtension.cs | 9 +++++++++ src/Navigator/Context/INavigatorContextFactory.cs | 2 +- src/Navigator/Context/NavigatorContextBuilder.cs | 11 +++++++---- .../NavigatorContextBuilderOptionsExtensions.cs | 2 +- 4 files changed, 18 insertions(+), 6 deletions(-) create mode 100644 src/Navigator/Context/Extensions/INavigatorContextExtension.cs diff --git a/src/Navigator/Context/Extensions/INavigatorContextExtension.cs b/src/Navigator/Context/Extensions/INavigatorContextExtension.cs new file mode 100644 index 0000000..03f792b --- /dev/null +++ b/src/Navigator/Context/Extensions/INavigatorContextExtension.cs @@ -0,0 +1,9 @@ +using System.Threading.Tasks; + +namespace Navigator.Context.Extensions +{ + public interface INavigatorContextExtension + { + Task Extend(INavigatorContext navigatorContext, NavigatorContextBuilderOptions builderOptions); + } +} \ No newline at end of file diff --git a/src/Navigator/Context/INavigatorContextFactory.cs b/src/Navigator/Context/INavigatorContextFactory.cs index b75e4dd..255cac8 100644 --- a/src/Navigator/Context/INavigatorContextFactory.cs +++ b/src/Navigator/Context/INavigatorContextFactory.cs @@ -5,7 +5,7 @@ namespace Navigator.Context { public interface INavigatorContextFactory { - Task Supply(Action action); + Task Supply(Action action); INavigatorContext Retrieve(); } diff --git a/src/Navigator/Context/NavigatorContextBuilder.cs b/src/Navigator/Context/NavigatorContextBuilder.cs index cfcfc2f..a8b8d0e 100644 --- a/src/Navigator/Context/NavigatorContextBuilder.cs +++ b/src/Navigator/Context/NavigatorContextBuilder.cs @@ -3,6 +3,7 @@ using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Logging; +using Navigator.Context.Extensions; using Navigator.Entities; namespace Navigator.Context @@ -11,18 +12,18 @@ public class NavigatorContextBuilder : INavigatorContextBuilder { private readonly ILogger _logger; private readonly IEnumerable _navigatorClients; + private readonly IEnumerable _navigatorContextExtensions; private readonly INavigatorContextBuilderOptions _options; - - public NavigatorContextBuilder(ILogger logger, IEnumerable navigatorClients) + public NavigatorContextBuilder(ILogger logger, IEnumerable navigatorClients, IEnumerable navigatorContextExtensions) { _logger = logger; _navigatorClients = navigatorClients; + _navigatorContextExtensions = navigatorContextExtensions; + _options = new NavigatorContextBuilderOptions(); } - - public async Task Build(Action optionsAction) { optionsAction.Invoke(_options); @@ -37,6 +38,8 @@ public async Task Build(Action(this NavigatorContextBuilderOptions contextBuilderOptions) where TProvider : IProvider, new() + public static void SetProvider(this INavigatorContextBuilderOptions contextBuilderOptions) where TProvider : IProvider, new() { contextBuilderOptions.TryRegisterOption(ProviderKey, typeof(TProvider)); From c8a393dff87f0292b0d200637c8c0a875c4624c8 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 16 Feb 2021 18:36:27 +0100 Subject: [PATCH 074/304] More work on extensions, now the flow applies them --- .../Context/Extensions/INavigatorContextExtension.cs | 2 +- src/Navigator/Context/NavigatorContextBuilder.cs | 6 +++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/src/Navigator/Context/Extensions/INavigatorContextExtension.cs b/src/Navigator/Context/Extensions/INavigatorContextExtension.cs index 03f792b..57c5028 100644 --- a/src/Navigator/Context/Extensions/INavigatorContextExtension.cs +++ b/src/Navigator/Context/Extensions/INavigatorContextExtension.cs @@ -4,6 +4,6 @@ namespace Navigator.Context.Extensions { public interface INavigatorContextExtension { - Task Extend(INavigatorContext navigatorContext, NavigatorContextBuilderOptions builderOptions); + Task Extend(INavigatorContext navigatorContext, INavigatorContextBuilderOptions builderOptions); } } \ No newline at end of file diff --git a/src/Navigator/Context/NavigatorContextBuilder.cs b/src/Navigator/Context/NavigatorContextBuilder.cs index a8b8d0e..fe222e8 100644 --- a/src/Navigator/Context/NavigatorContextBuilder.cs +++ b/src/Navigator/Context/NavigatorContextBuilder.cs @@ -38,7 +38,11 @@ public async Task Build(Action Date: Tue, 16 Feb 2021 20:35:57 +0100 Subject: [PATCH 075/304] Started work in actions --- src/Navigator/Actions/{Action.cs => BaseAction.cs} | 6 ++++-- src/Navigator/Actions/GenericActions.cs | 7 +++++++ 2 files changed, 11 insertions(+), 2 deletions(-) rename src/Navigator/Actions/{Action.cs => BaseAction.cs} (68%) create mode 100644 src/Navigator/Actions/GenericActions.cs diff --git a/src/Navigator/Actions/Action.cs b/src/Navigator/Actions/BaseAction.cs similarity index 68% rename from src/Navigator/Actions/Action.cs rename to src/Navigator/Actions/BaseAction.cs index a6bdc7a..6e08e1d 100644 --- a/src/Navigator/Actions/Action.cs +++ b/src/Navigator/Actions/BaseAction.cs @@ -5,8 +5,10 @@ namespace Navigator.Actions { public abstract class Action : IRequest { - protected readonly NavigatorContext NavigatorContext; - + public string Type { get; protected set; } + f + protected readonly INavigatorContext NavigatorContext; + public Action(INavigatorContextAccessor navigatorContextAccessor) { NavigatorContext = navigatorContextAccessor.NavigatorContext; diff --git a/src/Navigator/Actions/GenericActions.cs b/src/Navigator/Actions/GenericActions.cs new file mode 100644 index 0000000..0b05ab6 --- /dev/null +++ b/src/Navigator/Actions/GenericActions.cs @@ -0,0 +1,7 @@ +namespace Navigator.Actions +{ + public class GenericActions + { + + } +} \ No newline at end of file From 2b5ce2a6d698d169ef2612d5cdadb8f4a9f7c5ce Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 22 Feb 2021 15:32:07 +0100 Subject: [PATCH 076/304] Woeking on actions and imports --- ...NavigatorProviderConfigurationExtension.cs | 2 ++ .../TelegramMiddleware.cs | 28 +++++++++++++++++++ src/Navigator/Actions/BaseAction.cs | 12 ++++---- src/Navigator/Actions/GenericActions.cs | 4 +-- src/Navigator/Actions/MessageBaseAction.cs | 26 +++++++++++++++++ .../Context/NavigatorContextBuilder.cs | 3 +- src/Navigator/Navigator.csproj | 13 ++------- 7 files changed, 66 insertions(+), 22 deletions(-) create mode 100644 src/Navigator.Providers.Telegram/TelegramMiddleware.cs create mode 100644 src/Navigator/Actions/MessageBaseAction.cs diff --git a/src/Navigator.Providers.Telegram/NavigatorProviderConfigurationExtension.cs b/src/Navigator.Providers.Telegram/NavigatorProviderConfigurationExtension.cs index eb43428..e47cba6 100644 --- a/src/Navigator.Providers.Telegram/NavigatorProviderConfigurationExtension.cs +++ b/src/Navigator.Providers.Telegram/NavigatorProviderConfigurationExtension.cs @@ -21,6 +21,8 @@ public static NavigatorConfiguration Telegram(this NavigatorProviderConfiguratio services.AddSingleton(); services.AddSingleton(sp => sp.GetRequiredService()); + services.AddScoped(); + services.AddHostedService(); }); diff --git a/src/Navigator.Providers.Telegram/TelegramMiddleware.cs b/src/Navigator.Providers.Telegram/TelegramMiddleware.cs new file mode 100644 index 0000000..d978ad2 --- /dev/null +++ b/src/Navigator.Providers.Telegram/TelegramMiddleware.cs @@ -0,0 +1,28 @@ +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using Navigator.Context; +using Telegram.Bot.Types; + +namespace Navigator.Providers.Telegram +{ + public class TelegramMiddleware + { + private readonly ILogger _logger; + private readonly INavigatorContextFactory _navigatorContextFactory; + + public TelegramMiddleware(ILogger logger, INavigatorContextFactory navigatorContextFactory) + { + _logger = logger; + _navigatorContextFactory = navigatorContextFactory; + } + + public async Task Process(Update update) + { + await _navigatorContextFactory.Supply(builder => + { + builder.SetProvider(); + builder.TryRegisterOption("navigator.provider.telegram.original_update", update); + }); + } + } +} \ No newline at end of file diff --git a/src/Navigator/Actions/BaseAction.cs b/src/Navigator/Actions/BaseAction.cs index 6e08e1d..7f0bb9a 100644 --- a/src/Navigator/Actions/BaseAction.cs +++ b/src/Navigator/Actions/BaseAction.cs @@ -1,17 +1,15 @@ +using System.Threading.Tasks; using MediatR; using Navigator.Context; namespace Navigator.Actions { - public abstract class Action : IRequest + public abstract class BaseAction : IRequest { - public string Type { get; protected set; } - f - protected readonly INavigatorContext NavigatorContext; - - public Action(INavigatorContextAccessor navigatorContextAccessor) + public static string Type { get; protected set; } + protected + public Task Init(INavigatorContext navigatorContext) { - NavigatorContext = navigatorContextAccessor.NavigatorContext; } } } \ No newline at end of file diff --git a/src/Navigator/Actions/GenericActions.cs b/src/Navigator/Actions/GenericActions.cs index 0b05ab6..c6076cb 100644 --- a/src/Navigator/Actions/GenericActions.cs +++ b/src/Navigator/Actions/GenericActions.cs @@ -1,7 +1,7 @@ namespace Navigator.Actions { - public class GenericActions + public static class GenericActions { - + public static string Message => "navigator.actions.default.message"; } } \ No newline at end of file diff --git a/src/Navigator/Actions/MessageBaseAction.cs b/src/Navigator/Actions/MessageBaseAction.cs new file mode 100644 index 0000000..1dafc1d --- /dev/null +++ b/src/Navigator/Actions/MessageBaseAction.cs @@ -0,0 +1,26 @@ +using System; +using Navigator.Context; + +namespace Navigator.Actions +{ + public abstract class MessageAction : BaseAction + { + + public DateTime MessageTimestamp { get; protected set; } + public int MessageId { get; protected set; } + public int? ReplyToMessageId { get; protected set; } + + public override IAction Init(INavigatorContext ctx) + { + MessageTimestamp = ctx.Update.Message.Date; + MessageId = ctx.Update.Message.MessageId; + ReplyToMessageId = ctx.Update.Message.ReplyToMessage?.MessageId; + + return this; + } + + protected MessageAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) + { + } + } +} \ No newline at end of file diff --git a/src/Navigator/Context/NavigatorContextBuilder.cs b/src/Navigator/Context/NavigatorContextBuilder.cs index fe222e8..c2a9b01 100644 --- a/src/Navigator/Context/NavigatorContextBuilder.cs +++ b/src/Navigator/Context/NavigatorContextBuilder.cs @@ -37,13 +37,12 @@ public async Task Build(Actionnet5.0 9 true - true + true 0.9.102-beta Navigator Navigator Framework @@ -25,20 +25,11 @@ + - - - - - - - - - - From ebb8a13e5045aca130ff262c126a3a3e06b36236 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 22 Feb 2021 18:30:20 +0100 Subject: [PATCH 077/304] Working on action types and providers --- src/Navigator/Actions/ActionPriority.cs | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 src/Navigator/Actions/ActionPriority.cs diff --git a/src/Navigator/Actions/ActionPriority.cs b/src/Navigator/Actions/ActionPriority.cs new file mode 100644 index 0000000..8596aac --- /dev/null +++ b/src/Navigator/Actions/ActionPriority.cs @@ -0,0 +1,7 @@ +namespace Navigator.Actions +{ + public struct ActionPriority + { + + } +} \ No newline at end of file From 32977df20f67337b939508d26c20711d1d917e41 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 22 Feb 2021 18:51:26 +0100 Subject: [PATCH 078/304] Started work on ActionLauncher --- .../Old/IActionLauncher.cs | 13 ----- .../Actions/MessageAction.cs | 17 ++++++ .../TelegramMiddleware.cs | 1 + .../TelegramProvider.cs | 25 ++++++++- src/Navigator/ActionLauncher.cs | 53 +++++++++++++++++++ src/Navigator/Actions/ActionPriority.cs | 17 +++++- src/Navigator/Actions/BaseAction.cs | 13 +++-- src/Navigator/Actions/IAction.cs | 8 +++ .../Context/NavigatorContextBuilder.cs | 8 +-- ...avigatorContextBuilderOptionsExtensions.cs | 17 ++++++ src/Navigator/IActionLauncher.cs | 9 ++++ src/Navigator/IProvider.cs | 3 +- .../NavigatorClientCollectionExtensions.cs | 2 +- 13 files changed, 157 insertions(+), 29 deletions(-) delete mode 100644 src/Navigator.Abstractions/Old/IActionLauncher.cs create mode 100644 src/Navigator.Providers.Telegram/Actions/MessageAction.cs create mode 100644 src/Navigator/ActionLauncher.cs create mode 100644 src/Navigator/Actions/IAction.cs create mode 100644 src/Navigator/IActionLauncher.cs diff --git a/src/Navigator.Abstractions/Old/IActionLauncher.cs b/src/Navigator.Abstractions/Old/IActionLauncher.cs deleted file mode 100644 index 0d141ba..0000000 --- a/src/Navigator.Abstractions/Old/IActionLauncher.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System.Collections.Generic; -using System.Threading.Tasks; -using Telegram.Bot.Types; - -namespace Navigator.Abstractions -{ - public interface IActionLauncher - { - Task Launch(); - IEnumerable GetActions(Update update); - public string? GetActionType(Update update); - } -} \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/Actions/MessageAction.cs b/src/Navigator.Providers.Telegram/Actions/MessageAction.cs new file mode 100644 index 0000000..605ae90 --- /dev/null +++ b/src/Navigator.Providers.Telegram/Actions/MessageAction.cs @@ -0,0 +1,17 @@ +using System.Threading.Tasks; +using Navigator.Actions; +using Navigator.Context; + +namespace Navigator.Providers.Telegram.Actions +{ + public class MessageAction : BaseAction + { + public override string Type { get; protected set; } = Action.Type.For("message"); + public override ushort Priority { get; protected set; } = Action.Priority.Default; + + public override Task Init(INavigatorContext navigatorContext) + { + throw new System.NotImplementedException(); + } + } +} \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/TelegramMiddleware.cs b/src/Navigator.Providers.Telegram/TelegramMiddleware.cs index d978ad2..9c1ddc8 100644 --- a/src/Navigator.Providers.Telegram/TelegramMiddleware.cs +++ b/src/Navigator.Providers.Telegram/TelegramMiddleware.cs @@ -21,6 +21,7 @@ public async Task Process(Update update) await _navigatorContextFactory.Supply(builder => { builder.SetProvider(); + builder.SetActionType builder.TryRegisterOption("navigator.provider.telegram.original_update", update); }); } diff --git a/src/Navigator.Providers.Telegram/TelegramProvider.cs b/src/Navigator.Providers.Telegram/TelegramProvider.cs index 4e99620..25825ff 100644 --- a/src/Navigator.Providers.Telegram/TelegramProvider.cs +++ b/src/Navigator.Providers.Telegram/TelegramProvider.cs @@ -1,7 +1,30 @@ +using System; +using Telegram.Bot.Types; + namespace Navigator.Providers.Telegram { public class TelegramProvider : IProvider { - + private readonly NavigatorTelegramClient _client; + + public TelegramProvider(NavigatorTelegramClient client) + { + _client = client; + } + + public INavigatorClient GetClient() + { + return _client; + } + + public string GetActionType(object original) + { + if (original is not Update) + { + return string.Empty; + } + + throw new NotImplementedException(); + } } } \ No newline at end of file diff --git a/src/Navigator/ActionLauncher.cs b/src/Navigator/ActionLauncher.cs new file mode 100644 index 0000000..40bb6af --- /dev/null +++ b/src/Navigator/ActionLauncher.cs @@ -0,0 +1,53 @@ +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Navigator.Actions; +using Navigator.Context; + +namespace Navigator +{ + public class ActionLauncher : IActionLauncher + { + protected readonly INavigatorContext NavigatorContext; + protected readonly IEnumerable Actions; + + public Task Launch() + { + + } + + protected IEnumerable GetActions(object origina) + { + var actions = new List(); + var actionType = NavigatorContext.; + + if (string.IsNullOrWhiteSpace(actionType)) + { + return actions; + } + + if (MultipleActionsUsage) + { + actions = Actions + .Where(a => a.Type == actionType) + .Where(a => a.Init(Ctx).CanHandle(Ctx)) + .OrderBy(a => a.Order) + .ToList(); + } + else + { + var action = Actions + .Where(a => a.Type == actionType) + .OrderBy(a => a.Order) + .FirstOrDefault(a => a.Init(Ctx).CanHandle(Ctx)); + + if (action != null) + { + actions.Add(action); + } + } + + return actions; + } + } +} \ No newline at end of file diff --git a/src/Navigator/Actions/ActionPriority.cs b/src/Navigator/Actions/ActionPriority.cs index 8596aac..65105fe 100644 --- a/src/Navigator/Actions/ActionPriority.cs +++ b/src/Navigator/Actions/ActionPriority.cs @@ -1,7 +1,20 @@ namespace Navigator.Actions { - public struct ActionPriority + public static class Action { - + public static class Priority + { + public static ushort Low = 15000; + public static ushort Default = 10000; + public static ushort High = 5000; + } + + public static class Type + { + public static string For(string name) where TProvider : IProvider + { + return $"_navigator.actions.{typeof(TProvider).Name}.{name}"; + } + } } } \ No newline at end of file diff --git a/src/Navigator/Actions/BaseAction.cs b/src/Navigator/Actions/BaseAction.cs index 7f0bb9a..2f0d3b6 100644 --- a/src/Navigator/Actions/BaseAction.cs +++ b/src/Navigator/Actions/BaseAction.cs @@ -1,15 +1,14 @@ using System.Threading.Tasks; -using MediatR; using Navigator.Context; namespace Navigator.Actions { - public abstract class BaseAction : IRequest + public abstract class BaseAction : IAction { - public static string Type { get; protected set; } - protected - public Task Init(INavigatorContext navigatorContext) - { - } + public abstract string Type { get; protected set; } + + public abstract ushort Priority { get; protected set; } + + public abstract Task Init(INavigatorContext navigatorContext); } } \ No newline at end of file diff --git a/src/Navigator/Actions/IAction.cs b/src/Navigator/Actions/IAction.cs new file mode 100644 index 0000000..55091d6 --- /dev/null +++ b/src/Navigator/Actions/IAction.cs @@ -0,0 +1,8 @@ +using MediatR; + +namespace Navigator.Actions +{ + public interface IAction : IRequest + { + } +} \ No newline at end of file diff --git a/src/Navigator/Context/NavigatorContextBuilder.cs b/src/Navigator/Context/NavigatorContextBuilder.cs index c2a9b01..9989520 100644 --- a/src/Navigator/Context/NavigatorContextBuilder.cs +++ b/src/Navigator/Context/NavigatorContextBuilder.cs @@ -11,14 +11,14 @@ namespace Navigator.Context public class NavigatorContextBuilder : INavigatorContextBuilder { private readonly ILogger _logger; - private readonly IEnumerable _navigatorClients; + private readonly IEnumerable _navigatorProviders; private readonly IEnumerable _navigatorContextExtensions; private readonly INavigatorContextBuilderOptions _options; - public NavigatorContextBuilder(ILogger logger, IEnumerable navigatorClients, IEnumerable navigatorContextExtensions) + public NavigatorContextBuilder(ILogger logger, IEnumerable navigatorClients, IEnumerable navigatorContextExtensions) { _logger = logger; - _navigatorClients = navigatorClients; + _navigatorProviders = navigatorClients; _navigatorContextExtensions = navigatorContextExtensions; _options = new NavigatorContextBuilderOptions(); @@ -28,7 +28,7 @@ public async Task Build(Action(ActionTypeKey); + } + + #endregion } } \ No newline at end of file diff --git a/src/Navigator/IActionLauncher.cs b/src/Navigator/IActionLauncher.cs new file mode 100644 index 0000000..9d30179 --- /dev/null +++ b/src/Navigator/IActionLauncher.cs @@ -0,0 +1,9 @@ +using System.Threading.Tasks; + +namespace Navigator +{ + public interface IActionLauncher + { + Task Launch(); + } +} \ No newline at end of file diff --git a/src/Navigator/IProvider.cs b/src/Navigator/IProvider.cs index 3ed8049..e25d497 100644 --- a/src/Navigator/IProvider.cs +++ b/src/Navigator/IProvider.cs @@ -2,6 +2,7 @@ namespace Navigator { public interface IProvider { - + INavigatorClient GetClient(); + string GetActionType(object original); } } \ No newline at end of file diff --git a/src/Navigator/NavigatorClientCollectionExtensions.cs b/src/Navigator/NavigatorClientCollectionExtensions.cs index e7ba8a1..481d38d 100644 --- a/src/Navigator/NavigatorClientCollectionExtensions.cs +++ b/src/Navigator/NavigatorClientCollectionExtensions.cs @@ -6,7 +6,7 @@ namespace Navigator { public static class NavigatorClientCollectionExtensions { - public static INavigatorClient? GetClientFor(this IEnumerable clients, Type? provider) + public static INavigatorClient? GetClientFor(this IEnumerable clients, Type? provider) { return clients.FirstOrDefault(client => client.IsClientFor().GetType() == provider); } From b1250d8cbc6d3a801a29af491140236d962a01a6 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 22 Feb 2021 20:29:47 +0100 Subject: [PATCH 079/304] Added ActionType as a field in NavigatorContext --- src/Navigator/ActionLauncher.cs | 2 +- src/Navigator/Context/NavigatorContext.cs | 10 ++++- .../Context/NavigatorContextBuilder.cs | 8 ++-- .../NavigatorClientCollectionExtensions.cs | 14 ------- src/Navigator/Old/NavigatorContextBuilder.cs | 40 ------------------- 5 files changed, 14 insertions(+), 60 deletions(-) delete mode 100644 src/Navigator/NavigatorClientCollectionExtensions.cs delete mode 100644 src/Navigator/Old/NavigatorContextBuilder.cs diff --git a/src/Navigator/ActionLauncher.cs b/src/Navigator/ActionLauncher.cs index 40bb6af..8a2796d 100644 --- a/src/Navigator/ActionLauncher.cs +++ b/src/Navigator/ActionLauncher.cs @@ -16,7 +16,7 @@ public Task Launch() } - protected IEnumerable GetActions(object origina) + protected IEnumerable GetActions() { var actions = new List(); var actionType = NavigatorContext.; diff --git a/src/Navigator/Context/NavigatorContext.cs b/src/Navigator/Context/NavigatorContext.cs index 4fcb3d4..1221977 100644 --- a/src/Navigator/Context/NavigatorContext.cs +++ b/src/Navigator/Context/NavigatorContext.cs @@ -23,14 +23,20 @@ public class NavigatorContext : INavigatorContext /// public Dictionary Items { get; } + /// + /// + /// + public string ActionType { get; } + /// /// Builds a new Navigator Context. /// - public NavigatorContext(INavigatorClient client, BotUser botProfile) + public NavigatorContext(INavigatorClient client, BotUser botProfile, string actionType) { Client = client; BotProfile = botProfile; - + ActionType = actionType; + Items = new Dictionary(); } } diff --git a/src/Navigator/Context/NavigatorContextBuilder.cs b/src/Navigator/Context/NavigatorContextBuilder.cs index 9989520..6aaf163 100644 --- a/src/Navigator/Context/NavigatorContextBuilder.cs +++ b/src/Navigator/Context/NavigatorContextBuilder.cs @@ -27,8 +27,8 @@ public NavigatorContextBuilder(ILogger logger, IEnumera public async Task Build(Action optionsAction) { optionsAction.Invoke(_options); - - var client = _navigatorProviders.GetClientFor(_options.GetProvider()); + + var client = _navigatorProviders.FirstOrDefault(provider => provider.GetType() == _options.GetProvider())?.GetClient(); if (client is null) { @@ -36,8 +36,10 @@ public async Task Build(Action clients, Type? provider) - { - return clients.FirstOrDefault(client => client.IsClientFor().GetType() == provider); - } - } -} \ No newline at end of file diff --git a/src/Navigator/Old/NavigatorContextBuilder.cs b/src/Navigator/Old/NavigatorContextBuilder.cs deleted file mode 100644 index ca7db5b..0000000 --- a/src/Navigator/Old/NavigatorContextBuilder.cs +++ /dev/null @@ -1,40 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using Microsoft.Extensions.Logging; -using Navigator.Abstractions; -using Navigator.Context; -using Telegram.Bot.Types; - -namespace Navigator.Old -{ - public class NavigatorContextBuilder : INavigatorContextBuilder - { - protected readonly ILogger Logger; - protected readonly IEnumerable ExtensionProviders; - protected readonly INavigatorContext Ctx; - public NavigatorContextBuilder(ILogger logger, IEnumerable extensionProviders, INavigatorContext ctx) - { - Logger = logger; - ExtensionProviders = extensionProviders.OrderBy(ep => ep.Order); - Ctx = ctx; - } - - public async Task Build(Update update) - { - var extensions = new Dictionary(); - - foreach (var extensionProvider in ExtensionProviders) - { - var (type, extension) = await extensionProvider.Process(update); - - if (type != null && extension != null) - { - extensions.Add(type, extension); - } - } - - await Ctx.Init(update, extensions); - } - } -} \ No newline at end of file From 5ef907b36b1f143c53dfd78bef2722ce46de9ab3 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 22 Feb 2021 20:48:32 +0100 Subject: [PATCH 080/304] Added action type to INavigatorContext --- src/Navigator/Context/INavigatorContext.cs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/Navigator/Context/INavigatorContext.cs b/src/Navigator/Context/INavigatorContext.cs index b159017..33afd4f 100644 --- a/src/Navigator/Context/INavigatorContext.cs +++ b/src/Navigator/Context/INavigatorContext.cs @@ -19,5 +19,10 @@ public interface INavigatorContext /// /// Dictionary Items { get; } + + /// + /// + /// + public string ActionType { get; } } } \ No newline at end of file From 46f1bf94fd781c14debe3a23e28910993982c4f4 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 22 Feb 2021 20:48:57 +0100 Subject: [PATCH 081/304] Updated ActionLauncher --- src/Navigator/ActionLauncher.cs | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/src/Navigator/ActionLauncher.cs b/src/Navigator/ActionLauncher.cs index 8a2796d..01cde71 100644 --- a/src/Navigator/ActionLauncher.cs +++ b/src/Navigator/ActionLauncher.cs @@ -2,6 +2,7 @@ using System.Linq; using System.Threading.Tasks; using Navigator.Actions; +using Navigator.Configuration; using Navigator.Context; namespace Navigator @@ -10,6 +11,14 @@ public class ActionLauncher : IActionLauncher { protected readonly INavigatorContext NavigatorContext; protected readonly IEnumerable Actions; + protected readonly NavigatorOptions NavigatorOptions; + + public ActionLauncher(INavigatorContext navigatorContext, IEnumerable actions, NavigatorOptions navigatorOptions) + { + NavigatorContext = navigatorContext; + Actions = actions; + NavigatorOptions = navigatorOptions; + } public Task Launch() { @@ -19,17 +28,17 @@ public Task Launch() protected IEnumerable GetActions() { var actions = new List(); - var actionType = NavigatorContext.; + var actionType = NavigatorContext.ActionType; if (string.IsNullOrWhiteSpace(actionType)) { return actions; } - if (MultipleActionsUsage) + if (NavigatorOptions.MultipleActionsUsageIsEnabled()) { actions = Actions - .Where(a => a.Type == actionType) + .Where(a => a. == actionType) .Where(a => a.Init(Ctx).CanHandle(Ctx)) .OrderBy(a => a.Order) .ToList(); From b2b22c8a494a460dcd0d6ffdc02fbe3b822e73d6 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 22 Feb 2021 22:59:44 +0100 Subject: [PATCH 082/304] Updated BaseAction and IAction --- src/Navigator/Actions/BaseAction.cs | 27 +++++++++++++++++++++++++-- src/Navigator/Actions/IAction.cs | 19 +++++++++++++++++++ 2 files changed, 44 insertions(+), 2 deletions(-) diff --git a/src/Navigator/Actions/BaseAction.cs b/src/Navigator/Actions/BaseAction.cs index 2f0d3b6..1ee29f3 100644 --- a/src/Navigator/Actions/BaseAction.cs +++ b/src/Navigator/Actions/BaseAction.cs @@ -1,14 +1,37 @@ +using System; using System.Threading.Tasks; using Navigator.Context; namespace Navigator.Actions { + /// + /// Base action to use for any action. + /// public abstract class BaseAction : IAction { + /// public abstract string Type { get; protected set; } - + + /// public abstract ushort Priority { get; protected set; } + + /// + /// Timestamp of the request on creation. + /// + public DateTime Timestamp { get; } + + /// + /// Default constructor for + /// + protected BaseAction() + { + Timestamp = DateTime.UtcNow; + } + + /// + public abstract IAction Init(INavigatorContext navigatorContext); - public abstract Task Init(INavigatorContext navigatorContext); + /// + public abstract bool CanHandle(INavigatorContext ctx); } } \ No newline at end of file diff --git a/src/Navigator/Actions/IAction.cs b/src/Navigator/Actions/IAction.cs index 55091d6..83795a6 100644 --- a/src/Navigator/Actions/IAction.cs +++ b/src/Navigator/Actions/IAction.cs @@ -1,8 +1,27 @@ +using System.Threading.Tasks; using MediatR; +using Navigator.Context; namespace Navigator.Actions { public interface IAction : IRequest { + string Type { get; } + + ushort Priority { get; } + + /// + /// Can be used to populate the action before triggering "CanHandle". + /// + /// + /// + IAction Init(INavigatorContext ctx); + + /// + /// This function must return true when the incoming update can be handled by this action. + /// + /// + /// + bool CanHandle(INavigatorContext ctx); } } \ No newline at end of file From fc7b7db074d49bc8fca07339ed3e7606df8dcc50 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 22 Feb 2021 23:00:20 +0100 Subject: [PATCH 083/304] Improved ActionLauncher --- src/Navigator/ActionLauncher.cs | 64 +++++++++++++++++++-------------- 1 file changed, 37 insertions(+), 27 deletions(-) diff --git a/src/Navigator/ActionLauncher.cs b/src/Navigator/ActionLauncher.cs index 01cde71..3629d60 100644 --- a/src/Navigator/ActionLauncher.cs +++ b/src/Navigator/ActionLauncher.cs @@ -1,3 +1,4 @@ +using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; @@ -9,54 +10,63 @@ namespace Navigator { public class ActionLauncher : IActionLauncher { - protected readonly INavigatorContext NavigatorContext; + /// + /// Navigator context accessor. + /// + protected readonly INavigatorContextAccessor NavigatorContextAccessor; + + /// + /// Collection of available actions. + /// protected readonly IEnumerable Actions; + + /// + /// Navigator otpions. + /// protected readonly NavigatorOptions NavigatorOptions; - public ActionLauncher(INavigatorContext navigatorContext, IEnumerable actions, NavigatorOptions navigatorOptions) + /// + /// Builds a new . + /// + /// + /// + /// + public ActionLauncher(IEnumerable actions, NavigatorOptions navigatorOptions, + INavigatorContextAccessor navigatorContextAccessor) { - NavigatorContext = navigatorContext; Actions = actions; NavigatorOptions = navigatorOptions; + NavigatorContextAccessor = navigatorContextAccessor; } public Task Launch() { - + throw new NotImplementedException(); } - + protected IEnumerable GetActions() { - var actions = new List(); - var actionType = NavigatorContext.ActionType; - - if (string.IsNullOrWhiteSpace(actionType)) + if (string.IsNullOrWhiteSpace(NavigatorContextAccessor.NavigatorContext.ActionType)) { - return actions; + return Array.Empty(); } if (NavigatorOptions.MultipleActionsUsageIsEnabled()) { - actions = Actions - .Where(a => a. == actionType) - .Where(a => a.Init(Ctx).CanHandle(Ctx)) - .OrderBy(a => a.Order) - .ToList(); + return Actions + .Where(a => a.Type == NavigatorContextAccessor.NavigatorContext.ActionType) + .Where(a => a.Init(NavigatorContextAccessor.NavigatorContext) + .CanHandle(NavigatorContextAccessor.NavigatorContext)) + .OrderBy(a => a.Priority).AsEnumerable(); } - else - { - var action = Actions - .Where(a => a.Type == actionType) - .OrderBy(a => a.Order) - .FirstOrDefault(a => a.Init(Ctx).CanHandle(Ctx)); - if (action != null) - { - actions.Add(action); - } - } + var action = Actions + .Where(a => a.Type == NavigatorContextAccessor.NavigatorContext.ActionType) + .OrderBy(a => a.Priority) + .FirstOrDefault(a => a.Init(NavigatorContextAccessor.NavigatorContext) + .CanHandle(NavigatorContextAccessor.NavigatorContext)); - return actions; + return action is not null ? new[] {action} : Array.Empty(); } } } \ No newline at end of file From c8dc30277f2819acdb16fa023a83a7345959fde9 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 22 Feb 2021 23:28:28 +0100 Subject: [PATCH 084/304] Renamed ActionHelper --- src/Navigator/Actions/{ActionPriority.cs => ActionHelper.cs} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename src/Navigator/Actions/{ActionPriority.cs => ActionHelper.cs} (92%) diff --git a/src/Navigator/Actions/ActionPriority.cs b/src/Navigator/Actions/ActionHelper.cs similarity index 92% rename from src/Navigator/Actions/ActionPriority.cs rename to src/Navigator/Actions/ActionHelper.cs index 65105fe..7b1fd58 100644 --- a/src/Navigator/Actions/ActionPriority.cs +++ b/src/Navigator/Actions/ActionHelper.cs @@ -1,6 +1,6 @@ namespace Navigator.Actions { - public static class Action + public static class ActionHelper { public static class Priority { From 7c98e4d82ed405e1b4b623f778bad0ec5b5a4b0f Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 22 Feb 2021 23:28:47 +0100 Subject: [PATCH 085/304] Erased faulted code --- src/Navigator/Actions/GenericActions.cs | 7 ------ src/Navigator/Actions/MessageBaseAction.cs | 26 ---------------------- 2 files changed, 33 deletions(-) delete mode 100644 src/Navigator/Actions/GenericActions.cs delete mode 100644 src/Navigator/Actions/MessageBaseAction.cs diff --git a/src/Navigator/Actions/GenericActions.cs b/src/Navigator/Actions/GenericActions.cs deleted file mode 100644 index c6076cb..0000000 --- a/src/Navigator/Actions/GenericActions.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace Navigator.Actions -{ - public static class GenericActions - { - public static string Message => "navigator.actions.default.message"; - } -} \ No newline at end of file diff --git a/src/Navigator/Actions/MessageBaseAction.cs b/src/Navigator/Actions/MessageBaseAction.cs deleted file mode 100644 index 1dafc1d..0000000 --- a/src/Navigator/Actions/MessageBaseAction.cs +++ /dev/null @@ -1,26 +0,0 @@ -using System; -using Navigator.Context; - -namespace Navigator.Actions -{ - public abstract class MessageAction : BaseAction - { - - public DateTime MessageTimestamp { get; protected set; } - public int MessageId { get; protected set; } - public int? ReplyToMessageId { get; protected set; } - - public override IAction Init(INavigatorContext ctx) - { - MessageTimestamp = ctx.Update.Message.Date; - MessageId = ctx.Update.Message.MessageId; - ReplyToMessageId = ctx.Update.Message.ReplyToMessage?.MessageId; - - return this; - } - - protected MessageAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) - { - } - } -} \ No newline at end of file From 976f890b190164a040a082249849557be6237e7c Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 22 Feb 2021 23:29:04 +0100 Subject: [PATCH 086/304] Updated requirements for SetProvider extension --- .../Context/NavigatorContextBuilderOptionsExtensions.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Navigator/Context/NavigatorContextBuilderOptionsExtensions.cs b/src/Navigator/Context/NavigatorContextBuilderOptionsExtensions.cs index cafc60c..7f5fb0c 100644 --- a/src/Navigator/Context/NavigatorContextBuilderOptionsExtensions.cs +++ b/src/Navigator/Context/NavigatorContextBuilderOptionsExtensions.cs @@ -8,7 +8,7 @@ public static class NavigatorContextBuilderOptionsExtensions private const string ProviderKey = "_navigator.context.options.provider"; - public static void SetProvider(this INavigatorContextBuilderOptions contextBuilderOptions) where TProvider : IProvider, new() + public static void SetProvider(this INavigatorContextBuilderOptions contextBuilderOptions) where TProvider : IProvider { contextBuilderOptions.TryRegisterOption(ProviderKey, typeof(TProvider)); From 539db402e629004ffbd5dca6240b8c0101f5175e Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 22 Feb 2021 23:29:14 +0100 Subject: [PATCH 087/304] Created CommandAction --- .../Actions/CommandAction.cs | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 src/Navigator.Providers.Telegram/Actions/CommandAction.cs diff --git a/src/Navigator.Providers.Telegram/Actions/CommandAction.cs b/src/Navigator.Providers.Telegram/Actions/CommandAction.cs new file mode 100644 index 0000000..8b3f659 --- /dev/null +++ b/src/Navigator.Providers.Telegram/Actions/CommandAction.cs @@ -0,0 +1,11 @@ +using Navigator.Actions; +using Navigator.Context; + +namespace Navigator.Providers.Telegram.Actions +{ + public abstract class CommandAction : BaseAction + { + public override string Type { get; protected set; } = ActionHelper.Type.For(nameof(CommandAction)); + public override ushort Priority { get; protected set; } = ActionHelper.Priority.Default; + } +} \ No newline at end of file From e867893556fdaf17d06fbd4a4f3a3e01e8ad541b Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 22 Feb 2021 23:29:35 +0100 Subject: [PATCH 088/304] Corrected MessageAction --- .../Actions/MessageAction.cs | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/src/Navigator.Providers.Telegram/Actions/MessageAction.cs b/src/Navigator.Providers.Telegram/Actions/MessageAction.cs index 605ae90..f656898 100644 --- a/src/Navigator.Providers.Telegram/Actions/MessageAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/MessageAction.cs @@ -4,14 +4,9 @@ namespace Navigator.Providers.Telegram.Actions { - public class MessageAction : BaseAction + public abstract class MessageAction : BaseAction { - public override string Type { get; protected set; } = Action.Type.For("message"); - public override ushort Priority { get; protected set; } = Action.Priority.Default; - - public override Task Init(INavigatorContext navigatorContext) - { - throw new System.NotImplementedException(); - } + public override string Type { get; protected set; } = ActionHelper.Type.For(nameof(MessageAction)); + public override ushort Priority { get; protected set; } = ActionHelper.Priority.Default; } } \ No newline at end of file From be363e1422dce1766df6b6473e3ac557aa370d3d Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 22 Feb 2021 23:29:58 +0100 Subject: [PATCH 089/304] Corrected whitespace --- src/Navigator.Providers.Telegram/TelegramProvider.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Navigator.Providers.Telegram/TelegramProvider.cs b/src/Navigator.Providers.Telegram/TelegramProvider.cs index 25825ff..316e1c8 100644 --- a/src/Navigator.Providers.Telegram/TelegramProvider.cs +++ b/src/Navigator.Providers.Telegram/TelegramProvider.cs @@ -11,7 +11,7 @@ public TelegramProvider(NavigatorTelegramClient client) { _client = client; } - + public INavigatorClient GetClient() { return _client; From 501121600c7bb14b8e3e78a6ae727fb2b5cfc5cd Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 22 Feb 2021 23:30:20 +0100 Subject: [PATCH 090/304] Corrected NavigatorRouteProviderConfigurationExtensions --- ...NavigatorRouteProviderConfigurationExtensions.cs | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/src/Navigator.Providers.Telegram/NavigatorRouteProviderConfigurationExtensions.cs b/src/Navigator.Providers.Telegram/NavigatorRouteProviderConfigurationExtensions.cs index f1fa827..84d9543 100644 --- a/src/Navigator.Providers.Telegram/NavigatorRouteProviderConfigurationExtensions.cs +++ b/src/Navigator.Providers.Telegram/NavigatorRouteProviderConfigurationExtensions.cs @@ -3,7 +3,6 @@ using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; -using Navigator.Abstractions; using Navigator.Configuration; using Navigator.Configuration.Provider; using Newtonsoft.Json; @@ -36,16 +35,14 @@ private static async Task ProcessTelegramUpdate(HttpContext context) var telegramUpdate = await ParseTelegramUpdate(context.Request.Body); - if (telegramUpdate is null) + if (telegramUpdate is not null) { - return; - } - - using var scope = context.RequestServices.CreateScope(); + using var scope = context.RequestServices.CreateScope(); - var navigatorMiddleware = context.RequestServices.GetRequiredService(); + var navigatorMiddleware = context.RequestServices.GetRequiredService(); - await navigatorMiddleware.Handle(context.Request); + await navigatorMiddleware.Process(telegramUpdate); + } } private static async Task ParseTelegramUpdate(Stream stream) From 822c090687c5730a814643f894fb22233555487c Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 22 Feb 2021 23:31:03 +0100 Subject: [PATCH 091/304] Erased old using statement on SetTelegramBotWebHookHostedService --- .../Hosted/SetTelegramBotWebHookHostedService.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/Navigator.Providers.Telegram/Hosted/SetTelegramBotWebHookHostedService.cs b/src/Navigator.Providers.Telegram/Hosted/SetTelegramBotWebHookHostedService.cs index 95dd2bc..04718ab 100644 --- a/src/Navigator.Providers.Telegram/Hosted/SetTelegramBotWebHookHostedService.cs +++ b/src/Navigator.Providers.Telegram/Hosted/SetTelegramBotWebHookHostedService.cs @@ -4,7 +4,6 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; -using Navigator.Abstractions; using Navigator.Configuration; namespace Navigator.Providers.Telegram.Hosted From c1cb938201ad289ef29bfe3d617bec4d89cc7a95 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 22 Feb 2021 23:31:29 +0100 Subject: [PATCH 092/304] Starting to implement Telegram middleware --- .../TelegramMiddleware.cs | 53 ++++++++++++++++++- 1 file changed, 51 insertions(+), 2 deletions(-) diff --git a/src/Navigator.Providers.Telegram/TelegramMiddleware.cs b/src/Navigator.Providers.Telegram/TelegramMiddleware.cs index 9c1ddc8..fdb058d 100644 --- a/src/Navigator.Providers.Telegram/TelegramMiddleware.cs +++ b/src/Navigator.Providers.Telegram/TelegramMiddleware.cs @@ -1,7 +1,11 @@ +using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Logging; +using Navigator.Actions; using Navigator.Context; +using Navigator.Providers.Telegram.Actions; using Telegram.Bot.Types; +using Telegram.Bot.Types.Enums; namespace Navigator.Providers.Telegram { @@ -9,21 +13,66 @@ public class TelegramMiddleware { private readonly ILogger _logger; private readonly INavigatorContextFactory _navigatorContextFactory; + private readonly IActionLauncher _actionLauncher; - public TelegramMiddleware(ILogger logger, INavigatorContextFactory navigatorContextFactory) + public TelegramMiddleware(ILogger logger, INavigatorContextFactory navigatorContextFactory, IActionLauncher actionLauncher) { _logger = logger; _navigatorContextFactory = navigatorContextFactory; + _actionLauncher = actionLauncher; } public async Task Process(Update update) { + var actionType = DefineActionType(update); + + if (actionType is null) + { + return; + } + await _navigatorContextFactory.Supply(builder => { builder.SetProvider(); - builder.SetActionType + builder.SetActionType(actionType); builder.TryRegisterOption("navigator.provider.telegram.original_update", update); }); + + await _actionLauncher.Launch(); + } + + public string? DefineActionType(Update update) + { + return update.Type switch + { + UpdateType.Message when update.Message.Entities?.First()?.Type == MessageEntityType.BotCommand => ActionHelper.Type.For(nameof(CommandAction)), + UpdateType.Message => update.Message.Type switch + { + // MessageType.ChatMembersAdded => ActionType.ChatMembersAdded, + // MessageType.ChatMemberLeft => ActionType.ChatMemberLeft, + // MessageType.ChatTitleChanged => ActionType.ChatTitleChanged, + // MessageType.ChatPhotoChanged => ActionType.ChatPhotoChanged, + // MessageType.MessagePinned => ActionType.MessagePinned, + // MessageType.ChatPhotoDeleted => ActionType.ChatPhotoDeleted, + // MessageType.GroupCreated => ActionType.GroupCreated, + // MessageType.SupergroupCreated => ActionType.SupergroupCreated, + // MessageType.ChannelCreated => ActionType.ChannelCreated, + // MessageType.MigratedToSupergroup => ActionType.MigratedToSupergroup, + // MessageType.MigratedFromGroup => ActionType.MigratedFromGroup, + _ => ActionHelper.Type.For(nameof(MessageAction)) + }, + // UpdateType.InlineQuery => ActionType.InlineQuery, + // UpdateType.ChosenInlineResult => ActionType.InlineResultChosen, + // UpdateType.CallbackQuery => ActionType.CallbackQuery, + // UpdateType.EditedMessage => ActionType.EditedMessage, + // UpdateType.ChannelPost => ActionType.ChannelPost, + // UpdateType.EditedChannelPost => ActionType.EditedChannelPost, + // UpdateType.ShippingQuery => ActionType.ShippingQuery, + // UpdateType.PreCheckoutQuery => ActionType.PreCheckoutQuery, + // UpdateType.Poll => ActionType.Poll, + // UpdateType.Unknown => ActionType.Unknown, + _ => default + }; } } } \ No newline at end of file From be0c54465ed736767ea4ab317c9582c77dd5b6d1 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 23 Feb 2021 10:57:56 +0100 Subject: [PATCH 093/304] Added CallbackQueryAction --- .../Actions/CallbackQueryAction.cs | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 src/Navigator.Providers.Telegram/Actions/CallbackQueryAction.cs diff --git a/src/Navigator.Providers.Telegram/Actions/CallbackQueryAction.cs b/src/Navigator.Providers.Telegram/Actions/CallbackQueryAction.cs new file mode 100644 index 0000000..c4d21d0 --- /dev/null +++ b/src/Navigator.Providers.Telegram/Actions/CallbackQueryAction.cs @@ -0,0 +1,10 @@ +using Navigator.Actions; + +namespace Navigator.Providers.Telegram.Actions +{ + public abstract class CallbackQueryAction : BaseAction + { + public override string Type { get; protected set; } = ActionHelper.Type.For(nameof(CallbackQueryAction)); + public override ushort Priority { get; protected set; } = ActionHelper.Priority.Default; + } +} \ No newline at end of file From 190dc9a96115b471920a8c8840f36342f0a0ca2d Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 23 Feb 2021 10:59:02 +0100 Subject: [PATCH 094/304] Erased old projects --- .../Navigator.Abstractions.csproj | 30 --------- src/Navigator.Abstractions/Old/IAction.cs | 66 ------------------- .../Old/INavigatorMiddleware.cs | 18 ----- .../Old/INavigatorNotification.cs | 11 ---- .../Old/INotificationLauncher.cs | 9 --- src/Navigator.sln | 7 -- 6 files changed, 141 deletions(-) delete mode 100644 src/Navigator.Abstractions/Navigator.Abstractions.csproj delete mode 100644 src/Navigator.Abstractions/Old/IAction.cs delete mode 100644 src/Navigator.Abstractions/Old/INavigatorMiddleware.cs delete mode 100644 src/Navigator.Abstractions/Old/INavigatorNotification.cs delete mode 100644 src/Navigator.Abstractions/Old/INotificationLauncher.cs diff --git a/src/Navigator.Abstractions/Navigator.Abstractions.csproj b/src/Navigator.Abstractions/Navigator.Abstractions.csproj deleted file mode 100644 index 907994d..0000000 --- a/src/Navigator.Abstractions/Navigator.Abstractions.csproj +++ /dev/null @@ -1,30 +0,0 @@ - - - - net5.0 - enable - true - true - 0.9.99-beta - Navigator.Abstractions - Navigator Framework Abstractions - Lucas Maximiliano Marino - A highly opinionated telegram bot framework, mainly based on Telegram.Bot. - https://github.com/navigatorframework/navigator - https://github.com/navigatorframework/navigator/blob/master/LICENSE - https://github.com/navigatorframework/navigator - Telegram, Bot, Framework, Navigator - true - Copyright © Lucas Maximiliano Marino 2021 - https://raw.githubusercontent.com/navigatorframework/navigator/master/assets/logo.png - - - - - - - - - - - diff --git a/src/Navigator.Abstractions/Old/IAction.cs b/src/Navigator.Abstractions/Old/IAction.cs deleted file mode 100644 index 52ea586..0000000 --- a/src/Navigator.Abstractions/Old/IAction.cs +++ /dev/null @@ -1,66 +0,0 @@ -using System; -using MediatR; - -namespace Navigator.Abstractions -{ - /// - /// Base action. - /// - public interface IAction : IRequest - { - /// - /// Order at which the action must be evaluated, default is 1000. - /// - int Order { get; } - /// - /// Defines the type of action it can handle. See - /// - string Type { get; } - - /// - /// Timestamp at which the action was launched, in UTC. - /// - DateTime Timestamp { get; } - - /// - /// Can be used to populate the action before triggering "CanHandle". - /// - /// - /// - IAction Init(INavigatorContext ctx); - - /// - /// This function must return true when the incoming update can be handled by this action. - /// - /// - /// - bool CanHandle(INavigatorContext ctx); - } - - public static class ActionType - { - public static readonly string Command = "_navigator_command"; - public static readonly string Message = "_navigator_message"; - public static readonly string CallbackQuery = "_navigator_callbackQuery"; - public static readonly string InlineQuery = "_navigator_inlineQuery"; - public static readonly string InlineResultChosen = "_navigator_inlineResultChosen"; - public static readonly string Poll = "_navigator_poll"; - public static readonly string EditedMessage = "_navigator_editedMessage"; - public static readonly string ChannelPost = "_navigator_channelPost"; - public static readonly string EditedChannelPost = "_navigator_editedChannelPost"; - public static readonly string ShippingQuery = "_navigator_shippingQuery"; - public static readonly string PreCheckoutQuery = "_navigator_preCheckoutQuery"; - public static readonly string ChatMembersAdded = "_navigator_message_chatMembersAdded"; - public static readonly string ChatMemberLeft = "_navigator_message_ChatMemberLeft"; - public static readonly string ChatTitleChanged = "_navigator_message_chatTitleChanged"; - public static readonly string ChatPhotoChanged = "_navigator_message_chatPhotoChanged"; - public static readonly string MessagePinned = "_navigator_message_messagePinned"; - public static readonly string ChatPhotoDeleted = "_navigator_message_chatPhotoDeleted"; - public static readonly string GroupCreated = "_navigator_message_groupCreated"; - public static readonly string SupergroupCreated = "_navigator_message_supergroupCreated"; - public static readonly string ChannelCreated = "_navigator_message_channelCreated"; - public static readonly string MigratedToSupergroup = "_navigator_message_migratedToSupergroup"; - public static readonly string MigratedFromGroup = "_navigator_message_migratedFromGroup"; - public static readonly string Unknown = "_navigator_unknown"; - } -} \ No newline at end of file diff --git a/src/Navigator.Abstractions/Old/INavigatorMiddleware.cs b/src/Navigator.Abstractions/Old/INavigatorMiddleware.cs deleted file mode 100644 index 0920ae8..0000000 --- a/src/Navigator.Abstractions/Old/INavigatorMiddleware.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System.Threading.Tasks; -using Microsoft.AspNetCore.Http; - -namespace Navigator.Abstractions -{ - /// - /// Middleware for handling telegram updates incoming as webhooks. - /// - public interface INavigatorMiddleware - { - /// - /// Handles an incoming update from telegram. - /// - /// - /// - Task Handle(HttpRequest httpRequest); - } -} \ No newline at end of file diff --git a/src/Navigator.Abstractions/Old/INavigatorNotification.cs b/src/Navigator.Abstractions/Old/INavigatorNotification.cs deleted file mode 100644 index 0571d65..0000000 --- a/src/Navigator.Abstractions/Old/INavigatorNotification.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System; -using MediatR; - -namespace Navigator.Abstractions -{ - public interface INavigatorNotification : INotification - { - DateTime Timestamp { get; } - int UpdateId { get; } - } -} \ No newline at end of file diff --git a/src/Navigator.Abstractions/Old/INotificationLauncher.cs b/src/Navigator.Abstractions/Old/INotificationLauncher.cs deleted file mode 100644 index ad88376..0000000 --- a/src/Navigator.Abstractions/Old/INotificationLauncher.cs +++ /dev/null @@ -1,9 +0,0 @@ -using System.Threading.Tasks; - -namespace Navigator.Abstractions -{ - public interface INotificationLauncher - { - Task Launch(); - } -} \ No newline at end of file diff --git a/src/Navigator.sln b/src/Navigator.sln index 649f740..677b6d6 100644 --- a/src/Navigator.sln +++ b/src/Navigator.sln @@ -16,8 +16,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Actions", "Actions", "{288F EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Packages", "Packages", "{895808DE-1CA6-406C-924A-7E43F293CF7D}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Navigator.Abstractions", "Navigator.Abstractions\Navigator.Abstractions.csproj", "{FAB1A6C8-EBEB-4338-B454-75DA358E7DE2}" -EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Navigator", "Navigator", "{E6F24E3B-A066-4572-94F0-14665E19EFC7}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Navigator.Abstractions.Extensions", "Navigator.Abstractions.Extensions\Navigator.Abstractions.Extensions.csproj", "{FACFECB8-1215-4F04-B9B2-F7FB7656804F}" @@ -62,10 +60,6 @@ Global {2711B76D-B24C-4A3A-A33F-5A0077C49CB6}.Debug|Any CPU.Build.0 = Debug|Any CPU {2711B76D-B24C-4A3A-A33F-5A0077C49CB6}.Release|Any CPU.ActiveCfg = Release|Any CPU {2711B76D-B24C-4A3A-A33F-5A0077C49CB6}.Release|Any CPU.Build.0 = Release|Any CPU - {FAB1A6C8-EBEB-4338-B454-75DA358E7DE2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {FAB1A6C8-EBEB-4338-B454-75DA358E7DE2}.Debug|Any CPU.Build.0 = Debug|Any CPU - {FAB1A6C8-EBEB-4338-B454-75DA358E7DE2}.Release|Any CPU.ActiveCfg = Release|Any CPU - {FAB1A6C8-EBEB-4338-B454-75DA358E7DE2}.Release|Any CPU.Build.0 = Release|Any CPU {FACFECB8-1215-4F04-B9B2-F7FB7656804F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {FACFECB8-1215-4F04-B9B2-F7FB7656804F}.Debug|Any CPU.Build.0 = Debug|Any CPU {FACFECB8-1215-4F04-B9B2-F7FB7656804F}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -100,7 +94,6 @@ Global {F178DCF2-AD03-44C8-AF8F-95C60664DD10} = {895808DE-1CA6-406C-924A-7E43F293CF7D} {E6F24E3B-A066-4572-94F0-14665E19EFC7} = {895808DE-1CA6-406C-924A-7E43F293CF7D} {6DBAD041-6623-4903-9939-254FDC4EBD60} = {E6F24E3B-A066-4572-94F0-14665E19EFC7} - {FAB1A6C8-EBEB-4338-B454-75DA358E7DE2} = {E6F24E3B-A066-4572-94F0-14665E19EFC7} {2711B76D-B24C-4A3A-A33F-5A0077C49CB6} = {288F4B0C-9EF0-443B-B893-5FC34F9D032B} {288F4B0C-9EF0-443B-B893-5FC34F9D032B} = {F178DCF2-AD03-44C8-AF8F-95C60664DD10} {FACFECB8-1215-4F04-B9B2-F7FB7656804F} = {E6F24E3B-A066-4572-94F0-14665E19EFC7} From 39a1a623da052016f1d6ed8c520dc4a7b8990a98 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 23 Feb 2021 11:21:00 +0100 Subject: [PATCH 095/304] Cleaned old code in INavigatorClient and Telegram Provider --- src/Navigator.Providers.Telegram/NavigatorTelegramClient.cs | 5 ----- src/Navigator/INavigatorClient.cs | 2 -- 2 files changed, 7 deletions(-) diff --git a/src/Navigator.Providers.Telegram/NavigatorTelegramClient.cs b/src/Navigator.Providers.Telegram/NavigatorTelegramClient.cs index 0cf77c3..17a73e6 100644 --- a/src/Navigator.Providers.Telegram/NavigatorTelegramClient.cs +++ b/src/Navigator.Providers.Telegram/NavigatorTelegramClient.cs @@ -24,10 +24,5 @@ public async Task GetProfile(CancellationToken cancellationToken = defa Username = bot.Username }; } - - public IProvider IsClientFor() - { - return Provider.For(); - } } } \ No newline at end of file diff --git a/src/Navigator/INavigatorClient.cs b/src/Navigator/INavigatorClient.cs index aa8ea93..5aabf86 100644 --- a/src/Navigator/INavigatorClient.cs +++ b/src/Navigator/INavigatorClient.cs @@ -12,7 +12,5 @@ public interface INavigatorClient /// /// Task GetProfile(CancellationToken cancellationToken = default); - - IProvider IsClientFor(); } } \ No newline at end of file From fde0bfc960fc3b9574eb776439203bab92f0e110 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 23 Feb 2021 11:21:13 +0100 Subject: [PATCH 096/304] Updated DI --- src/Navigator/ServiceCollectionExtensions.cs | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/src/Navigator/ServiceCollectionExtensions.cs b/src/Navigator/ServiceCollectionExtensions.cs index 5e793b4..a10b84f 100644 --- a/src/Navigator/ServiceCollectionExtensions.cs +++ b/src/Navigator/ServiceCollectionExtensions.cs @@ -1,9 +1,8 @@ using System; using Microsoft.Extensions.DependencyInjection; -using Navigator.Abstractions; +using Navigator.Actions; using Navigator.Configuration; using Navigator.Context; -using Navigator.Old; using Scrutor; namespace Navigator @@ -19,11 +18,9 @@ public static NavigatorConfiguration AddNavigator(this IServiceCollection servic var navigatorBuilder = new NavigatorConfiguration(options, services); - services.AddScoped(); + services.AddNavigatorContextServices(); + services.AddScoped(); - services.AddScoped(); - services.AddScoped(); - services.AddScoped(); services.Scan(scan => scan .FromAssemblies(navigatorBuilder.Options.GetActionsAssemblies()) @@ -36,5 +33,12 @@ public static NavigatorConfiguration AddNavigator(this IServiceCollection servic return navigatorBuilder; } + + internal static void AddNavigatorContextServices(this IServiceCollection services) + { + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + } } } \ No newline at end of file From d0c5577c5cf0613d089e563d6bbba2e03823a052 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 23 Feb 2021 11:21:24 +0100 Subject: [PATCH 097/304] Made ActionLauncher internal --- src/Navigator/ActionLauncher.cs | 77 +++++++++++++++++---------------- 1 file changed, 39 insertions(+), 38 deletions(-) diff --git a/src/Navigator/ActionLauncher.cs b/src/Navigator/ActionLauncher.cs index 3629d60..19b17c8 100644 --- a/src/Navigator/ActionLauncher.cs +++ b/src/Navigator/ActionLauncher.cs @@ -2,69 +2,70 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; +using MediatR; using Navigator.Actions; using Navigator.Configuration; using Navigator.Context; namespace Navigator { - public class ActionLauncher : IActionLauncher + internal class ActionLauncher : IActionLauncher { - /// - /// Navigator context accessor. - /// - protected readonly INavigatorContextAccessor NavigatorContextAccessor; - - /// - /// Collection of available actions. - /// - protected readonly IEnumerable Actions; - - /// - /// Navigator otpions. - /// - protected readonly NavigatorOptions NavigatorOptions; + private readonly INavigatorContextAccessor _navigatorContextAccessor; + + private readonly IEnumerable _actions; + + private readonly NavigatorOptions _navigatorOptions; - /// - /// Builds a new . - /// - /// - /// - /// + private readonly ISender _sender; + public ActionLauncher(IEnumerable actions, NavigatorOptions navigatorOptions, - INavigatorContextAccessor navigatorContextAccessor) + INavigatorContextAccessor navigatorContextAccessor, ISender sender) { - Actions = actions; - NavigatorOptions = navigatorOptions; - NavigatorContextAccessor = navigatorContextAccessor; + _actions = actions; + _navigatorOptions = navigatorOptions; + _navigatorContextAccessor = navigatorContextAccessor; + _sender = sender; } - public Task Launch() + public async Task Launch() { - throw new NotImplementedException(); + var actions = GetActions(); + + foreach (var action in actions) + { + try + { + await _sender.Send(action); + } + catch (Exception e) + { + //TODO: logs + } + } } - protected IEnumerable GetActions() + private IEnumerable GetActions() { - if (string.IsNullOrWhiteSpace(NavigatorContextAccessor.NavigatorContext.ActionType)) + if (string.IsNullOrWhiteSpace(_navigatorContextAccessor.NavigatorContext.ActionType)) { return Array.Empty(); } - if (NavigatorOptions.MultipleActionsUsageIsEnabled()) + if (_navigatorOptions.MultipleActionsUsageIsEnabled()) { - return Actions - .Where(a => a.Type == NavigatorContextAccessor.NavigatorContext.ActionType) - .Where(a => a.Init(NavigatorContextAccessor.NavigatorContext) - .CanHandle(NavigatorContextAccessor.NavigatorContext)) + return _actions + .Where(a => a.Type == _navigatorContextAccessor.NavigatorContext.ActionType) + .Where(a => a.Init(_navigatorContextAccessor.NavigatorContext) + .CanHandle(_navigatorContextAccessor.NavigatorContext)) .OrderBy(a => a.Priority).AsEnumerable(); } - var action = Actions - .Where(a => a.Type == NavigatorContextAccessor.NavigatorContext.ActionType) + var action = _actions + .Where(a => a.Type == _navigatorContextAccessor.NavigatorContext.ActionType) .OrderBy(a => a.Priority) - .FirstOrDefault(a => a.Init(NavigatorContextAccessor.NavigatorContext) - .CanHandle(NavigatorContextAccessor.NavigatorContext)); + .FirstOrDefault(a => a.Init(_navigatorContextAccessor.NavigatorContext) + .CanHandle(_navigatorContextAccessor.NavigatorContext)); return action is not null ? new[] {action} : Array.Empty(); } From eef8af60004fd27860e97977e354538698280d7a Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 23 Feb 2021 12:32:59 +0100 Subject: [PATCH 098/304] Added documentation for IAction --- src/Navigator/Actions/IAction.cs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/Navigator/Actions/IAction.cs b/src/Navigator/Actions/IAction.cs index 83795a6..a09e98e 100644 --- a/src/Navigator/Actions/IAction.cs +++ b/src/Navigator/Actions/IAction.cs @@ -6,8 +6,14 @@ namespace Navigator.Actions { public interface IAction : IRequest { + /// + /// Type of the action. + /// string Type { get; } + /// + /// Priority of the action when launching multiple actions. + /// ushort Priority { get; } /// From ea5e1ab09f039c7f54a27c63ff0d97cab79455e0 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 23 Feb 2021 12:33:19 +0100 Subject: [PATCH 099/304] Added OriginalUpdateContextExtension --- .../Extensions/OriginalUpdateContextExtension.cs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 src/Navigator/Context/Extensions/OriginalUpdateContextExtension.cs diff --git a/src/Navigator/Context/Extensions/OriginalUpdateContextExtension.cs b/src/Navigator/Context/Extensions/OriginalUpdateContextExtension.cs new file mode 100644 index 0000000..9331752 --- /dev/null +++ b/src/Navigator/Context/Extensions/OriginalUpdateContextExtension.cs @@ -0,0 +1,16 @@ +using System.Threading.Tasks; + +namespace Navigator.Context.Extensions +{ + public class OriginalUpdateContextExtension : INavigatorContextExtension + { + public const string OriginalUpdateKey = "_navigator.extensions.original_update"; + + public Task Extend(INavigatorContext navigatorContext, INavigatorContextBuilderOptions builderOptions) + { + navigatorContext.Extensions.TryAdd(OriginalUpdateKey, builderOptions.GetOriginalUpdateOrDefault()); + + return Task.FromResult(navigatorContext); + } + } +} \ No newline at end of file From f947eefb4c26b023ff3aacbb4703a1fe4acf8e88 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 23 Feb 2021 12:33:31 +0100 Subject: [PATCH 100/304] Added GetOriginalUpdateOrDefault --- .../Extensions/NavigatorContextExtensions.cs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 src/Navigator/Context/Extensions/NavigatorContextExtensions.cs diff --git a/src/Navigator/Context/Extensions/NavigatorContextExtensions.cs b/src/Navigator/Context/Extensions/NavigatorContextExtensions.cs new file mode 100644 index 0000000..21625a9 --- /dev/null +++ b/src/Navigator/Context/Extensions/NavigatorContextExtensions.cs @@ -0,0 +1,19 @@ +using System.Collections.Generic; + +namespace Navigator.Context.Extensions +{ + public static class NavigatorContextExtensions + { + public static TUpdate? GetOriginalUpdateOrDefault(this INavigatorContext navigatorContext) where TUpdate : class + { + var update = navigatorContext.Extensions.GetValueOrDefault(OriginalUpdateContextExtension.OriginalUpdateKey); + + if (update is TUpdate originalUpdate) + { + return originalUpdate; + } + + return default; + } + } +} \ No newline at end of file From daeaea6adaf3bc17a0fd879829eb63aa351bfd7d Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 23 Feb 2021 12:33:47 +0100 Subject: [PATCH 101/304] Added Extensions to INavigatorContext --- src/Navigator/Context/INavigatorContext.cs | 5 +++++ src/Navigator/Context/NavigatorContext.cs | 2 ++ 2 files changed, 7 insertions(+) diff --git a/src/Navigator/Context/INavigatorContext.cs b/src/Navigator/Context/INavigatorContext.cs index 33afd4f..0cd46a4 100644 --- a/src/Navigator/Context/INavigatorContext.cs +++ b/src/Navigator/Context/INavigatorContext.cs @@ -15,6 +15,11 @@ public interface INavigatorContext /// BotUser BotProfile { get; } + /// + /// + /// + Dictionary Extensions { get; } + /// /// /// diff --git a/src/Navigator/Context/NavigatorContext.cs b/src/Navigator/Context/NavigatorContext.cs index 1221977..1592310 100644 --- a/src/Navigator/Context/NavigatorContext.cs +++ b/src/Navigator/Context/NavigatorContext.cs @@ -18,6 +18,8 @@ public class NavigatorContext : INavigatorContext /// public BotUser BotProfile { get; } + public Dictionary Extensions { get; } + /// /// /// From 9096969415e22609ee811d037fe7c62c23d07101 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 23 Feb 2021 12:34:02 +0100 Subject: [PATCH 102/304] Added Set and Get for OriginalUpdate in builder --- .../NavigatorContextBuilderOptionsExtensions.cs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/src/Navigator/Context/NavigatorContextBuilderOptionsExtensions.cs b/src/Navigator/Context/NavigatorContextBuilderOptionsExtensions.cs index 7f5fb0c..d4ad9bc 100644 --- a/src/Navigator/Context/NavigatorContextBuilderOptionsExtensions.cs +++ b/src/Navigator/Context/NavigatorContextBuilderOptionsExtensions.cs @@ -37,5 +37,22 @@ public static void SetActionType(this INavigatorContextBuilderOptions contextBui } #endregion + + #region ActionType + + private const string OriginalUpdateKey = "_navigator.context.options.original_update"; + + public static void SetOriginalUpdate(this INavigatorContextBuilderOptions contextBuilderOptions, object originalUpdate) + { + contextBuilderOptions.TryRegisterOption(OriginalUpdateKey, originalUpdate); + + } + + public static object? GetOriginalUpdateOrDefault(this INavigatorContextBuilderOptions contextBuilderOptions) + { + return contextBuilderOptions.RetrieveOption(OriginalUpdateKey); + } + + #endregion } } \ No newline at end of file From 3a5d333ed9963f91326f392874928a96400ce8f7 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 23 Feb 2021 12:34:14 +0100 Subject: [PATCH 103/304] Updated TelegramMiddleware to set OriginalUpdate --- src/Navigator.Providers.Telegram/TelegramMiddleware.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Navigator.Providers.Telegram/TelegramMiddleware.cs b/src/Navigator.Providers.Telegram/TelegramMiddleware.cs index fdb058d..04779f5 100644 --- a/src/Navigator.Providers.Telegram/TelegramMiddleware.cs +++ b/src/Navigator.Providers.Telegram/TelegramMiddleware.cs @@ -35,7 +35,7 @@ await _navigatorContextFactory.Supply(builder => { builder.SetProvider(); builder.SetActionType(actionType); - builder.TryRegisterOption("navigator.provider.telegram.original_update", update); + builder.SetOriginalUpdate(update); }); await _actionLauncher.Launch(); From d2e75daa2088ef60075162913d53dd250009dd68 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 23 Feb 2021 12:34:46 +0100 Subject: [PATCH 104/304] Bit of work in DiscordProvider --- src/Navigator.Providers.Discord/DiscordProvider.cs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/Navigator.Providers.Discord/DiscordProvider.cs b/src/Navigator.Providers.Discord/DiscordProvider.cs index 67ddf6b..6622623 100644 --- a/src/Navigator.Providers.Discord/DiscordProvider.cs +++ b/src/Navigator.Providers.Discord/DiscordProvider.cs @@ -2,6 +2,14 @@ namespace Navigator.Providers.Discord { public class DiscordProvider : IProvider { - + public INavigatorClient GetClient() + { + throw new System.NotImplementedException(); + } + + public string GetActionType(object original) + { + throw new System.NotImplementedException(); + } } } \ No newline at end of file From 4fc3b4f084dc8f02749c8f5bb2959a8d7e80f650 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 23 Feb 2021 12:35:03 +0100 Subject: [PATCH 105/304] Added some MessageExtensions --- .../Extensions/MessageExtension.cs | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 src/Navigator.Providers.Telegram/Extensions/MessageExtension.cs diff --git a/src/Navigator.Providers.Telegram/Extensions/MessageExtension.cs b/src/Navigator.Providers.Telegram/Extensions/MessageExtension.cs new file mode 100644 index 0000000..96fdf19 --- /dev/null +++ b/src/Navigator.Providers.Telegram/Extensions/MessageExtension.cs @@ -0,0 +1,33 @@ +using System; +using System.Linq; +using Microsoft.AspNetCore.Mvc; +using Telegram.Bot.Types; +using Telegram.Bot.Types.Enums; + +namespace Navigator.Providers.Telegram.Extensions +{ + public static class MessageExtension + { + public static string? ExtractCommand(this Message message, string botName) + { + if (message.Entities?.First()?.Type != MessageEntityType.BotCommand) return default; + + var command = message.EntityValues.First(); + + if (!command.Contains('@')) return command; + + if (!command.Contains(botName)) return default; + + command = command.Substring(0, command.IndexOf('@')); + + return command; + } + + public static string ExtractArguments(this Message message, string botName) + { + return message.Text.Contains(' ') + ? message.Text.Remove(0, message.Text.IndexOf(' ') + 1) + : string.Empty; + } + } +} \ No newline at end of file From 40085849d51f08c554fb41292d8392fd3c7ef1af Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 23 Feb 2021 12:35:15 +0100 Subject: [PATCH 106/304] Updated MessageAction in Telegram Provider --- .../Actions/MessageAction.cs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/Navigator.Providers.Telegram/Actions/MessageAction.cs b/src/Navigator.Providers.Telegram/Actions/MessageAction.cs index f656898..74aad6b 100644 --- a/src/Navigator.Providers.Telegram/Actions/MessageAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/MessageAction.cs @@ -1,6 +1,8 @@ using System.Threading.Tasks; using Navigator.Actions; using Navigator.Context; +using Navigator.Context.Extensions; +using Telegram.Bot.Types; namespace Navigator.Providers.Telegram.Actions { @@ -8,5 +10,19 @@ public abstract class MessageAction : BaseAction { public override string Type { get; protected set; } = ActionHelper.Type.For(nameof(MessageAction)); public override ushort Priority { get; protected set; } = ActionHelper.Priority.Default; + + public override IAction Init(INavigatorContext navigatorContext) + { + var update = navigatorContext.GetOriginalUpdateOrDefault(); + + if (update is not null) + { + Message = update.Message; + } + + return this; + } + + public Message Message { get; protected set; } } } \ No newline at end of file From 2f6fe39534e0490cf20b8ebdb05c34257a3a2f8c Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 23 Feb 2021 12:36:52 +0100 Subject: [PATCH 107/304] Implemented CommandAction --- .../Actions/CommandAction.cs | 22 ++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/src/Navigator.Providers.Telegram/Actions/CommandAction.cs b/src/Navigator.Providers.Telegram/Actions/CommandAction.cs index 8b3f659..593d555 100644 --- a/src/Navigator.Providers.Telegram/Actions/CommandAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/CommandAction.cs @@ -1,11 +1,31 @@ using Navigator.Actions; using Navigator.Context; +using Navigator.Providers.Telegram.Extensions; namespace Navigator.Providers.Telegram.Actions { - public abstract class CommandAction : BaseAction + public abstract class CommandAction : MessageAction { + protected CommandAction() + { + Command = string.Empty; + Arguments = string.Empty; + } + public override string Type { get; protected set; } = ActionHelper.Type.For(nameof(CommandAction)); public override ushort Priority { get; protected set; } = ActionHelper.Priority.Default; + + public override IAction Init(INavigatorContext navigatorContext) + { + Command = Message.ExtractCommand(navigatorContext.BotProfile.Username) ?? string.Empty; + + Arguments = Message.ExtractArguments(navigatorContext.BotProfile.Username) ?? string.Empty; + + return this; + } + + public string Command { get; protected set; } + public string Arguments { get; protected set; } + } } \ No newline at end of file From ca459049f993ceb759be0fcb6465b538c1209810 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 23 Feb 2021 12:43:00 +0100 Subject: [PATCH 108/304] Adjusted namespaces --- src/Navigator.Extensions.Actions/CommandAction.cs | 2 +- src/Navigator.Extensions.Actions/MessageExtension.cs | 2 +- .../Actions/CallbackQueryAction.cs | 5 +++-- src/Navigator.Providers.Telegram/Actions/CommandAction.cs | 5 +++-- src/Navigator.Providers.Telegram/Actions/MessageAction.cs | 5 +++-- src/Navigator.Providers.Telegram/TelegramMiddleware.cs | 4 ++-- src/Navigator/{ => Actions}/ActionLauncher.cs | 4 ++-- src/Navigator/Actions/{ActionHelper.cs => ActionsHelper.cs} | 2 +- src/Navigator/{ => Actions}/IActionLauncher.cs | 2 +- src/Navigator/Actions/{ => Model}/BaseAction.cs | 3 +-- src/Navigator/Actions/{ => Model}/IAction.cs | 3 +-- src/Navigator/Old/ActionLauncher.cs | 1 + src/Navigator/Old/NavigatorMiddleware.cs | 1 + src/Navigator/ServiceCollectionExtensions.cs | 1 + 14 files changed, 22 insertions(+), 18 deletions(-) rename src/Navigator/{ => Actions}/ActionLauncher.cs (97%) rename src/Navigator/Actions/{ActionHelper.cs => ActionsHelper.cs} (92%) rename src/Navigator/{ => Actions}/IActionLauncher.cs (79%) rename src/Navigator/Actions/{ => Model}/BaseAction.cs (93%) rename src/Navigator/Actions/{ => Model}/IAction.cs (93%) diff --git a/src/Navigator.Extensions.Actions/CommandAction.cs b/src/Navigator.Extensions.Actions/CommandAction.cs index 9332a46..12ce414 100644 --- a/src/Navigator.Extensions.Actions/CommandAction.cs +++ b/src/Navigator.Extensions.Actions/CommandAction.cs @@ -11,7 +11,7 @@ public abstract class CommandAction : Action public int? ReplyToMessageId { get; protected set; } public string Command { get; set; } = string.Empty; - public override IAction Init(INavigatorContext ctx) + public override IAction Init(Update ctx) { MessageTimestamp = ctx.Update.Message.Date; MessageId = ctx.Update.Message.MessageId; diff --git a/src/Navigator.Extensions.Actions/MessageExtension.cs b/src/Navigator.Extensions.Actions/MessageExtension.cs index 9fdde01..968837d 100644 --- a/src/Navigator.Extensions.Actions/MessageExtension.cs +++ b/src/Navigator.Extensions.Actions/MessageExtension.cs @@ -14,7 +14,7 @@ public static class MessageExtension if (!command.Contains('@')) return command; - if (!command.Contains(botName)) return default; + if (!command.Contains(botName)) return command; command = command.Substring(0, command.IndexOf('@')); diff --git a/src/Navigator.Providers.Telegram/Actions/CallbackQueryAction.cs b/src/Navigator.Providers.Telegram/Actions/CallbackQueryAction.cs index c4d21d0..e044d0d 100644 --- a/src/Navigator.Providers.Telegram/Actions/CallbackQueryAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/CallbackQueryAction.cs @@ -1,10 +1,11 @@ using Navigator.Actions; +using Navigator.Actions.Model; namespace Navigator.Providers.Telegram.Actions { public abstract class CallbackQueryAction : BaseAction { - public override string Type { get; protected set; } = ActionHelper.Type.For(nameof(CallbackQueryAction)); - public override ushort Priority { get; protected set; } = ActionHelper.Priority.Default; + public override string Type { get; protected set; } = ActionsHelper.Type.For(nameof(CallbackQueryAction)); + public override ushort Priority { get; protected set; } = ActionsHelper.Priority.Default; } } \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/Actions/CommandAction.cs b/src/Navigator.Providers.Telegram/Actions/CommandAction.cs index 593d555..4cc036b 100644 --- a/src/Navigator.Providers.Telegram/Actions/CommandAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/CommandAction.cs @@ -1,4 +1,5 @@ using Navigator.Actions; +using Navigator.Actions.Model; using Navigator.Context; using Navigator.Providers.Telegram.Extensions; @@ -12,8 +13,8 @@ protected CommandAction() Arguments = string.Empty; } - public override string Type { get; protected set; } = ActionHelper.Type.For(nameof(CommandAction)); - public override ushort Priority { get; protected set; } = ActionHelper.Priority.Default; + public override string Type { get; protected set; } = ActionsHelper.Type.For(nameof(CommandAction)); + public override ushort Priority { get; protected set; } = ActionsHelper.Priority.Default; public override IAction Init(INavigatorContext navigatorContext) { diff --git a/src/Navigator.Providers.Telegram/Actions/MessageAction.cs b/src/Navigator.Providers.Telegram/Actions/MessageAction.cs index 74aad6b..7726f16 100644 --- a/src/Navigator.Providers.Telegram/Actions/MessageAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/MessageAction.cs @@ -1,5 +1,6 @@ using System.Threading.Tasks; using Navigator.Actions; +using Navigator.Actions.Model; using Navigator.Context; using Navigator.Context.Extensions; using Telegram.Bot.Types; @@ -8,8 +9,8 @@ namespace Navigator.Providers.Telegram.Actions { public abstract class MessageAction : BaseAction { - public override string Type { get; protected set; } = ActionHelper.Type.For(nameof(MessageAction)); - public override ushort Priority { get; protected set; } = ActionHelper.Priority.Default; + public override string Type { get; protected set; } = ActionsHelper.Type.For(nameof(MessageAction)); + public override ushort Priority { get; protected set; } = ActionsHelper.Priority.Default; public override IAction Init(INavigatorContext navigatorContext) { diff --git a/src/Navigator.Providers.Telegram/TelegramMiddleware.cs b/src/Navigator.Providers.Telegram/TelegramMiddleware.cs index 04779f5..fe03e8a 100644 --- a/src/Navigator.Providers.Telegram/TelegramMiddleware.cs +++ b/src/Navigator.Providers.Telegram/TelegramMiddleware.cs @@ -45,7 +45,7 @@ await _navigatorContextFactory.Supply(builder => { return update.Type switch { - UpdateType.Message when update.Message.Entities?.First()?.Type == MessageEntityType.BotCommand => ActionHelper.Type.For(nameof(CommandAction)), + UpdateType.Message when update.Message.Entities?.First()?.Type == MessageEntityType.BotCommand => ActionsHelper.Type.For(nameof(CommandAction)), UpdateType.Message => update.Message.Type switch { // MessageType.ChatMembersAdded => ActionType.ChatMembersAdded, @@ -59,7 +59,7 @@ await _navigatorContextFactory.Supply(builder => // MessageType.ChannelCreated => ActionType.ChannelCreated, // MessageType.MigratedToSupergroup => ActionType.MigratedToSupergroup, // MessageType.MigratedFromGroup => ActionType.MigratedFromGroup, - _ => ActionHelper.Type.For(nameof(MessageAction)) + _ => ActionsHelper.Type.For(nameof(MessageAction)) }, // UpdateType.InlineQuery => ActionType.InlineQuery, // UpdateType.ChosenInlineResult => ActionType.InlineResultChosen, diff --git a/src/Navigator/ActionLauncher.cs b/src/Navigator/Actions/ActionLauncher.cs similarity index 97% rename from src/Navigator/ActionLauncher.cs rename to src/Navigator/Actions/ActionLauncher.cs index 19b17c8..cc43fc1 100644 --- a/src/Navigator/ActionLauncher.cs +++ b/src/Navigator/Actions/ActionLauncher.cs @@ -3,11 +3,11 @@ using System.Linq; using System.Threading.Tasks; using MediatR; -using Navigator.Actions; +using Navigator.Actions.Model; using Navigator.Configuration; using Navigator.Context; -namespace Navigator +namespace Navigator.Actions { internal class ActionLauncher : IActionLauncher { diff --git a/src/Navigator/Actions/ActionHelper.cs b/src/Navigator/Actions/ActionsHelper.cs similarity index 92% rename from src/Navigator/Actions/ActionHelper.cs rename to src/Navigator/Actions/ActionsHelper.cs index 7b1fd58..a3b23c1 100644 --- a/src/Navigator/Actions/ActionHelper.cs +++ b/src/Navigator/Actions/ActionsHelper.cs @@ -1,6 +1,6 @@ namespace Navigator.Actions { - public static class ActionHelper + public static class ActionsHelper { public static class Priority { diff --git a/src/Navigator/IActionLauncher.cs b/src/Navigator/Actions/IActionLauncher.cs similarity index 79% rename from src/Navigator/IActionLauncher.cs rename to src/Navigator/Actions/IActionLauncher.cs index 9d30179..0bd7543 100644 --- a/src/Navigator/IActionLauncher.cs +++ b/src/Navigator/Actions/IActionLauncher.cs @@ -1,6 +1,6 @@ using System.Threading.Tasks; -namespace Navigator +namespace Navigator.Actions { public interface IActionLauncher { diff --git a/src/Navigator/Actions/BaseAction.cs b/src/Navigator/Actions/Model/BaseAction.cs similarity index 93% rename from src/Navigator/Actions/BaseAction.cs rename to src/Navigator/Actions/Model/BaseAction.cs index 1ee29f3..ecf03b7 100644 --- a/src/Navigator/Actions/BaseAction.cs +++ b/src/Navigator/Actions/Model/BaseAction.cs @@ -1,8 +1,7 @@ using System; -using System.Threading.Tasks; using Navigator.Context; -namespace Navigator.Actions +namespace Navigator.Actions.Model { /// /// Base action to use for any action. diff --git a/src/Navigator/Actions/IAction.cs b/src/Navigator/Actions/Model/IAction.cs similarity index 93% rename from src/Navigator/Actions/IAction.cs rename to src/Navigator/Actions/Model/IAction.cs index a09e98e..2d42c96 100644 --- a/src/Navigator/Actions/IAction.cs +++ b/src/Navigator/Actions/Model/IAction.cs @@ -1,8 +1,7 @@ -using System.Threading.Tasks; using MediatR; using Navigator.Context; -namespace Navigator.Actions +namespace Navigator.Actions.Model { public interface IAction : IRequest { diff --git a/src/Navigator/Old/ActionLauncher.cs b/src/Navigator/Old/ActionLauncher.cs index d7f04f7..6bc5c7c 100644 --- a/src/Navigator/Old/ActionLauncher.cs +++ b/src/Navigator/Old/ActionLauncher.cs @@ -5,6 +5,7 @@ using MediatR; using Microsoft.Extensions.Logging; using Navigator.Abstractions; +using Navigator.Actions; using Navigator.Configuration; using Navigator.Context; using Telegram.Bot.Types; diff --git a/src/Navigator/Old/NavigatorMiddleware.cs b/src/Navigator/Old/NavigatorMiddleware.cs index 848326b..87c343d 100644 --- a/src/Navigator/Old/NavigatorMiddleware.cs +++ b/src/Navigator/Old/NavigatorMiddleware.cs @@ -3,6 +3,7 @@ using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using Navigator.Abstractions; +using Navigator.Actions; using Newtonsoft.Json; using Telegram.Bot.Types; diff --git a/src/Navigator/ServiceCollectionExtensions.cs b/src/Navigator/ServiceCollectionExtensions.cs index a10b84f..c60b66f 100644 --- a/src/Navigator/ServiceCollectionExtensions.cs +++ b/src/Navigator/ServiceCollectionExtensions.cs @@ -1,6 +1,7 @@ using System; using Microsoft.Extensions.DependencyInjection; using Navigator.Actions; +using Navigator.Actions.Model; using Navigator.Configuration; using Navigator.Context; using Scrutor; From 7bb5d28aaefa1cc06815462461fdeee3760218e2 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 23 Feb 2021 13:26:06 +0100 Subject: [PATCH 109/304] Renamed IProvider, added docs --- ...rovider.cs => DiscordNavigatorProvider.cs} | 2 +- .../NavigatorDiscordClient.cs | 4 +-- .../Actions/CallbackQueryAction.cs | 2 +- .../Actions/CommandAction.cs | 2 +- .../Actions/MessageAction.cs | 9 ++++-- .../TelegramMiddleware.cs | 6 ++-- .../TelegramNavigatorProvider.cs | 20 +++++++++++++ .../TelegramProvider.cs | 30 ------------------- src/Navigator/Actions/ActionsHelper.cs | 2 +- .../Context/NavigatorContextBuilder.cs | 4 +-- ...avigatorContextBuilderOptionsExtensions.cs | 2 +- src/Navigator/INavigatorProvider.cs | 14 +++++++++ src/Navigator/IProvider.cs | 8 ----- src/Navigator/Provider.cs | 2 +- 14 files changed, 54 insertions(+), 53 deletions(-) rename src/Navigator.Providers.Discord/{DiscordProvider.cs => DiscordNavigatorProvider.cs} (82%) create mode 100644 src/Navigator.Providers.Telegram/TelegramNavigatorProvider.cs delete mode 100644 src/Navigator.Providers.Telegram/TelegramProvider.cs create mode 100644 src/Navigator/INavigatorProvider.cs delete mode 100644 src/Navigator/IProvider.cs diff --git a/src/Navigator.Providers.Discord/DiscordProvider.cs b/src/Navigator.Providers.Discord/DiscordNavigatorProvider.cs similarity index 82% rename from src/Navigator.Providers.Discord/DiscordProvider.cs rename to src/Navigator.Providers.Discord/DiscordNavigatorProvider.cs index 6622623..b670a65 100644 --- a/src/Navigator.Providers.Discord/DiscordProvider.cs +++ b/src/Navigator.Providers.Discord/DiscordNavigatorProvider.cs @@ -1,6 +1,6 @@ namespace Navigator.Providers.Discord { - public class DiscordProvider : IProvider + public class DiscordNavigatorProvider : INavigatorProvider { public INavigatorClient GetClient() { diff --git a/src/Navigator.Providers.Discord/NavigatorDiscordClient.cs b/src/Navigator.Providers.Discord/NavigatorDiscordClient.cs index 937483c..3110988 100644 --- a/src/Navigator.Providers.Discord/NavigatorDiscordClient.cs +++ b/src/Navigator.Providers.Discord/NavigatorDiscordClient.cs @@ -69,9 +69,9 @@ public Task GetProfile(CancellationToken cancellationToken = default) }); } - public IProvider IsClientFor() + public INavigatorProvider IsClientFor() { - return Provider.For(); + return Provider.For(); } } } \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/Actions/CallbackQueryAction.cs b/src/Navigator.Providers.Telegram/Actions/CallbackQueryAction.cs index e044d0d..a199323 100644 --- a/src/Navigator.Providers.Telegram/Actions/CallbackQueryAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/CallbackQueryAction.cs @@ -5,7 +5,7 @@ namespace Navigator.Providers.Telegram.Actions { public abstract class CallbackQueryAction : BaseAction { - public override string Type { get; protected set; } = ActionsHelper.Type.For(nameof(CallbackQueryAction)); + public override string Type { get; protected set; } = ActionsHelper.Type.For(nameof(CallbackQueryAction)); public override ushort Priority { get; protected set; } = ActionsHelper.Priority.Default; } } \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/Actions/CommandAction.cs b/src/Navigator.Providers.Telegram/Actions/CommandAction.cs index 4cc036b..b0c77eb 100644 --- a/src/Navigator.Providers.Telegram/Actions/CommandAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/CommandAction.cs @@ -13,7 +13,7 @@ protected CommandAction() Arguments = string.Empty; } - public override string Type { get; protected set; } = ActionsHelper.Type.For(nameof(CommandAction)); + public override string Type { get; protected set; } = ActionsHelper.Type.For(nameof(CommandAction)); public override ushort Priority { get; protected set; } = ActionsHelper.Priority.Default; public override IAction Init(INavigatorContext navigatorContext) diff --git a/src/Navigator.Providers.Telegram/Actions/MessageAction.cs b/src/Navigator.Providers.Telegram/Actions/MessageAction.cs index 7726f16..e7c6951 100644 --- a/src/Navigator.Providers.Telegram/Actions/MessageAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/MessageAction.cs @@ -1,4 +1,3 @@ -using System.Threading.Tasks; using Navigator.Actions; using Navigator.Actions.Model; using Navigator.Context; @@ -9,7 +8,7 @@ namespace Navigator.Providers.Telegram.Actions { public abstract class MessageAction : BaseAction { - public override string Type { get; protected set; } = ActionsHelper.Type.For(nameof(MessageAction)); + public override string Type { get; protected set; } = ActionsHelper.Type.For(nameof(MessageAction)); public override ushort Priority { get; protected set; } = ActionsHelper.Priority.Default; public override IAction Init(INavigatorContext navigatorContext) @@ -19,11 +18,17 @@ public override IAction Init(INavigatorContext navigatorContext) if (update is not null) { Message = update.Message; + IsReply = update.Message.ReplyToMessage is not null; + IsForwarded = update.Message.ForwardDate is not null; } return this; } public Message Message { get; protected set; } + + public bool IsReply { get; protected set; } + + public bool IsForwarded { get; protected set; } } } \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/TelegramMiddleware.cs b/src/Navigator.Providers.Telegram/TelegramMiddleware.cs index fe03e8a..539baf0 100644 --- a/src/Navigator.Providers.Telegram/TelegramMiddleware.cs +++ b/src/Navigator.Providers.Telegram/TelegramMiddleware.cs @@ -33,7 +33,7 @@ public async Task Process(Update update) await _navigatorContextFactory.Supply(builder => { - builder.SetProvider(); + builder.SetProvider(); builder.SetActionType(actionType); builder.SetOriginalUpdate(update); }); @@ -45,7 +45,7 @@ await _navigatorContextFactory.Supply(builder => { return update.Type switch { - UpdateType.Message when update.Message.Entities?.First()?.Type == MessageEntityType.BotCommand => ActionsHelper.Type.For(nameof(CommandAction)), + UpdateType.Message when update.Message.Entities?.First()?.Type == MessageEntityType.BotCommand => ActionsHelper.Type.For(nameof(CommandAction)), UpdateType.Message => update.Message.Type switch { // MessageType.ChatMembersAdded => ActionType.ChatMembersAdded, @@ -59,7 +59,7 @@ await _navigatorContextFactory.Supply(builder => // MessageType.ChannelCreated => ActionType.ChannelCreated, // MessageType.MigratedToSupergroup => ActionType.MigratedToSupergroup, // MessageType.MigratedFromGroup => ActionType.MigratedFromGroup, - _ => ActionsHelper.Type.For(nameof(MessageAction)) + _ => ActionsHelper.Type.For(nameof(MessageAction)) }, // UpdateType.InlineQuery => ActionType.InlineQuery, // UpdateType.ChosenInlineResult => ActionType.InlineResultChosen, diff --git a/src/Navigator.Providers.Telegram/TelegramNavigatorProvider.cs b/src/Navigator.Providers.Telegram/TelegramNavigatorProvider.cs new file mode 100644 index 0000000..711f46f --- /dev/null +++ b/src/Navigator.Providers.Telegram/TelegramNavigatorProvider.cs @@ -0,0 +1,20 @@ +using System; +using Telegram.Bot.Types; + +namespace Navigator.Providers.Telegram +{ + public class TelegramNavigatorProvider : INavigatorProvider + { + private readonly NavigatorTelegramClient _client; + + public TelegramNavigatorProvider(NavigatorTelegramClient client) + { + _client = client; + } + + public INavigatorClient GetClient() + { + return _client; + } + } +} \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/TelegramProvider.cs b/src/Navigator.Providers.Telegram/TelegramProvider.cs deleted file mode 100644 index 316e1c8..0000000 --- a/src/Navigator.Providers.Telegram/TelegramProvider.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System; -using Telegram.Bot.Types; - -namespace Navigator.Providers.Telegram -{ - public class TelegramProvider : IProvider - { - private readonly NavigatorTelegramClient _client; - - public TelegramProvider(NavigatorTelegramClient client) - { - _client = client; - } - - public INavigatorClient GetClient() - { - return _client; - } - - public string GetActionType(object original) - { - if (original is not Update) - { - return string.Empty; - } - - throw new NotImplementedException(); - } - } -} \ No newline at end of file diff --git a/src/Navigator/Actions/ActionsHelper.cs b/src/Navigator/Actions/ActionsHelper.cs index a3b23c1..cfc5391 100644 --- a/src/Navigator/Actions/ActionsHelper.cs +++ b/src/Navigator/Actions/ActionsHelper.cs @@ -11,7 +11,7 @@ public static class Priority public static class Type { - public static string For(string name) where TProvider : IProvider + public static string For(string name) where TProvider : INavigatorProvider { return $"_navigator.actions.{typeof(TProvider).Name}.{name}"; } diff --git a/src/Navigator/Context/NavigatorContextBuilder.cs b/src/Navigator/Context/NavigatorContextBuilder.cs index 6aaf163..c46c0b6 100644 --- a/src/Navigator/Context/NavigatorContextBuilder.cs +++ b/src/Navigator/Context/NavigatorContextBuilder.cs @@ -11,11 +11,11 @@ namespace Navigator.Context public class NavigatorContextBuilder : INavigatorContextBuilder { private readonly ILogger _logger; - private readonly IEnumerable _navigatorProviders; + private readonly IEnumerable _navigatorProviders; private readonly IEnumerable _navigatorContextExtensions; private readonly INavigatorContextBuilderOptions _options; - public NavigatorContextBuilder(ILogger logger, IEnumerable navigatorClients, IEnumerable navigatorContextExtensions) + public NavigatorContextBuilder(ILogger logger, IEnumerable navigatorClients, IEnumerable navigatorContextExtensions) { _logger = logger; _navigatorProviders = navigatorClients; diff --git a/src/Navigator/Context/NavigatorContextBuilderOptionsExtensions.cs b/src/Navigator/Context/NavigatorContextBuilderOptionsExtensions.cs index d4ad9bc..72b5765 100644 --- a/src/Navigator/Context/NavigatorContextBuilderOptionsExtensions.cs +++ b/src/Navigator/Context/NavigatorContextBuilderOptionsExtensions.cs @@ -8,7 +8,7 @@ public static class NavigatorContextBuilderOptionsExtensions private const string ProviderKey = "_navigator.context.options.provider"; - public static void SetProvider(this INavigatorContextBuilderOptions contextBuilderOptions) where TProvider : IProvider + public static void SetProvider(this INavigatorContextBuilderOptions contextBuilderOptions) where TProvider : INavigatorProvider { contextBuilderOptions.TryRegisterOption(ProviderKey, typeof(TProvider)); diff --git a/src/Navigator/INavigatorProvider.cs b/src/Navigator/INavigatorProvider.cs new file mode 100644 index 0000000..ac2bd0b --- /dev/null +++ b/src/Navigator/INavigatorProvider.cs @@ -0,0 +1,14 @@ +namespace Navigator +{ + /// + /// Represents a provider for Navigator. + /// + public interface INavigatorProvider + { + /// + /// Gets the specific client for this provider. + /// + /// An implementation of + INavigatorClient GetClient(); + } +} \ No newline at end of file diff --git a/src/Navigator/IProvider.cs b/src/Navigator/IProvider.cs deleted file mode 100644 index e25d497..0000000 --- a/src/Navigator/IProvider.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace Navigator -{ - public interface IProvider - { - INavigatorClient GetClient(); - string GetActionType(object original); - } -} \ No newline at end of file diff --git a/src/Navigator/Provider.cs b/src/Navigator/Provider.cs index 26696f8..d400459 100644 --- a/src/Navigator/Provider.cs +++ b/src/Navigator/Provider.cs @@ -2,7 +2,7 @@ namespace Navigator { public static class Provider { - public static TProvider For() where TProvider : IProvider, new() + public static TProvider For() where TProvider : INavigatorProvider, new() { return new(); } From e172d554c7b33a39cbc6077e348a0fd4e5be376f Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 23 Feb 2021 13:49:08 +0100 Subject: [PATCH 110/304] Moved old code to new project. --- .../INavigatorContextExtensions.cs | 249 ------------------ .../Navigator.Abstractions.Extensions.csproj | 30 --- .../Extensions/NavigatorContextExtensions.cs | 249 ++++++++++++++++++ .../Actions/EchoActionHandler.cs | 1 - src/Navigator.sln | 7 - 5 files changed, 249 insertions(+), 287 deletions(-) delete mode 100644 src/Navigator.Abstractions.Extensions/INavigatorContextExtensions.cs delete mode 100644 src/Navigator.Abstractions.Extensions/Navigator.Abstractions.Extensions.csproj create mode 100644 src/Navigator.Providers.Telegram/Extensions/NavigatorContextExtensions.cs diff --git a/src/Navigator.Abstractions.Extensions/INavigatorContextExtensions.cs b/src/Navigator.Abstractions.Extensions/INavigatorContextExtensions.cs deleted file mode 100644 index 9d1c902..0000000 --- a/src/Navigator.Abstractions.Extensions/INavigatorContextExtensions.cs +++ /dev/null @@ -1,249 +0,0 @@ -using System; -using Telegram.Bot.Types; -using Telegram.Bot.Types.Enums; -using Telegram.Bot.Types.Payments; - -namespace Navigator.Abstractions.Extensions -{ - /// - /// Useful extensions for Navigator Context. - /// - public static class INavigatorContextExtensions - { - #region User - - /// - /// Get a Telegram user. - /// - /// - /// When user is not found. - /// - public static User GetTelegramUser(this INavigatorContext ctx) - { - var user = ctx.GetTelegramUserOrDefault(); - - return user ?? throw new Exception("User not found in update."); - } - - /// - /// Get a Telegram user or default if not found. - /// - /// - /// - public static User? GetTelegramUserOrDefault(this INavigatorContext ctx) - { - return ctx.Update.Type switch - { - UpdateType.Message => ctx.Update.Message.From, - UpdateType.InlineQuery => ctx.Update.InlineQuery.From, - UpdateType.ChosenInlineResult => ctx.Update.ChosenInlineResult.From, - UpdateType.CallbackQuery => ctx.Update.CallbackQuery.From, - UpdateType.EditedMessage => ctx.Update.EditedMessage.From, - UpdateType.ChannelPost => ctx.Update.ChannelPost.From, - UpdateType.EditedChannelPost => ctx.Update.EditedChannelPost.From, - UpdateType.ShippingQuery => ctx.Update.ShippingQuery.From, - UpdateType.PreCheckoutQuery => ctx.Update.PreCheckoutQuery.From, - _ => default - }; - } - - #endregion - - #region Chat - - /// - /// Get a Telegram chat. - /// - /// - /// When chat is not found. - /// - public static Chat GetTelegramChat(this INavigatorContext ctx) - { - var chat = ctx.GetTelegramChatOrDefault(); - - return chat ?? throw new Exception("Chat not found in update."); - } - - /// - /// Get a Telegram chat or default if not found. - /// - /// - /// Telegram Chat - public static Chat? GetTelegramChatOrDefault(this INavigatorContext ctx) - { - return ctx.Update.Type switch - { - UpdateType.CallbackQuery => ctx.Update.CallbackQuery.Message.Chat, - UpdateType.Message => ctx.Update.Message.Chat, - UpdateType.EditedMessage => ctx.Update.EditedMessage.Chat, - UpdateType.ChannelPost => ctx.Update.ChannelPost.Chat, - UpdateType.EditedChannelPost => ctx.Update.EditedChannelPost.Chat, - _ => default - }; - } - - #endregion - - #region Message - - /// - /// Get a Telegram message. - /// - /// - /// When message is not found. - /// - public static Message GetMessage(this INavigatorContext ctx) - { - return ctx.GetMessageOrDefault() ?? throw new Exception("Message not found in update."); - } - - /// - /// Get a Telegram message or default if not found. - /// - /// - /// - public static Message? GetMessageOrDefault(this INavigatorContext ctx) - { - return ctx.Update.Type == UpdateType.Message ? ctx.Update.Message : default; - } - - #endregion - - #region InlineQuery - - /// - /// Get a Telegram inline query - /// - /// - /// When inline query is not found. - /// - public static InlineQuery GetInlineQuery(this INavigatorContext ctx) - { - return ctx.GetInlineQueryOrDefault() ?? throw new Exception("InlineQuery not found in update."); - } - - /// - /// Get a Telegram inline query or default if not found. - /// - /// - /// - public static InlineQuery? GetInlineQueryOrDefault(this INavigatorContext ctx) - { - return ctx.Update.Type == UpdateType.InlineQuery ? ctx.Update.InlineQuery : default; - } - - #endregion - - #region ChosenInlineResult - - public static ChosenInlineResult GetChosenInlineResult(this INavigatorContext ctx) - { - return ctx.GetChosenInlineResultOrDefault() ?? throw new Exception("ChosenInlineResult not found in update."); - } - - public static ChosenInlineResult? GetChosenInlineResultOrDefault(this INavigatorContext ctx) - { - return ctx.Update.Type == UpdateType.ChosenInlineResult ? ctx.Update.ChosenInlineResult : default; - } - - #endregion - - #region CallbackQuery - - public static CallbackQuery GetCallbackQuery(this INavigatorContext ctx) - { - return ctx.GetCallbackQueryOrDefault() ?? throw new Exception("CallbackQuery not found in update."); - } - - public static CallbackQuery? GetCallbackQueryOrDefault(this INavigatorContext ctx) - { - return ctx.Update.Type == UpdateType.CallbackQuery ? ctx.Update.CallbackQuery : default; - } - - #endregion - - #region EditedMessage - - public static Message GetEditedMessage(this INavigatorContext ctx) - { - return ctx.GetEditedMessageOrDefault() ?? throw new Exception("EditedMessage not found in update."); - } - - public static Message? GetEditedMessageOrDefault(this INavigatorContext ctx) - { - return ctx.Update.Type == UpdateType.EditedMessage ? ctx.Update.EditedMessage : default; - } - - #endregion - - #region ChannelPost - - public static Message GetChannelPost(this INavigatorContext ctx) - { - return ctx.GetChannelPostOrDefault() ?? throw new Exception("ChannelPost not found in update."); - } - - public static Message? GetChannelPostOrDefault(this INavigatorContext ctx) - { - return ctx.Update.Type == UpdateType.ChannelPost ? ctx.Update.ChannelPost : default; - } - - #endregion - - #region EditedChannelPost - - public static Message GetEditedChannelPost(this INavigatorContext ctx) - { - return ctx.GetEditedChannelPostOrDefault() ?? throw new Exception("EditedChannelPost not found in update."); - } - - public static Message? GetEditedChannelPostOrDefault(this INavigatorContext ctx) - { - return ctx.Update.Type == UpdateType.EditedChannelPost ? ctx.Update.EditedChannelPost : default; - } - - #endregion - - #region ShippingQuery - - public static ShippingQuery GetShippingQuery(this INavigatorContext ctx) - { - return ctx.GetShippingQueryOrDefault() ?? throw new Exception("ShippingQuery not found in update."); - } - - public static ShippingQuery? GetShippingQueryOrDefault(this INavigatorContext ctx) - { - return ctx.Update.Type == UpdateType.ShippingQuery ? ctx.Update.ShippingQuery : default; - } - - #endregion - - #region PreCheckoutQuery - - public static PreCheckoutQuery GetPreCheckoutQuery(this INavigatorContext ctx) - { - return ctx.GetPreCheckoutQueryOrDefault() ?? throw new Exception("PreCheckoutQuery not found in update."); - } - - public static PreCheckoutQuery? GetPreCheckoutQueryOrDefault(this INavigatorContext ctx) - { - return ctx.Update.Type == UpdateType.PreCheckoutQuery ? ctx.Update.PreCheckoutQuery : default; - } - - #endregion - - #region Poll - - public static Poll GetPoll(this INavigatorContext ctx) - { - return ctx.GetPollOrDefault() ?? throw new Exception("Poll not found in update."); - } - - public static Poll? GetPollOrDefault(this INavigatorContext ctx) - { - return ctx.Update.Type == UpdateType.Poll ? ctx.Update.Poll : default; - } - - #endregion - } -} \ No newline at end of file diff --git a/src/Navigator.Abstractions.Extensions/Navigator.Abstractions.Extensions.csproj b/src/Navigator.Abstractions.Extensions/Navigator.Abstractions.Extensions.csproj deleted file mode 100644 index 4c53843..0000000 --- a/src/Navigator.Abstractions.Extensions/Navigator.Abstractions.Extensions.csproj +++ /dev/null @@ -1,30 +0,0 @@ - - - - net5.0 - enable - true - true - 0.9.99-beta - Navigator.Abstractions.Extensions - Navigator Framework Abstractions Extensions - Lucas Maximiliano Marino - A highly opinionated telegram bot framework, mainly based on Telegram.Bot. - https://github.com/navigatorframework/navigator - https://github.com/navigatorframework/navigator/blob/master/LICENSE - https://github.com/navigatorframework/navigator - Telegram, Bot, Framework, Navigator - true - Copyright © Lucas Maximiliano Marino 2021 - https://raw.githubusercontent.com/navigatorframework/navigator/master/assets/logo.png - - - - - - - - - - - diff --git a/src/Navigator.Providers.Telegram/Extensions/NavigatorContextExtensions.cs b/src/Navigator.Providers.Telegram/Extensions/NavigatorContextExtensions.cs new file mode 100644 index 0000000..528c3fd --- /dev/null +++ b/src/Navigator.Providers.Telegram/Extensions/NavigatorContextExtensions.cs @@ -0,0 +1,249 @@ +using System; +using Telegram.Bot.Types; +using Telegram.Bot.Types.Enums; +using Telegram.Bot.Types.Payments; + +namespace Navigator.Providers.Telegram.Extensions +{ + /// + /// Useful extensions for Navigator Context. + /// + public static class NavigatorContextExtensions + { + // #region User + // + // /// + // /// Get a Telegram user. + // /// + // /// + // /// When user is not found. + // /// + // public static User GetTelegramUser(this INavigatorContext ctx) + // { + // var user = ctx.GetTelegramUserOrDefault(); + // + // return user ?? throw new Exception("User not found in update."); + // } + // + // /// + // /// Get a Telegram user or default if not found. + // /// + // /// + // /// + // public static User? GetTelegramUserOrDefault(this INavigatorContext ctx) + // { + // return ctx.Update.Type switch + // { + // UpdateType.Message => ctx.Update.Message.From, + // UpdateType.InlineQuery => ctx.Update.InlineQuery.From, + // UpdateType.ChosenInlineResult => ctx.Update.ChosenInlineResult.From, + // UpdateType.CallbackQuery => ctx.Update.CallbackQuery.From, + // UpdateType.EditedMessage => ctx.Update.EditedMessage.From, + // UpdateType.ChannelPost => ctx.Update.ChannelPost.From, + // UpdateType.EditedChannelPost => ctx.Update.EditedChannelPost.From, + // UpdateType.ShippingQuery => ctx.Update.ShippingQuery.From, + // UpdateType.PreCheckoutQuery => ctx.Update.PreCheckoutQuery.From, + // _ => default + // }; + // } + // + // #endregion + // + // #region Chat + // + // /// + // /// Get a Telegram chat. + // /// + // /// + // /// When chat is not found. + // /// + // public static Chat GetTelegramChat(this INavigatorContext ctx) + // { + // var chat = ctx.GetTelegramChatOrDefault(); + // + // return chat ?? throw new Exception("Chat not found in update."); + // } + // + // /// + // /// Get a Telegram chat or default if not found. + // /// + // /// + // /// Telegram Chat + // public static Chat? GetTelegramChatOrDefault(this INavigatorContext ctx) + // { + // return ctx.Update.Type switch + // { + // UpdateType.CallbackQuery => ctx.Update.CallbackQuery.Message.Chat, + // UpdateType.Message => ctx.Update.Message.Chat, + // UpdateType.EditedMessage => ctx.Update.EditedMessage.Chat, + // UpdateType.ChannelPost => ctx.Update.ChannelPost.Chat, + // UpdateType.EditedChannelPost => ctx.Update.EditedChannelPost.Chat, + // _ => default + // }; + // } + // + // #endregion + // + // #region Message + // + // /// + // /// Get a Telegram message. + // /// + // /// + // /// When message is not found. + // /// + // public static Message GetMessage(this INavigatorContext ctx) + // { + // return ctx.GetMessageOrDefault() ?? throw new Exception("Message not found in update."); + // } + // + // /// + // /// Get a Telegram message or default if not found. + // /// + // /// + // /// + // public static Message? GetMessageOrDefault(this INavigatorContext ctx) + // { + // return ctx.Update.Type == UpdateType.Message ? ctx.Update.Message : default; + // } + // + // #endregion + // + // #region InlineQuery + // + // /// + // /// Get a Telegram inline query + // /// + // /// + // /// When inline query is not found. + // /// + // public static InlineQuery GetInlineQuery(this INavigatorContext ctx) + // { + // return ctx.GetInlineQueryOrDefault() ?? throw new Exception("InlineQuery not found in update."); + // } + // + // /// + // /// Get a Telegram inline query or default if not found. + // /// + // /// + // /// + // public static InlineQuery? GetInlineQueryOrDefault(this INavigatorContext ctx) + // { + // return ctx.Update.Type == UpdateType.InlineQuery ? ctx.Update.InlineQuery : default; + // } + // + // #endregion + // + // #region ChosenInlineResult + // + // public static ChosenInlineResult GetChosenInlineResult(this INavigatorContext ctx) + // { + // return ctx.GetChosenInlineResultOrDefault() ?? throw new Exception("ChosenInlineResult not found in update."); + // } + // + // public static ChosenInlineResult? GetChosenInlineResultOrDefault(this INavigatorContext ctx) + // { + // return ctx.Update.Type == UpdateType.ChosenInlineResult ? ctx.Update.ChosenInlineResult : default; + // } + // + // #endregion + // + // #region CallbackQuery + // + // public static CallbackQuery GetCallbackQuery(this INavigatorContext ctx) + // { + // return ctx.GetCallbackQueryOrDefault() ?? throw new Exception("CallbackQuery not found in update."); + // } + // + // public static CallbackQuery? GetCallbackQueryOrDefault(this INavigatorContext ctx) + // { + // return ctx.Update.Type == UpdateType.CallbackQuery ? ctx.Update.CallbackQuery : default; + // } + // + // #endregion + // + // #region EditedMessage + // + // public static Message GetEditedMessage(this INavigatorContext ctx) + // { + // return ctx.GetEditedMessageOrDefault() ?? throw new Exception("EditedMessage not found in update."); + // } + // + // public static Message? GetEditedMessageOrDefault(this INavigatorContext ctx) + // { + // return ctx.Update.Type == UpdateType.EditedMessage ? ctx.Update.EditedMessage : default; + // } + // + // #endregion + // + // #region ChannelPost + // + // public static Message GetChannelPost(this INavigatorContext ctx) + // { + // return ctx.GetChannelPostOrDefault() ?? throw new Exception("ChannelPost not found in update."); + // } + // + // public static Message? GetChannelPostOrDefault(this INavigatorContext ctx) + // { + // return ctx.Update.Type == UpdateType.ChannelPost ? ctx.Update.ChannelPost : default; + // } + // + // #endregion + // + // #region EditedChannelPost + // + // public static Message GetEditedChannelPost(this INavigatorContext ctx) + // { + // return ctx.GetEditedChannelPostOrDefault() ?? throw new Exception("EditedChannelPost not found in update."); + // } + // + // public static Message? GetEditedChannelPostOrDefault(this INavigatorContext ctx) + // { + // return ctx.Update.Type == UpdateType.EditedChannelPost ? ctx.Update.EditedChannelPost : default; + // } + // + // #endregion + // + // #region ShippingQuery + // + // public static ShippingQuery GetShippingQuery(this INavigatorContext ctx) + // { + // return ctx.GetShippingQueryOrDefault() ?? throw new Exception("ShippingQuery not found in update."); + // } + // + // public static ShippingQuery? GetShippingQueryOrDefault(this INavigatorContext ctx) + // { + // return ctx.Update.Type == UpdateType.ShippingQuery ? ctx.Update.ShippingQuery : default; + // } + // + // #endregion + // + // #region PreCheckoutQuery + // + // public static PreCheckoutQuery GetPreCheckoutQuery(this INavigatorContext ctx) + // { + // return ctx.GetPreCheckoutQueryOrDefault() ?? throw new Exception("PreCheckoutQuery not found in update."); + // } + // + // public static PreCheckoutQuery? GetPreCheckoutQueryOrDefault(this INavigatorContext ctx) + // { + // return ctx.Update.Type == UpdateType.PreCheckoutQuery ? ctx.Update.PreCheckoutQuery : default; + // } + // + // #endregion + // + // #region Poll + // + // public static Poll GetPoll(this INavigatorContext ctx) + // { + // return ctx.GetPollOrDefault() ?? throw new Exception("Poll not found in update."); + // } + // + // public static Poll? GetPollOrDefault(this INavigatorContext ctx) + // { + // return ctx.Update.Type == UpdateType.Poll ? ctx.Update.Poll : default; + // } + // + // #endregion + } +} \ No newline at end of file diff --git a/src/Navigator.Samples.Echo/Actions/EchoActionHandler.cs b/src/Navigator.Samples.Echo/Actions/EchoActionHandler.cs index 769f59a..ea48ca2 100644 --- a/src/Navigator.Samples.Echo/Actions/EchoActionHandler.cs +++ b/src/Navigator.Samples.Echo/Actions/EchoActionHandler.cs @@ -2,7 +2,6 @@ using System.Threading.Tasks; using MediatR; using Navigator.Abstractions; -using Navigator.Abstractions.Extensions; using Navigator.Context; using Navigator.Extensions.Actions; using Navigator.Extensions.Store.Abstractions.Extensions; diff --git a/src/Navigator.sln b/src/Navigator.sln index 677b6d6..57474d3 100644 --- a/src/Navigator.sln +++ b/src/Navigator.sln @@ -18,8 +18,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Packages", "Packages", "{89 EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Navigator", "Navigator", "{E6F24E3B-A066-4572-94F0-14665E19EFC7}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Navigator.Abstractions.Extensions", "Navigator.Abstractions.Extensions\Navigator.Abstractions.Extensions.csproj", "{FACFECB8-1215-4F04-B9B2-F7FB7656804F}" -EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Store", "Store", "{F26BD166-0ED4-4096-8841-47959645B3DE}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Navigator.Extensions.Store.Abstractions", "Navigator.Extensions.Store.Abstractions\Navigator.Extensions.Store.Abstractions.csproj", "{8E680AE7-33EC-4049-A9DC-0F42C6A03184}" @@ -60,10 +58,6 @@ Global {2711B76D-B24C-4A3A-A33F-5A0077C49CB6}.Debug|Any CPU.Build.0 = Debug|Any CPU {2711B76D-B24C-4A3A-A33F-5A0077C49CB6}.Release|Any CPU.ActiveCfg = Release|Any CPU {2711B76D-B24C-4A3A-A33F-5A0077C49CB6}.Release|Any CPU.Build.0 = Release|Any CPU - {FACFECB8-1215-4F04-B9B2-F7FB7656804F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {FACFECB8-1215-4F04-B9B2-F7FB7656804F}.Debug|Any CPU.Build.0 = Debug|Any CPU - {FACFECB8-1215-4F04-B9B2-F7FB7656804F}.Release|Any CPU.ActiveCfg = Release|Any CPU - {FACFECB8-1215-4F04-B9B2-F7FB7656804F}.Release|Any CPU.Build.0 = Release|Any CPU {8E680AE7-33EC-4049-A9DC-0F42C6A03184}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {8E680AE7-33EC-4049-A9DC-0F42C6A03184}.Debug|Any CPU.Build.0 = Debug|Any CPU {8E680AE7-33EC-4049-A9DC-0F42C6A03184}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -96,7 +90,6 @@ Global {6DBAD041-6623-4903-9939-254FDC4EBD60} = {E6F24E3B-A066-4572-94F0-14665E19EFC7} {2711B76D-B24C-4A3A-A33F-5A0077C49CB6} = {288F4B0C-9EF0-443B-B893-5FC34F9D032B} {288F4B0C-9EF0-443B-B893-5FC34F9D032B} = {F178DCF2-AD03-44C8-AF8F-95C60664DD10} - {FACFECB8-1215-4F04-B9B2-F7FB7656804F} = {E6F24E3B-A066-4572-94F0-14665E19EFC7} {F26BD166-0ED4-4096-8841-47959645B3DE} = {F178DCF2-AD03-44C8-AF8F-95C60664DD10} {9DEA166A-AE92-438F-8F3D-7C2F777ABBDD} = {F26BD166-0ED4-4096-8841-47959645B3DE} {8E680AE7-33EC-4049-A9DC-0F42C6A03184} = {F26BD166-0ED4-4096-8841-47959645B3DE} From bdd65de4766d2a8ce39db6a448a71fcdf07eacdf Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 23 Feb 2021 14:35:28 +0100 Subject: [PATCH 111/304] Updated package metadata --- .../Navigator.Providers.Discord.csproj | 11 ++ .../Navigator.Providers.Telegram.csproj | 11 ++ src/Navigator/Navigator.csproj | 10 +- src/Navigator/Old/ActionLauncher.cs | 127 ------------------ src/Navigator/Old/NavigatorMiddleware.cs | 89 ------------ .../Old/Notification/NavigatorNotification.cs | 119 ---------------- src/Navigator/Old/NotificationLauncher.cs | 52 ------- 7 files changed, 25 insertions(+), 394 deletions(-) delete mode 100644 src/Navigator/Old/ActionLauncher.cs delete mode 100644 src/Navigator/Old/NavigatorMiddleware.cs delete mode 100644 src/Navigator/Old/Notification/NavigatorNotification.cs delete mode 100644 src/Navigator/Old/NotificationLauncher.cs diff --git a/src/Navigator.Providers.Discord/Navigator.Providers.Discord.csproj b/src/Navigator.Providers.Discord/Navigator.Providers.Discord.csproj index 874e3c7..ddf4c52 100644 --- a/src/Navigator.Providers.Discord/Navigator.Providers.Discord.csproj +++ b/src/Navigator.Providers.Discord/Navigator.Providers.Discord.csproj @@ -3,6 +3,17 @@ net5.0 enable + true + Telegram Provider for Navigator + Lucas Maximiliano Marino + Discord provider for Navigator Framework. Implementation based on Discord.Net. + https://github.com/navigatorframework/navigator + https://github.com/navigatorframework/navigator/blob/master/LICENSE + https://github.com/navigatorframework/navigator + Discord, Bot, Framework, Navigator + true + Copyright © Lucas Maximiliano Marino 2021 + https://raw.githubusercontent.com/navigatorframework/navigator/master/assets/logo.png diff --git a/src/Navigator.Providers.Telegram/Navigator.Providers.Telegram.csproj b/src/Navigator.Providers.Telegram/Navigator.Providers.Telegram.csproj index d45fcd2..2327862 100644 --- a/src/Navigator.Providers.Telegram/Navigator.Providers.Telegram.csproj +++ b/src/Navigator.Providers.Telegram/Navigator.Providers.Telegram.csproj @@ -3,6 +3,17 @@ net5.0 enable + true + Telegram Provider for Navigator + Lucas Maximiliano Marino + Telegram provider for Navigator Framework. Implementation based on Telegram.Bot. + https://github.com/navigatorframework/navigator + https://github.com/navigatorframework/navigator/blob/master/LICENSE + https://github.com/navigatorframework/navigator + Telegram, Bot, Framework, Navigator + true + Copyright © Lucas Maximiliano Marino 2021 + https://raw.githubusercontent.com/navigatorframework/navigator/master/assets/logo.png diff --git a/src/Navigator/Navigator.csproj b/src/Navigator/Navigator.csproj index f3dc2cd..f528702 100644 --- a/src/Navigator/Navigator.csproj +++ b/src/Navigator/Navigator.csproj @@ -2,14 +2,11 @@ net5.0 - 9 - true - true - 0.9.102-beta - Navigator + enable + true Navigator Framework Lucas Maximiliano Marino - A highly opinionated telegram bot framework, mainly based on Telegram.Bot. + A highly opinionated universal bot framework. https://github.com/navigatorframework/navigator https://github.com/navigatorframework/navigator/blob/master/LICENSE https://github.com/navigatorframework/navigator @@ -17,7 +14,6 @@ true Copyright © Lucas Maximiliano Marino 2021 https://raw.githubusercontent.com/navigatorframework/navigator/master/assets/logo.png - enable diff --git a/src/Navigator/Old/ActionLauncher.cs b/src/Navigator/Old/ActionLauncher.cs deleted file mode 100644 index 6bc5c7c..0000000 --- a/src/Navigator/Old/ActionLauncher.cs +++ /dev/null @@ -1,127 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using MediatR; -using Microsoft.Extensions.Logging; -using Navigator.Abstractions; -using Navigator.Actions; -using Navigator.Configuration; -using Navigator.Context; -using Telegram.Bot.Types; -using Telegram.Bot.Types.Enums; - -namespace Navigator.Old -{ - public class ActionLauncher : IActionLauncher - { - protected readonly ILogger Logger; - protected readonly IMediator Mediator; - protected readonly bool MultipleActionsUsage; - protected readonly IEnumerable Actions; - protected readonly INavigatorContext Ctx; - - public ActionLauncher(ILogger logger, NavigatorOptions options, IMediator mediator, IEnumerable actions, INavigatorContext navigatorContext) - { - Logger = logger; - MultipleActionsUsage = options.MultipleActionsUsageIsEnabled(); - Mediator = mediator; - Actions = actions; - Ctx = navigatorContext; - } - - public async Task Launch() - { - Logger.LogTrace("Launching of multiple actions is {MultipleActionLaunchState}.", MultipleActionsUsage ? "active" : "inactive"); - Logger.LogTrace("Starting with action launching."); - - var actions = GetActions(Ctx.Update).ToList(); - - Logger.LogTrace("Found a total of {NumberOfActionsFound} actions to launch.", actions.Count); - - foreach (var action in actions) - { - try - { - Logger.LogTrace("Launching action {ActionName}", action.GetType().Name); - - await Mediator.Send(action); - - Logger.LogTrace("Action {ActionName} successfully launched", action.GetType().Name); - } - catch (Exception e) - { - Logger.LogError(e, "Action {ActionName} finished launch with errors", action.GetType().Name); - } - } - } - - public IEnumerable GetActions(Update update) - { - var actions = new List(); - var actionType = GetActionType(update); - - if (string.IsNullOrWhiteSpace(actionType)) - { - return actions; - } - - if (MultipleActionsUsage) - { - actions = Actions - .Where(a => a.Type == actionType) - .Where(a => a.Init(Ctx).CanHandle(Ctx)) - .OrderBy(a => a.Order) - .ToList(); - } - else - { - var action = Actions - .Where(a => a.Type == actionType) - .OrderBy(a => a.Order) - .FirstOrDefault(a => a.Init(Ctx).CanHandle(Ctx)); - - if (action != null) - { - actions.Add(action); - } - } - - return actions; - } - - public string? GetActionType(Update update) - { - return update.Type switch - { - UpdateType.Message when update.Message.Entities?.First()?.Type == MessageEntityType.BotCommand => ActionType.Command, - UpdateType.Message => update.Message.Type switch - { - MessageType.ChatMembersAdded => ActionType.ChatMembersAdded, - MessageType.ChatMemberLeft => ActionType.ChatMemberLeft, - MessageType.ChatTitleChanged => ActionType.ChatTitleChanged, - MessageType.ChatPhotoChanged => ActionType.ChatPhotoChanged, - MessageType.MessagePinned => ActionType.MessagePinned, - MessageType.ChatPhotoDeleted => ActionType.ChatPhotoDeleted, - MessageType.GroupCreated => ActionType.GroupCreated, - MessageType.SupergroupCreated => ActionType.SupergroupCreated, - MessageType.ChannelCreated => ActionType.ChannelCreated, - MessageType.MigratedToSupergroup => ActionType.MigratedToSupergroup, - MessageType.MigratedFromGroup => ActionType.MigratedFromGroup, - _ => ActionType.Message - }, - UpdateType.InlineQuery => ActionType.InlineQuery, - UpdateType.ChosenInlineResult => ActionType.InlineResultChosen, - UpdateType.CallbackQuery => ActionType.CallbackQuery, - UpdateType.EditedMessage => ActionType.EditedMessage, - UpdateType.ChannelPost => ActionType.ChannelPost, - UpdateType.EditedChannelPost => ActionType.EditedChannelPost, - UpdateType.ShippingQuery => ActionType.ShippingQuery, - UpdateType.PreCheckoutQuery => ActionType.PreCheckoutQuery, - UpdateType.Poll => ActionType.Poll, - UpdateType.Unknown => ActionType.Unknown, - _ => default - }; - } - } -} \ No newline at end of file diff --git a/src/Navigator/Old/NavigatorMiddleware.cs b/src/Navigator/Old/NavigatorMiddleware.cs deleted file mode 100644 index 87c343d..0000000 --- a/src/Navigator/Old/NavigatorMiddleware.cs +++ /dev/null @@ -1,89 +0,0 @@ -using System.IO; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Http; -using Microsoft.Extensions.Logging; -using Navigator.Abstractions; -using Navigator.Actions; -using Newtonsoft.Json; -using Telegram.Bot.Types; - -namespace Navigator.Old -{ - /// - /// - /// - public class NavigatorMiddleware : INavigatorMiddleware - { - /// - /// Logger. - /// - protected readonly ILogger Logger; - - /// - /// Notification Launcher. - /// - protected readonly INotificationLauncher NotificationLauncher; - - /// - /// Action Launcher. - /// - protected readonly IActionLauncher ActionLauncher; - - /// - /// Context Builder. - /// - protected readonly INavigatorContextBuilder NavigatorContextBuilder; - - /// - /// Default constructor. - /// - /// - /// - /// - /// - public NavigatorMiddleware(ILogger logger, INotificationLauncher notificationLauncher, IActionLauncher actionLauncher, INavigatorContextBuilder navigatorContextBuilder) - { - Logger = logger; - NotificationLauncher = notificationLauncher; - ActionLauncher = actionLauncher; - NavigatorContextBuilder = navigatorContextBuilder; - } - - /// - public async Task Handle(HttpRequest httpRequest) - { - Logger.LogTrace("Parsing telegram update."); - var update = await ParseTelegramUpdate(httpRequest.Body); - - if (update == null) - { - Logger.LogInformation("Telegram update was not parsed."); - return; - } - - Logger.LogTrace("Parsed telegram update with id: {UpdateId}", update.Id); - - await NavigatorContextBuilder.Build(update); - await NotificationLauncher.Launch(); - await ActionLauncher.Launch(); - } - - private static async Task ParseTelegramUpdate(Stream stream) - { - try - { - var reader = new StreamReader(stream); - var update = JsonConvert.DeserializeObject(await reader.ReadToEndAsync()); - - // TODO: Activate this when Telegram.Bot supports System.Text.Json - // update = await JsonSerializer.DeserializeAsync(stream); - - return update.Id == default ? default : update; - } - catch - { - return default; - } - } - } -} \ No newline at end of file diff --git a/src/Navigator/Old/Notification/NavigatorNotification.cs b/src/Navigator/Old/Notification/NavigatorNotification.cs deleted file mode 100644 index f479c55..0000000 --- a/src/Navigator/Old/Notification/NavigatorNotification.cs +++ /dev/null @@ -1,119 +0,0 @@ -using System; -using Navigator.Abstractions; -using Telegram.Bot.Types; -using Telegram.Bot.Types.Payments; - -namespace Navigator.Old.Notification -{ - public abstract class NavigatorNotification : INavigatorNotification - { - public DateTime Timestamp { get; } - public int UpdateId { get; } - - protected NavigatorNotification(Update update) - { - UpdateId = update.Id; - Timestamp = DateTime.UtcNow; - } - } - - public class MessageNotification : NavigatorNotification - { - public readonly Message Message; - - public MessageNotification(Update update) : base(update) - { - Message = update.Message; - } - } - - public class InlineQueryNotification : NavigatorNotification - { - public readonly InlineQuery InlineQuery; - - public InlineQueryNotification(Update update) : base(update) - { - InlineQuery = update.InlineQuery; - } - } - - public class ChosenInlineResultNotification : NavigatorNotification - { - public readonly ChosenInlineResult ChosenInlineResult; - - public ChosenInlineResultNotification(Update update) : base(update) - { - ChosenInlineResult = update.ChosenInlineResult; - } - } - - public class CallbackQueryNotification : NavigatorNotification - { - public readonly CallbackQuery CallbackQuery; - - public CallbackQueryNotification(Update update) : base(update) - { - CallbackQuery = update.CallbackQuery; - } - } - - public class EditedMessageNotification : NavigatorNotification - { - public readonly Message EditedMessage; - - public EditedMessageNotification(Update update) : base(update) - { - EditedMessage = update.EditedMessage; - } - } - - public class ChannelPostNotification : NavigatorNotification - { - public readonly Message ChannelPost; - - public ChannelPostNotification(Update update) : base(update) - { - ChannelPost = update.ChannelPost; - } - } - - public class EditedChannelPostNotification : NavigatorNotification - { - public readonly Message EditedChannelPost; - - public EditedChannelPostNotification(Update update) : base(update) - { - EditedChannelPost = update.EditedChannelPost; - } - } - - public class ShippingQueryNotification : NavigatorNotification - { - public readonly ShippingQuery ShippingQuery; - - public ShippingQueryNotification(Update update) : base(update) - { - ShippingQuery = update.ShippingQuery; - } - } - - public class PreCheckoutQueryNotification : NavigatorNotification - { - public readonly PreCheckoutQuery PreCheckoutQuery; - - public PreCheckoutQueryNotification(Update update) : base(update) - { - PreCheckoutQuery = update.PreCheckoutQuery; - } - } - - public class PollNotification : NavigatorNotification - { - public readonly Poll Poll; - - public PollNotification(Update update) : base(update) - { - Poll = update.Poll; - } - } -} \ No newline at end of file diff --git a/src/Navigator/Old/NotificationLauncher.cs b/src/Navigator/Old/NotificationLauncher.cs deleted file mode 100644 index e712528..0000000 --- a/src/Navigator/Old/NotificationLauncher.cs +++ /dev/null @@ -1,52 +0,0 @@ -using System.Threading.Tasks; -using MediatR; -using Microsoft.Extensions.Logging; -using Navigator.Abstractions; -using Navigator.Context; -using Navigator.Old.Notification; -using Telegram.Bot.Types.Enums; - -namespace Navigator.Old -{ - public class NotificationLauncher : INotificationLauncher - { - protected readonly ILogger Logger; - protected readonly INavigatorContext Ctx; - protected readonly IMediator Mediator; - - public NotificationLauncher(ILogger logger, INavigatorContext navigatorContext, IMediator mediator) - { - Logger = logger; - Ctx = navigatorContext; - Mediator = mediator; - } - - public async Task Launch() - { - Logger.LogTrace("Starting with notification launch for update {UpdateId}", Ctx.Update.Id); - - if (Ctx.Update.Type == UpdateType.Message) - await Mediator.Publish(new MessageNotification(Ctx.Update)); - else if (Ctx.Update.Type == UpdateType.InlineQuery) - await Mediator.Publish(new InlineQueryNotification(Ctx.Update)); - else if (Ctx.Update.Type == UpdateType.ChosenInlineResult) - await Mediator.Publish(new ChosenInlineResultNotification(Ctx.Update)); - else if (Ctx.Update.Type == UpdateType.CallbackQuery) - await Mediator.Publish(new CallbackQueryNotification(Ctx.Update)); - else if (Ctx.Update.Type == UpdateType.EditedMessage) - await Mediator.Publish(new EditedMessageNotification(Ctx.Update)); - else if (Ctx.Update.Type == UpdateType.ChannelPost) - await Mediator.Publish(new ChannelPostNotification(Ctx.Update)); - else if (Ctx.Update.Type == UpdateType.EditedChannelPost) - await Mediator.Publish(new EditedChannelPostNotification(Ctx.Update)); - else if (Ctx.Update.Type == UpdateType.ShippingQuery) - await Mediator.Publish(new ShippingQueryNotification(Ctx.Update)); - else if (Ctx.Update.Type == UpdateType.PreCheckoutQuery) - await Mediator.Publish(new PreCheckoutQueryNotification(Ctx.Update)); - else if (Ctx.Update.Type == UpdateType.Poll) - await Mediator.Publish(new PollNotification(Ctx.Update)); - else - Logger.LogInformation("Unknown update type received"); - } - } -} \ No newline at end of file From 1f74878f80acad6f9775437551769f9d6053930e Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 23 Feb 2021 14:38:10 +0100 Subject: [PATCH 112/304] Adjusted namespaces --- src/Navigator.Providers.Telegram/Actions/CommandAction.cs | 1 - .../{Extensions => }/MessageExtension.cs | 4 +--- .../{Extensions => }/NavigatorContextExtensions.cs | 7 +------ 3 files changed, 2 insertions(+), 10 deletions(-) rename src/Navigator.Providers.Telegram/{Extensions => }/MessageExtension.cs (90%) rename src/Navigator.Providers.Telegram/{Extensions => }/NavigatorContextExtensions.cs (98%) diff --git a/src/Navigator.Providers.Telegram/Actions/CommandAction.cs b/src/Navigator.Providers.Telegram/Actions/CommandAction.cs index b0c77eb..0d72159 100644 --- a/src/Navigator.Providers.Telegram/Actions/CommandAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/CommandAction.cs @@ -1,7 +1,6 @@ using Navigator.Actions; using Navigator.Actions.Model; using Navigator.Context; -using Navigator.Providers.Telegram.Extensions; namespace Navigator.Providers.Telegram.Actions { diff --git a/src/Navigator.Providers.Telegram/Extensions/MessageExtension.cs b/src/Navigator.Providers.Telegram/MessageExtension.cs similarity index 90% rename from src/Navigator.Providers.Telegram/Extensions/MessageExtension.cs rename to src/Navigator.Providers.Telegram/MessageExtension.cs index 96fdf19..1f6a872 100644 --- a/src/Navigator.Providers.Telegram/Extensions/MessageExtension.cs +++ b/src/Navigator.Providers.Telegram/MessageExtension.cs @@ -1,10 +1,8 @@ -using System; using System.Linq; -using Microsoft.AspNetCore.Mvc; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; -namespace Navigator.Providers.Telegram.Extensions +namespace Navigator.Providers.Telegram { public static class MessageExtension { diff --git a/src/Navigator.Providers.Telegram/Extensions/NavigatorContextExtensions.cs b/src/Navigator.Providers.Telegram/NavigatorContextExtensions.cs similarity index 98% rename from src/Navigator.Providers.Telegram/Extensions/NavigatorContextExtensions.cs rename to src/Navigator.Providers.Telegram/NavigatorContextExtensions.cs index 528c3fd..a1ccd3c 100644 --- a/src/Navigator.Providers.Telegram/Extensions/NavigatorContextExtensions.cs +++ b/src/Navigator.Providers.Telegram/NavigatorContextExtensions.cs @@ -1,9 +1,4 @@ -using System; -using Telegram.Bot.Types; -using Telegram.Bot.Types.Enums; -using Telegram.Bot.Types.Payments; - -namespace Navigator.Providers.Telegram.Extensions +namespace Navigator.Providers.Telegram { /// /// Useful extensions for Navigator Context. From 815bd1174428c4ec370e306536e925cf39599bec Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 23 Feb 2021 17:04:44 +0100 Subject: [PATCH 113/304] NavigatorContext references provider instead of client --- .../TelegramMiddleware.cs | 2 +- src/Navigator/Context/INavigatorContext.cs | 2 +- src/Navigator/Context/NavigatorContext.cs | 6 +++--- src/Navigator/Context/NavigatorContextBuilder.cs | 12 ++++++------ 4 files changed, 11 insertions(+), 11 deletions(-) diff --git a/src/Navigator.Providers.Telegram/TelegramMiddleware.cs b/src/Navigator.Providers.Telegram/TelegramMiddleware.cs index 539baf0..a61a493 100644 --- a/src/Navigator.Providers.Telegram/TelegramMiddleware.cs +++ b/src/Navigator.Providers.Telegram/TelegramMiddleware.cs @@ -9,7 +9,7 @@ namespace Navigator.Providers.Telegram { - public class TelegramMiddleware + internal class TelegramMiddleware { private readonly ILogger _logger; private readonly INavigatorContextFactory _navigatorContextFactory; diff --git a/src/Navigator/Context/INavigatorContext.cs b/src/Navigator/Context/INavigatorContext.cs index 0cd46a4..024d192 100644 --- a/src/Navigator/Context/INavigatorContext.cs +++ b/src/Navigator/Context/INavigatorContext.cs @@ -8,7 +8,7 @@ public interface INavigatorContext /// /// /// - INavigatorClient Client { get; } + INavigatorProvider Provider { get; } /// /// diff --git a/src/Navigator/Context/NavigatorContext.cs b/src/Navigator/Context/NavigatorContext.cs index 1592310..2e4c3aa 100644 --- a/src/Navigator/Context/NavigatorContext.cs +++ b/src/Navigator/Context/NavigatorContext.cs @@ -11,7 +11,7 @@ public class NavigatorContext : INavigatorContext /// /// /// - public INavigatorClient Client { get; } + public INavigatorProvider Provider { get; } /// /// @@ -33,9 +33,9 @@ public class NavigatorContext : INavigatorContext /// /// Builds a new Navigator Context. /// - public NavigatorContext(INavigatorClient client, BotUser botProfile, string actionType) + public NavigatorContext(INavigatorProvider provider, BotUser botProfile, string actionType) { - Client = client; + Provider = provider; BotProfile = botProfile; ActionType = actionType; diff --git a/src/Navigator/Context/NavigatorContextBuilder.cs b/src/Navigator/Context/NavigatorContextBuilder.cs index c46c0b6..14dac44 100644 --- a/src/Navigator/Context/NavigatorContextBuilder.cs +++ b/src/Navigator/Context/NavigatorContextBuilder.cs @@ -28,18 +28,18 @@ public async Task Build(Action provider.GetType() == _options.GetProvider())?.GetClient(); + var provider = _navigatorProviders.FirstOrDefault(p => p.GetType() == _options.GetProvider()); - if (client is null) + if (provider is null) { - _logger.LogError("No client found for provider: {@Provider}", _options.GetProvider()); + _logger.LogError("No provider found for: {@Provider}", _options.GetProvider()); //TODO: make NavigatorException - throw new Exception($"No client found for provider: {_options.GetProvider()?.Name}"); + throw new Exception($"No provider found for: {_options.GetProvider()?.Name}"); } - var acitonType = _options.GetAcitonType() ?? throw new InvalidOperationException(); + var actionType = _options.GetAcitonType() ?? throw new InvalidOperationException(); - INavigatorContext context = new NavigatorContext(client, await client.GetProfile(), acitonType); + INavigatorContext context = new NavigatorContext(provider, await provider.GetClient().GetProfile(), actionType); foreach (var contextExtension in _navigatorContextExtensions) { From 2cb3fbc571cb0795ef447d2648349a67d67cf1c6 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 23 Feb 2021 17:05:03 +0100 Subject: [PATCH 114/304] Started work in reply flow --- src/Navigator/Actions/ActionHandler.cs | 29 +++++++++++++++++++ .../Actions/ActionHandlerExtensions.cs | 7 +++++ src/Navigator/Actions/Model/ActionResult.cs | 15 ++++++++++ src/Navigator/Actions/Model/IAction.cs | 5 +++- src/Navigator/INavigatorProvider.cs | 6 +++- src/Navigator/Replies/ReplyBuilderOptions.cs | 7 +++++ 6 files changed, 67 insertions(+), 2 deletions(-) create mode 100644 src/Navigator/Actions/ActionHandler.cs create mode 100644 src/Navigator/Actions/ActionHandlerExtensions.cs create mode 100644 src/Navigator/Actions/Model/ActionResult.cs create mode 100644 src/Navigator/Replies/ReplyBuilderOptions.cs diff --git a/src/Navigator/Actions/ActionHandler.cs b/src/Navigator/Actions/ActionHandler.cs new file mode 100644 index 0000000..ad28ff7 --- /dev/null +++ b/src/Navigator/Actions/ActionHandler.cs @@ -0,0 +1,29 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using MediatR; +using Navigator.Actions.Model; +using Navigator.Context; +using Navigator.Replies; + +namespace Navigator.Actions +{ + public abstract class ActionHandler : IRequestHandler where TAction : IAction + { + public INavigatorContext NavigatorContext; + + protected ActionHandler(INavigatorContextAccessor navigatorContextAccessor) + { + NavigatorContext = navigatorContextAccessor.NavigatorContext; + } + + public abstract Task Handle(TAction request, CancellationToken cancellationToken); + + public Task Reply(Action replyBuilder, CancellationToken cancellationToken) + { + + + NavigatorContext.Provider.HandleReply() + } + } +} \ No newline at end of file diff --git a/src/Navigator/Actions/ActionHandlerExtensions.cs b/src/Navigator/Actions/ActionHandlerExtensions.cs new file mode 100644 index 0000000..9a44a20 --- /dev/null +++ b/src/Navigator/Actions/ActionHandlerExtensions.cs @@ -0,0 +1,7 @@ +namespace Navigator.Actions +{ + public class ActionHandlerExtensions + { + + } +} \ No newline at end of file diff --git a/src/Navigator/Actions/Model/ActionResult.cs b/src/Navigator/Actions/Model/ActionResult.cs new file mode 100644 index 0000000..ea2c9a0 --- /dev/null +++ b/src/Navigator/Actions/Model/ActionResult.cs @@ -0,0 +1,15 @@ +namespace Navigator.Actions.Model +{ + public struct ActionResult + { + private readonly bool _isSuccess; + + public bool IsSuccess => _isSuccess; + public bool IsError => !_isSuccess; + + public ActionResult(bool isSuccess) + { + _isSuccess = isSuccess; + } + } +} \ No newline at end of file diff --git a/src/Navigator/Actions/Model/IAction.cs b/src/Navigator/Actions/Model/IAction.cs index 2d42c96..6561098 100644 --- a/src/Navigator/Actions/Model/IAction.cs +++ b/src/Navigator/Actions/Model/IAction.cs @@ -3,7 +3,10 @@ namespace Navigator.Actions.Model { - public interface IAction : IRequest + /// + /// Base contract for an action. + /// + public interface IAction : IRequest { /// /// Type of the action. diff --git a/src/Navigator/INavigatorProvider.cs b/src/Navigator/INavigatorProvider.cs index ac2bd0b..a403b21 100644 --- a/src/Navigator/INavigatorProvider.cs +++ b/src/Navigator/INavigatorProvider.cs @@ -1,3 +1,5 @@ +using System.Threading.Tasks; + namespace Navigator { /// @@ -9,6 +11,8 @@ public interface INavigatorProvider /// Gets the specific client for this provider. /// /// An implementation of - INavigatorClient GetClient(); + INavigatorClient GetClient(); + + Task HandleReply(); } } \ No newline at end of file diff --git a/src/Navigator/Replies/ReplyBuilderOptions.cs b/src/Navigator/Replies/ReplyBuilderOptions.cs new file mode 100644 index 0000000..8f08365 --- /dev/null +++ b/src/Navigator/Replies/ReplyBuilderOptions.cs @@ -0,0 +1,7 @@ +namespace Navigator.Replies +{ + public class ReplyBuilderOptions + { + + } +} \ No newline at end of file From c503a6e7d3f3576be4d417e4233688399efd49ba Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Wed, 3 Mar 2021 11:42:42 +0100 Subject: [PATCH 115/304] Renamed ActionResult to ActionStatus --- src/Navigator/Actions/ActionHandler.cs | 16 ++++++++++------ .../Model/{ActionResult.cs => ActionStatus.cs} | 4 ++-- src/Navigator/Actions/Model/IAction.cs | 2 +- 3 files changed, 13 insertions(+), 9 deletions(-) rename src/Navigator/Actions/Model/{ActionResult.cs => ActionStatus.cs} (76%) diff --git a/src/Navigator/Actions/ActionHandler.cs b/src/Navigator/Actions/ActionHandler.cs index ad28ff7..129d819 100644 --- a/src/Navigator/Actions/ActionHandler.cs +++ b/src/Navigator/Actions/ActionHandler.cs @@ -8,7 +8,7 @@ namespace Navigator.Actions { - public abstract class ActionHandler : IRequestHandler where TAction : IAction + public abstract class ActionHandler : IRequestHandler where TAction : IAction { public INavigatorContext NavigatorContext; @@ -17,13 +17,17 @@ protected ActionHandler(INavigatorContextAccessor navigatorContextAccessor) NavigatorContext = navigatorContextAccessor.NavigatorContext; } - public abstract Task Handle(TAction request, CancellationToken cancellationToken); + public abstract Task Handle(TAction request, CancellationToken cancellationToken); - public Task Reply(Action replyBuilder, CancellationToken cancellationToken) + public static ActionStatus Success() { - - - NavigatorContext.Provider.HandleReply() + return new(true); + } + + + public static ActionStatus Error() + { + return new(false); } } } \ No newline at end of file diff --git a/src/Navigator/Actions/Model/ActionResult.cs b/src/Navigator/Actions/Model/ActionStatus.cs similarity index 76% rename from src/Navigator/Actions/Model/ActionResult.cs rename to src/Navigator/Actions/Model/ActionStatus.cs index ea2c9a0..20c0abb 100644 --- a/src/Navigator/Actions/Model/ActionResult.cs +++ b/src/Navigator/Actions/Model/ActionStatus.cs @@ -1,13 +1,13 @@ namespace Navigator.Actions.Model { - public struct ActionResult + public struct ActionStatus { private readonly bool _isSuccess; public bool IsSuccess => _isSuccess; public bool IsError => !_isSuccess; - public ActionResult(bool isSuccess) + public ActionStatus(bool isSuccess) { _isSuccess = isSuccess; } diff --git a/src/Navigator/Actions/Model/IAction.cs b/src/Navigator/Actions/Model/IAction.cs index 6561098..8ec333c 100644 --- a/src/Navigator/Actions/Model/IAction.cs +++ b/src/Navigator/Actions/Model/IAction.cs @@ -6,7 +6,7 @@ namespace Navigator.Actions.Model /// /// Base contract for an action. /// - public interface IAction : IRequest + public interface IAction : IRequest { /// /// Type of the action. From be84ca8659f60acf772ae65aea4bae5921705ec3 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Wed, 3 Mar 2021 11:43:08 +0100 Subject: [PATCH 116/304] Updated ActionHandler --- src/Navigator/Actions/ActionHandler.cs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/Navigator/Actions/ActionHandler.cs b/src/Navigator/Actions/ActionHandler.cs index 129d819..d2d1d6f 100644 --- a/src/Navigator/Actions/ActionHandler.cs +++ b/src/Navigator/Actions/ActionHandler.cs @@ -17,14 +17,13 @@ protected ActionHandler(INavigatorContextAccessor navigatorContextAccessor) NavigatorContext = navigatorContextAccessor.NavigatorContext; } - public abstract Task Handle(TAction request, CancellationToken cancellationToken); + public abstract Task Handle(TAction action, CancellationToken cancellationToken); public static ActionStatus Success() { return new(true); } - - + public static ActionStatus Error() { return new(false); From c979c89ee65bbccc0113c693a0b38951600c93de Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Wed, 3 Mar 2021 11:43:47 +0100 Subject: [PATCH 117/304] Added ActionFilter --- src/Navigator/Actions/Filter/ActionFilter.cs | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 src/Navigator/Actions/Filter/ActionFilter.cs diff --git a/src/Navigator/Actions/Filter/ActionFilter.cs b/src/Navigator/Actions/Filter/ActionFilter.cs new file mode 100644 index 0000000..b40de33 --- /dev/null +++ b/src/Navigator/Actions/Filter/ActionFilter.cs @@ -0,0 +1,12 @@ +using System.Threading; +using System.Threading.Tasks; +using MediatR; +using Navigator.Actions.Model; + +namespace Navigator.Actions.Filter +{ + public abstract class ActionFilter : IPipelineBehavior where TAction : IAction + { + public abstract Task Handle(TAction action, CancellationToken cancellationToken, RequestHandlerDelegate next); + } +} \ No newline at end of file From 981238c3a057f915b8bfd31d8a745466f0218355 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Wed, 3 Mar 2021 11:46:07 +0100 Subject: [PATCH 118/304] Renamed namespace --- src/Navigator/Actions/{Filter => Filters}/ActionFilter.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename src/Navigator/Actions/{Filter => Filters}/ActionFilter.cs (91%) diff --git a/src/Navigator/Actions/Filter/ActionFilter.cs b/src/Navigator/Actions/Filters/ActionFilter.cs similarity index 91% rename from src/Navigator/Actions/Filter/ActionFilter.cs rename to src/Navigator/Actions/Filters/ActionFilter.cs index b40de33..b6badb2 100644 --- a/src/Navigator/Actions/Filter/ActionFilter.cs +++ b/src/Navigator/Actions/Filters/ActionFilter.cs @@ -3,7 +3,7 @@ using MediatR; using Navigator.Actions.Model; -namespace Navigator.Actions.Filter +namespace Navigator.Actions.Filters { public abstract class ActionFilter : IPipelineBehavior where TAction : IAction { From c16b5f5daee747f99dfe4e057bf0b211a435f9a6 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Wed, 3 Mar 2021 12:28:03 +0100 Subject: [PATCH 119/304] Moved and renamed MessageExtensions --- .../TelegramUpdateExtensions.cs} | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) rename src/Navigator.Providers.Telegram/{MessageExtension.cs => Extensions/TelegramUpdateExtensions.cs} (89%) diff --git a/src/Navigator.Providers.Telegram/MessageExtension.cs b/src/Navigator.Providers.Telegram/Extensions/TelegramUpdateExtensions.cs similarity index 89% rename from src/Navigator.Providers.Telegram/MessageExtension.cs rename to src/Navigator.Providers.Telegram/Extensions/TelegramUpdateExtensions.cs index 1f6a872..3691544 100644 --- a/src/Navigator.Providers.Telegram/MessageExtension.cs +++ b/src/Navigator.Providers.Telegram/Extensions/TelegramUpdateExtensions.cs @@ -2,9 +2,9 @@ using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; -namespace Navigator.Providers.Telegram +namespace Navigator.Providers.Telegram.Extensions { - public static class MessageExtension + internal static class TelegramUpdateExtensions { public static string? ExtractCommand(this Message message, string botName) { From 90ca03442a5eef4cc912753cbb5acb963fdbf4ac Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Wed, 3 Mar 2021 12:28:22 +0100 Subject: [PATCH 120/304] Updated IConversation --- src/Navigator/Entities/IConversation.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Navigator/Entities/IConversation.cs b/src/Navigator/Entities/IConversation.cs index b411140..addfbf5 100644 --- a/src/Navigator/Entities/IConversation.cs +++ b/src/Navigator/Entities/IConversation.cs @@ -11,6 +11,6 @@ public interface IConversation public interface IChat { string Id { get; init; } - string Title { get; init; } + string? Title { get; init; } } } \ No newline at end of file From 625b2ad9f2a35617d4cdab6f6e586ed6c3e65046 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Wed, 3 Mar 2021 12:28:34 +0100 Subject: [PATCH 121/304] Added Telegram provider conversation --- .../Entities/Conversation.cs | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 src/Navigator.Providers.Telegram/Entities/Conversation.cs diff --git a/src/Navigator.Providers.Telegram/Entities/Conversation.cs b/src/Navigator.Providers.Telegram/Entities/Conversation.cs new file mode 100644 index 0000000..d16a24f --- /dev/null +++ b/src/Navigator.Providers.Telegram/Entities/Conversation.cs @@ -0,0 +1,22 @@ +using Navigator.Entities; + +namespace Navigator.Providers.Telegram.Entities +{ + public class Conversation : IConversation + { + public IUser User { get; init; } + public IChat Chat { get; init; } + } + + public class User : IUser + { + public string Id { get; init; } + public string? Username { get; init; } + } + + public class Chat : IChat + { + public string Id { get; init; } + public string? Title { get; init; } + } +} \ No newline at end of file From aa86fcea59bce483b88204916024d58ef6824412 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Wed, 3 Mar 2021 22:06:58 +0100 Subject: [PATCH 122/304] Added SetConversation --- .../TelegramMiddleware.cs | 3 +++ ...avigatorContextBuilderOptionsExtensions.cs | 20 ++++++++++++++++++- 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/Navigator.Providers.Telegram/TelegramMiddleware.cs b/src/Navigator.Providers.Telegram/TelegramMiddleware.cs index a61a493..82c09e5 100644 --- a/src/Navigator.Providers.Telegram/TelegramMiddleware.cs +++ b/src/Navigator.Providers.Telegram/TelegramMiddleware.cs @@ -4,6 +4,8 @@ using Navigator.Actions; using Navigator.Context; using Navigator.Providers.Telegram.Actions; +using Navigator.Providers.Telegram.Entities; +using Navigator.Providers.Telegram.Extensions; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; @@ -36,6 +38,7 @@ await _navigatorContextFactory.Supply(builder => builder.SetProvider(); builder.SetActionType(actionType); builder.SetOriginalUpdate(update); + builder.SetConversation(update.GetConversation()); }); await _actionLauncher.Launch(); diff --git a/src/Navigator/Context/NavigatorContextBuilderOptionsExtensions.cs b/src/Navigator/Context/NavigatorContextBuilderOptionsExtensions.cs index 72b5765..ea78b34 100644 --- a/src/Navigator/Context/NavigatorContextBuilderOptionsExtensions.cs +++ b/src/Navigator/Context/NavigatorContextBuilderOptionsExtensions.cs @@ -1,4 +1,5 @@ using System; +using Navigator.Entities; namespace Navigator.Context { @@ -38,7 +39,7 @@ public static void SetActionType(this INavigatorContextBuilderOptions contextBui #endregion - #region ActionType + #region OriginalUpdate private const string OriginalUpdateKey = "_navigator.context.options.original_update"; @@ -54,5 +55,22 @@ public static void SetOriginalUpdate(this INavigatorContextBuilderOptions contex } #endregion + + #region Conversation + + private const string ConversationKey = "_navigator.context.options.conversation"; + + public static void SetConversation(this INavigatorContextBuilderOptions contextBuilderOptions, IConversation conversation) + { + contextBuilderOptions.TryRegisterOption(ConversationKey, conversation); + + } + + public static IConversation? GetConversationOrDefault(this INavigatorContextBuilderOptions contextBuilderOptions) + { + return contextBuilderOptions.RetrieveOption(ConversationKey); + } + + #endregion } } \ No newline at end of file From f2c358a2ba8a6fba95e04ad8ee766fd45a4f7479 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Wed, 3 Mar 2021 22:07:38 +0100 Subject: [PATCH 123/304] Updated NavigatorContext to include conversation --- src/Navigator/Context/INavigatorContext.cs | 2 ++ src/Navigator/Context/NavigatorContext.cs | 11 ++++------- src/Navigator/Context/NavigatorContextBuilder.cs | 3 ++- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/Navigator/Context/INavigatorContext.cs b/src/Navigator/Context/INavigatorContext.cs index 024d192..b0ea141 100644 --- a/src/Navigator/Context/INavigatorContext.cs +++ b/src/Navigator/Context/INavigatorContext.cs @@ -29,5 +29,7 @@ public interface INavigatorContext /// /// public string ActionType { get; } + + public IConversation Conversation { get; } } } \ No newline at end of file diff --git a/src/Navigator/Context/NavigatorContext.cs b/src/Navigator/Context/NavigatorContext.cs index 2e4c3aa..b4bd451 100644 --- a/src/Navigator/Context/NavigatorContext.cs +++ b/src/Navigator/Context/NavigatorContext.cs @@ -20,24 +20,21 @@ public class NavigatorContext : INavigatorContext public Dictionary Extensions { get; } - /// - /// - /// public Dictionary Items { get; } - /// - /// - /// public string ActionType { get; } + public IConversation Conversation { get; } + /// /// Builds a new Navigator Context. /// - public NavigatorContext(INavigatorProvider provider, BotUser botProfile, string actionType) + public NavigatorContext(INavigatorProvider provider, BotUser botProfile, string actionType, IConversation conversation) { Provider = provider; BotProfile = botProfile; ActionType = actionType; + Conversation = conversation; Items = new Dictionary(); } diff --git a/src/Navigator/Context/NavigatorContextBuilder.cs b/src/Navigator/Context/NavigatorContextBuilder.cs index 14dac44..3b40b2f 100644 --- a/src/Navigator/Context/NavigatorContextBuilder.cs +++ b/src/Navigator/Context/NavigatorContextBuilder.cs @@ -38,8 +38,9 @@ public async Task Build(Action Date: Wed, 3 Mar 2021 22:10:01 +0100 Subject: [PATCH 124/304] Added some internal extensions for distributed cache --- src/Navigator/DistributedCacheExtensions.cs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 src/Navigator/DistributedCacheExtensions.cs diff --git a/src/Navigator/DistributedCacheExtensions.cs b/src/Navigator/DistributedCacheExtensions.cs new file mode 100644 index 0000000..6d77c30 --- /dev/null +++ b/src/Navigator/DistributedCacheExtensions.cs @@ -0,0 +1,17 @@ +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.Caching.Distributed; + +namespace Navigator +{ + internal static class DistributedCacheExtensions + { + public static async Task GetAsync(this IDistributedCache distributedCache, string key, CancellationToken cancellationToken = default) + { + var cachedItem = await distributedCache.GetAsync(key, cancellationToken); + + return cachedItem is not null ? JsonSerializer.Deserialize(cachedItem) : default; + } + } +} \ No newline at end of file From 68d15cf0c1b4f2ee67d4229668e219fdda789c5a Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Wed, 3 Mar 2021 22:10:17 +0100 Subject: [PATCH 125/304] Updated TelegramUpdateExtensions --- .../Extensions/TelegramUpdateExtensions.cs | 62 +++++++++++++++++++ 1 file changed, 62 insertions(+) diff --git a/src/Navigator.Providers.Telegram/Extensions/TelegramUpdateExtensions.cs b/src/Navigator.Providers.Telegram/Extensions/TelegramUpdateExtensions.cs index 3691544..7c189ae 100644 --- a/src/Navigator.Providers.Telegram/Extensions/TelegramUpdateExtensions.cs +++ b/src/Navigator.Providers.Telegram/Extensions/TelegramUpdateExtensions.cs @@ -1,6 +1,13 @@ +using System; using System.Linq; +using Navigator.Context; +using Navigator.Context.Extensions; +using Navigator.Entities; +using Navigator.Providers.Telegram.Entities; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; +using Chat = Telegram.Bot.Types.Chat; +using User = Telegram.Bot.Types.User; namespace Navigator.Providers.Telegram.Extensions { @@ -27,5 +34,60 @@ public static string ExtractArguments(this Message message, string botName) ? message.Text.Remove(0, message.Text.IndexOf(' ') + 1) : string.Empty; } + + public static User? GetUserOrDefault(this Update update) + { + return update.Type switch + { + UpdateType.Message => update.Message.From, + UpdateType.InlineQuery => update.InlineQuery.From, + UpdateType.ChosenInlineResult => update.ChosenInlineResult.From, + UpdateType.CallbackQuery => update.CallbackQuery.From, + UpdateType.EditedMessage => update.EditedMessage.From, + UpdateType.ChannelPost => update.ChannelPost.From, + UpdateType.EditedChannelPost => update.EditedChannelPost.From, + UpdateType.ShippingQuery => update.ShippingQuery.From, + UpdateType.PreCheckoutQuery => update.PreCheckoutQuery.From, + _ => default + }; + } + + public static Chat? GetChatOrDefault(this Update update) + { + return update.Type switch + { + UpdateType.CallbackQuery => update.CallbackQuery.Message.Chat, + UpdateType.Message => update.Message.Chat, + UpdateType.EditedMessage => update.EditedMessage.Chat, + UpdateType.ChannelPost => update.ChannelPost.Chat, + UpdateType.EditedChannelPost => update.EditedChannelPost.Chat, + _ => default + }; + } + + public static IConversation GetConversation(this Update update) + { + var user = update.GetUserOrDefault(); + var chat = update.GetChatOrDefault(); + + if (chat is null || user is null) + { + throw new Exception("TODO NAvigator exception no conversation could be built."); + } + + return new Conversation + { + User = new Entities.User + { + Id = user.Id.ToString(), + Username = string.IsNullOrWhiteSpace(user.Username) ? chat.FirstName : user.Username + }, + Chat = new Entities.Chat + { + Id = chat.Id.ToString(), + Title = string.IsNullOrWhiteSpace(chat.Title) ? chat.Username : chat.Title + } + }; + } } } \ No newline at end of file From 1021737ec3d0d046cfb8b881fed09700c0437914 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Wed, 3 Mar 2021 22:17:19 +0100 Subject: [PATCH 126/304] Started with CooldownActionFilter implementation --- .../Actions/Filters/CooldownActionFilter.cs | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 src/Navigator/Actions/Filters/CooldownActionFilter.cs diff --git a/src/Navigator/Actions/Filters/CooldownActionFilter.cs b/src/Navigator/Actions/Filters/CooldownActionFilter.cs new file mode 100644 index 0000000..b492322 --- /dev/null +++ b/src/Navigator/Actions/Filters/CooldownActionFilter.cs @@ -0,0 +1,46 @@ +using System.Threading; +using System.Threading.Tasks; +using MediatR; +using Microsoft.Extensions.Caching.Distributed; +using Navigator.Actions.Model; +using Navigator.Context; + +namespace Navigator.Actions.Filters +{ + public class CooldownActionFilter : ActionFilter where TAction : IAction + { + private readonly IDistributedCache _cache; + private readonly INavigatorContext _navigatorContext; + public CooldownActionFilter(IDistributedCache cache, INavigatorContextAccessor navigatorContextAccessor) + { + _cache = cache; + _navigatorContext = navigatorContextAccessor.NavigatorContext; + } + + public override async Task Handle(TAction action, CancellationToken cancellationToken, RequestHandlerDelegate next) + { + var key = GenerateKey(action); + + var cooldownStatus = await _cache.GetAsync(key, cancellationToken); + + if (cooldownStatus is not null) + { + return new ActionStatus(true); + } + + var status = await next(); + + if (status.IsSuccess) + { + await _cache.SetStringAsync(key, key); //TODO add timer with attribute; + } + + return status; + } + + private string GenerateKey(TAction action) + { + return $"{action.Type}:{_navigatorContext.Conversation.Chat.Id}"; + } + } +} \ No newline at end of file From a95a345777591bf1992e2f4e803145fc3b6c3f85 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 9 Mar 2021 14:41:32 +0100 Subject: [PATCH 127/304] Leaving Discord in pause for now --- .../DiscordNavigatorProvider.cs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/Navigator.Providers.Discord/DiscordNavigatorProvider.cs b/src/Navigator.Providers.Discord/DiscordNavigatorProvider.cs index b670a65..4ac8aba 100644 --- a/src/Navigator.Providers.Discord/DiscordNavigatorProvider.cs +++ b/src/Navigator.Providers.Discord/DiscordNavigatorProvider.cs @@ -1,3 +1,5 @@ +using System.Threading.Tasks; + namespace Navigator.Providers.Discord { public class DiscordNavigatorProvider : INavigatorProvider @@ -7,6 +9,11 @@ public INavigatorClient GetClient() throw new System.NotImplementedException(); } + public Task HandleReply() + { + throw new System.NotImplementedException(); + } + public string GetActionType(object original) { throw new System.NotImplementedException(); From 85f4e50829eb8ca679dc0fb3b27e377e5c197173 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 9 Mar 2021 14:50:11 +0100 Subject: [PATCH 128/304] Added arguments to CommandAction --- src/Navigator.Providers.Telegram/Actions/CommandAction.cs | 1 + .../Extensions/TelegramUpdateExtensions.cs | 8 ++++---- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/src/Navigator.Providers.Telegram/Actions/CommandAction.cs b/src/Navigator.Providers.Telegram/Actions/CommandAction.cs index 0d72159..b0c77eb 100644 --- a/src/Navigator.Providers.Telegram/Actions/CommandAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/CommandAction.cs @@ -1,6 +1,7 @@ using Navigator.Actions; using Navigator.Actions.Model; using Navigator.Context; +using Navigator.Providers.Telegram.Extensions; namespace Navigator.Providers.Telegram.Actions { diff --git a/src/Navigator.Providers.Telegram/Extensions/TelegramUpdateExtensions.cs b/src/Navigator.Providers.Telegram/Extensions/TelegramUpdateExtensions.cs index 7c189ae..c9bb204 100644 --- a/src/Navigator.Providers.Telegram/Extensions/TelegramUpdateExtensions.cs +++ b/src/Navigator.Providers.Telegram/Extensions/TelegramUpdateExtensions.cs @@ -28,11 +28,11 @@ internal static class TelegramUpdateExtensions return command; } - public static string ExtractArguments(this Message message, string botName) + public static string? ExtractArguments(this Message message, string botName) { - return message.Text.Contains(' ') - ? message.Text.Remove(0, message.Text.IndexOf(' ') + 1) - : string.Empty; + return message.Text.Contains(' ') + ? message.Text.Remove(0, message.Text.IndexOf(' ') + 1) + : default; } public static User? GetUserOrDefault(this Update update) From d0ccb08dfdb45fe1cfc64a83701642bdf8b7a5ff Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 9 Mar 2021 14:50:57 +0100 Subject: [PATCH 129/304] Added fluent addition of extensions to NavigatorConfiguration --- .../NavigatorExtensionConfiguration.cs | 39 +++++++++++++++++++ .../Configuration/NavigatorConfiguration.cs | 4 +- 2 files changed, 42 insertions(+), 1 deletion(-) create mode 100644 src/Navigator/Configuration/Extension/NavigatorExtensionConfiguration.cs diff --git a/src/Navigator/Configuration/Extension/NavigatorExtensionConfiguration.cs b/src/Navigator/Configuration/Extension/NavigatorExtensionConfiguration.cs new file mode 100644 index 0000000..93e8fff --- /dev/null +++ b/src/Navigator/Configuration/Extension/NavigatorExtensionConfiguration.cs @@ -0,0 +1,39 @@ +using System; +using Microsoft.Extensions.DependencyInjection; + +namespace Navigator.Configuration.Provider +{ + /// + /// Provides a entry point for configuring new extensions for Navigator. + /// + public class NavigatorExtensionConfiguration + { + private readonly NavigatorConfiguration _navigatorConfiguration; + + /// + /// Default constructor for . + /// + /// + public NavigatorExtensionConfiguration(NavigatorConfiguration navigatorConfiguration) + { + _navigatorConfiguration = navigatorConfiguration; + } + + /// + /// Configure a new extension using this method. + /// + /// + /// + /// + public NavigatorConfiguration Extension(Action? optionsAction, Action? servicesAction) + { + optionsAction?.Invoke(_navigatorConfiguration.Options); + + servicesAction?.Invoke(_navigatorConfiguration.Services); + + _navigatorConfiguration.RegisterOrReplaceOptions(); + + return _navigatorConfiguration; + } + } +} \ No newline at end of file diff --git a/src/Navigator/Configuration/NavigatorConfiguration.cs b/src/Navigator/Configuration/NavigatorConfiguration.cs index 944c005..a27ba73 100644 --- a/src/Navigator/Configuration/NavigatorConfiguration.cs +++ b/src/Navigator/Configuration/NavigatorConfiguration.cs @@ -11,6 +11,8 @@ namespace Navigator.Configuration public class NavigatorConfiguration { public NavigatorProviderConfiguration WithProvider { get; internal set; } + + public NavigatorExtensionConfiguration WithExtension { get; internal set; } /// /// Gets the that are being used. @@ -33,7 +35,6 @@ public class NavigatorConfiguration /// /// The to use. /// The to attach to. - public NavigatorConfiguration(Action options, IServiceCollection services) { Options = new NavigatorOptions(); @@ -44,6 +45,7 @@ public NavigatorConfiguration(Action options, IServiceCollecti services.AddSingleton(Options); WithProvider = new NavigatorProviderConfiguration(this); + WithExtension = new NavigatorExtensionConfiguration(this); } From 92958d87f85d0f73b7e5fde3754c9ba0ddca6fe5 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 9 Mar 2021 14:51:44 +0100 Subject: [PATCH 130/304] Added HandleReply as NotImplemented --- .../TelegramNavigatorProvider.cs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/Navigator.Providers.Telegram/TelegramNavigatorProvider.cs b/src/Navigator.Providers.Telegram/TelegramNavigatorProvider.cs index 711f46f..5a465eb 100644 --- a/src/Navigator.Providers.Telegram/TelegramNavigatorProvider.cs +++ b/src/Navigator.Providers.Telegram/TelegramNavigatorProvider.cs @@ -1,4 +1,5 @@ using System; +using System.Threading.Tasks; using Telegram.Bot.Types; namespace Navigator.Providers.Telegram @@ -16,5 +17,10 @@ public INavigatorClient GetClient() { return _client; } + + public Task HandleReply() + { + throw new NotImplementedException(); + } } } \ No newline at end of file From 6de2257d9ab5c2dc09d04d750430c7dc417cf9af Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 9 Mar 2021 16:49:43 +0100 Subject: [PATCH 131/304] Added GetOriginalUpdate extension to NavigatorContextExtensions --- .../Context/Extensions/NavigatorContextExtensions.cs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/Navigator/Context/Extensions/NavigatorContextExtensions.cs b/src/Navigator/Context/Extensions/NavigatorContextExtensions.cs index 21625a9..65f350b 100644 --- a/src/Navigator/Context/Extensions/NavigatorContextExtensions.cs +++ b/src/Navigator/Context/Extensions/NavigatorContextExtensions.cs @@ -1,9 +1,17 @@ +using System; using System.Collections.Generic; namespace Navigator.Context.Extensions { public static class NavigatorContextExtensions { + public static TUpdate GetOriginalUpdate(this INavigatorContext navigatorContext) where TUpdate : class + { + var update = navigatorContext.GetOriginalUpdateOrDefault(); + + return update ?? throw new Exception("Update was not found."); + } + public static TUpdate? GetOriginalUpdateOrDefault(this INavigatorContext navigatorContext) where TUpdate : class { var update = navigatorContext.Extensions.GetValueOrDefault(OriginalUpdateContextExtension.OriginalUpdateKey); From 8dfca51fec9225735da9fc6beb1768c7e3987291 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 9 Mar 2021 16:49:58 +0100 Subject: [PATCH 132/304] Worked on some extension methods --- .../NavigatorContextExtensions.cs | 74 ++++++++++--------- .../NavigatorProviderExtensions.cs | 35 +++++++++ 2 files changed, 75 insertions(+), 34 deletions(-) create mode 100644 src/Navigator.Providers.Telegram/NavigatorProviderExtensions.cs diff --git a/src/Navigator.Providers.Telegram/NavigatorContextExtensions.cs b/src/Navigator.Providers.Telegram/NavigatorContextExtensions.cs index a1ccd3c..c92c755 100644 --- a/src/Navigator.Providers.Telegram/NavigatorContextExtensions.cs +++ b/src/Navigator.Providers.Telegram/NavigatorContextExtensions.cs @@ -1,3 +1,9 @@ +using System; +using Navigator.Context; +using Navigator.Context.Extensions; +using Telegram.Bot.Types; +using Telegram.Bot.Types.Enums; + namespace Navigator.Providers.Telegram { /// @@ -44,40 +50,40 @@ public static class NavigatorContextExtensions // // #endregion // - // #region Chat - // - // /// - // /// Get a Telegram chat. - // /// - // /// - // /// When chat is not found. - // /// - // public static Chat GetTelegramChat(this INavigatorContext ctx) - // { - // var chat = ctx.GetTelegramChatOrDefault(); - // - // return chat ?? throw new Exception("Chat not found in update."); - // } - // - // /// - // /// Get a Telegram chat or default if not found. - // /// - // /// - // /// Telegram Chat - // public static Chat? GetTelegramChatOrDefault(this INavigatorContext ctx) - // { - // return ctx.Update.Type switch - // { - // UpdateType.CallbackQuery => ctx.Update.CallbackQuery.Message.Chat, - // UpdateType.Message => ctx.Update.Message.Chat, - // UpdateType.EditedMessage => ctx.Update.EditedMessage.Chat, - // UpdateType.ChannelPost => ctx.Update.ChannelPost.Chat, - // UpdateType.EditedChannelPost => ctx.Update.EditedChannelPost.Chat, - // _ => default - // }; - // } - // - // #endregion + #region Chat + + /// + /// Gets a . + /// + /// + /// When chat is not found. + /// + public static Chat GetTelegramChat(this INavigatorContext ctx) + { + var chat = ctx.GetTelegramChatOrDefault(); + + return chat ?? throw new Exception("Chat was not found."); + } + + /// + /// Get a Telegram chat or default if not found. + /// + /// + /// Telegram Chat + public static Chat? GetTelegramChatOrDefault(this INavigatorContext ctx) + { + return ctx.GetOriginalUpdateOrDefault()?.Type switch + { + UpdateType.CallbackQuery => ctx.GetOriginalUpdate().CallbackQuery.Message.Chat, + UpdateType.Message => ctx.GetOriginalUpdate().Message.Chat, + UpdateType.EditedMessage => ctx.GetOriginalUpdate().EditedMessage.Chat, + UpdateType.ChannelPost => ctx.GetOriginalUpdate().ChannelPost.Chat, + UpdateType.EditedChannelPost => ctx.GetOriginalUpdate().EditedChannelPost.Chat, + _ => default + }; + } + + #endregion // // #region Message // diff --git a/src/Navigator.Providers.Telegram/NavigatorProviderExtensions.cs b/src/Navigator.Providers.Telegram/NavigatorProviderExtensions.cs new file mode 100644 index 0000000..2fbbc51 --- /dev/null +++ b/src/Navigator.Providers.Telegram/NavigatorProviderExtensions.cs @@ -0,0 +1,35 @@ +using System; + +namespace Navigator.Providers.Telegram +{ + public static class NavigatorProviderExtensions + { + public static NavigatorTelegramClient GetTelegramClient(this INavigatorProvider provider) + { + var client = provider.GetTelegramClientOrDefault(); + + if (client is not null) + { + return client; + } + + throw new Exception($"Navigator client was not of type {nameof(NavigatorTelegramClient)}") + { + Data = + { + {nameof(Type), provider.GetClient().GetType()} + } + }; + } + + public static NavigatorTelegramClient? GetTelegramClientOrDefault(this INavigatorProvider provider) + { + if (provider.GetClient() is NavigatorTelegramClient navigatorTelegramClient) + { + return navigatorTelegramClient; + } + + return default; + } + } +} \ No newline at end of file From 2f32d8b6cfeb208717a45cf484b594e435eed9b3 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 9 Mar 2021 16:50:13 +0100 Subject: [PATCH 133/304] Updated sample EchoAction --- .../Actions/EchoAction.cs | 9 +++++---- .../Actions/EchoActionHandler.cs | 18 ++++++++---------- 2 files changed, 13 insertions(+), 14 deletions(-) diff --git a/src/Navigator.Samples.Echo/Actions/EchoAction.cs b/src/Navigator.Samples.Echo/Actions/EchoAction.cs index 2343f3e..f698b1f 100644 --- a/src/Navigator.Samples.Echo/Actions/EchoAction.cs +++ b/src/Navigator.Samples.Echo/Actions/EchoAction.cs @@ -1,6 +1,6 @@ -using Navigator.Abstractions; +using Navigator.Actions.Model; using Navigator.Context; -using Navigator.Extensions.Actions; +using Navigator.Providers.Telegram.Actions; namespace Navigator.Samples.Echo.Actions { @@ -10,10 +10,11 @@ public class EchoAction : MessageAction public override IAction Init(INavigatorContext ctx) { - if (string.IsNullOrWhiteSpace(ctx.Update.Message.Text)) + if (string.IsNullOrWhiteSpace(Message.Text)) { - MessageToEcho = ctx.Update.Message.Text; + MessageToEcho = Message.Text; } + return this; } diff --git a/src/Navigator.Samples.Echo/Actions/EchoActionHandler.cs b/src/Navigator.Samples.Echo/Actions/EchoActionHandler.cs index ea48ca2..b92b430 100644 --- a/src/Navigator.Samples.Echo/Actions/EchoActionHandler.cs +++ b/src/Navigator.Samples.Echo/Actions/EchoActionHandler.cs @@ -1,27 +1,25 @@ using System.Threading; using System.Threading.Tasks; using MediatR; -using Navigator.Abstractions; +using Navigator.Actions; +using Navigator.Actions.Model; using Navigator.Context; -using Navigator.Extensions.Actions; -using Navigator.Extensions.Store.Abstractions.Extensions; -using Navigator.Samples.Echo.Entity; -using Newtonsoft.Json; +using Navigator.Providers.Telegram; namespace Navigator.Samples.Echo.Actions { public class EchoActionHandler : ActionHandler { - public EchoActionHandler(INavigatorContext ctx) : base(ctx) + public EchoActionHandler(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) { } - public override async Task Handle(EchoAction request, CancellationToken cancellationToken) + public override async Task Handle(EchoAction action, CancellationToken cancellationToken) { - await Ctx.Client.SendTextMessageAsync(Ctx.GetTelegramChat(), request.MessageToEcho, - cancellationToken: cancellationToken); + await NavigatorContext.Provider.GetTelegramClient().SendTextMessageAsync(NavigatorContext.GetTelegramChat(), + action.MessageToEcho, cancellationToken: cancellationToken); - return Unit.Value; + return Success(); } } } \ No newline at end of file From 918cf5d8913192eff32329edd238aa27fa5449f2 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 9 Mar 2021 16:50:48 +0100 Subject: [PATCH 134/304] Updated dependencies of sample --- src/Navigator.Samples.Echo/Navigator.Samples.Echo.csproj | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/Navigator.Samples.Echo/Navigator.Samples.Echo.csproj b/src/Navigator.Samples.Echo/Navigator.Samples.Echo.csproj index f4b9a66..1393d8c 100644 --- a/src/Navigator.Samples.Echo/Navigator.Samples.Echo.csproj +++ b/src/Navigator.Samples.Echo/Navigator.Samples.Echo.csproj @@ -16,11 +16,8 @@ - - - From 384acd59482da00f85d95642655ced0007c81765 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 9 Mar 2021 17:42:49 +0100 Subject: [PATCH 135/304] Updated namespace of configuration related classes for Telegram provider --- .../NavigatorProviderConfigurationExtensions.cs} | 4 +++- .../{ => Configuration}/NavigatorProviderExtensions.cs | 0 .../NavigatorRouteProviderConfigurationExtensions.cs | 0 3 files changed, 3 insertions(+), 1 deletion(-) rename src/Navigator.Providers.Telegram/{NavigatorProviderConfigurationExtension.cs => Configuration/NavigatorProviderConfigurationExtensions.cs} (84%) rename src/Navigator.Providers.Telegram/{ => Configuration}/NavigatorProviderExtensions.cs (100%) rename src/Navigator.Providers.Telegram/{ => Configuration}/NavigatorRouteProviderConfigurationExtensions.cs (100%) diff --git a/src/Navigator.Providers.Telegram/NavigatorProviderConfigurationExtension.cs b/src/Navigator.Providers.Telegram/Configuration/NavigatorProviderConfigurationExtensions.cs similarity index 84% rename from src/Navigator.Providers.Telegram/NavigatorProviderConfigurationExtension.cs rename to src/Navigator.Providers.Telegram/Configuration/NavigatorProviderConfigurationExtensions.cs index e47cba6..cdf19bf 100644 --- a/src/Navigator.Providers.Telegram/NavigatorProviderConfigurationExtension.cs +++ b/src/Navigator.Providers.Telegram/Configuration/NavigatorProviderConfigurationExtensions.cs @@ -15,12 +15,14 @@ public static NavigatorConfiguration Telegram(this NavigatorProviderConfiguratio options.Invoke(telegramProviderOptions); return providerConfiguration.Provider( - optionsAction => optionsAction.Import(optionsAction.RetrieveAllOptions()), + optionsAction => optionsAction.Import(telegramProviderOptions.RetrieveAllOptions()), services => { services.AddSingleton(); services.AddSingleton(sp => sp.GetRequiredService()); + services.AddScoped(); + services.AddScoped(); services.AddHostedService(); diff --git a/src/Navigator.Providers.Telegram/NavigatorProviderExtensions.cs b/src/Navigator.Providers.Telegram/Configuration/NavigatorProviderExtensions.cs similarity index 100% rename from src/Navigator.Providers.Telegram/NavigatorProviderExtensions.cs rename to src/Navigator.Providers.Telegram/Configuration/NavigatorProviderExtensions.cs diff --git a/src/Navigator.Providers.Telegram/NavigatorRouteProviderConfigurationExtensions.cs b/src/Navigator.Providers.Telegram/Configuration/NavigatorRouteProviderConfigurationExtensions.cs similarity index 100% rename from src/Navigator.Providers.Telegram/NavigatorRouteProviderConfigurationExtensions.cs rename to src/Navigator.Providers.Telegram/Configuration/NavigatorRouteProviderConfigurationExtensions.cs From 49c9b47620a8ab28284834a557a37b802697cfde Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 9 Mar 2021 17:43:05 +0100 Subject: [PATCH 136/304] Updated sample --- .../Actions/EchoAction.cs | 11 +- .../ConfigurationExtension.cs | 40 ------ .../Entity/SampleUser.cs | 36 ----- ...0210114093457_InitialMigration.Designer.cs | 134 ------------------ .../20210114093457_InitialMigration.cs | 87 ------------ .../NavigatorSampleDbContextModelSnapshot.cs | 132 ----------------- .../Navigator.Samples.Echo.csproj | 1 + .../Persistence/NavigatorSampleDbContext.cs | 21 --- src/Navigator.Samples.Echo/Program.cs | 7 +- src/Navigator.Samples.Echo/Startup.cs | 26 ---- 10 files changed, 15 insertions(+), 480 deletions(-) delete mode 100644 src/Navigator.Samples.Echo/ConfigurationExtension.cs delete mode 100644 src/Navigator.Samples.Echo/Entity/SampleUser.cs delete mode 100644 src/Navigator.Samples.Echo/Migrations/20210114093457_InitialMigration.Designer.cs delete mode 100644 src/Navigator.Samples.Echo/Migrations/20210114093457_InitialMigration.cs delete mode 100644 src/Navigator.Samples.Echo/Migrations/NavigatorSampleDbContextModelSnapshot.cs delete mode 100644 src/Navigator.Samples.Echo/Persistence/NavigatorSampleDbContext.cs diff --git a/src/Navigator.Samples.Echo/Actions/EchoAction.cs b/src/Navigator.Samples.Echo/Actions/EchoAction.cs index f698b1f..699c4eb 100644 --- a/src/Navigator.Samples.Echo/Actions/EchoAction.cs +++ b/src/Navigator.Samples.Echo/Actions/EchoAction.cs @@ -6,11 +6,18 @@ namespace Navigator.Samples.Echo.Actions { public class EchoAction : MessageAction { - public string MessageToEcho { get; set; } = string.Empty; + public EchoAction() + { + MessageToEcho = string.Empty; + } + + public string MessageToEcho { get; set; } public override IAction Init(INavigatorContext ctx) { - if (string.IsNullOrWhiteSpace(Message.Text)) + base.Init(ctx); + + if (!string.IsNullOrWhiteSpace(Message.Text)) { MessageToEcho = Message.Text; } diff --git a/src/Navigator.Samples.Echo/ConfigurationExtension.cs b/src/Navigator.Samples.Echo/ConfigurationExtension.cs deleted file mode 100644 index f6a4de5..0000000 --- a/src/Navigator.Samples.Echo/ConfigurationExtension.cs +++ /dev/null @@ -1,40 +0,0 @@ -using System; -using System.IO; -using Microsoft.Extensions.Configuration; -using Serilog; -using Serilog.Exceptions; - -namespace Navigator.Samples.Echo -{ - public static class ConfigurationExtension - { - public static IConfiguration LoadConfiguration() - { - return new ConfigurationBuilder() - .SetBasePath(Directory.GetCurrentDirectory()) - .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) - .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true) - .AddEnvironmentVariables() - .Build(); - } - - public static ILogger LoadLogger(IConfiguration configuration) - { - var loggerConf = new LoggerConfiguration() - .Enrich.FromLogContext() - .Enrich.WithExceptionDetails() - .WriteTo.Console(); - - if (Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "Development") - { - loggerConf.MinimumLevel.Verbose(); - } - else - { - loggerConf.MinimumLevel.Debug(); - } - - return loggerConf.CreateLogger(); - } - } -} \ No newline at end of file diff --git a/src/Navigator.Samples.Echo/Entity/SampleUser.cs b/src/Navigator.Samples.Echo/Entity/SampleUser.cs deleted file mode 100644 index 2bc476f..0000000 --- a/src/Navigator.Samples.Echo/Entity/SampleUser.cs +++ /dev/null @@ -1,36 +0,0 @@ -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Metadata.Builders; -using Navigator.Extensions.Store.Abstractions; -using Navigator.Extensions.Store.Abstractions.Entity; - -namespace Navigator.Samples.Echo.Entity -{ - public class SampleUser : User - { - public string Secret { get; set; } - } - - public class SampleUserEntityTypeConfiguration : IEntityTypeConfiguration - { - public void Configure(EntityTypeBuilder builder) - { - builder.Property(e => e.Secret) - .HasMaxLength(100); - } - } - - public class SampleUserMapper : IUserMapper - { - public SampleUser Parse(Telegram.Bot.Types.User user) - { - return new SampleUser - { - Id = user.Id, - IsBot = user.IsBot, - LanguageCode = user.LanguageCode, - Username = user.Username, - Secret = "no secret" - }; - } - } -} \ No newline at end of file diff --git a/src/Navigator.Samples.Echo/Migrations/20210114093457_InitialMigration.Designer.cs b/src/Navigator.Samples.Echo/Migrations/20210114093457_InitialMigration.Designer.cs deleted file mode 100644 index ab6b922..0000000 --- a/src/Navigator.Samples.Echo/Migrations/20210114093457_InitialMigration.Designer.cs +++ /dev/null @@ -1,134 +0,0 @@ -// -using System; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Infrastructure; -using Microsoft.EntityFrameworkCore.Migrations; -using Microsoft.EntityFrameworkCore.Storage.ValueConversion; -using Navigator.Samples.Echo.Persistence; - -namespace Navigator.Samples.Echo.Migrations -{ - [DbContext(typeof(NavigatorSampleDbContext))] - [Migration("20210114093457_InitialMigration")] - partial class InitialMigration - { - protected override void BuildTargetModel(ModelBuilder modelBuilder) - { -#pragma warning disable 612, 618 - modelBuilder - .HasAnnotation("ProductVersion", "5.0.1"); - - modelBuilder.Entity("Navigator.Extensions.Store.Abstractions.Entity.Chat", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("CreatedAt") - .HasColumnType("TEXT"); - - b.Property("Title") - .HasColumnType("TEXT"); - - b.Property("Type") - .HasColumnType("INTEGER"); - - b.Property("Username") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("Chats"); - }); - - modelBuilder.Entity("Navigator.Extensions.Store.Abstractions.Entity.Conversation", b => - { - b.Property("ChatId") - .HasColumnType("INTEGER"); - - b.Property("UserId") - .HasColumnType("INTEGER"); - - b.Property("CreatedAt") - .HasColumnType("TEXT"); - - b.HasKey("ChatId", "UserId"); - - b.HasIndex("UserId"); - - b.ToTable("Conversations"); - }); - - modelBuilder.Entity("Navigator.Extensions.Store.Abstractions.Entity.User", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("CreatedAt") - .HasColumnType("TEXT"); - - b.Property("Discriminator") - .IsRequired() - .HasColumnType("TEXT"); - - b.Property("IsBot") - .HasColumnType("INTEGER"); - - b.Property("LanguageCode") - .HasColumnType("TEXT"); - - b.Property("Username") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("User"); - - b.HasDiscriminator("Discriminator").HasValue("User"); - }); - - modelBuilder.Entity("Navigator.Samples.Echo.Entity.SampleUser", b => - { - b.HasBaseType("Navigator.Extensions.Store.Abstractions.Entity.User"); - - b.Property("Secret") - .IsRequired() - .HasMaxLength(100) - .HasColumnType("TEXT"); - - b.HasDiscriminator().HasValue("SampleUser"); - }); - - modelBuilder.Entity("Navigator.Extensions.Store.Abstractions.Entity.Conversation", b => - { - b.HasOne("Navigator.Extensions.Store.Abstractions.Entity.Chat", "Chat") - .WithMany("Conversations") - .HasForeignKey("ChatId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.HasOne("Navigator.Extensions.Store.Abstractions.Entity.User", "User") - .WithMany("Conversations") - .HasForeignKey("UserId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("Chat"); - - b.Navigation("User"); - }); - - modelBuilder.Entity("Navigator.Extensions.Store.Abstractions.Entity.Chat", b => - { - b.Navigation("Conversations"); - }); - - modelBuilder.Entity("Navigator.Extensions.Store.Abstractions.Entity.User", b => - { - b.Navigation("Conversations"); - }); -#pragma warning restore 612, 618 - } - } -} diff --git a/src/Navigator.Samples.Echo/Migrations/20210114093457_InitialMigration.cs b/src/Navigator.Samples.Echo/Migrations/20210114093457_InitialMigration.cs deleted file mode 100644 index d7f16a7..0000000 --- a/src/Navigator.Samples.Echo/Migrations/20210114093457_InitialMigration.cs +++ /dev/null @@ -1,87 +0,0 @@ -using System; -using Microsoft.EntityFrameworkCore.Migrations; - -namespace Navigator.Samples.Echo.Migrations -{ - public partial class InitialMigration : Migration - { - protected override void Up(MigrationBuilder migrationBuilder) - { - migrationBuilder.CreateTable( - name: "Chats", - columns: table => new - { - Id = table.Column(type: "INTEGER", nullable: false) - .Annotation("Sqlite:Autoincrement", true), - Username = table.Column(type: "TEXT", nullable: true), - Title = table.Column(type: "TEXT", nullable: true), - Type = table.Column(type: "INTEGER", nullable: false), - CreatedAt = table.Column(type: "TEXT", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_Chats", x => x.Id); - }); - - migrationBuilder.CreateTable( - name: "User", - columns: table => new - { - Id = table.Column(type: "INTEGER", nullable: false) - .Annotation("Sqlite:Autoincrement", true), - IsBot = table.Column(type: "INTEGER", nullable: false), - LanguageCode = table.Column(type: "TEXT", nullable: true), - Username = table.Column(type: "TEXT", nullable: true), - CreatedAt = table.Column(type: "TEXT", nullable: false), - Discriminator = table.Column(type: "TEXT", nullable: false), - Secret = table.Column(type: "TEXT", maxLength: 100, nullable: true) - }, - constraints: table => - { - table.PrimaryKey("PK_User", x => x.Id); - }); - - migrationBuilder.CreateTable( - name: "Conversations", - columns: table => new - { - ChatId = table.Column(type: "INTEGER", nullable: false), - UserId = table.Column(type: "INTEGER", nullable: false), - CreatedAt = table.Column(type: "TEXT", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_Conversations", x => new { x.ChatId, x.UserId }); - table.ForeignKey( - name: "FK_Conversations_Chats_ChatId", - column: x => x.ChatId, - principalTable: "Chats", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - table.ForeignKey( - name: "FK_Conversations_User_UserId", - column: x => x.UserId, - principalTable: "User", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); - - migrationBuilder.CreateIndex( - name: "IX_Conversations_UserId", - table: "Conversations", - column: "UserId"); - } - - protected override void Down(MigrationBuilder migrationBuilder) - { - migrationBuilder.DropTable( - name: "Conversations"); - - migrationBuilder.DropTable( - name: "Chats"); - - migrationBuilder.DropTable( - name: "User"); - } - } -} diff --git a/src/Navigator.Samples.Echo/Migrations/NavigatorSampleDbContextModelSnapshot.cs b/src/Navigator.Samples.Echo/Migrations/NavigatorSampleDbContextModelSnapshot.cs deleted file mode 100644 index ddb143d..0000000 --- a/src/Navigator.Samples.Echo/Migrations/NavigatorSampleDbContextModelSnapshot.cs +++ /dev/null @@ -1,132 +0,0 @@ -// -using System; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Infrastructure; -using Microsoft.EntityFrameworkCore.Storage.ValueConversion; -using Navigator.Samples.Echo.Persistence; - -namespace Navigator.Samples.Echo.Migrations -{ - [DbContext(typeof(NavigatorSampleDbContext))] - partial class NavigatorSampleDbContextModelSnapshot : ModelSnapshot - { - protected override void BuildModel(ModelBuilder modelBuilder) - { -#pragma warning disable 612, 618 - modelBuilder - .HasAnnotation("ProductVersion", "5.0.1"); - - modelBuilder.Entity("Navigator.Extensions.Store.Abstractions.Entity.Chat", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("CreatedAt") - .HasColumnType("TEXT"); - - b.Property("Title") - .HasColumnType("TEXT"); - - b.Property("Type") - .HasColumnType("INTEGER"); - - b.Property("Username") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("Chats"); - }); - - modelBuilder.Entity("Navigator.Extensions.Store.Abstractions.Entity.Conversation", b => - { - b.Property("ChatId") - .HasColumnType("INTEGER"); - - b.Property("UserId") - .HasColumnType("INTEGER"); - - b.Property("CreatedAt") - .HasColumnType("TEXT"); - - b.HasKey("ChatId", "UserId"); - - b.HasIndex("UserId"); - - b.ToTable("Conversations"); - }); - - modelBuilder.Entity("Navigator.Extensions.Store.Abstractions.Entity.User", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("CreatedAt") - .HasColumnType("TEXT"); - - b.Property("Discriminator") - .IsRequired() - .HasColumnType("TEXT"); - - b.Property("IsBot") - .HasColumnType("INTEGER"); - - b.Property("LanguageCode") - .HasColumnType("TEXT"); - - b.Property("Username") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("User"); - - b.HasDiscriminator("Discriminator").HasValue("User"); - }); - - modelBuilder.Entity("Navigator.Samples.Echo.Entity.SampleUser", b => - { - b.HasBaseType("Navigator.Extensions.Store.Abstractions.Entity.User"); - - b.Property("Secret") - .IsRequired() - .HasMaxLength(100) - .HasColumnType("TEXT"); - - b.HasDiscriminator().HasValue("SampleUser"); - }); - - modelBuilder.Entity("Navigator.Extensions.Store.Abstractions.Entity.Conversation", b => - { - b.HasOne("Navigator.Extensions.Store.Abstractions.Entity.Chat", "Chat") - .WithMany("Conversations") - .HasForeignKey("ChatId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.HasOne("Navigator.Extensions.Store.Abstractions.Entity.User", "User") - .WithMany("Conversations") - .HasForeignKey("UserId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("Chat"); - - b.Navigation("User"); - }); - - modelBuilder.Entity("Navigator.Extensions.Store.Abstractions.Entity.Chat", b => - { - b.Navigation("Conversations"); - }); - - modelBuilder.Entity("Navigator.Extensions.Store.Abstractions.Entity.User", b => - { - b.Navigation("Conversations"); - }); -#pragma warning restore 612, 618 - } - } -} diff --git a/src/Navigator.Samples.Echo/Navigator.Samples.Echo.csproj b/src/Navigator.Samples.Echo/Navigator.Samples.Echo.csproj index 1393d8c..3eba1b7 100644 --- a/src/Navigator.Samples.Echo/Navigator.Samples.Echo.csproj +++ b/src/Navigator.Samples.Echo/Navigator.Samples.Echo.csproj @@ -7,6 +7,7 @@ + diff --git a/src/Navigator.Samples.Echo/Persistence/NavigatorSampleDbContext.cs b/src/Navigator.Samples.Echo/Persistence/NavigatorSampleDbContext.cs deleted file mode 100644 index fb5a2e8..0000000 --- a/src/Navigator.Samples.Echo/Persistence/NavigatorSampleDbContext.cs +++ /dev/null @@ -1,21 +0,0 @@ -using Microsoft.EntityFrameworkCore; -using Navigator.Extensions.Store.Abstractions.Entity; -using Navigator.Extensions.Store.Context; -using Navigator.Samples.Echo.Entity; - -namespace Navigator.Samples.Echo.Persistence -{ - public class NavigatorSampleDbContext : NavigatorDbContext - { - public NavigatorSampleDbContext(DbContextOptions options) : base(options) - { - } - - protected override void OnModelCreating(ModelBuilder modelBuilder) - { - base.OnModelCreating(modelBuilder); - - modelBuilder.ApplyConfiguration(new SampleUserEntityTypeConfiguration()); - } - } -} \ No newline at end of file diff --git a/src/Navigator.Samples.Echo/Program.cs b/src/Navigator.Samples.Echo/Program.cs index fc124d5..44db3d3 100644 --- a/src/Navigator.Samples.Echo/Program.cs +++ b/src/Navigator.Samples.Echo/Program.cs @@ -1,14 +1,17 @@ using System; +using System.IO; +using Ele.Extensions.Configuration; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Serilog; +using ConfigurationExtensions = Ele.Extensions.Configuration.ConfigurationExtensions; namespace Navigator.Samples.Echo { public class Program { - private static IConfiguration Configuration { get; } = ConfigurationExtension.LoadConfiguration(); + private static IConfiguration Configuration { get; } = ConfigurationExtensions.LoadConfiguration(Directory.GetCurrentDirectory()); public static IHostBuilder CreateHostBuilder(string[] args) => @@ -21,7 +24,7 @@ public static IHostBuilder CreateHostBuilder(string[] args) => public static void Main(string[] args) { - Log.Logger = ConfigurationExtension.LoadLogger(Configuration); + Log.Logger = LoggingExtensions.LoadLogger(Configuration); try { diff --git a/src/Navigator.Samples.Echo/Startup.cs b/src/Navigator.Samples.Echo/Startup.cs index 2a07458..fe16ad0 100644 --- a/src/Navigator.Samples.Echo/Startup.cs +++ b/src/Navigator.Samples.Echo/Startup.cs @@ -1,16 +1,11 @@ using MediatR; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; -using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Navigator.Configuration; -using Navigator.Extensions.Shipyard; -using Navigator.Extensions.Store; using Navigator.Providers.Telegram; -using Navigator.Samples.Echo.Entity; -using Navigator.Samples.Echo.Persistence; namespace Navigator.Samples.Echo { @@ -28,10 +23,6 @@ public void ConfigureServices(IServiceCollection services) { services.AddControllers().AddNewtonsoftJson(); - services.AddMediatR(typeof(Startup).Assembly); - - services.AddApiVersioning(); - services.AddNavigator(options => { options.SetWebHookBaseUrl(Configuration["BASE_WEBHOOK_URL"]); @@ -40,17 +31,6 @@ public void ConfigureServices(IServiceCollection services) { options.SetTelegramToken(Configuration["BOT_TOKEN"]); }); - // ).AddNavigatorStore( - // builder => - // { - // builder.UseSqlite(Configuration.GetConnectionString("DefaultConnection"), - // b => b.MigrationsAssembly("Navigator.Samples.Echo")); - // }, - // options => { options.SetUserMapper(); } - // ).AddShipyard(options => - // { - // options.SetShipyardApiKey(Configuration["SHIPYARD_API_KEY"]); - // }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. @@ -61,14 +41,8 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env) app.UseDeveloperExceptionPage(); } - using var serviceScope = app.ApplicationServices.GetService()?.CreateScope(); - serviceScope?.ServiceProvider.GetRequiredService().Database.Migrate(); - app.UseRouting(); - app.UseAuthentication(); - app.UseAuthorization(); - app.UseEndpoints(endpoints => { endpoints.MapControllers(); From a1ccdfd04da79ea43a9f91df7444efae281356b4 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 9 Mar 2021 17:43:19 +0100 Subject: [PATCH 137/304] Corrected null --- src/Navigator/Context/NavigatorContext.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Navigator/Context/NavigatorContext.cs b/src/Navigator/Context/NavigatorContext.cs index b4bd451..84c13ad 100644 --- a/src/Navigator/Context/NavigatorContext.cs +++ b/src/Navigator/Context/NavigatorContext.cs @@ -37,6 +37,7 @@ public NavigatorContext(INavigatorProvider provider, BotUser botProfile, string Conversation = conversation; Items = new Dictionary(); + Extensions = new Dictionary(); } } } \ No newline at end of file From 18f3eed556b8a47cc943368fcfc191187b4e65cd Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 9 Mar 2021 17:43:27 +0100 Subject: [PATCH 138/304] Corrected replace --- src/Navigator/Configuration/NavigatorConfiguration.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Navigator/Configuration/NavigatorConfiguration.cs b/src/Navigator/Configuration/NavigatorConfiguration.cs index a27ba73..0751aef 100644 --- a/src/Navigator/Configuration/NavigatorConfiguration.cs +++ b/src/Navigator/Configuration/NavigatorConfiguration.cs @@ -51,7 +51,7 @@ public NavigatorConfiguration(Action options, IServiceCollecti public void RegisterOrReplaceOptions() { - Services.Replace(ServiceDescriptor.Singleton(Options)); + Services.Replace(ServiceDescriptor.Singleton(_ => Options)); } } } \ No newline at end of file From 2d0400a92d53d21ffa130016989ad8e7143fd80f Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 9 Mar 2021 17:43:36 +0100 Subject: [PATCH 139/304] Corrected getter --- src/Navigator/Context/NavigatorContextAccessor.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Navigator/Context/NavigatorContextAccessor.cs b/src/Navigator/Context/NavigatorContextAccessor.cs index fa9d13d..94dd44f 100644 --- a/src/Navigator/Context/NavigatorContextAccessor.cs +++ b/src/Navigator/Context/NavigatorContextAccessor.cs @@ -9,6 +9,6 @@ public NavigatorContextAccessor(INavigatorContextFactory navigatorContextFactory _navigatorContextFactory = navigatorContextFactory; } - public INavigatorContext NavigatorContext { get; } + public INavigatorContext NavigatorContext => _navigatorContextFactory.Retrieve(); } } \ No newline at end of file From 07fc51824bf4a64e6ee6bc04a616e5376cee2bd2 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 9 Mar 2021 17:43:42 +0100 Subject: [PATCH 140/304] Updated DI --- src/Navigator/Navigator.csproj | 2 +- src/Navigator/ServiceCollectionExtensions.cs | 8 +++++++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/src/Navigator/Navigator.csproj b/src/Navigator/Navigator.csproj index f528702..811b1f2 100644 --- a/src/Navigator/Navigator.csproj +++ b/src/Navigator/Navigator.csproj @@ -21,7 +21,7 @@ - + diff --git a/src/Navigator/ServiceCollectionExtensions.cs b/src/Navigator/ServiceCollectionExtensions.cs index c60b66f..7d907d9 100644 --- a/src/Navigator/ServiceCollectionExtensions.cs +++ b/src/Navigator/ServiceCollectionExtensions.cs @@ -1,9 +1,11 @@ using System; +using MediatR; using Microsoft.Extensions.DependencyInjection; using Navigator.Actions; using Navigator.Actions.Model; using Navigator.Configuration; using Navigator.Context; +using Navigator.Context.Extensions; using Scrutor; namespace Navigator @@ -20,8 +22,12 @@ public static NavigatorConfiguration AddNavigator(this IServiceCollection servic var navigatorBuilder = new NavigatorConfiguration(options, services); services.AddNavigatorContextServices(); + + services.AddScoped(); services.AddScoped(); + + services.AddMediatR(navigatorBuilder.Options.GetActionsAssemblies()); services.Scan(scan => scan .FromAssemblies(navigatorBuilder.Options.GetActionsAssemblies()) @@ -39,7 +45,7 @@ internal static void AddNavigatorContextServices(this IServiceCollection service { services.AddScoped(); services.AddScoped(); - services.AddScoped(); + services.AddTransient(); } } } \ No newline at end of file From 22b9f68e9d82ca7f7321310df3e32992f59196d3 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 9 Mar 2021 17:47:00 +0100 Subject: [PATCH 141/304] Adjusted namespaces --- .../NavigatorProviderConfigurationExtensions.cs | 0 .../{Configuration => }/NavigatorProviderExtensions.cs | 0 .../NavigatorRouteProviderConfigurationExtensions.cs | 0 src/Navigator.Providers.Telegram/TelegramMiddleware.cs | 2 +- .../Configuration/Extension/NavigatorExtensionConfiguration.cs | 2 +- src/Navigator/Configuration/NavigatorConfiguration.cs | 1 + 6 files changed, 3 insertions(+), 2 deletions(-) rename src/Navigator.Providers.Telegram/{Configuration => }/NavigatorProviderConfigurationExtensions.cs (100%) rename src/Navigator.Providers.Telegram/{Configuration => }/NavigatorProviderExtensions.cs (100%) rename src/Navigator.Providers.Telegram/{Configuration => }/NavigatorRouteProviderConfigurationExtensions.cs (100%) diff --git a/src/Navigator.Providers.Telegram/Configuration/NavigatorProviderConfigurationExtensions.cs b/src/Navigator.Providers.Telegram/NavigatorProviderConfigurationExtensions.cs similarity index 100% rename from src/Navigator.Providers.Telegram/Configuration/NavigatorProviderConfigurationExtensions.cs rename to src/Navigator.Providers.Telegram/NavigatorProviderConfigurationExtensions.cs diff --git a/src/Navigator.Providers.Telegram/Configuration/NavigatorProviderExtensions.cs b/src/Navigator.Providers.Telegram/NavigatorProviderExtensions.cs similarity index 100% rename from src/Navigator.Providers.Telegram/Configuration/NavigatorProviderExtensions.cs rename to src/Navigator.Providers.Telegram/NavigatorProviderExtensions.cs diff --git a/src/Navigator.Providers.Telegram/Configuration/NavigatorRouteProviderConfigurationExtensions.cs b/src/Navigator.Providers.Telegram/NavigatorRouteProviderConfigurationExtensions.cs similarity index 100% rename from src/Navigator.Providers.Telegram/Configuration/NavigatorRouteProviderConfigurationExtensions.cs rename to src/Navigator.Providers.Telegram/NavigatorRouteProviderConfigurationExtensions.cs diff --git a/src/Navigator.Providers.Telegram/TelegramMiddleware.cs b/src/Navigator.Providers.Telegram/TelegramMiddleware.cs index 82c09e5..6078081 100644 --- a/src/Navigator.Providers.Telegram/TelegramMiddleware.cs +++ b/src/Navigator.Providers.Telegram/TelegramMiddleware.cs @@ -44,7 +44,7 @@ await _navigatorContextFactory.Supply(builder => await _actionLauncher.Launch(); } - public string? DefineActionType(Update update) + private string? DefineActionType(Update update) { return update.Type switch { diff --git a/src/Navigator/Configuration/Extension/NavigatorExtensionConfiguration.cs b/src/Navigator/Configuration/Extension/NavigatorExtensionConfiguration.cs index 93e8fff..0921190 100644 --- a/src/Navigator/Configuration/Extension/NavigatorExtensionConfiguration.cs +++ b/src/Navigator/Configuration/Extension/NavigatorExtensionConfiguration.cs @@ -1,7 +1,7 @@ using System; using Microsoft.Extensions.DependencyInjection; -namespace Navigator.Configuration.Provider +namespace Navigator.Configuration.Extension { /// /// Provides a entry point for configuring new extensions for Navigator. diff --git a/src/Navigator/Configuration/NavigatorConfiguration.cs b/src/Navigator/Configuration/NavigatorConfiguration.cs index 0751aef..b778d41 100644 --- a/src/Navigator/Configuration/NavigatorConfiguration.cs +++ b/src/Navigator/Configuration/NavigatorConfiguration.cs @@ -1,6 +1,7 @@ using System; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; +using Navigator.Configuration.Extension; using Navigator.Configuration.Provider; namespace Navigator.Configuration From ff2641dd539dda06b2d6e13b415998a58e503c2c Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 9 Mar 2021 18:10:39 +0100 Subject: [PATCH 142/304] Improved CommandAction --- .../CommandAction.cs | 25 ----------------- .../Actions/CommandAction.cs | 28 ++++++++++++------- 2 files changed, 18 insertions(+), 35 deletions(-) delete mode 100644 src/Navigator.Extensions.Actions/CommandAction.cs diff --git a/src/Navigator.Extensions.Actions/CommandAction.cs b/src/Navigator.Extensions.Actions/CommandAction.cs deleted file mode 100644 index 12ce414..0000000 --- a/src/Navigator.Extensions.Actions/CommandAction.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System; -using Navigator.Abstractions; - -namespace Navigator.Extensions.Actions -{ - public abstract class CommandAction : Action - { - public override string Type => ActionType.Command; - public DateTime MessageTimestamp { get; protected set; } - public int MessageId { get; protected set; } - public int? ReplyToMessageId { get; protected set; } - public string Command { get; set; } = string.Empty; - - public override IAction Init(Update ctx) - { - MessageTimestamp = ctx.Update.Message.Date; - MessageId = ctx.Update.Message.MessageId; - ReplyToMessageId = ctx.Update.Message.ReplyToMessage?.MessageId; - - Command = ctx.Update.Message.ExtractCommand(ctx.BotProfile.Username) ?? string.Empty; - - return this; - } - } -} \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/Actions/CommandAction.cs b/src/Navigator.Providers.Telegram/Actions/CommandAction.cs index b0c77eb..2082b81 100644 --- a/src/Navigator.Providers.Telegram/Actions/CommandAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/CommandAction.cs @@ -5,28 +5,36 @@ namespace Navigator.Providers.Telegram.Actions { + /// + /// Command based action. + /// public abstract class CommandAction : MessageAction { - protected CommandAction() - { - Command = string.Empty; - Arguments = string.Empty; - } - + /// public override string Type { get; protected set; } = ActionsHelper.Type.For(nameof(CommandAction)); + + /// public override ushort Priority { get; protected set; } = ActionsHelper.Priority.Default; - + + /// public override IAction Init(INavigatorContext navigatorContext) { Command = Message.ExtractCommand(navigatorContext.BotProfile.Username) ?? string.Empty; - Arguments = Message.ExtractArguments(navigatorContext.BotProfile.Username) ?? string.Empty; + Arguments = Message.ExtractArguments(navigatorContext.BotProfile.Username); return this; } - public string Command { get; protected set; } - public string Arguments { get; protected set; } + /// + /// Command. + /// + public string Command { get; protected set; } = null!; + + /// + /// Any arguments passed with the command. If no arguments were passed, it will be null. + /// + public string? Arguments { get; protected set; } } } \ No newline at end of file From f03037c3fc067f7b29cbb97c00b054d8613ca22b Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 9 Mar 2021 18:10:53 +0100 Subject: [PATCH 143/304] Implemented CallbackQueryAction --- .../Actions/CallbackQueryAction.cs | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/src/Navigator.Providers.Telegram/Actions/CallbackQueryAction.cs b/src/Navigator.Providers.Telegram/Actions/CallbackQueryAction.cs index a199323..8b763d3 100644 --- a/src/Navigator.Providers.Telegram/Actions/CallbackQueryAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/CallbackQueryAction.cs @@ -1,11 +1,57 @@ using Navigator.Actions; using Navigator.Actions.Model; +using Navigator.Context; +using Navigator.Context.Extensions; +using Telegram.Bot.Types; namespace Navigator.Providers.Telegram.Actions { + /// + /// A callback query based action. + /// public abstract class CallbackQueryAction : BaseAction { + /// public override string Type { get; protected set; } = ActionsHelper.Type.For(nameof(CallbackQueryAction)); + + /// public override ushort Priority { get; protected set; } = ActionsHelper.Priority.Default; + + /// + public override IAction Init(INavigatorContext navigatorContext) + { + var update = navigatorContext.GetOriginalUpdateOrDefault(); + + if (update is not null) + { + CallbackQuery = update.CallbackQuery; + OriginalMessage = update.CallbackQuery.Message; + Data = string.IsNullOrWhiteSpace(update.CallbackQuery.Data) ? update.CallbackQuery.Data : default; + IsGameQuery = update.CallbackQuery.IsGameQuery; + } + + return this; + } + + /// + /// The original + /// + public CallbackQuery CallbackQuery { get; protected set; } = null!; + + /// + /// The message that originated the callback query. Iy may be null if the message is too old. + /// + public Message? OriginalMessage { get; protected set; } + + /// + /// Any data present on the callback query. + /// + public string? Data { get; protected set; } + + /// + /// True if the callback query is from a game. + /// + public bool IsGameQuery { get; protected set; } + } } \ No newline at end of file From c99d7862092b5e0673d506e95aae1a9f7ed1f266 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 9 Mar 2021 18:11:05 +0100 Subject: [PATCH 144/304] Improved MessageAction --- .../Actions/MessageAction.cs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/Navigator.Providers.Telegram/Actions/MessageAction.cs b/src/Navigator.Providers.Telegram/Actions/MessageAction.cs index e7c6951..e8b5cd8 100644 --- a/src/Navigator.Providers.Telegram/Actions/MessageAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/MessageAction.cs @@ -6,11 +6,18 @@ namespace Navigator.Providers.Telegram.Actions { + /// + /// A message based action. + /// public abstract class MessageAction : BaseAction { + /// public override string Type { get; protected set; } = ActionsHelper.Type.For(nameof(MessageAction)); + + /// public override ushort Priority { get; protected set; } = ActionsHelper.Priority.Default; + /// public override IAction Init(INavigatorContext navigatorContext) { var update = navigatorContext.GetOriginalUpdateOrDefault(); @@ -25,8 +32,8 @@ public override IAction Init(INavigatorContext navigatorContext) return this; } - public Message Message { get; protected set; } - + public Message Message { get; protected set; } = null!; + public bool IsReply { get; protected set; } public bool IsForwarded { get; protected set; } From 66368ad6550f79e4f716ea4912d45a0efecfb058 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 9 Mar 2021 21:52:19 +0100 Subject: [PATCH 145/304] Corrected CommandAction --- src/Navigator.Providers.Telegram/Actions/CommandAction.cs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/Navigator.Providers.Telegram/Actions/CommandAction.cs b/src/Navigator.Providers.Telegram/Actions/CommandAction.cs index 2082b81..4f0e834 100644 --- a/src/Navigator.Providers.Telegram/Actions/CommandAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/CommandAction.cs @@ -13,12 +13,11 @@ public abstract class CommandAction : MessageAction /// public override string Type { get; protected set; } = ActionsHelper.Type.For(nameof(CommandAction)); - /// - public override ushort Priority { get; protected set; } = ActionsHelper.Priority.Default; - /// public override IAction Init(INavigatorContext navigatorContext) { + base.Init(navigatorContext); + Command = Message.ExtractCommand(navigatorContext.BotProfile.Username) ?? string.Empty; Arguments = Message.ExtractArguments(navigatorContext.BotProfile.Username); From f7dcf50759bb8e2ce5c3468fe62a367d49b9b8db Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 15 Mar 2021 21:45:04 +0100 Subject: [PATCH 146/304] Added EditedMessageAction --- .../Actions/EditedMessageAction.cs | 34 +++++++++++++++++++ .../TelegramMiddleware.cs | 4 +-- .../Actions/EditedEchoAction.cs | 13 +++++++ .../Actions/EditedEchoActionHandler.cs | 25 ++++++++++++++ 4 files changed, 74 insertions(+), 2 deletions(-) create mode 100644 src/Navigator.Providers.Telegram/Actions/EditedMessageAction.cs create mode 100644 src/Navigator.Samples.Echo/Actions/EditedEchoAction.cs create mode 100644 src/Navigator.Samples.Echo/Actions/EditedEchoActionHandler.cs diff --git a/src/Navigator.Providers.Telegram/Actions/EditedMessageAction.cs b/src/Navigator.Providers.Telegram/Actions/EditedMessageAction.cs new file mode 100644 index 0000000..a0684ec --- /dev/null +++ b/src/Navigator.Providers.Telegram/Actions/EditedMessageAction.cs @@ -0,0 +1,34 @@ +using Navigator.Actions; +using Navigator.Actions.Model; +using Navigator.Context; +using Navigator.Context.Extensions; +using Telegram.Bot.Types; + +namespace Navigator.Providers.Telegram.Actions +{ + public abstract class EditedMessageAction : BaseAction + { + /// + public override string Type { get; protected set; } = ActionsHelper.Type.For(nameof(EditedMessageAction)); + + /// + public override ushort Priority { get; protected set; } =ActionsHelper.Priority.Default; + + /// + public override IAction Init(INavigatorContext navigatorContext) + { + var update = navigatorContext.GetOriginalUpdateOrDefault(); + + if (update is not null) + { + OriginalMessage = update.EditedMessage; + } + + return this; + } + + public Message OriginalMessage { get; protected set; } = null!; + public Message EditedMessage { get; protected set; } = null!; + + } +} \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/TelegramMiddleware.cs b/src/Navigator.Providers.Telegram/TelegramMiddleware.cs index 6078081..bf487f5 100644 --- a/src/Navigator.Providers.Telegram/TelegramMiddleware.cs +++ b/src/Navigator.Providers.Telegram/TelegramMiddleware.cs @@ -66,8 +66,8 @@ await _navigatorContextFactory.Supply(builder => }, // UpdateType.InlineQuery => ActionType.InlineQuery, // UpdateType.ChosenInlineResult => ActionType.InlineResultChosen, - // UpdateType.CallbackQuery => ActionType.CallbackQuery, - // UpdateType.EditedMessage => ActionType.EditedMessage, + UpdateType.CallbackQuery => ActionsHelper.Type.For(nameof(CallbackQueryAction)), + UpdateType.EditedMessage => ActionsHelper.Type.For(nameof(EditedMessageAction)), // UpdateType.ChannelPost => ActionType.ChannelPost, // UpdateType.EditedChannelPost => ActionType.EditedChannelPost, // UpdateType.ShippingQuery => ActionType.ShippingQuery, diff --git a/src/Navigator.Samples.Echo/Actions/EditedEchoAction.cs b/src/Navigator.Samples.Echo/Actions/EditedEchoAction.cs new file mode 100644 index 0000000..10c7796 --- /dev/null +++ b/src/Navigator.Samples.Echo/Actions/EditedEchoAction.cs @@ -0,0 +1,13 @@ +using Navigator.Context; +using Navigator.Providers.Telegram.Actions; + +namespace Navigator.Samples.Echo.Actions +{ + public class EditedEchoAction : EditedMessageAction + { + public override bool CanHandle(INavigatorContext ctx) + { + return true; + } + } +} \ No newline at end of file diff --git a/src/Navigator.Samples.Echo/Actions/EditedEchoActionHandler.cs b/src/Navigator.Samples.Echo/Actions/EditedEchoActionHandler.cs new file mode 100644 index 0000000..09a154b --- /dev/null +++ b/src/Navigator.Samples.Echo/Actions/EditedEchoActionHandler.cs @@ -0,0 +1,25 @@ +using System.Threading; +using System.Threading.Tasks; +using MediatR; +using Navigator.Actions; +using Navigator.Actions.Model; +using Navigator.Context; +using Navigator.Providers.Telegram; + +namespace Navigator.Samples.Echo.Actions +{ + public class EditedEchoActionHandler : ActionHandler + { + public EditedEchoActionHandler(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) + { + } + + public override async Task Handle(EditedEchoAction action, CancellationToken cancellationToken) + { + await NavigatorContext.Provider.GetTelegramClient().SendTextMessageAsync(NavigatorContext.GetTelegramChat(), + action.EditedMessage.Text, cancellationToken: cancellationToken); + + return Success(); + } + } +} \ No newline at end of file From e910f5610e325b4c60a4a0ed62cf254e0e44c51b Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 15 Mar 2021 21:48:04 +0100 Subject: [PATCH 147/304] Added UnknownAction --- src/Navigator.Extensions.Actions/UnknownAction.cs | 9 --------- .../Actions/UnknownAction.cs | 14 ++++++++++++++ 2 files changed, 14 insertions(+), 9 deletions(-) delete mode 100644 src/Navigator.Extensions.Actions/UnknownAction.cs create mode 100644 src/Navigator.Providers.Telegram/Actions/UnknownAction.cs diff --git a/src/Navigator.Extensions.Actions/UnknownAction.cs b/src/Navigator.Extensions.Actions/UnknownAction.cs deleted file mode 100644 index 970666a..0000000 --- a/src/Navigator.Extensions.Actions/UnknownAction.cs +++ /dev/null @@ -1,9 +0,0 @@ -using Navigator.Abstractions; - -namespace Navigator.Extensions.Actions -{ - public abstract class UnknownAction : Action - { - public override string Type => ActionType.Unknown; - } -} \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/Actions/UnknownAction.cs b/src/Navigator.Providers.Telegram/Actions/UnknownAction.cs new file mode 100644 index 0000000..f3adef5 --- /dev/null +++ b/src/Navigator.Providers.Telegram/Actions/UnknownAction.cs @@ -0,0 +1,14 @@ +using Navigator.Actions; +using Navigator.Actions.Model; + +namespace Navigator.Providers.Telegram.Actions +{ + public abstract class UnknownAction : BaseAction + { + /// + public override string Type { get; protected set; } = ActionsHelper.Type.For(nameof(UnknownAction)); + + /// + public override ushort Priority { get; protected set; } = ActionsHelper.Priority.Default; + } +} \ No newline at end of file From dd857e9e3483ce3cf4422bea1f61007168c18c6c Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 15 Mar 2021 21:49:08 +0100 Subject: [PATCH 148/304] Updated switch on TelegramMiddleware --- src/Navigator.Providers.Telegram/TelegramMiddleware.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Navigator.Providers.Telegram/TelegramMiddleware.cs b/src/Navigator.Providers.Telegram/TelegramMiddleware.cs index bf487f5..8dd9884 100644 --- a/src/Navigator.Providers.Telegram/TelegramMiddleware.cs +++ b/src/Navigator.Providers.Telegram/TelegramMiddleware.cs @@ -73,7 +73,7 @@ await _navigatorContextFactory.Supply(builder => // UpdateType.ShippingQuery => ActionType.ShippingQuery, // UpdateType.PreCheckoutQuery => ActionType.PreCheckoutQuery, // UpdateType.Poll => ActionType.Poll, - // UpdateType.Unknown => ActionType.Unknown, + UpdateType.Unknown => ActionsHelper.Type.For(nameof(UnknownAction)), _ => default }; } From beb95a2da411bf500e0e97e30fa436b5569bbebe Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 15 Mar 2021 21:53:18 +0100 Subject: [PATCH 149/304] Added PollAction --- .../Actions/PollAction.cs | 32 +++++++++++++++++++ .../TelegramMiddleware.cs | 2 +- 2 files changed, 33 insertions(+), 1 deletion(-) create mode 100644 src/Navigator.Providers.Telegram/Actions/PollAction.cs diff --git a/src/Navigator.Providers.Telegram/Actions/PollAction.cs b/src/Navigator.Providers.Telegram/Actions/PollAction.cs new file mode 100644 index 0000000..00dd8eb --- /dev/null +++ b/src/Navigator.Providers.Telegram/Actions/PollAction.cs @@ -0,0 +1,32 @@ +using Navigator.Actions; +using Navigator.Actions.Model; +using Navigator.Context; +using Navigator.Context.Extensions; +using Telegram.Bot.Types; + +namespace Navigator.Providers.Telegram.Actions +{ + public abstract class PollAction : BaseAction + { + /// + public override string Type { get; protected set; } = ActionsHelper.Type.For(nameof(PollAction)); + + /// + public override ushort Priority { get; protected set; } = ActionsHelper.Priority.Default; + + /// + public override IAction Init(INavigatorContext navigatorContext) + { + var update = navigatorContext.GetOriginalUpdateOrDefault(); + + if (update is not null) + { + Poll = update.Poll; + } + + return this; + } + + public Poll Poll { get; protected set; } = null!; + } +} \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/TelegramMiddleware.cs b/src/Navigator.Providers.Telegram/TelegramMiddleware.cs index 8dd9884..f807bae 100644 --- a/src/Navigator.Providers.Telegram/TelegramMiddleware.cs +++ b/src/Navigator.Providers.Telegram/TelegramMiddleware.cs @@ -72,7 +72,7 @@ await _navigatorContextFactory.Supply(builder => // UpdateType.EditedChannelPost => ActionType.EditedChannelPost, // UpdateType.ShippingQuery => ActionType.ShippingQuery, // UpdateType.PreCheckoutQuery => ActionType.PreCheckoutQuery, - // UpdateType.Poll => ActionType.Poll, + UpdateType.Poll => ActionsHelper.Type.For(nameof(PollAction)), UpdateType.Unknown => ActionsHelper.Type.For(nameof(UnknownAction)), _ => default }; From be5f19e2ab07c316181b45265575091684debfed Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 19 Jul 2021 14:39:28 +0300 Subject: [PATCH 150/304] chore: update dependencies --- .../Navigator.Providers.Discord.csproj | 4 ++-- .../Navigator.Samples.Echo.csproj | 10 +++++----- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/Navigator.Providers.Discord/Navigator.Providers.Discord.csproj b/src/Navigator.Providers.Discord/Navigator.Providers.Discord.csproj index ddf4c52..8ac1c3e 100644 --- a/src/Navigator.Providers.Discord/Navigator.Providers.Discord.csproj +++ b/src/Navigator.Providers.Discord/Navigator.Providers.Discord.csproj @@ -17,8 +17,8 @@ - - + + diff --git a/src/Navigator.Samples.Echo/Navigator.Samples.Echo.csproj b/src/Navigator.Samples.Echo/Navigator.Samples.Echo.csproj index 3eba1b7..599182c 100644 --- a/src/Navigator.Samples.Echo/Navigator.Samples.Echo.csproj +++ b/src/Navigator.Samples.Echo/Navigator.Samples.Echo.csproj @@ -9,11 +9,11 @@ - - - - - + + + + + From 456f03fc20ff2f2b7cc863ced9f12ad964aef523 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 19 Jul 2021 15:07:24 +0300 Subject: [PATCH 151/304] chore: update telegram client --- .../Navigator.Providers.Telegram.csproj | 2 +- .../NavigatorTelegramClient.cs | 7 +++---- ...avigatorTelegramProviderOptionsExtensions.cs | 17 ----------------- 3 files changed, 4 insertions(+), 22 deletions(-) diff --git a/src/Navigator.Providers.Telegram/Navigator.Providers.Telegram.csproj b/src/Navigator.Providers.Telegram/Navigator.Providers.Telegram.csproj index 2327862..f7c0c5d 100644 --- a/src/Navigator.Providers.Telegram/Navigator.Providers.Telegram.csproj +++ b/src/Navigator.Providers.Telegram/Navigator.Providers.Telegram.csproj @@ -21,7 +21,7 @@ - + diff --git a/src/Navigator.Providers.Telegram/NavigatorTelegramClient.cs b/src/Navigator.Providers.Telegram/NavigatorTelegramClient.cs index 17a73e6..cffd12a 100644 --- a/src/Navigator.Providers.Telegram/NavigatorTelegramClient.cs +++ b/src/Navigator.Providers.Telegram/NavigatorTelegramClient.cs @@ -1,16 +1,15 @@ -using System.Net.Http; using System.Threading; using System.Threading.Tasks; -using MihaZupan.TelegramBotClients; using Navigator.Configuration; using Navigator.Entities; +using Telegram.Bot; namespace Navigator.Providers.Telegram { - public class NavigatorTelegramClient : RateLimitedTelegramBotClient, INavigatorClient + public class NavigatorTelegramClient : TelegramBotClient, INavigatorClient { public NavigatorTelegramClient(INavigatorOptions options) - : base(options.GetTelegramToken(), (HttpClient) default!, options.GetSchedulerSettingsOrDefault()) + : base(options.GetTelegramToken()) { } diff --git a/src/Navigator.Providers.Telegram/NavigatorTelegramProviderOptionsExtensions.cs b/src/Navigator.Providers.Telegram/NavigatorTelegramProviderOptionsExtensions.cs index d02258c..e9edfb2 100644 --- a/src/Navigator.Providers.Telegram/NavigatorTelegramProviderOptionsExtensions.cs +++ b/src/Navigator.Providers.Telegram/NavigatorTelegramProviderOptionsExtensions.cs @@ -1,27 +1,10 @@ using System; -using MihaZupan.TelegramBotClients.RateLimitedClient; using Navigator.Configuration; namespace Navigator.Providers.Telegram { public static class NavigatorTelegramProviderOptionsExtensions { - #region SchedulerSettings - - private const string SchedulerSettingsKey = "_navigator.options.telegram.scheduler_settings"; - - public static void SetSchedulerSettings(this NavigatorTelegramProviderOptions navigatorOptions, SchedulerSettings schedulerSettings) - { - navigatorOptions.TryRegisterOption(SchedulerSettingsKey, schedulerSettings); - } - - public static SchedulerSettings GetSchedulerSettingsOrDefault(this INavigatorOptions navigatorOptions) - { - return navigatorOptions.RetrieveOption(SchedulerSettingsKey) ?? SchedulerSettings.Default; - } - - #endregion - #region TelegramToken private const string TelegramTokenKey = "_navigator.options.telegram.telegram_token"; From 05d7d742fe8a2c52d267731a19ae1968ccd92eee Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 19 Jul 2021 15:08:32 +0300 Subject: [PATCH 152/304] feat: implement InlineQueryAction for Telegram --- .../CallbackQueryAction.cs | 21 -------- .../InlineQueryAction.cs | 21 -------- .../Actions/InlineQueryAction.cs | 50 +++++++++++++++++++ .../TelegramMiddleware.cs | 2 +- 4 files changed, 51 insertions(+), 43 deletions(-) delete mode 100644 src/Navigator.Extensions.Actions/CallbackQueryAction.cs delete mode 100644 src/Navigator.Extensions.Actions/InlineQueryAction.cs create mode 100644 src/Navigator.Providers.Telegram/Actions/InlineQueryAction.cs diff --git a/src/Navigator.Extensions.Actions/CallbackQueryAction.cs b/src/Navigator.Extensions.Actions/CallbackQueryAction.cs deleted file mode 100644 index c9016b0..0000000 --- a/src/Navigator.Extensions.Actions/CallbackQueryAction.cs +++ /dev/null @@ -1,21 +0,0 @@ -using Navigator.Abstractions; - -namespace Navigator.Extensions.Actions -{ - public abstract class CallbackQueryAction : Action - { - public override string Type => ActionType.CallbackQuery; - - public string Data { get; set; } = string.Empty; - - public bool IsGameQuery { get; set; } - - public override IAction Init(INavigatorContext ctx) - { - Data = ctx.Update.CallbackQuery.Data; - IsGameQuery = ctx.Update.CallbackQuery.IsGameQuery; - - return this; - } - } -} \ No newline at end of file diff --git a/src/Navigator.Extensions.Actions/InlineQueryAction.cs b/src/Navigator.Extensions.Actions/InlineQueryAction.cs deleted file mode 100644 index 709f5f8..0000000 --- a/src/Navigator.Extensions.Actions/InlineQueryAction.cs +++ /dev/null @@ -1,21 +0,0 @@ -using Navigator.Abstractions; - -namespace Navigator.Extensions.Actions -{ - public abstract class InlineQueryAction : Action - { - public override string Type => ActionType.InlineQuery; - public string InlineQueryId { get; protected set; } = string.Empty; - public string Query { get; protected set; } = string.Empty; - public string Offset { get; protected set; } = string.Empty; - - public override IAction Init(INavigatorContext ctx) - { - InlineQueryId = ctx.Update.InlineQuery.Id; - Query = ctx.Update.InlineQuery.Query; - Offset = ctx.Update.InlineQuery.Offset; - - return this; - } - } -} \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/Actions/InlineQueryAction.cs b/src/Navigator.Providers.Telegram/Actions/InlineQueryAction.cs new file mode 100644 index 0000000..8d4b318 --- /dev/null +++ b/src/Navigator.Providers.Telegram/Actions/InlineQueryAction.cs @@ -0,0 +1,50 @@ +using Navigator.Actions; +using Navigator.Actions.Model; +using Navigator.Context; +using Navigator.Context.Extensions; +using Telegram.Bot.Types; + +namespace Navigator.Providers.Telegram.Actions +{ + /// + /// Inline query based action. + /// + public abstract class InlineQueryAction : BaseAction + { + /// + public override string Type { get; protected set; } = ActionsHelper.Type.For(nameof(InlineQueryAction)); + + /// + public override ushort Priority { get; protected set; } = ActionsHelper.Priority.Default; + + /// + public override IAction Init(INavigatorContext navigatorContext) + { + var update = navigatorContext.GetOriginalUpdateOrDefault(); + + if (update is not null) + { + InlineQuery = update.InlineQuery; + Query = update.InlineQuery.Query; + Offset = update.InlineQuery.Offset; + } + + return this; + } + + /// + /// The original + /// + public InlineQuery InlineQuery { get; protected set; } = null!; + + /// + /// The query from the user. + /// + public string Query { get; protected set; } = string.Empty; + + /// + /// The offset. + /// + public string Offset { get; protected set; } = string.Empty; + } +} \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/TelegramMiddleware.cs b/src/Navigator.Providers.Telegram/TelegramMiddleware.cs index f807bae..7a8c00e 100644 --- a/src/Navigator.Providers.Telegram/TelegramMiddleware.cs +++ b/src/Navigator.Providers.Telegram/TelegramMiddleware.cs @@ -64,7 +64,7 @@ await _navigatorContextFactory.Supply(builder => // MessageType.MigratedFromGroup => ActionType.MigratedFromGroup, _ => ActionsHelper.Type.For(nameof(MessageAction)) }, - // UpdateType.InlineQuery => ActionType.InlineQuery, + UpdateType.InlineQuery => ActionsHelper.Type.For(nameof(InlineQueryAction)), // UpdateType.ChosenInlineResult => ActionType.InlineResultChosen, UpdateType.CallbackQuery => ActionsHelper.Type.For(nameof(CallbackQueryAction)), UpdateType.EditedMessage => ActionsHelper.Type.For(nameof(EditedMessageAction)), From f9123a61db037f5a1fd38d4e41fbfc0c84318fdd Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 19 Jul 2021 15:26:56 +0300 Subject: [PATCH 153/304] feat: implement ChosenInlineResult action --- src/Navigator.Extensions.Actions/Action.cs | 25 ---------- .../ActionHandler.cs | 19 ------- .../EditedMessageAction.cs | 9 ---- .../InlineResultChosenAction.cs | 19 ------- .../MessageAction.cs | 22 -------- .../MessageExtension.cs | 24 --------- .../PollAction.cs | 9 ---- .../Actions/ChosenInlineResultAction.cs | 50 +++++++++++++++++++ .../TelegramMiddleware.cs | 2 +- 9 files changed, 51 insertions(+), 128 deletions(-) delete mode 100644 src/Navigator.Extensions.Actions/Action.cs delete mode 100644 src/Navigator.Extensions.Actions/ActionHandler.cs delete mode 100644 src/Navigator.Extensions.Actions/EditedMessageAction.cs delete mode 100644 src/Navigator.Extensions.Actions/InlineResultChosenAction.cs delete mode 100644 src/Navigator.Extensions.Actions/MessageAction.cs delete mode 100644 src/Navigator.Extensions.Actions/MessageExtension.cs delete mode 100644 src/Navigator.Extensions.Actions/PollAction.cs create mode 100644 src/Navigator.Providers.Telegram/Actions/ChosenInlineResultAction.cs diff --git a/src/Navigator.Extensions.Actions/Action.cs b/src/Navigator.Extensions.Actions/Action.cs deleted file mode 100644 index c8a15ec..0000000 --- a/src/Navigator.Extensions.Actions/Action.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System; -using Navigator.Abstractions; - -namespace Navigator.Extensions.Actions -{ - /// - public abstract class Action : IAction - { - /// - public virtual int Order => 1000; - - /// - public abstract string Type { get; } - - /// - public DateTime Timestamp { get; } = DateTime.UtcNow; - - /// - public abstract IAction Init(INavigatorContext ctx); - - /// - public abstract bool CanHandle(INavigatorContext ctx); - - } -} \ No newline at end of file diff --git a/src/Navigator.Extensions.Actions/ActionHandler.cs b/src/Navigator.Extensions.Actions/ActionHandler.cs deleted file mode 100644 index 287ec68..0000000 --- a/src/Navigator.Extensions.Actions/ActionHandler.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System.Threading; -using System.Threading.Tasks; -using MediatR; -using Navigator.Abstractions; - -namespace Navigator.Extensions.Actions -{ - public abstract class ActionHandler : IRequestHandler where TAction : IAction - { - public readonly INavigatorContext Ctx; - - public ActionHandler(INavigatorContext ctx) - { - Ctx = ctx; - } - - public abstract Task Handle(TAction request, CancellationToken cancellationToken); - } -} \ No newline at end of file diff --git a/src/Navigator.Extensions.Actions/EditedMessageAction.cs b/src/Navigator.Extensions.Actions/EditedMessageAction.cs deleted file mode 100644 index c938cb8..0000000 --- a/src/Navigator.Extensions.Actions/EditedMessageAction.cs +++ /dev/null @@ -1,9 +0,0 @@ -using Navigator.Abstractions; - -namespace Navigator.Extensions.Actions -{ - public abstract class EditedMessageAction : MessageAction - { - public override string Type => ActionType.EditedMessage; - } -} \ No newline at end of file diff --git a/src/Navigator.Extensions.Actions/InlineResultChosenAction.cs b/src/Navigator.Extensions.Actions/InlineResultChosenAction.cs deleted file mode 100644 index 703a6fa..0000000 --- a/src/Navigator.Extensions.Actions/InlineResultChosenAction.cs +++ /dev/null @@ -1,19 +0,0 @@ -using Navigator.Abstractions; - -namespace Navigator.Extensions.Actions -{ - public abstract class InlineResultChosenAction : Action - { - public override string Type => ActionType.InlineResultChosen; - public string ChosenResultId { get; protected set; } = string.Empty; - public string Query { get; protected set; } = string.Empty; - - public override IAction Init(INavigatorContext ctx) - { - ChosenResultId = ctx.Update.ChosenInlineResult.ResultId; - Query = ctx.Update.ChosenInlineResult.Query; - - return this; - } - } -} \ No newline at end of file diff --git a/src/Navigator.Extensions.Actions/MessageAction.cs b/src/Navigator.Extensions.Actions/MessageAction.cs deleted file mode 100644 index 6141292..0000000 --- a/src/Navigator.Extensions.Actions/MessageAction.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System; -using Navigator.Abstractions; - -namespace Navigator.Extensions.Actions -{ - public abstract class MessageAction : Action - { - public override string Type => ActionType.Message; - public DateTime MessageTimestamp { get; protected set; } - public int MessageId { get; protected set; } - public int? ReplyToMessageId { get; protected set; } - - public override IAction Init(INavigatorContext ctx) - { - MessageTimestamp = ctx.Update.Message.Date; - MessageId = ctx.Update.Message.MessageId; - ReplyToMessageId = ctx.Update.Message.ReplyToMessage?.MessageId; - - return this; - } - } -} \ No newline at end of file diff --git a/src/Navigator.Extensions.Actions/MessageExtension.cs b/src/Navigator.Extensions.Actions/MessageExtension.cs deleted file mode 100644 index 968837d..0000000 --- a/src/Navigator.Extensions.Actions/MessageExtension.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System.Linq; -using Telegram.Bot.Types; -using Telegram.Bot.Types.Enums; - -namespace Navigator.Extensions.Actions -{ - public static class MessageExtension - { - public static string? ExtractCommand(this Message message, string botName) - { - if (message.Entities?.First()?.Type != MessageEntityType.BotCommand) return default; - - var command = message.EntityValues.First(); - - if (!command.Contains('@')) return command; - - if (!command.Contains(botName)) return command; - - command = command.Substring(0, command.IndexOf('@')); - - return command; - } - } -} \ No newline at end of file diff --git a/src/Navigator.Extensions.Actions/PollAction.cs b/src/Navigator.Extensions.Actions/PollAction.cs deleted file mode 100644 index 64a2e8b..0000000 --- a/src/Navigator.Extensions.Actions/PollAction.cs +++ /dev/null @@ -1,9 +0,0 @@ -using Navigator.Abstractions; - -namespace Navigator.Extensions.Actions -{ - public abstract class PollAction : Action - { - public override string Type => ActionType.Poll; - } -} \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/Actions/ChosenInlineResultAction.cs b/src/Navigator.Providers.Telegram/Actions/ChosenInlineResultAction.cs new file mode 100644 index 0000000..7e63ddc --- /dev/null +++ b/src/Navigator.Providers.Telegram/Actions/ChosenInlineResultAction.cs @@ -0,0 +1,50 @@ +using Navigator.Actions; +using Navigator.Actions.Model; +using Navigator.Context; +using Navigator.Context.Extensions; +using Telegram.Bot.Types; + +namespace Navigator.Providers.Telegram.Actions +{ + /// + /// Inline result based action. + /// + public abstract class ChosenInlineResultAction : BaseAction + { + /// + public override string Type { get; protected set; } = ActionsHelper.Type.For(nameof(ChosenInlineResultAction)); + + /// + public override ushort Priority { get; protected set; } = ActionsHelper.Priority.Default; + + /// + public override IAction Init(INavigatorContext navigatorContext) + { + var update = navigatorContext.GetOriginalUpdateOrDefault(); + + if (update is not null) + { + ChosenInlineResult = update.ChosenInlineResult; + ResultId = update.ChosenInlineResult.ResultId; + Query = update.ChosenInlineResult.Query; + } + + return this; + } + + /// + /// The original chosen inline result. + /// + public ChosenInlineResult ChosenInlineResult { get; protected set; } = null!; + + /// + /// The chosen result id. + /// + public string ResultId { get; protected set; } = string.Empty; + + /// + /// The original query. + /// + public string Query { get; protected set; } = string.Empty; + } +} \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/TelegramMiddleware.cs b/src/Navigator.Providers.Telegram/TelegramMiddleware.cs index 7a8c00e..a11d0ea 100644 --- a/src/Navigator.Providers.Telegram/TelegramMiddleware.cs +++ b/src/Navigator.Providers.Telegram/TelegramMiddleware.cs @@ -65,7 +65,7 @@ await _navigatorContextFactory.Supply(builder => _ => ActionsHelper.Type.For(nameof(MessageAction)) }, UpdateType.InlineQuery => ActionsHelper.Type.For(nameof(InlineQueryAction)), - // UpdateType.ChosenInlineResult => ActionType.InlineResultChosen, + UpdateType.ChosenInlineResult => ActionsHelper.Type.For(nameof(ChosenInlineResult)), UpdateType.CallbackQuery => ActionsHelper.Type.For(nameof(CallbackQueryAction)), UpdateType.EditedMessage => ActionsHelper.Type.For(nameof(EditedMessageAction)), // UpdateType.ChannelPost => ActionType.ChannelPost, From 472b0c72a2ccb1312ce1d69858987c632dab4f9c Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 19 Jul 2021 15:29:04 +0300 Subject: [PATCH 154/304] chore: move Priority to its own file --- .../Actions/CallbackQueryAction.cs | 2 +- .../Actions/ChosenInlineResultAction.cs | 2 +- .../Actions/EditedMessageAction.cs | 2 +- .../Actions/InlineQueryAction.cs | 2 +- .../Actions/MessageAction.cs | 2 +- src/Navigator.Providers.Telegram/Actions/PollAction.cs | 2 +- .../Actions/UnknownAction.cs | 2 +- src/Navigator/Actions/ActionsHelper.cs | 7 ------- src/Navigator/Actions/Priority.cs | 9 +++++++++ 9 files changed, 16 insertions(+), 14 deletions(-) create mode 100644 src/Navigator/Actions/Priority.cs diff --git a/src/Navigator.Providers.Telegram/Actions/CallbackQueryAction.cs b/src/Navigator.Providers.Telegram/Actions/CallbackQueryAction.cs index 8b763d3..ae5a675 100644 --- a/src/Navigator.Providers.Telegram/Actions/CallbackQueryAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/CallbackQueryAction.cs @@ -15,7 +15,7 @@ public abstract class CallbackQueryAction : BaseAction public override string Type { get; protected set; } = ActionsHelper.Type.For(nameof(CallbackQueryAction)); /// - public override ushort Priority { get; protected set; } = ActionsHelper.Priority.Default; + public override ushort Priority { get; protected set; } = Navigator.Actions.Priority.Default; /// public override IAction Init(INavigatorContext navigatorContext) diff --git a/src/Navigator.Providers.Telegram/Actions/ChosenInlineResultAction.cs b/src/Navigator.Providers.Telegram/Actions/ChosenInlineResultAction.cs index 7e63ddc..7cb1fc5 100644 --- a/src/Navigator.Providers.Telegram/Actions/ChosenInlineResultAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/ChosenInlineResultAction.cs @@ -15,7 +15,7 @@ public abstract class ChosenInlineResultAction : BaseAction public override string Type { get; protected set; } = ActionsHelper.Type.For(nameof(ChosenInlineResultAction)); /// - public override ushort Priority { get; protected set; } = ActionsHelper.Priority.Default; + public override ushort Priority { get; protected set; } = Navigator.Actions.Priority.Default; /// public override IAction Init(INavigatorContext navigatorContext) diff --git a/src/Navigator.Providers.Telegram/Actions/EditedMessageAction.cs b/src/Navigator.Providers.Telegram/Actions/EditedMessageAction.cs index a0684ec..afb696f 100644 --- a/src/Navigator.Providers.Telegram/Actions/EditedMessageAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/EditedMessageAction.cs @@ -12,7 +12,7 @@ public abstract class EditedMessageAction : BaseAction public override string Type { get; protected set; } = ActionsHelper.Type.For(nameof(EditedMessageAction)); /// - public override ushort Priority { get; protected set; } =ActionsHelper.Priority.Default; + public override ushort Priority { get; protected set; } =Navigator.Actions.Priority.Default; /// public override IAction Init(INavigatorContext navigatorContext) diff --git a/src/Navigator.Providers.Telegram/Actions/InlineQueryAction.cs b/src/Navigator.Providers.Telegram/Actions/InlineQueryAction.cs index 8d4b318..4b8048c 100644 --- a/src/Navigator.Providers.Telegram/Actions/InlineQueryAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/InlineQueryAction.cs @@ -15,7 +15,7 @@ public abstract class InlineQueryAction : BaseAction public override string Type { get; protected set; } = ActionsHelper.Type.For(nameof(InlineQueryAction)); /// - public override ushort Priority { get; protected set; } = ActionsHelper.Priority.Default; + public override ushort Priority { get; protected set; } = Navigator.Actions.Priority.Default; /// public override IAction Init(INavigatorContext navigatorContext) diff --git a/src/Navigator.Providers.Telegram/Actions/MessageAction.cs b/src/Navigator.Providers.Telegram/Actions/MessageAction.cs index e8b5cd8..5f8a8ab 100644 --- a/src/Navigator.Providers.Telegram/Actions/MessageAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/MessageAction.cs @@ -15,7 +15,7 @@ public abstract class MessageAction : BaseAction public override string Type { get; protected set; } = ActionsHelper.Type.For(nameof(MessageAction)); /// - public override ushort Priority { get; protected set; } = ActionsHelper.Priority.Default; + public override ushort Priority { get; protected set; } = Navigator.Actions.Priority.Default; /// public override IAction Init(INavigatorContext navigatorContext) diff --git a/src/Navigator.Providers.Telegram/Actions/PollAction.cs b/src/Navigator.Providers.Telegram/Actions/PollAction.cs index 00dd8eb..c31272a 100644 --- a/src/Navigator.Providers.Telegram/Actions/PollAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/PollAction.cs @@ -12,7 +12,7 @@ public abstract class PollAction : BaseAction public override string Type { get; protected set; } = ActionsHelper.Type.For(nameof(PollAction)); /// - public override ushort Priority { get; protected set; } = ActionsHelper.Priority.Default; + public override ushort Priority { get; protected set; } = Navigator.Actions.Priority.Default; /// public override IAction Init(INavigatorContext navigatorContext) diff --git a/src/Navigator.Providers.Telegram/Actions/UnknownAction.cs b/src/Navigator.Providers.Telegram/Actions/UnknownAction.cs index f3adef5..9883556 100644 --- a/src/Navigator.Providers.Telegram/Actions/UnknownAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/UnknownAction.cs @@ -9,6 +9,6 @@ public abstract class UnknownAction : BaseAction public override string Type { get; protected set; } = ActionsHelper.Type.For(nameof(UnknownAction)); /// - public override ushort Priority { get; protected set; } = ActionsHelper.Priority.Default; + public override ushort Priority { get; protected set; } = Navigator.Actions.Priority.Default; } } \ No newline at end of file diff --git a/src/Navigator/Actions/ActionsHelper.cs b/src/Navigator/Actions/ActionsHelper.cs index cfc5391..94ab1a0 100644 --- a/src/Navigator/Actions/ActionsHelper.cs +++ b/src/Navigator/Actions/ActionsHelper.cs @@ -2,13 +2,6 @@ namespace Navigator.Actions { public static class ActionsHelper { - public static class Priority - { - public static ushort Low = 15000; - public static ushort Default = 10000; - public static ushort High = 5000; - } - public static class Type { public static string For(string name) where TProvider : INavigatorProvider diff --git a/src/Navigator/Actions/Priority.cs b/src/Navigator/Actions/Priority.cs new file mode 100644 index 0000000..81a3665 --- /dev/null +++ b/src/Navigator/Actions/Priority.cs @@ -0,0 +1,9 @@ +namespace Navigator.Actions +{ + public static class Priority + { + public static ushort Low = 15000; + public static ushort Default = 10000; + public static ushort High = 5000; + } +} \ No newline at end of file From 0e2fa271d4a606a404725a86cd6e094e8755bf67 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 19 Jul 2021 16:58:33 +0300 Subject: [PATCH 155/304] chore: move files around --- .../Actions/CallbackQueryAction.cs | 4 ---- .../Actions/ChosenInlineResultAction.cs | 4 ---- .../Actions/CommandAction.cs | 2 -- .../Actions/EditedMessageAction.cs | 4 ---- .../Actions/InlineQueryAction.cs | 4 ---- .../Actions/MessageAction.cs | 4 ---- src/Navigator.Providers.Telegram/Actions/PollAction.cs | 4 ---- .../Actions/UnknownAction.cs | 4 ---- .../NavigatorTelegramProviderOptionsExtensions.cs | 2 +- src/Navigator.Samples.Echo/Actions/EchoAction.cs | 6 ++++-- src/Navigator.Samples.Echo/Actions/EchoActionHandler.cs | 3 +-- .../Actions/EditedEchoActionHandler.cs | 3 +-- src/Navigator.Samples.Echo/Navigator.Samples.Echo.csproj | 3 --- src/Navigator/Actions/ActionHandler.cs | 9 ++++----- src/Navigator/Actions/ActionLauncher.cs | 1 - src/Navigator/Actions/{Model => }/BaseAction.cs | 4 ++-- src/Navigator/Actions/Filters/ActionFilter.cs | 5 ++--- src/Navigator/Actions/Filters/CooldownActionFilter.cs | 5 ++--- src/Navigator/Actions/{Model => }/IAction.cs | 4 ++-- .../Actions/{Model/ActionStatus.cs => Status.cs} | 6 +++--- src/Navigator/ServiceCollectionExtensions.cs | 1 - 21 files changed, 22 insertions(+), 60 deletions(-) rename src/Navigator/Actions/{Model => }/BaseAction.cs (87%) rename src/Navigator/Actions/{Model => }/IAction.cs (91%) rename src/Navigator/Actions/{Model/ActionStatus.cs => Status.cs} (65%) diff --git a/src/Navigator.Providers.Telegram/Actions/CallbackQueryAction.cs b/src/Navigator.Providers.Telegram/Actions/CallbackQueryAction.cs index ae5a675..ed2fd53 100644 --- a/src/Navigator.Providers.Telegram/Actions/CallbackQueryAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/CallbackQueryAction.cs @@ -1,5 +1,4 @@ using Navigator.Actions; -using Navigator.Actions.Model; using Navigator.Context; using Navigator.Context.Extensions; using Telegram.Bot.Types; @@ -14,9 +13,6 @@ public abstract class CallbackQueryAction : BaseAction /// public override string Type { get; protected set; } = ActionsHelper.Type.For(nameof(CallbackQueryAction)); - /// - public override ushort Priority { get; protected set; } = Navigator.Actions.Priority.Default; - /// public override IAction Init(INavigatorContext navigatorContext) { diff --git a/src/Navigator.Providers.Telegram/Actions/ChosenInlineResultAction.cs b/src/Navigator.Providers.Telegram/Actions/ChosenInlineResultAction.cs index 7cb1fc5..6e44bd0 100644 --- a/src/Navigator.Providers.Telegram/Actions/ChosenInlineResultAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/ChosenInlineResultAction.cs @@ -1,5 +1,4 @@ using Navigator.Actions; -using Navigator.Actions.Model; using Navigator.Context; using Navigator.Context.Extensions; using Telegram.Bot.Types; @@ -14,9 +13,6 @@ public abstract class ChosenInlineResultAction : BaseAction /// public override string Type { get; protected set; } = ActionsHelper.Type.For(nameof(ChosenInlineResultAction)); - /// - public override ushort Priority { get; protected set; } = Navigator.Actions.Priority.Default; - /// public override IAction Init(INavigatorContext navigatorContext) { diff --git a/src/Navigator.Providers.Telegram/Actions/CommandAction.cs b/src/Navigator.Providers.Telegram/Actions/CommandAction.cs index 4f0e834..d04014e 100644 --- a/src/Navigator.Providers.Telegram/Actions/CommandAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/CommandAction.cs @@ -1,5 +1,4 @@ using Navigator.Actions; -using Navigator.Actions.Model; using Navigator.Context; using Navigator.Providers.Telegram.Extensions; @@ -19,7 +18,6 @@ public override IAction Init(INavigatorContext navigatorContext) base.Init(navigatorContext); Command = Message.ExtractCommand(navigatorContext.BotProfile.Username) ?? string.Empty; - Arguments = Message.ExtractArguments(navigatorContext.BotProfile.Username); return this; diff --git a/src/Navigator.Providers.Telegram/Actions/EditedMessageAction.cs b/src/Navigator.Providers.Telegram/Actions/EditedMessageAction.cs index afb696f..67a7750 100644 --- a/src/Navigator.Providers.Telegram/Actions/EditedMessageAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/EditedMessageAction.cs @@ -1,5 +1,4 @@ using Navigator.Actions; -using Navigator.Actions.Model; using Navigator.Context; using Navigator.Context.Extensions; using Telegram.Bot.Types; @@ -11,9 +10,6 @@ public abstract class EditedMessageAction : BaseAction /// public override string Type { get; protected set; } = ActionsHelper.Type.For(nameof(EditedMessageAction)); - /// - public override ushort Priority { get; protected set; } =Navigator.Actions.Priority.Default; - /// public override IAction Init(INavigatorContext navigatorContext) { diff --git a/src/Navigator.Providers.Telegram/Actions/InlineQueryAction.cs b/src/Navigator.Providers.Telegram/Actions/InlineQueryAction.cs index 4b8048c..5b6f1be 100644 --- a/src/Navigator.Providers.Telegram/Actions/InlineQueryAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/InlineQueryAction.cs @@ -1,5 +1,4 @@ using Navigator.Actions; -using Navigator.Actions.Model; using Navigator.Context; using Navigator.Context.Extensions; using Telegram.Bot.Types; @@ -14,9 +13,6 @@ public abstract class InlineQueryAction : BaseAction /// public override string Type { get; protected set; } = ActionsHelper.Type.For(nameof(InlineQueryAction)); - /// - public override ushort Priority { get; protected set; } = Navigator.Actions.Priority.Default; - /// public override IAction Init(INavigatorContext navigatorContext) { diff --git a/src/Navigator.Providers.Telegram/Actions/MessageAction.cs b/src/Navigator.Providers.Telegram/Actions/MessageAction.cs index 5f8a8ab..85566dd 100644 --- a/src/Navigator.Providers.Telegram/Actions/MessageAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/MessageAction.cs @@ -1,5 +1,4 @@ using Navigator.Actions; -using Navigator.Actions.Model; using Navigator.Context; using Navigator.Context.Extensions; using Telegram.Bot.Types; @@ -14,9 +13,6 @@ public abstract class MessageAction : BaseAction /// public override string Type { get; protected set; } = ActionsHelper.Type.For(nameof(MessageAction)); - /// - public override ushort Priority { get; protected set; } = Navigator.Actions.Priority.Default; - /// public override IAction Init(INavigatorContext navigatorContext) { diff --git a/src/Navigator.Providers.Telegram/Actions/PollAction.cs b/src/Navigator.Providers.Telegram/Actions/PollAction.cs index c31272a..14c1aa8 100644 --- a/src/Navigator.Providers.Telegram/Actions/PollAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/PollAction.cs @@ -1,5 +1,4 @@ using Navigator.Actions; -using Navigator.Actions.Model; using Navigator.Context; using Navigator.Context.Extensions; using Telegram.Bot.Types; @@ -11,9 +10,6 @@ public abstract class PollAction : BaseAction /// public override string Type { get; protected set; } = ActionsHelper.Type.For(nameof(PollAction)); - /// - public override ushort Priority { get; protected set; } = Navigator.Actions.Priority.Default; - /// public override IAction Init(INavigatorContext navigatorContext) { diff --git a/src/Navigator.Providers.Telegram/Actions/UnknownAction.cs b/src/Navigator.Providers.Telegram/Actions/UnknownAction.cs index 9883556..1ffb743 100644 --- a/src/Navigator.Providers.Telegram/Actions/UnknownAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/UnknownAction.cs @@ -1,5 +1,4 @@ using Navigator.Actions; -using Navigator.Actions.Model; namespace Navigator.Providers.Telegram.Actions { @@ -7,8 +6,5 @@ public abstract class UnknownAction : BaseAction { /// public override string Type { get; protected set; } = ActionsHelper.Type.For(nameof(UnknownAction)); - - /// - public override ushort Priority { get; protected set; } = Navigator.Actions.Priority.Default; } } \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/NavigatorTelegramProviderOptionsExtensions.cs b/src/Navigator.Providers.Telegram/NavigatorTelegramProviderOptionsExtensions.cs index e9edfb2..05197c4 100644 --- a/src/Navigator.Providers.Telegram/NavigatorTelegramProviderOptionsExtensions.cs +++ b/src/Navigator.Providers.Telegram/NavigatorTelegramProviderOptionsExtensions.cs @@ -37,7 +37,7 @@ public static string GetWebHookEndpointOrDefault(this INavigatorOptions navigato if (webHookEndpoint is null) { - navigatorOptions.TryRegisterOption(WebHookEndpointKey,$"bot/{Guid.NewGuid()}"); + navigatorOptions.TryRegisterOption(WebHookEndpointKey,$"telegram/bot/{Guid.NewGuid()}"); } return navigatorOptions.RetrieveOption(WebHookEndpointKey)!; diff --git a/src/Navigator.Samples.Echo/Actions/EchoAction.cs b/src/Navigator.Samples.Echo/Actions/EchoAction.cs index 699c4eb..311ced5 100644 --- a/src/Navigator.Samples.Echo/Actions/EchoAction.cs +++ b/src/Navigator.Samples.Echo/Actions/EchoAction.cs @@ -1,4 +1,4 @@ -using Navigator.Actions.Model; +using Navigator.Actions; using Navigator.Context; using Navigator.Providers.Telegram.Actions; @@ -12,7 +12,9 @@ public EchoAction() } public string MessageToEcho { get; set; } - + + public override ushort Priority { get; protected set; } = Navigator.Actions.Priority.High; + public override IAction Init(INavigatorContext ctx) { base.Init(ctx); diff --git a/src/Navigator.Samples.Echo/Actions/EchoActionHandler.cs b/src/Navigator.Samples.Echo/Actions/EchoActionHandler.cs index b92b430..9d45e1d 100644 --- a/src/Navigator.Samples.Echo/Actions/EchoActionHandler.cs +++ b/src/Navigator.Samples.Echo/Actions/EchoActionHandler.cs @@ -2,7 +2,6 @@ using System.Threading.Tasks; using MediatR; using Navigator.Actions; -using Navigator.Actions.Model; using Navigator.Context; using Navigator.Providers.Telegram; @@ -14,7 +13,7 @@ public EchoActionHandler(INavigatorContextAccessor navigatorContextAccessor) : b { } - public override async Task Handle(EchoAction action, CancellationToken cancellationToken) + public override async Task Handle(EchoAction action, CancellationToken cancellationToken) { await NavigatorContext.Provider.GetTelegramClient().SendTextMessageAsync(NavigatorContext.GetTelegramChat(), action.MessageToEcho, cancellationToken: cancellationToken); diff --git a/src/Navigator.Samples.Echo/Actions/EditedEchoActionHandler.cs b/src/Navigator.Samples.Echo/Actions/EditedEchoActionHandler.cs index 09a154b..608d91c 100644 --- a/src/Navigator.Samples.Echo/Actions/EditedEchoActionHandler.cs +++ b/src/Navigator.Samples.Echo/Actions/EditedEchoActionHandler.cs @@ -2,7 +2,6 @@ using System.Threading.Tasks; using MediatR; using Navigator.Actions; -using Navigator.Actions.Model; using Navigator.Context; using Navigator.Providers.Telegram; @@ -14,7 +13,7 @@ public EditedEchoActionHandler(INavigatorContextAccessor navigatorContextAccesso { } - public override async Task Handle(EditedEchoAction action, CancellationToken cancellationToken) + public override async Task Handle(EditedEchoAction action, CancellationToken cancellationToken) { await NavigatorContext.Provider.GetTelegramClient().SendTextMessageAsync(NavigatorContext.GetTelegramChat(), action.EditedMessage.Text, cancellationToken: cancellationToken); diff --git a/src/Navigator.Samples.Echo/Navigator.Samples.Echo.csproj b/src/Navigator.Samples.Echo/Navigator.Samples.Echo.csproj index 599182c..3676fe1 100644 --- a/src/Navigator.Samples.Echo/Navigator.Samples.Echo.csproj +++ b/src/Navigator.Samples.Echo/Navigator.Samples.Echo.csproj @@ -10,9 +10,6 @@ - - - diff --git a/src/Navigator/Actions/ActionHandler.cs b/src/Navigator/Actions/ActionHandler.cs index d2d1d6f..5609ec2 100644 --- a/src/Navigator/Actions/ActionHandler.cs +++ b/src/Navigator/Actions/ActionHandler.cs @@ -2,13 +2,12 @@ using System.Threading; using System.Threading.Tasks; using MediatR; -using Navigator.Actions.Model; using Navigator.Context; using Navigator.Replies; namespace Navigator.Actions { - public abstract class ActionHandler : IRequestHandler where TAction : IAction + public abstract class ActionHandler : IRequestHandler where TAction : IAction { public INavigatorContext NavigatorContext; @@ -17,14 +16,14 @@ protected ActionHandler(INavigatorContextAccessor navigatorContextAccessor) NavigatorContext = navigatorContextAccessor.NavigatorContext; } - public abstract Task Handle(TAction action, CancellationToken cancellationToken); + public abstract Task Handle(TAction action, CancellationToken cancellationToken); - public static ActionStatus Success() + public static Status Success() { return new(true); } - public static ActionStatus Error() + public static Status Error() { return new(false); } diff --git a/src/Navigator/Actions/ActionLauncher.cs b/src/Navigator/Actions/ActionLauncher.cs index cc43fc1..71b32e2 100644 --- a/src/Navigator/Actions/ActionLauncher.cs +++ b/src/Navigator/Actions/ActionLauncher.cs @@ -3,7 +3,6 @@ using System.Linq; using System.Threading.Tasks; using MediatR; -using Navigator.Actions.Model; using Navigator.Configuration; using Navigator.Context; diff --git a/src/Navigator/Actions/Model/BaseAction.cs b/src/Navigator/Actions/BaseAction.cs similarity index 87% rename from src/Navigator/Actions/Model/BaseAction.cs rename to src/Navigator/Actions/BaseAction.cs index ecf03b7..5e5b852 100644 --- a/src/Navigator/Actions/Model/BaseAction.cs +++ b/src/Navigator/Actions/BaseAction.cs @@ -1,7 +1,7 @@ using System; using Navigator.Context; -namespace Navigator.Actions.Model +namespace Navigator.Actions { /// /// Base action to use for any action. @@ -12,7 +12,7 @@ public abstract class BaseAction : IAction public abstract string Type { get; protected set; } /// - public abstract ushort Priority { get; protected set; } + public virtual ushort Priority { get; protected set; } = Actions.Priority.Default; /// /// Timestamp of the request on creation. diff --git a/src/Navigator/Actions/Filters/ActionFilter.cs b/src/Navigator/Actions/Filters/ActionFilter.cs index b6badb2..4ce458a 100644 --- a/src/Navigator/Actions/Filters/ActionFilter.cs +++ b/src/Navigator/Actions/Filters/ActionFilter.cs @@ -1,12 +1,11 @@ using System.Threading; using System.Threading.Tasks; using MediatR; -using Navigator.Actions.Model; namespace Navigator.Actions.Filters { - public abstract class ActionFilter : IPipelineBehavior where TAction : IAction + public abstract class ActionFilter : IPipelineBehavior where TAction : IAction { - public abstract Task Handle(TAction action, CancellationToken cancellationToken, RequestHandlerDelegate next); + public abstract Task Handle(TAction action, CancellationToken cancellationToken, RequestHandlerDelegate next); } } \ No newline at end of file diff --git a/src/Navigator/Actions/Filters/CooldownActionFilter.cs b/src/Navigator/Actions/Filters/CooldownActionFilter.cs index b492322..f938fc0 100644 --- a/src/Navigator/Actions/Filters/CooldownActionFilter.cs +++ b/src/Navigator/Actions/Filters/CooldownActionFilter.cs @@ -2,7 +2,6 @@ using System.Threading.Tasks; using MediatR; using Microsoft.Extensions.Caching.Distributed; -using Navigator.Actions.Model; using Navigator.Context; namespace Navigator.Actions.Filters @@ -17,7 +16,7 @@ public CooldownActionFilter(IDistributedCache cache, INavigatorContextAccessor n _navigatorContext = navigatorContextAccessor.NavigatorContext; } - public override async Task Handle(TAction action, CancellationToken cancellationToken, RequestHandlerDelegate next) + public override async Task Handle(TAction action, CancellationToken cancellationToken, RequestHandlerDelegate next) { var key = GenerateKey(action); @@ -25,7 +24,7 @@ public override async Task Handle(TAction action, CancellationToke if (cooldownStatus is not null) { - return new ActionStatus(true); + return new Status(true); } var status = await next(); diff --git a/src/Navigator/Actions/Model/IAction.cs b/src/Navigator/Actions/IAction.cs similarity index 91% rename from src/Navigator/Actions/Model/IAction.cs rename to src/Navigator/Actions/IAction.cs index 8ec333c..9b66b48 100644 --- a/src/Navigator/Actions/Model/IAction.cs +++ b/src/Navigator/Actions/IAction.cs @@ -1,12 +1,12 @@ using MediatR; using Navigator.Context; -namespace Navigator.Actions.Model +namespace Navigator.Actions { /// /// Base contract for an action. /// - public interface IAction : IRequest + public interface IAction : IRequest { /// /// Type of the action. diff --git a/src/Navigator/Actions/Model/ActionStatus.cs b/src/Navigator/Actions/Status.cs similarity index 65% rename from src/Navigator/Actions/Model/ActionStatus.cs rename to src/Navigator/Actions/Status.cs index 20c0abb..842b47b 100644 --- a/src/Navigator/Actions/Model/ActionStatus.cs +++ b/src/Navigator/Actions/Status.cs @@ -1,13 +1,13 @@ -namespace Navigator.Actions.Model +namespace Navigator.Actions { - public struct ActionStatus + public struct Status { private readonly bool _isSuccess; public bool IsSuccess => _isSuccess; public bool IsError => !_isSuccess; - public ActionStatus(bool isSuccess) + public Status(bool isSuccess) { _isSuccess = isSuccess; } diff --git a/src/Navigator/ServiceCollectionExtensions.cs b/src/Navigator/ServiceCollectionExtensions.cs index 7d907d9..9e27776 100644 --- a/src/Navigator/ServiceCollectionExtensions.cs +++ b/src/Navigator/ServiceCollectionExtensions.cs @@ -2,7 +2,6 @@ using MediatR; using Microsoft.Extensions.DependencyInjection; using Navigator.Actions; -using Navigator.Actions.Model; using Navigator.Configuration; using Navigator.Context; using Navigator.Context.Extensions; From f155f53c1ac4bb2ec66ad30486eb76c253d3ea3c Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 17 Aug 2021 20:48:57 +0300 Subject: [PATCH 156/304] feat: changes --- .../Actions/{ => Message}/CommandAction.cs | 4 +- .../Actions/{ => Message}/MessageAction.cs | 18 ++++++--- .../Actions/UnknownAction.cs | 2 +- .../{ => Update}/CallbackQueryAction.cs | 10 ++--- .../{ => Update}/ChosenInlineResultAction.cs | 6 +-- .../Actions/Update/DocumentAction.cs | 22 +++++++++++ .../{ => Update}/EditedMessageAction.cs | 11 +++--- .../Actions/{ => Update}/InlineQueryAction.cs | 6 +-- .../Actions/{ => Update}/PollAction.cs | 9 +++-- .../TelegramMiddleware.cs | 37 ++++++++++++++----- .../Actions/EchoAction.cs | 1 + .../Actions/EditedEchoAction.cs | 1 + src/Navigator/Actions/ActionLauncher.cs | 10 ++--- src/Navigator/Actions/ActionsHelper.cs | 13 ------- src/Navigator/INavigatorProvider.cs | 2 - 15 files changed, 95 insertions(+), 57 deletions(-) rename src/Navigator.Providers.Telegram/Actions/{ => Message}/CommandAction.cs (84%) rename src/Navigator.Providers.Telegram/Actions/{ => Message}/MessageAction.cs (58%) rename src/Navigator.Providers.Telegram/Actions/{ => Update}/CallbackQueryAction.cs (83%) rename src/Navigator.Providers.Telegram/Actions/{ => Update}/ChosenInlineResultAction.cs (85%) create mode 100644 src/Navigator.Providers.Telegram/Actions/Update/DocumentAction.cs rename src/Navigator.Providers.Telegram/Actions/{ => Update}/EditedMessageAction.cs (57%) rename src/Navigator.Providers.Telegram/Actions/{ => Update}/InlineQueryAction.cs (85%) rename src/Navigator.Providers.Telegram/Actions/{ => Update}/PollAction.cs (68%) delete mode 100644 src/Navigator/Actions/ActionsHelper.cs diff --git a/src/Navigator.Providers.Telegram/Actions/CommandAction.cs b/src/Navigator.Providers.Telegram/Actions/Message/CommandAction.cs similarity index 84% rename from src/Navigator.Providers.Telegram/Actions/CommandAction.cs rename to src/Navigator.Providers.Telegram/Actions/Message/CommandAction.cs index d04014e..e0421eb 100644 --- a/src/Navigator.Providers.Telegram/Actions/CommandAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Message/CommandAction.cs @@ -2,7 +2,7 @@ using Navigator.Context; using Navigator.Providers.Telegram.Extensions; -namespace Navigator.Providers.Telegram.Actions +namespace Navigator.Providers.Telegram.Actions.Message { /// /// Command based action. @@ -10,7 +10,7 @@ namespace Navigator.Providers.Telegram.Actions public abstract class CommandAction : MessageAction { /// - public override string Type { get; protected set; } = ActionsHelper.Type.For(nameof(CommandAction)); + public override string Type { get; protected set; } = typeof(CommandAction).FullName!; /// public override IAction Init(INavigatorContext navigatorContext) diff --git a/src/Navigator.Providers.Telegram/Actions/MessageAction.cs b/src/Navigator.Providers.Telegram/Actions/Message/MessageAction.cs similarity index 58% rename from src/Navigator.Providers.Telegram/Actions/MessageAction.cs rename to src/Navigator.Providers.Telegram/Actions/Message/MessageAction.cs index 85566dd..dffe41c 100644 --- a/src/Navigator.Providers.Telegram/Actions/MessageAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Message/MessageAction.cs @@ -1,9 +1,8 @@ using Navigator.Actions; using Navigator.Context; using Navigator.Context.Extensions; -using Telegram.Bot.Types; -namespace Navigator.Providers.Telegram.Actions +namespace Navigator.Providers.Telegram.Actions.Message { /// /// A message based action. @@ -11,12 +10,12 @@ namespace Navigator.Providers.Telegram.Actions public abstract class MessageAction : BaseAction { /// - public override string Type { get; protected set; } = ActionsHelper.Type.For(nameof(MessageAction)); + public override string Type { get; protected set; } = typeof(MessageAction).FullName!; /// public override IAction Init(INavigatorContext navigatorContext) { - var update = navigatorContext.GetOriginalUpdateOrDefault(); + var update = navigatorContext.GetOriginalUpdateOrDefault(); if (update is not null) { @@ -28,10 +27,19 @@ public override IAction Init(INavigatorContext navigatorContext) return this; } - public Message Message { get; protected set; } = null!; + /// + /// The original Message. + /// + public global::Telegram.Bot.Types.Message Message { get; protected set; } = null!; + /// + /// Determines if this message is a reply to another message. + /// public bool IsReply { get; protected set; } + /// + /// Determines if this message is a forwarded message. + /// public bool IsForwarded { get; protected set; } } } \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/Actions/UnknownAction.cs b/src/Navigator.Providers.Telegram/Actions/UnknownAction.cs index 1ffb743..cda1aca 100644 --- a/src/Navigator.Providers.Telegram/Actions/UnknownAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/UnknownAction.cs @@ -5,6 +5,6 @@ namespace Navigator.Providers.Telegram.Actions public abstract class UnknownAction : BaseAction { /// - public override string Type { get; protected set; } = ActionsHelper.Type.For(nameof(UnknownAction)); + public override string Type { get; protected set; } = typeof(UnknownAction).FullName!; } } \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/Actions/CallbackQueryAction.cs b/src/Navigator.Providers.Telegram/Actions/Update/CallbackQueryAction.cs similarity index 83% rename from src/Navigator.Providers.Telegram/Actions/CallbackQueryAction.cs rename to src/Navigator.Providers.Telegram/Actions/Update/CallbackQueryAction.cs index ed2fd53..11048d0 100644 --- a/src/Navigator.Providers.Telegram/Actions/CallbackQueryAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Update/CallbackQueryAction.cs @@ -3,7 +3,7 @@ using Navigator.Context.Extensions; using Telegram.Bot.Types; -namespace Navigator.Providers.Telegram.Actions +namespace Navigator.Providers.Telegram.Actions.Update { /// /// A callback query based action. @@ -11,12 +11,12 @@ namespace Navigator.Providers.Telegram.Actions public abstract class CallbackQueryAction : BaseAction { /// - public override string Type { get; protected set; } = ActionsHelper.Type.For(nameof(CallbackQueryAction)); + public override string Type { get; protected set; } = typeof(CallbackQueryAction).FullName!; /// public override IAction Init(INavigatorContext navigatorContext) { - var update = navigatorContext.GetOriginalUpdateOrDefault(); + var update = navigatorContext.GetOriginalUpdateOrDefault(); if (update is not null) { @@ -27,7 +27,7 @@ public override IAction Init(INavigatorContext navigatorContext) } return this; - } + } /// /// The original @@ -37,7 +37,7 @@ public override IAction Init(INavigatorContext navigatorContext) /// /// The message that originated the callback query. Iy may be null if the message is too old. /// - public Message? OriginalMessage { get; protected set; } + public global::Telegram.Bot.Types.Message? OriginalMessage { get; protected set; } /// /// Any data present on the callback query. diff --git a/src/Navigator.Providers.Telegram/Actions/ChosenInlineResultAction.cs b/src/Navigator.Providers.Telegram/Actions/Update/ChosenInlineResultAction.cs similarity index 85% rename from src/Navigator.Providers.Telegram/Actions/ChosenInlineResultAction.cs rename to src/Navigator.Providers.Telegram/Actions/Update/ChosenInlineResultAction.cs index 6e44bd0..bab17e9 100644 --- a/src/Navigator.Providers.Telegram/Actions/ChosenInlineResultAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Update/ChosenInlineResultAction.cs @@ -3,7 +3,7 @@ using Navigator.Context.Extensions; using Telegram.Bot.Types; -namespace Navigator.Providers.Telegram.Actions +namespace Navigator.Providers.Telegram.Actions.Update { /// /// Inline result based action. @@ -11,12 +11,12 @@ namespace Navigator.Providers.Telegram.Actions public abstract class ChosenInlineResultAction : BaseAction { /// - public override string Type { get; protected set; } = ActionsHelper.Type.For(nameof(ChosenInlineResultAction)); + public override string Type { get; protected set; } = typeof(ChosenInlineResultAction).FullName!; /// public override IAction Init(INavigatorContext navigatorContext) { - var update = navigatorContext.GetOriginalUpdateOrDefault(); + var update = navigatorContext.GetOriginalUpdateOrDefault(); if (update is not null) { diff --git a/src/Navigator.Providers.Telegram/Actions/Update/DocumentAction.cs b/src/Navigator.Providers.Telegram/Actions/Update/DocumentAction.cs new file mode 100644 index 0000000..d0448e9 --- /dev/null +++ b/src/Navigator.Providers.Telegram/Actions/Update/DocumentAction.cs @@ -0,0 +1,22 @@ +using Navigator.Actions; +using Navigator.Context; +using Navigator.Context.Extensions; +using Telegram.Bot.Types; + +namespace Navigator.Providers.Telegram.Actions.Update +{ + public class DocumentAction : BaseAction + { + public override string Type { get; protected set; } = typeof(DocumentAction).FullName!; + + public override IAction Init(INavigatorContext navigatorContext) + { + throw new System.NotImplementedException(); + } + + public override bool CanHandle(INavigatorContext ctx) + { + throw new System.NotImplementedException(); + } + } +} \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/Actions/EditedMessageAction.cs b/src/Navigator.Providers.Telegram/Actions/Update/EditedMessageAction.cs similarity index 57% rename from src/Navigator.Providers.Telegram/Actions/EditedMessageAction.cs rename to src/Navigator.Providers.Telegram/Actions/Update/EditedMessageAction.cs index 67a7750..6af5eb8 100644 --- a/src/Navigator.Providers.Telegram/Actions/EditedMessageAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Update/EditedMessageAction.cs @@ -1,19 +1,18 @@ using Navigator.Actions; using Navigator.Context; using Navigator.Context.Extensions; -using Telegram.Bot.Types; -namespace Navigator.Providers.Telegram.Actions +namespace Navigator.Providers.Telegram.Actions.Update { public abstract class EditedMessageAction : BaseAction { /// - public override string Type { get; protected set; } = ActionsHelper.Type.For(nameof(EditedMessageAction)); + public override string Type { get; protected set; } = typeof(EditedMessageAction).FullName!; /// public override IAction Init(INavigatorContext navigatorContext) { - var update = navigatorContext.GetOriginalUpdateOrDefault(); + var update = navigatorContext.GetOriginalUpdateOrDefault(); if (update is not null) { @@ -23,8 +22,8 @@ public override IAction Init(INavigatorContext navigatorContext) return this; } - public Message OriginalMessage { get; protected set; } = null!; - public Message EditedMessage { get; protected set; } = null!; + public global::Telegram.Bot.Types.Message OriginalMessage { get; protected set; } = null!; + public global::Telegram.Bot.Types.Message EditedMessage { get; protected set; } = null!; } } \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/Actions/InlineQueryAction.cs b/src/Navigator.Providers.Telegram/Actions/Update/InlineQueryAction.cs similarity index 85% rename from src/Navigator.Providers.Telegram/Actions/InlineQueryAction.cs rename to src/Navigator.Providers.Telegram/Actions/Update/InlineQueryAction.cs index 5b6f1be..17852d0 100644 --- a/src/Navigator.Providers.Telegram/Actions/InlineQueryAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Update/InlineQueryAction.cs @@ -3,7 +3,7 @@ using Navigator.Context.Extensions; using Telegram.Bot.Types; -namespace Navigator.Providers.Telegram.Actions +namespace Navigator.Providers.Telegram.Actions.Update { /// /// Inline query based action. @@ -11,12 +11,12 @@ namespace Navigator.Providers.Telegram.Actions public abstract class InlineQueryAction : BaseAction { /// - public override string Type { get; protected set; } = ActionsHelper.Type.For(nameof(InlineQueryAction)); + public override string Type { get; protected set; } = typeof(InlineQueryAction).FullName!; /// public override IAction Init(INavigatorContext navigatorContext) { - var update = navigatorContext.GetOriginalUpdateOrDefault(); + var update = navigatorContext.GetOriginalUpdateOrDefault(); if (update is not null) { diff --git a/src/Navigator.Providers.Telegram/Actions/PollAction.cs b/src/Navigator.Providers.Telegram/Actions/Update/PollAction.cs similarity index 68% rename from src/Navigator.Providers.Telegram/Actions/PollAction.cs rename to src/Navigator.Providers.Telegram/Actions/Update/PollAction.cs index 14c1aa8..a22ec54 100644 --- a/src/Navigator.Providers.Telegram/Actions/PollAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Update/PollAction.cs @@ -3,17 +3,17 @@ using Navigator.Context.Extensions; using Telegram.Bot.Types; -namespace Navigator.Providers.Telegram.Actions +namespace Navigator.Providers.Telegram.Actions.Update { public abstract class PollAction : BaseAction { /// - public override string Type { get; protected set; } = ActionsHelper.Type.For(nameof(PollAction)); + public override string Type { get; protected set; } = typeof(PollAction).FullName!; /// public override IAction Init(INavigatorContext navigatorContext) { - var update = navigatorContext.GetOriginalUpdateOrDefault(); + var update = navigatorContext.GetOriginalUpdateOrDefault(); if (update is not null) { @@ -23,6 +23,9 @@ public override IAction Init(INavigatorContext navigatorContext) return this; } + /// + /// The original Poll. + /// public Poll Poll { get; protected set; } = null!; } } \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/TelegramMiddleware.cs b/src/Navigator.Providers.Telegram/TelegramMiddleware.cs index a11d0ea..ea00c75 100644 --- a/src/Navigator.Providers.Telegram/TelegramMiddleware.cs +++ b/src/Navigator.Providers.Telegram/TelegramMiddleware.cs @@ -4,6 +4,8 @@ using Navigator.Actions; using Navigator.Context; using Navigator.Providers.Telegram.Actions; +using Navigator.Providers.Telegram.Actions.Message; +using Navigator.Providers.Telegram.Actions.Update; using Navigator.Providers.Telegram.Entities; using Navigator.Providers.Telegram.Extensions; using Telegram.Bot.Types; @@ -44,13 +46,20 @@ await _navigatorContextFactory.Supply(builder => await _actionLauncher.Launch(); } - private string? DefineActionType(Update update) + private static string? DefineActionType(Update update) { return update.Type switch { - UpdateType.Message when update.Message.Entities?.First()?.Type == MessageEntityType.BotCommand => ActionsHelper.Type.For(nameof(CommandAction)), + UpdateType.Message when update.Message.Entities?.First()?.Type == MessageEntityType.BotCommand => typeof(CommandAction).FullName, UpdateType.Message => update.Message.Type switch { + // MessageType.Document => ActionType.ChatMembersAdded, + // MessageType.Location => ActionType.ChatMembersAdded, + // MessageType.Contact => ActionType.ChatMembersAdded, + // MessageType.Game => ActionType.ChatMembersAdded, + // MessageType.Invoice => ActionType.ChatMembersAdded, + // MessageType.SuccessfulPayment => ActionType.ChatMembersAdded, + // MessageType.WebsiteConnected => ActionType.ChatMembersAdded, // MessageType.ChatMembersAdded => ActionType.ChatMembersAdded, // MessageType.ChatMemberLeft => ActionType.ChatMemberLeft, // MessageType.ChatTitleChanged => ActionType.ChatTitleChanged, @@ -62,18 +71,28 @@ await _navigatorContextFactory.Supply(builder => // MessageType.ChannelCreated => ActionType.ChannelCreated, // MessageType.MigratedToSupergroup => ActionType.MigratedToSupergroup, // MessageType.MigratedFromGroup => ActionType.MigratedFromGroup, - _ => ActionsHelper.Type.For(nameof(MessageAction)) + // MessageType.Dice => ActionType.MigratedFromGroup, + // MessageType.MessageAutoDeleteTimerChanged => ActionType.MigratedFromGroup, + // MessageType.ProximityAlertTriggered => ActionType.MigratedFromGroup, + // MessageType.VoiceChatScheduled => ActionType.MigratedFromGroup, + // MessageType.VoiceChatStarted => ActionType.MigratedFromGroup, + // MessageType.VoiceChatEnded => ActionType.MigratedFromGroup, + // MessageType.VoiceChatParticipantsInvited => ActionType.MigratedFromGroup, + _ => typeof(MessageAction).FullName, }, - UpdateType.InlineQuery => ActionsHelper.Type.For(nameof(InlineQueryAction)), - UpdateType.ChosenInlineResult => ActionsHelper.Type.For(nameof(ChosenInlineResult)), - UpdateType.CallbackQuery => ActionsHelper.Type.For(nameof(CallbackQueryAction)), - UpdateType.EditedMessage => ActionsHelper.Type.For(nameof(EditedMessageAction)), + UpdateType.InlineQuery => typeof(CommandAction).FullName, + UpdateType.ChosenInlineResult => typeof(ChosenInlineResultAction).FullName, + UpdateType.CallbackQuery => typeof(CallbackQueryAction).FullName, + UpdateType.EditedMessage => typeof(EditedMessageAction).FullName, // UpdateType.ChannelPost => ActionType.ChannelPost, // UpdateType.EditedChannelPost => ActionType.EditedChannelPost, // UpdateType.ShippingQuery => ActionType.ShippingQuery, // UpdateType.PreCheckoutQuery => ActionType.PreCheckoutQuery, - UpdateType.Poll => ActionsHelper.Type.For(nameof(PollAction)), - UpdateType.Unknown => ActionsHelper.Type.For(nameof(UnknownAction)), + UpdateType.Poll => typeof(PollAction).FullName, + // UpdateType.PollAnswer => typeof(PollAction).FullName, + // UpdateType.MyChatMember => typeof(UnknownAction).FullName, + // UpdateType.ChatMember => typeof(UnknownAction).FullName, + UpdateType.Unknown => typeof(UnknownAction).FullName, _ => default }; } diff --git a/src/Navigator.Samples.Echo/Actions/EchoAction.cs b/src/Navigator.Samples.Echo/Actions/EchoAction.cs index 311ced5..70610fe 100644 --- a/src/Navigator.Samples.Echo/Actions/EchoAction.cs +++ b/src/Navigator.Samples.Echo/Actions/EchoAction.cs @@ -1,6 +1,7 @@ using Navigator.Actions; using Navigator.Context; using Navigator.Providers.Telegram.Actions; +using Navigator.Providers.Telegram.Actions.Message; namespace Navigator.Samples.Echo.Actions { diff --git a/src/Navigator.Samples.Echo/Actions/EditedEchoAction.cs b/src/Navigator.Samples.Echo/Actions/EditedEchoAction.cs index 10c7796..6068f84 100644 --- a/src/Navigator.Samples.Echo/Actions/EditedEchoAction.cs +++ b/src/Navigator.Samples.Echo/Actions/EditedEchoAction.cs @@ -1,5 +1,6 @@ using Navigator.Context; using Navigator.Providers.Telegram.Actions; +using Navigator.Providers.Telegram.Actions.Update; namespace Navigator.Samples.Echo.Actions { diff --git a/src/Navigator/Actions/ActionLauncher.cs b/src/Navigator/Actions/ActionLauncher.cs index 71b32e2..14920ad 100644 --- a/src/Navigator/Actions/ActionLauncher.cs +++ b/src/Navigator/Actions/ActionLauncher.cs @@ -3,6 +3,7 @@ using System.Linq; using System.Threading.Tasks; using MediatR; +using Microsoft.Extensions.Logging; using Navigator.Configuration; using Navigator.Context; @@ -11,20 +12,19 @@ namespace Navigator.Actions internal class ActionLauncher : IActionLauncher { private readonly INavigatorContextAccessor _navigatorContextAccessor; - private readonly IEnumerable _actions; - private readonly NavigatorOptions _navigatorOptions; - private readonly ISender _sender; + private readonly ILogger _logger; public ActionLauncher(IEnumerable actions, NavigatorOptions navigatorOptions, - INavigatorContextAccessor navigatorContextAccessor, ISender sender) + INavigatorContextAccessor navigatorContextAccessor, ISender sender, ILogger logger) { _actions = actions; _navigatorOptions = navigatorOptions; _navigatorContextAccessor = navigatorContextAccessor; _sender = sender; + _logger = logger; } public async Task Launch() @@ -39,7 +39,7 @@ public async Task Launch() } catch (Exception e) { - //TODO: logs + _logger.LogError(e, "Unhandled exception running {@Action}", action); } } } diff --git a/src/Navigator/Actions/ActionsHelper.cs b/src/Navigator/Actions/ActionsHelper.cs deleted file mode 100644 index 94ab1a0..0000000 --- a/src/Navigator/Actions/ActionsHelper.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace Navigator.Actions -{ - public static class ActionsHelper - { - public static class Type - { - public static string For(string name) where TProvider : INavigatorProvider - { - return $"_navigator.actions.{typeof(TProvider).Name}.{name}"; - } - } - } -} \ No newline at end of file diff --git a/src/Navigator/INavigatorProvider.cs b/src/Navigator/INavigatorProvider.cs index a403b21..c3e3730 100644 --- a/src/Navigator/INavigatorProvider.cs +++ b/src/Navigator/INavigatorProvider.cs @@ -12,7 +12,5 @@ public interface INavigatorProvider /// /// An implementation of INavigatorClient GetClient(); - - Task HandleReply(); } } \ No newline at end of file From 594dff38b958c8516ea296289f8252d15745474f Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 6 Sep 2021 18:48:24 +0300 Subject: [PATCH 157/304] chore: erase old code --- .../DiscordNavigatorProvider.cs | 22 ------ .../SetDiscordShardedSocketHostedService.cs | 58 -------------- .../Navigator.Providers.Discord.csproj | 28 ------- .../NavigatorDiscordClient.cs | 77 ------------------- ...vigatorDiscordProviderOptionsExtensions.cs | 47 ----------- ...NavigatorProviderConfigurationExtension.cs | 28 ------- .../NavigatorTelegramProviderOptions.cs | 9 --- src/Navigator.sln | 7 -- 8 files changed, 276 deletions(-) delete mode 100644 src/Navigator.Providers.Discord/DiscordNavigatorProvider.cs delete mode 100644 src/Navigator.Providers.Discord/Hosted/SetDiscordShardedSocketHostedService.cs delete mode 100644 src/Navigator.Providers.Discord/Navigator.Providers.Discord.csproj delete mode 100644 src/Navigator.Providers.Discord/NavigatorDiscordClient.cs delete mode 100644 src/Navigator.Providers.Discord/NavigatorDiscordProviderOptionsExtensions.cs delete mode 100644 src/Navigator.Providers.Discord/NavigatorProviderConfigurationExtension.cs delete mode 100644 src/Navigator.Providers.Discord/NavigatorTelegramProviderOptions.cs diff --git a/src/Navigator.Providers.Discord/DiscordNavigatorProvider.cs b/src/Navigator.Providers.Discord/DiscordNavigatorProvider.cs deleted file mode 100644 index 4ac8aba..0000000 --- a/src/Navigator.Providers.Discord/DiscordNavigatorProvider.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System.Threading.Tasks; - -namespace Navigator.Providers.Discord -{ - public class DiscordNavigatorProvider : INavigatorProvider - { - public INavigatorClient GetClient() - { - throw new System.NotImplementedException(); - } - - public Task HandleReply() - { - throw new System.NotImplementedException(); - } - - public string GetActionType(object original) - { - throw new System.NotImplementedException(); - } - } -} \ No newline at end of file diff --git a/src/Navigator.Providers.Discord/Hosted/SetDiscordShardedSocketHostedService.cs b/src/Navigator.Providers.Discord/Hosted/SetDiscordShardedSocketHostedService.cs deleted file mode 100644 index e729a4a..0000000 --- a/src/Navigator.Providers.Discord/Hosted/SetDiscordShardedSocketHostedService.cs +++ /dev/null @@ -1,58 +0,0 @@ -using System; -using System.Threading; -using System.Threading.Tasks; -using Discord; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.Logging; -using Navigator.Configuration; - -namespace Navigator.Providers.Discord.Hosted -{ - /// - /// WebHook service for navigator's telegram provider. - /// - public class SetDiscordShardedSocketHostedService : BackgroundService - { - private readonly ILogger _logger; - private readonly IServiceScopeFactory _serviceScopeFactory; - private readonly NavigatorOptions _navigatorOptions; - - /// - /// Default constructor. - /// - /// - /// - /// - /// - public SetDiscordShardedSocketHostedService(ILogger logger, IServiceScopeFactory serviceScopeFactory, - NavigatorOptions navigatorOptions) - { - _logger = logger; - _serviceScopeFactory = serviceScopeFactory; - _navigatorOptions = navigatorOptions; - } - - /// - protected override async Task ExecuteAsync(CancellationToken stoppingToken) - { - using var scope = _serviceScopeFactory.CreateScope(); - - var navigatorClient = scope.ServiceProvider.GetRequiredService(); - - await navigatorClient.LoginAsync(TokenType.Bot, _navigatorOptions.GetDiscordToken()); - await navigatorClient.StartAsync(); - - var me = navigatorClient.CurrentUser; - - if (me is not null) - { - _logger.LogInformation($"Navigator Discord Client is receiving updates for bot: @{me.Username}"); - } - else - { - _logger.LogCritical("Unhandled error starting navigator discord client"); - } - } - } -} \ No newline at end of file diff --git a/src/Navigator.Providers.Discord/Navigator.Providers.Discord.csproj b/src/Navigator.Providers.Discord/Navigator.Providers.Discord.csproj deleted file mode 100644 index 8ac1c3e..0000000 --- a/src/Navigator.Providers.Discord/Navigator.Providers.Discord.csproj +++ /dev/null @@ -1,28 +0,0 @@ - - - - net5.0 - enable - true - Telegram Provider for Navigator - Lucas Maximiliano Marino - Discord provider for Navigator Framework. Implementation based on Discord.Net. - https://github.com/navigatorframework/navigator - https://github.com/navigatorframework/navigator/blob/master/LICENSE - https://github.com/navigatorframework/navigator - Discord, Bot, Framework, Navigator - true - Copyright © Lucas Maximiliano Marino 2021 - https://raw.githubusercontent.com/navigatorframework/navigator/master/assets/logo.png - - - - - - - - - - - - diff --git a/src/Navigator.Providers.Discord/NavigatorDiscordClient.cs b/src/Navigator.Providers.Discord/NavigatorDiscordClient.cs deleted file mode 100644 index 3110988..0000000 --- a/src/Navigator.Providers.Discord/NavigatorDiscordClient.cs +++ /dev/null @@ -1,77 +0,0 @@ -using System.Threading; -using System.Threading.Tasks; -using Discord; -using Discord.WebSocket; -using Microsoft.Extensions.Logging; -using Navigator.Configuration; -using Navigator.Entities; - -namespace Navigator.Providers.Discord -{ - public class NavigatorDiscordClient : DiscordShardedClient, INavigatorClient - { - private readonly ILogger _logger; - - public NavigatorDiscordClient(INavigatorOptions options, ILogger logger) - : base(new DiscordSocketConfig - { - TotalShards = options.GetTotalShardsOrDefault() - }) - { - _logger = logger; - - ShardReady += ReadyAsync; - Log += LogAsync; - } - - private Task ReadyAsync(DiscordSocketClient shard) - { - _logger.LogInformation("Navigator Discord Shard Number {ShardId} is connected and ready", shard.ShardId); - return Task.CompletedTask; - } - - private Task LogAsync(LogMessage log) - { - switch (log.Severity) - { - case LogSeverity.Critical: - _logger.LogCritical(log.Exception, "Message: {Message} Source: {Source}", log.Message, log.Source); - break; - case LogSeverity.Error: - _logger.LogError(log.Exception, "Message: {Message} Source: {Source}", log.Message, log.Source); - break; - case LogSeverity.Warning: - _logger.LogWarning(log.Exception, "Message: {Message} Source: {Source}", log.Message, log.Source); - break; - case LogSeverity.Info: - _logger.LogInformation("Message: {Message} Source: {Source}", log.Message, log.Source); - break; - case LogSeverity.Verbose: - _logger.LogTrace("Message: {Message} Source: {Source}", log.Message, log.Source); - break; - case LogSeverity.Debug: - _logger.LogDebug("Message: {Message} Source: {Source}", log.Message, log.Source); - break; - default: - _logger.LogInformation("Message: {Message} Source: {Source}", log.Message, log.Source); - break; - } - - return Task.CompletedTask; - } - - public Task GetProfile(CancellationToken cancellationToken = default) - { - return Task.FromResult(new BotUser - { - Id = CurrentUser.Id.ToString(), - Username = CurrentUser.Username - }); - } - - public INavigatorProvider IsClientFor() - { - return Provider.For(); - } - } -} \ No newline at end of file diff --git a/src/Navigator.Providers.Discord/NavigatorDiscordProviderOptionsExtensions.cs b/src/Navigator.Providers.Discord/NavigatorDiscordProviderOptionsExtensions.cs deleted file mode 100644 index c0ee25f..0000000 --- a/src/Navigator.Providers.Discord/NavigatorDiscordProviderOptionsExtensions.cs +++ /dev/null @@ -1,47 +0,0 @@ -using Navigator.Configuration; - -namespace Navigator.Providers.Discord -{ - public static class NavigatorDiscordProviderOptionsExtensions - { - #region DiscordToken - - private const string DiscordTokenKey = "_navigator.options.discord.discord_token"; - - public static void SetDiscordToken(this NavigatorDiscordProviderOptions navigatorOptions, string telegramToken) - { - navigatorOptions.TryRegisterOption(DiscordTokenKey, telegramToken); - - } - - public static string? GetDiscordToken(this INavigatorOptions navigatorOptions) - { - return navigatorOptions.RetrieveOption(DiscordTokenKey); - } - - #endregion - - #region Shards - - private const string TotalShardsKey = "_navigator.options.discord.total_shards"; - - public static void SetTotalShards(this NavigatorDiscordProviderOptions navigatorOptions, int totalShards) - { - navigatorOptions.TryRegisterOption(TotalShardsKey, totalShards); - } - - public static int GetTotalShardsOrDefault(this INavigatorOptions navigatorOptions) - { - var totalShards = navigatorOptions.RetrieveOption(TotalShardsKey); - - if (totalShards is null) - { - navigatorOptions.TryRegisterOption(TotalShardsKey, 1); - } - - return navigatorOptions.RetrieveOption(TotalShardsKey)!; - } - - #endregion - } -} \ No newline at end of file diff --git a/src/Navigator.Providers.Discord/NavigatorProviderConfigurationExtension.cs b/src/Navigator.Providers.Discord/NavigatorProviderConfigurationExtension.cs deleted file mode 100644 index 81951c7..0000000 --- a/src/Navigator.Providers.Discord/NavigatorProviderConfigurationExtension.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System; -using Microsoft.Extensions.DependencyInjection; -using Navigator.Configuration; -using Navigator.Configuration.Provider; -using Navigator.Providers.Discord.Hosted; - -namespace Navigator.Providers.Discord -{ - public static class NavigatorProviderConfigurationExtensions - { - public static NavigatorConfiguration Discord(this NavigatorProviderConfiguration providerConfiguration, - Action options) - { - var discordProviderOptions = new NavigatorDiscordProviderOptions(); - options.Invoke(discordProviderOptions); - - return providerConfiguration.Provider( - optionsAction => optionsAction.Import(optionsAction.RetrieveAllOptions()), - services => - { - services.AddSingleton(); - services.AddSingleton(sp => sp.GetRequiredService()); - - services.AddHostedService(); - }); - } - } -} \ No newline at end of file diff --git a/src/Navigator.Providers.Discord/NavigatorTelegramProviderOptions.cs b/src/Navigator.Providers.Discord/NavigatorTelegramProviderOptions.cs deleted file mode 100644 index a2c1c13..0000000 --- a/src/Navigator.Providers.Discord/NavigatorTelegramProviderOptions.cs +++ /dev/null @@ -1,9 +0,0 @@ -using Navigator.Configuration; - -namespace Navigator.Providers.Discord -{ - public class NavigatorDiscordProviderOptions : NavigatorOptions - { - - } -} \ No newline at end of file diff --git a/src/Navigator.sln b/src/Navigator.sln index 57474d3..618ec51 100644 --- a/src/Navigator.sln +++ b/src/Navigator.sln @@ -34,8 +34,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Providers", "Providers", "{ EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Navigator.Providers.Telegram", "Navigator.Providers.Telegram\Navigator.Providers.Telegram.csproj", "{8E0F6DCA-FAA4-4FA8-B9E0-75E9DC0F3573}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Navigator.Providers.Discord", "Navigator.Providers.Discord\Navigator.Providers.Discord.csproj", "{54039A52-DB2D-4428-A8D0-F998CA50B079}" -EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -78,10 +76,6 @@ Global {8E0F6DCA-FAA4-4FA8-B9E0-75E9DC0F3573}.Debug|Any CPU.Build.0 = Debug|Any CPU {8E0F6DCA-FAA4-4FA8-B9E0-75E9DC0F3573}.Release|Any CPU.ActiveCfg = Release|Any CPU {8E0F6DCA-FAA4-4FA8-B9E0-75E9DC0F3573}.Release|Any CPU.Build.0 = Release|Any CPU - {54039A52-DB2D-4428-A8D0-F998CA50B079}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {54039A52-DB2D-4428-A8D0-F998CA50B079}.Debug|Any CPU.Build.0 = Debug|Any CPU - {54039A52-DB2D-4428-A8D0-F998CA50B079}.Release|Any CPU.ActiveCfg = Release|Any CPU - {54039A52-DB2D-4428-A8D0-F998CA50B079}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(NestedProjects) = preSolution {7E8F867E-70E1-4C5B-AE65-A2C6822BFD6E} = {6D6A8E40-8C40-49AA-BEAD-B046D43F511A} @@ -99,6 +93,5 @@ Global {294C1716-C054-4585-B66E-C79D155AE684} = {E2FF61C3-F081-40C8-9CC3-BBE1F81543F6} {DAA22477-BB29-475C-AD2C-905F81B4AD8E} = {895808DE-1CA6-406C-924A-7E43F293CF7D} {8E0F6DCA-FAA4-4FA8-B9E0-75E9DC0F3573} = {DAA22477-BB29-475C-AD2C-905F81B4AD8E} - {54039A52-DB2D-4428-A8D0-F998CA50B079} = {DAA22477-BB29-475C-AD2C-905F81B4AD8E} EndGlobalSection EndGlobal From 66572a5485008ea013c47e5957b86237c4a30af9 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 6 Sep 2021 19:24:56 +0300 Subject: [PATCH 158/304] feat: create NavigatorException --- src/Navigator/NavigatorException.cs | 31 +++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 src/Navigator/NavigatorException.cs diff --git a/src/Navigator/NavigatorException.cs b/src/Navigator/NavigatorException.cs new file mode 100644 index 0000000..db96b8c --- /dev/null +++ b/src/Navigator/NavigatorException.cs @@ -0,0 +1,31 @@ +using System; +using System.Runtime.Serialization; + +namespace Navigator +{ + /// + /// TODO + /// + public class NavigatorException : Exception + { + /// + public NavigatorException() + { + } + + /// + protected NavigatorException(SerializationInfo info, StreamingContext context) : base(info, context) + { + } + + /// + public NavigatorException(string? message) : base(message) + { + } + + /// + public NavigatorException(string? message, Exception? innerException) : base(message, innerException) + { + } + } +} \ No newline at end of file From 76ee6b8ccb8e2fb29143b1f373d28f9d971d9deb Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 6 Sep 2021 19:26:14 +0300 Subject: [PATCH 159/304] refactor: rename original update to original event --- .../NavigatorContextExtensions.cs | 12 ++++++------ .../TelegramMiddleware.cs | 2 +- .../Extensions/NavigatorContextExtensions.cs | 14 +++++++------- ...tension.cs => OriginalEventContextExtension.cs} | 6 +++--- .../NavigatorContextBuilderOptionsExtensions.cs | 10 +++++----- src/Navigator/ServiceCollectionExtensions.cs | 2 +- 6 files changed, 23 insertions(+), 23 deletions(-) rename src/Navigator/Context/Extensions/{OriginalUpdateContextExtension.cs => OriginalEventContextExtension.cs} (51%) diff --git a/src/Navigator.Providers.Telegram/NavigatorContextExtensions.cs b/src/Navigator.Providers.Telegram/NavigatorContextExtensions.cs index c92c755..469881f 100644 --- a/src/Navigator.Providers.Telegram/NavigatorContextExtensions.cs +++ b/src/Navigator.Providers.Telegram/NavigatorContextExtensions.cs @@ -72,13 +72,13 @@ public static Chat GetTelegramChat(this INavigatorContext ctx) /// Telegram Chat public static Chat? GetTelegramChatOrDefault(this INavigatorContext ctx) { - return ctx.GetOriginalUpdateOrDefault()?.Type switch + return ctx.GetOriginalEventOrDefault()?.Type switch { - UpdateType.CallbackQuery => ctx.GetOriginalUpdate().CallbackQuery.Message.Chat, - UpdateType.Message => ctx.GetOriginalUpdate().Message.Chat, - UpdateType.EditedMessage => ctx.GetOriginalUpdate().EditedMessage.Chat, - UpdateType.ChannelPost => ctx.GetOriginalUpdate().ChannelPost.Chat, - UpdateType.EditedChannelPost => ctx.GetOriginalUpdate().EditedChannelPost.Chat, + UpdateType.CallbackQuery => ctx.GetOriginalEvent().CallbackQuery.Message.Chat, + UpdateType.Message => ctx.GetOriginalEvent().Message.Chat, + UpdateType.EditedMessage => ctx.GetOriginalEvent().EditedMessage.Chat, + UpdateType.ChannelPost => ctx.GetOriginalEvent().ChannelPost.Chat, + UpdateType.EditedChannelPost => ctx.GetOriginalEvent().EditedChannelPost.Chat, _ => default }; } diff --git a/src/Navigator.Providers.Telegram/TelegramMiddleware.cs b/src/Navigator.Providers.Telegram/TelegramMiddleware.cs index ea00c75..a21cdea 100644 --- a/src/Navigator.Providers.Telegram/TelegramMiddleware.cs +++ b/src/Navigator.Providers.Telegram/TelegramMiddleware.cs @@ -39,7 +39,7 @@ await _navigatorContextFactory.Supply(builder => { builder.SetProvider(); builder.SetActionType(actionType); - builder.SetOriginalUpdate(update); + builder.SetOriginalEvent(update); builder.SetConversation(update.GetConversation()); }); diff --git a/src/Navigator/Context/Extensions/NavigatorContextExtensions.cs b/src/Navigator/Context/Extensions/NavigatorContextExtensions.cs index 65f350b..a07738d 100644 --- a/src/Navigator/Context/Extensions/NavigatorContextExtensions.cs +++ b/src/Navigator/Context/Extensions/NavigatorContextExtensions.cs @@ -5,20 +5,20 @@ namespace Navigator.Context.Extensions { public static class NavigatorContextExtensions { - public static TUpdate GetOriginalUpdate(this INavigatorContext navigatorContext) where TUpdate : class + public static TEvent GetOriginalEvent(this INavigatorContext navigatorContext) where TEvent : class { - var update = navigatorContext.GetOriginalUpdateOrDefault(); + var update = navigatorContext.GetOriginalEventOrDefault(); - return update ?? throw new Exception("Update was not found."); + return update ?? throw new NavigatorException("Update was not found."); } - public static TUpdate? GetOriginalUpdateOrDefault(this INavigatorContext navigatorContext) where TUpdate : class + public static TEvent? GetOriginalEventOrDefault(this INavigatorContext navigatorContext) where TEvent : class { - var update = navigatorContext.Extensions.GetValueOrDefault(OriginalUpdateContextExtension.OriginalUpdateKey); + var @event = navigatorContext.Extensions.GetValueOrDefault(OriginalEventContextExtension.OriginalEventKey); - if (update is TUpdate originalUpdate) + if (@event is TEvent originalEvent) { - return originalUpdate; + return originalEvent; } return default; diff --git a/src/Navigator/Context/Extensions/OriginalUpdateContextExtension.cs b/src/Navigator/Context/Extensions/OriginalEventContextExtension.cs similarity index 51% rename from src/Navigator/Context/Extensions/OriginalUpdateContextExtension.cs rename to src/Navigator/Context/Extensions/OriginalEventContextExtension.cs index 9331752..38aca08 100644 --- a/src/Navigator/Context/Extensions/OriginalUpdateContextExtension.cs +++ b/src/Navigator/Context/Extensions/OriginalEventContextExtension.cs @@ -2,13 +2,13 @@ namespace Navigator.Context.Extensions { - public class OriginalUpdateContextExtension : INavigatorContextExtension + public class OriginalEventContextExtension : INavigatorContextExtension { - public const string OriginalUpdateKey = "_navigator.extensions.original_update"; + public const string OriginalEventKey = "_navigator.extensions.original_event"; public Task Extend(INavigatorContext navigatorContext, INavigatorContextBuilderOptions builderOptions) { - navigatorContext.Extensions.TryAdd(OriginalUpdateKey, builderOptions.GetOriginalUpdateOrDefault()); + navigatorContext.Extensions.TryAdd(OriginalEventKey, builderOptions.GetOriginalEventOrDefault()); return Task.FromResult(navigatorContext); } diff --git a/src/Navigator/Context/NavigatorContextBuilderOptionsExtensions.cs b/src/Navigator/Context/NavigatorContextBuilderOptionsExtensions.cs index ea78b34..366b10d 100644 --- a/src/Navigator/Context/NavigatorContextBuilderOptionsExtensions.cs +++ b/src/Navigator/Context/NavigatorContextBuilderOptionsExtensions.cs @@ -41,17 +41,17 @@ public static void SetActionType(this INavigatorContextBuilderOptions contextBui #region OriginalUpdate - private const string OriginalUpdateKey = "_navigator.context.options.original_update"; + private const string OriginalEventKey = "_navigator.context.options.original_event"; - public static void SetOriginalUpdate(this INavigatorContextBuilderOptions contextBuilderOptions, object originalUpdate) + public static void SetOriginalEvent(this INavigatorContextBuilderOptions contextBuilderOptions, object originalUpdate) { - contextBuilderOptions.TryRegisterOption(OriginalUpdateKey, originalUpdate); + contextBuilderOptions.TryRegisterOption(OriginalEventKey, originalUpdate); } - public static object? GetOriginalUpdateOrDefault(this INavigatorContextBuilderOptions contextBuilderOptions) + public static object? GetOriginalEventOrDefault(this INavigatorContextBuilderOptions contextBuilderOptions) { - return contextBuilderOptions.RetrieveOption(OriginalUpdateKey); + return contextBuilderOptions.RetrieveOption(OriginalEventKey); } #endregion diff --git a/src/Navigator/ServiceCollectionExtensions.cs b/src/Navigator/ServiceCollectionExtensions.cs index 9e27776..bb40897 100644 --- a/src/Navigator/ServiceCollectionExtensions.cs +++ b/src/Navigator/ServiceCollectionExtensions.cs @@ -22,7 +22,7 @@ public static NavigatorConfiguration AddNavigator(this IServiceCollection servic services.AddNavigatorContextServices(); - services.AddScoped(); + services.AddScoped(); services.AddScoped(); From 75505a0ffe3913b486fd5b04c30b534c0526554f Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 6 Sep 2021 19:26:50 +0300 Subject: [PATCH 160/304] refactor: new flow for base action --- src/Navigator/Actions/ActionLauncher.cs | 9 ++++----- src/Navigator/Actions/BaseAction.cs | 13 ++++++++----- src/Navigator/Actions/IAction.cs | 10 +--------- 3 files changed, 13 insertions(+), 19 deletions(-) diff --git a/src/Navigator/Actions/ActionLauncher.cs b/src/Navigator/Actions/ActionLauncher.cs index 14920ad..30b3bc8 100644 --- a/src/Navigator/Actions/ActionLauncher.cs +++ b/src/Navigator/Actions/ActionLauncher.cs @@ -55,16 +55,15 @@ private IEnumerable GetActions() { return _actions .Where(a => a.Type == _navigatorContextAccessor.NavigatorContext.ActionType) - .Where(a => a.Init(_navigatorContextAccessor.NavigatorContext) - .CanHandle(_navigatorContextAccessor.NavigatorContext)) - .OrderBy(a => a.Priority).AsEnumerable(); + .Where(a => a.CanHandleCurrentContext()) + .OrderBy(a => a.Priority) + .AsEnumerable(); } var action = _actions .Where(a => a.Type == _navigatorContextAccessor.NavigatorContext.ActionType) .OrderBy(a => a.Priority) - .FirstOrDefault(a => a.Init(_navigatorContextAccessor.NavigatorContext) - .CanHandle(_navigatorContextAccessor.NavigatorContext)); + .FirstOrDefault(a => a.CanHandleCurrentContext()); return action is not null ? new[] {action} : Array.Empty(); } diff --git a/src/Navigator/Actions/BaseAction.cs b/src/Navigator/Actions/BaseAction.cs index 5e5b852..d72ee5c 100644 --- a/src/Navigator/Actions/BaseAction.cs +++ b/src/Navigator/Actions/BaseAction.cs @@ -8,6 +8,11 @@ namespace Navigator.Actions /// public abstract class BaseAction : IAction { + /// + /// Used to access inside the action. + /// + protected readonly INavigatorContextAccessor NavigatorContextAccessor; + /// public abstract string Type { get; protected set; } @@ -22,15 +27,13 @@ public abstract class BaseAction : IAction /// /// Default constructor for /// - protected BaseAction() + public BaseAction(INavigatorContextAccessor navigatorContextAccessor) { + NavigatorContextAccessor = navigatorContextAccessor; Timestamp = DateTime.UtcNow; } /// - public abstract IAction Init(INavigatorContext navigatorContext); - - /// - public abstract bool CanHandle(INavigatorContext ctx); + public abstract bool CanHandleCurrentContext(); } } \ No newline at end of file diff --git a/src/Navigator/Actions/IAction.cs b/src/Navigator/Actions/IAction.cs index 9b66b48..38afad6 100644 --- a/src/Navigator/Actions/IAction.cs +++ b/src/Navigator/Actions/IAction.cs @@ -18,18 +18,10 @@ public interface IAction : IRequest /// ushort Priority { get; } - /// - /// Can be used to populate the action before triggering "CanHandle". - /// - /// - /// - IAction Init(INavigatorContext ctx); - /// /// This function must return true when the incoming update can be handled by this action. /// - /// /// - bool CanHandle(INavigatorContext ctx); + bool CanHandleCurrentContext(); } } \ No newline at end of file From 42a48dd4f25d730996c27ec39d10682ddd4ea3e8 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 6 Sep 2021 19:27:02 +0300 Subject: [PATCH 161/304] feat: update actions to new flow --- .../{Message => Messages}/CommandAction.cs | 29 +++++++-------- .../{Message => Messages}/MessageAction.cs | 32 ++++++++--------- .../Actions/UnknownAction.cs | 6 ++++ .../Actions/Update/DocumentAction.cs | 22 ------------ .../Actions/Update/EditedMessageAction.cs | 29 --------------- .../CallbackQueryAction.cs | 36 ++++++++----------- .../ChosenInlineResultAction.cs | 33 ++++++++--------- .../Actions/Updates/DocumentAction.cs | 20 +++++++++++ .../Actions/Updates/EditedMessageAction.cs | 35 ++++++++++++++++++ .../{Update => Updates}/InlineQueryAction.cs | 27 ++++++-------- .../Actions/{Update => Updates}/PollAction.cs | 26 +++++++------- .../TelegramMiddleware.cs | 4 +-- .../Actions/EchoAction.cs | 19 +++------- .../Actions/EditedEchoAction.cs | 8 +++-- 14 files changed, 153 insertions(+), 173 deletions(-) rename src/Navigator.Providers.Telegram/Actions/{Message => Messages}/CommandAction.cs (52%) rename src/Navigator.Providers.Telegram/Actions/{Message => Messages}/MessageAction.cs (56%) delete mode 100644 src/Navigator.Providers.Telegram/Actions/Update/DocumentAction.cs delete mode 100644 src/Navigator.Providers.Telegram/Actions/Update/EditedMessageAction.cs rename src/Navigator.Providers.Telegram/Actions/{Update => Updates}/CallbackQueryAction.cs (57%) rename src/Navigator.Providers.Telegram/Actions/{Update => Updates}/ChosenInlineResultAction.cs (53%) create mode 100644 src/Navigator.Providers.Telegram/Actions/Updates/DocumentAction.cs create mode 100644 src/Navigator.Providers.Telegram/Actions/Updates/EditedMessageAction.cs rename src/Navigator.Providers.Telegram/Actions/{Update => Updates}/InlineQueryAction.cs (65%) rename src/Navigator.Providers.Telegram/Actions/{Update => Updates}/PollAction.cs (50%) diff --git a/src/Navigator.Providers.Telegram/Actions/Message/CommandAction.cs b/src/Navigator.Providers.Telegram/Actions/Messages/CommandAction.cs similarity index 52% rename from src/Navigator.Providers.Telegram/Actions/Message/CommandAction.cs rename to src/Navigator.Providers.Telegram/Actions/Messages/CommandAction.cs index e0421eb..51b4909 100644 --- a/src/Navigator.Providers.Telegram/Actions/Message/CommandAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Messages/CommandAction.cs @@ -2,7 +2,7 @@ using Navigator.Context; using Navigator.Providers.Telegram.Extensions; -namespace Navigator.Providers.Telegram.Actions.Message +namespace Navigator.Providers.Telegram.Actions.Messages { /// /// Command based action. @@ -12,26 +12,23 @@ public abstract class CommandAction : MessageAction /// public override string Type { get; protected set; } = typeof(CommandAction).FullName!; - /// - public override IAction Init(INavigatorContext navigatorContext) - { - base.Init(navigatorContext); - - Command = Message.ExtractCommand(navigatorContext.BotProfile.Username) ?? string.Empty; - Arguments = Message.ExtractArguments(navigatorContext.BotProfile.Username); - - return this; - } - /// /// Command. /// - public string Command { get; protected set; } = null!; - + public readonly string Command; + /// /// Any arguments passed with the command. If no arguments were passed, it will be null. /// - public string? Arguments { get; protected set; } - + public readonly string? Arguments; + + /// + protected CommandAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) + { + var botProfile = NavigatorContextAccessor.NavigatorContext.BotProfile; + + Command = Message.ExtractCommand(botProfile.Username) ?? string.Empty; + Arguments = Message.ExtractArguments(botProfile.Username); + } } } \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/Actions/Message/MessageAction.cs b/src/Navigator.Providers.Telegram/Actions/Messages/MessageAction.cs similarity index 56% rename from src/Navigator.Providers.Telegram/Actions/Message/MessageAction.cs rename to src/Navigator.Providers.Telegram/Actions/Messages/MessageAction.cs index dffe41c..8eaa5db 100644 --- a/src/Navigator.Providers.Telegram/Actions/Message/MessageAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Messages/MessageAction.cs @@ -1,8 +1,9 @@ using Navigator.Actions; using Navigator.Context; using Navigator.Context.Extensions; +using Telegram.Bot.Types; -namespace Navigator.Providers.Telegram.Actions.Message +namespace Navigator.Providers.Telegram.Actions.Messages { /// /// A message based action. @@ -12,34 +13,29 @@ public abstract class MessageAction : BaseAction /// public override string Type { get; protected set; } = typeof(MessageAction).FullName!; - /// - public override IAction Init(INavigatorContext navigatorContext) - { - var update = navigatorContext.GetOriginalUpdateOrDefault(); - - if (update is not null) - { - Message = update.Message; - IsReply = update.Message.ReplyToMessage is not null; - IsForwarded = update.Message.ForwardDate is not null; - } - - return this; - } - /// /// The original Message. /// - public global::Telegram.Bot.Types.Message Message { get; protected set; } = null!; + public Message Message { get; protected set; } /// /// Determines if this message is a reply to another message. /// public bool IsReply { get; protected set; } - + /// /// Determines if this message is a forwarded message. /// public bool IsForwarded { get; protected set; } + + /// + protected MessageAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) + { + var update = navigatorContextAccessor.NavigatorContext.GetOriginalEvent(); + + Message = update.Message; + IsReply = update.Message.ReplyToMessage is not null; + IsForwarded = update.Message.ForwardDate is not null; + } } } \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/Actions/UnknownAction.cs b/src/Navigator.Providers.Telegram/Actions/UnknownAction.cs index cda1aca..9bddbe1 100644 --- a/src/Navigator.Providers.Telegram/Actions/UnknownAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/UnknownAction.cs @@ -1,4 +1,5 @@ using Navigator.Actions; +using Navigator.Context; namespace Navigator.Providers.Telegram.Actions { @@ -6,5 +7,10 @@ public abstract class UnknownAction : BaseAction { /// public override string Type { get; protected set; } = typeof(UnknownAction).FullName!; + + /// + protected UnknownAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) + { + } } } \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/Actions/Update/DocumentAction.cs b/src/Navigator.Providers.Telegram/Actions/Update/DocumentAction.cs deleted file mode 100644 index d0448e9..0000000 --- a/src/Navigator.Providers.Telegram/Actions/Update/DocumentAction.cs +++ /dev/null @@ -1,22 +0,0 @@ -using Navigator.Actions; -using Navigator.Context; -using Navigator.Context.Extensions; -using Telegram.Bot.Types; - -namespace Navigator.Providers.Telegram.Actions.Update -{ - public class DocumentAction : BaseAction - { - public override string Type { get; protected set; } = typeof(DocumentAction).FullName!; - - public override IAction Init(INavigatorContext navigatorContext) - { - throw new System.NotImplementedException(); - } - - public override bool CanHandle(INavigatorContext ctx) - { - throw new System.NotImplementedException(); - } - } -} \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/Actions/Update/EditedMessageAction.cs b/src/Navigator.Providers.Telegram/Actions/Update/EditedMessageAction.cs deleted file mode 100644 index 6af5eb8..0000000 --- a/src/Navigator.Providers.Telegram/Actions/Update/EditedMessageAction.cs +++ /dev/null @@ -1,29 +0,0 @@ -using Navigator.Actions; -using Navigator.Context; -using Navigator.Context.Extensions; - -namespace Navigator.Providers.Telegram.Actions.Update -{ - public abstract class EditedMessageAction : BaseAction - { - /// - public override string Type { get; protected set; } = typeof(EditedMessageAction).FullName!; - - /// - public override IAction Init(INavigatorContext navigatorContext) - { - var update = navigatorContext.GetOriginalUpdateOrDefault(); - - if (update is not null) - { - OriginalMessage = update.EditedMessage; - } - - return this; - } - - public global::Telegram.Bot.Types.Message OriginalMessage { get; protected set; } = null!; - public global::Telegram.Bot.Types.Message EditedMessage { get; protected set; } = null!; - - } -} \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/Actions/Update/CallbackQueryAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/CallbackQueryAction.cs similarity index 57% rename from src/Navigator.Providers.Telegram/Actions/Update/CallbackQueryAction.cs rename to src/Navigator.Providers.Telegram/Actions/Updates/CallbackQueryAction.cs index 11048d0..c12606c 100644 --- a/src/Navigator.Providers.Telegram/Actions/Update/CallbackQueryAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/CallbackQueryAction.cs @@ -3,7 +3,7 @@ using Navigator.Context.Extensions; using Telegram.Bot.Types; -namespace Navigator.Providers.Telegram.Actions.Update +namespace Navigator.Providers.Telegram.Actions.Updates { /// /// A callback query based action. @@ -13,41 +13,35 @@ public abstract class CallbackQueryAction : BaseAction /// public override string Type { get; protected set; } = typeof(CallbackQueryAction).FullName!; - /// - public override IAction Init(INavigatorContext navigatorContext) - { - var update = navigatorContext.GetOriginalUpdateOrDefault(); - - if (update is not null) - { - CallbackQuery = update.CallbackQuery; - OriginalMessage = update.CallbackQuery.Message; - Data = string.IsNullOrWhiteSpace(update.CallbackQuery.Data) ? update.CallbackQuery.Data : default; - IsGameQuery = update.CallbackQuery.IsGameQuery; - } - - return this; - } - /// /// The original /// - public CallbackQuery CallbackQuery { get; protected set; } = null!; + public CallbackQuery CallbackQuery { get; protected set; } /// /// The message that originated the callback query. Iy may be null if the message is too old. /// - public global::Telegram.Bot.Types.Message? OriginalMessage { get; protected set; } - + public Message? OriginalMessage { get; protected set; } + /// /// Any data present on the callback query. /// public string? Data { get; protected set; } - + /// /// True if the callback query is from a game. /// public bool IsGameQuery { get; protected set; } + /// + protected CallbackQueryAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) + { + var update = NavigatorContextAccessor.NavigatorContext.GetOriginalEvent(); + + CallbackQuery = update.CallbackQuery; + OriginalMessage = update.CallbackQuery.Message; + Data = string.IsNullOrWhiteSpace(update.CallbackQuery.Data) ? update.CallbackQuery.Data : default; + IsGameQuery = update.CallbackQuery.IsGameQuery; + } } } \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/Actions/Update/ChosenInlineResultAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/ChosenInlineResultAction.cs similarity index 53% rename from src/Navigator.Providers.Telegram/Actions/Update/ChosenInlineResultAction.cs rename to src/Navigator.Providers.Telegram/Actions/Updates/ChosenInlineResultAction.cs index bab17e9..17e9fe7 100644 --- a/src/Navigator.Providers.Telegram/Actions/Update/ChosenInlineResultAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/ChosenInlineResultAction.cs @@ -3,7 +3,7 @@ using Navigator.Context.Extensions; using Telegram.Bot.Types; -namespace Navigator.Providers.Telegram.Actions.Update +namespace Navigator.Providers.Telegram.Actions.Updates { /// /// Inline result based action. @@ -13,34 +13,29 @@ public abstract class ChosenInlineResultAction : BaseAction /// public override string Type { get; protected set; } = typeof(ChosenInlineResultAction).FullName!; - /// - public override IAction Init(INavigatorContext navigatorContext) - { - var update = navigatorContext.GetOriginalUpdateOrDefault(); - - if (update is not null) - { - ChosenInlineResult = update.ChosenInlineResult; - ResultId = update.ChosenInlineResult.ResultId; - Query = update.ChosenInlineResult.Query; - } - - return this; - } - /// /// The original chosen inline result. /// - public ChosenInlineResult ChosenInlineResult { get; protected set; } = null!; + public ChosenInlineResult ChosenInlineResult { get; protected set; } /// /// The chosen result id. /// - public string ResultId { get; protected set; } = string.Empty; + public string ResultId { get; protected set; } /// /// The original query. /// - public string Query { get; protected set; } = string.Empty; + public string Query { get; protected set; } + + /// + protected ChosenInlineResultAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) + { + var update = NavigatorContextAccessor.NavigatorContext.GetOriginalEvent(); + + ChosenInlineResult = update.ChosenInlineResult; + ResultId = update.ChosenInlineResult.ResultId; + Query = update.ChosenInlineResult.Query; + } } } \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/DocumentAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/DocumentAction.cs new file mode 100644 index 0000000..2d4b24c --- /dev/null +++ b/src/Navigator.Providers.Telegram/Actions/Updates/DocumentAction.cs @@ -0,0 +1,20 @@ +using System; +using Navigator.Actions; +using Navigator.Context; + +namespace Navigator.Providers.Telegram.Actions.Updates +{ + /// + /// TODO + /// + public abstract class DocumentAction : BaseAction + { + public override string Type { get; protected set; } = typeof(DocumentAction).FullName!; + + /// + public DocumentAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) + { + //TODO + } + } +} \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/EditedMessageAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/EditedMessageAction.cs new file mode 100644 index 0000000..27ced25 --- /dev/null +++ b/src/Navigator.Providers.Telegram/Actions/Updates/EditedMessageAction.cs @@ -0,0 +1,35 @@ +using Navigator.Actions; +using Navigator.Context; +using Navigator.Context.Extensions; +using Telegram.Bot.Types; + +namespace Navigator.Providers.Telegram.Actions.Updates +{ + /// + /// TODO + /// + public abstract class EditedMessageAction : BaseAction + { + /// + public override string Type { get; protected set; } = typeof(EditedMessageAction).FullName!; + + /// + /// TODO + /// + public Message OriginalMessage { get; protected set; } + + /// + /// TODO + /// + public Message EditedMessage { get; protected set; } + + /// + protected EditedMessageAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) + { + var update = NavigatorContextAccessor.NavigatorContext.GetOriginalEvent(); + + OriginalMessage = update.Message; + EditedMessage = update.EditedMessage; + } + } +} \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/Actions/Update/InlineQueryAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/InlineQueryAction.cs similarity index 65% rename from src/Navigator.Providers.Telegram/Actions/Update/InlineQueryAction.cs rename to src/Navigator.Providers.Telegram/Actions/Updates/InlineQueryAction.cs index 17852d0..2fabb5d 100644 --- a/src/Navigator.Providers.Telegram/Actions/Update/InlineQueryAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/InlineQueryAction.cs @@ -3,7 +3,7 @@ using Navigator.Context.Extensions; using Telegram.Bot.Types; -namespace Navigator.Providers.Telegram.Actions.Update +namespace Navigator.Providers.Telegram.Actions.Updates { /// /// Inline query based action. @@ -13,21 +13,6 @@ public abstract class InlineQueryAction : BaseAction /// public override string Type { get; protected set; } = typeof(InlineQueryAction).FullName!; - /// - public override IAction Init(INavigatorContext navigatorContext) - { - var update = navigatorContext.GetOriginalUpdateOrDefault(); - - if (update is not null) - { - InlineQuery = update.InlineQuery; - Query = update.InlineQuery.Query; - Offset = update.InlineQuery.Offset; - } - - return this; - } - /// /// The original /// @@ -42,5 +27,15 @@ public override IAction Init(INavigatorContext navigatorContext) /// The offset. /// public string Offset { get; protected set; } = string.Empty; + + /// + protected InlineQueryAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) + { + var update = NavigatorContextAccessor.NavigatorContext.GetOriginalEvent(); + + InlineQuery = update.InlineQuery; + Query = update.InlineQuery.Query; + Offset = update.InlineQuery.Offset; + } } } \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/Actions/Update/PollAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/PollAction.cs similarity index 50% rename from src/Navigator.Providers.Telegram/Actions/Update/PollAction.cs rename to src/Navigator.Providers.Telegram/Actions/Updates/PollAction.cs index a22ec54..e8eb7a1 100644 --- a/src/Navigator.Providers.Telegram/Actions/Update/PollAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/PollAction.cs @@ -3,29 +3,27 @@ using Navigator.Context.Extensions; using Telegram.Bot.Types; -namespace Navigator.Providers.Telegram.Actions.Update +namespace Navigator.Providers.Telegram.Actions.Updates { + /// + /// TODO + /// public abstract class PollAction : BaseAction { /// public override string Type { get; protected set; } = typeof(PollAction).FullName!; + /// + /// The original Poll. + /// + public Poll Poll { get; protected set; } + /// - public override IAction Init(INavigatorContext navigatorContext) + protected PollAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) { - var update = navigatorContext.GetOriginalUpdateOrDefault(); - - if (update is not null) - { - Poll = update.Poll; - } + var update = NavigatorContextAccessor.NavigatorContext.GetOriginalEvent(); - return this; + Poll = update.Poll; } - - /// - /// The original Poll. - /// - public Poll Poll { get; protected set; } = null!; } } \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/TelegramMiddleware.cs b/src/Navigator.Providers.Telegram/TelegramMiddleware.cs index a21cdea..2748153 100644 --- a/src/Navigator.Providers.Telegram/TelegramMiddleware.cs +++ b/src/Navigator.Providers.Telegram/TelegramMiddleware.cs @@ -4,8 +4,8 @@ using Navigator.Actions; using Navigator.Context; using Navigator.Providers.Telegram.Actions; -using Navigator.Providers.Telegram.Actions.Message; -using Navigator.Providers.Telegram.Actions.Update; +using Navigator.Providers.Telegram.Actions.Messages; +using Navigator.Providers.Telegram.Actions.Updates; using Navigator.Providers.Telegram.Entities; using Navigator.Providers.Telegram.Extensions; using Telegram.Bot.Types; diff --git a/src/Navigator.Samples.Echo/Actions/EchoAction.cs b/src/Navigator.Samples.Echo/Actions/EchoAction.cs index 70610fe..bd416bd 100644 --- a/src/Navigator.Samples.Echo/Actions/EchoAction.cs +++ b/src/Navigator.Samples.Echo/Actions/EchoAction.cs @@ -1,34 +1,25 @@ using Navigator.Actions; using Navigator.Context; using Navigator.Providers.Telegram.Actions; -using Navigator.Providers.Telegram.Actions.Message; +using Navigator.Providers.Telegram.Actions.Messages; namespace Navigator.Samples.Echo.Actions { public class EchoAction : MessageAction { - public EchoAction() - { - MessageToEcho = string.Empty; - } - - public string MessageToEcho { get; set; } - public override ushort Priority { get; protected set; } = Navigator.Actions.Priority.High; - public override IAction Init(INavigatorContext ctx) + public string MessageToEcho { get; protected set; } = string.Empty; + + public EchoAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) { - base.Init(ctx); - if (!string.IsNullOrWhiteSpace(Message.Text)) { MessageToEcho = Message.Text; } - - return this; } - public override bool CanHandle(INavigatorContext ctx) + public override bool CanHandleCurrentContext() { return !string.IsNullOrWhiteSpace(MessageToEcho); } diff --git a/src/Navigator.Samples.Echo/Actions/EditedEchoAction.cs b/src/Navigator.Samples.Echo/Actions/EditedEchoAction.cs index 6068f84..4cc8853 100644 --- a/src/Navigator.Samples.Echo/Actions/EditedEchoAction.cs +++ b/src/Navigator.Samples.Echo/Actions/EditedEchoAction.cs @@ -1,12 +1,16 @@ using Navigator.Context; using Navigator.Providers.Telegram.Actions; -using Navigator.Providers.Telegram.Actions.Update; +using Navigator.Providers.Telegram.Actions.Updates; namespace Navigator.Samples.Echo.Actions { public class EditedEchoAction : EditedMessageAction { - public override bool CanHandle(INavigatorContext ctx) + public EditedEchoAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) + { + } + + public override bool CanHandleCurrentContext() { return true; } From cfe70e8df29254e57597cf409bc29a103ff42860 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sun, 5 Dec 2021 11:48:45 +0100 Subject: [PATCH 162/304] chore: update to .net 6 --- .../Hosted/SetTelegramBotWebHookHostedService.cs | 1 + .../Navigator.Providers.Telegram.csproj | 4 ++-- .../TelegramMiddleware.cs | 13 +++++++------ src/Navigator/Navigator.csproj | 8 ++++---- 4 files changed, 14 insertions(+), 12 deletions(-) diff --git a/src/Navigator.Providers.Telegram/Hosted/SetTelegramBotWebHookHostedService.cs b/src/Navigator.Providers.Telegram/Hosted/SetTelegramBotWebHookHostedService.cs index 04718ab..797f202 100644 --- a/src/Navigator.Providers.Telegram/Hosted/SetTelegramBotWebHookHostedService.cs +++ b/src/Navigator.Providers.Telegram/Hosted/SetTelegramBotWebHookHostedService.cs @@ -5,6 +5,7 @@ using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Navigator.Configuration; +using Telegram.Bot; namespace Navigator.Providers.Telegram.Hosted { diff --git a/src/Navigator.Providers.Telegram/Navigator.Providers.Telegram.csproj b/src/Navigator.Providers.Telegram/Navigator.Providers.Telegram.csproj index f7c0c5d..f2b4683 100644 --- a/src/Navigator.Providers.Telegram/Navigator.Providers.Telegram.csproj +++ b/src/Navigator.Providers.Telegram/Navigator.Providers.Telegram.csproj @@ -1,7 +1,7 @@ - net5.0 + net6.0 enable true Telegram Provider for Navigator @@ -21,7 +21,7 @@ - + diff --git a/src/Navigator.Providers.Telegram/TelegramMiddleware.cs b/src/Navigator.Providers.Telegram/TelegramMiddleware.cs index 2748153..8472457 100644 --- a/src/Navigator.Providers.Telegram/TelegramMiddleware.cs +++ b/src/Navigator.Providers.Telegram/TelegramMiddleware.cs @@ -10,6 +10,7 @@ using Navigator.Providers.Telegram.Extensions; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; +using Telegram.Bot.Types.Payments; namespace Navigator.Providers.Telegram { @@ -53,7 +54,7 @@ await _navigatorContextFactory.Supply(builder => UpdateType.Message when update.Message.Entities?.First()?.Type == MessageEntityType.BotCommand => typeof(CommandAction).FullName, UpdateType.Message => update.Message.Type switch { - // MessageType.Document => ActionType.ChatMembersAdded, + MessageType.Document => typeof(DocumentAction).FullName, // MessageType.Location => ActionType.ChatMembersAdded, // MessageType.Contact => ActionType.ChatMembersAdded, // MessageType.Game => ActionType.ChatMembersAdded, @@ -67,8 +68,8 @@ await _navigatorContextFactory.Supply(builder => // MessageType.MessagePinned => ActionType.MessagePinned, // MessageType.ChatPhotoDeleted => ActionType.ChatPhotoDeleted, // MessageType.GroupCreated => ActionType.GroupCreated, - // MessageType.SupergroupCreated => ActionType.SupergroupCreated, - // MessageType.ChannelCreated => ActionType.ChannelCreated, + MessageType.SupergroupCreated => typeof(SupergroupCreatedAction).FullName, + MessageType.ChannelCreated => typeof(ChannelCreatedAction).FullName, // MessageType.MigratedToSupergroup => ActionType.MigratedToSupergroup, // MessageType.MigratedFromGroup => ActionType.MigratedFromGroup, // MessageType.Dice => ActionType.MigratedFromGroup, @@ -84,10 +85,10 @@ await _navigatorContextFactory.Supply(builder => UpdateType.ChosenInlineResult => typeof(ChosenInlineResultAction).FullName, UpdateType.CallbackQuery => typeof(CallbackQueryAction).FullName, UpdateType.EditedMessage => typeof(EditedMessageAction).FullName, - // UpdateType.ChannelPost => ActionType.ChannelPost, + UpdateType.ChannelPost => typeof(ChannelPostAction).FullName, // UpdateType.EditedChannelPost => ActionType.EditedChannelPost, - // UpdateType.ShippingQuery => ActionType.ShippingQuery, - // UpdateType.PreCheckoutQuery => ActionType.PreCheckoutQuery, + UpdateType.ShippingQuery => typeof(ShippingQueryAction).FullName, + UpdateType.PreCheckoutQuery => typeof(PreCheckoutQuery).FullName, UpdateType.Poll => typeof(PollAction).FullName, // UpdateType.PollAnswer => typeof(PollAction).FullName, // UpdateType.MyChatMember => typeof(UnknownAction).FullName, diff --git a/src/Navigator/Navigator.csproj b/src/Navigator/Navigator.csproj index 811b1f2..99a0901 100644 --- a/src/Navigator/Navigator.csproj +++ b/src/Navigator/Navigator.csproj @@ -1,7 +1,7 @@  - net5.0 + net6.0 enable true Navigator Framework @@ -22,9 +22,9 @@ - - - + + + From 40851062493664a0ccfa8eb491f23fa088a98053 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sun, 5 Dec 2021 12:53:18 +0100 Subject: [PATCH 163/304] feat: update sample to .net 6 --- .../Actions/EchoActionHandler.cs | 1 + .../Actions/EditedEchoAction.cs | 18 ----- .../Actions/EditedEchoActionHandler.cs | 24 ------ .../Navigator.Samples.Echo.csproj | 17 ++-- src/Navigator.Samples.Echo/Program.cs | 79 ++++++++----------- src/Navigator.Samples.Echo/Startup.cs | 54 ------------- src/Navigator.Samples.Echo/WeatherForecast.cs | 12 +++ .../appsettings.Development.json | 6 ++ src/Navigator.Samples.Echo/appsettings.json | 10 ++- src/Navigator.sln | 14 ++-- 10 files changed, 73 insertions(+), 162 deletions(-) delete mode 100644 src/Navigator.Samples.Echo/Actions/EditedEchoAction.cs delete mode 100644 src/Navigator.Samples.Echo/Actions/EditedEchoActionHandler.cs delete mode 100644 src/Navigator.Samples.Echo/Startup.cs create mode 100644 src/Navigator.Samples.Echo/WeatherForecast.cs diff --git a/src/Navigator.Samples.Echo/Actions/EchoActionHandler.cs b/src/Navigator.Samples.Echo/Actions/EchoActionHandler.cs index 9d45e1d..132cef9 100644 --- a/src/Navigator.Samples.Echo/Actions/EchoActionHandler.cs +++ b/src/Navigator.Samples.Echo/Actions/EchoActionHandler.cs @@ -4,6 +4,7 @@ using Navigator.Actions; using Navigator.Context; using Navigator.Providers.Telegram; +using Telegram.Bot; namespace Navigator.Samples.Echo.Actions { diff --git a/src/Navigator.Samples.Echo/Actions/EditedEchoAction.cs b/src/Navigator.Samples.Echo/Actions/EditedEchoAction.cs deleted file mode 100644 index 4cc8853..0000000 --- a/src/Navigator.Samples.Echo/Actions/EditedEchoAction.cs +++ /dev/null @@ -1,18 +0,0 @@ -using Navigator.Context; -using Navigator.Providers.Telegram.Actions; -using Navigator.Providers.Telegram.Actions.Updates; - -namespace Navigator.Samples.Echo.Actions -{ - public class EditedEchoAction : EditedMessageAction - { - public EditedEchoAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) - { - } - - public override bool CanHandleCurrentContext() - { - return true; - } - } -} \ No newline at end of file diff --git a/src/Navigator.Samples.Echo/Actions/EditedEchoActionHandler.cs b/src/Navigator.Samples.Echo/Actions/EditedEchoActionHandler.cs deleted file mode 100644 index 608d91c..0000000 --- a/src/Navigator.Samples.Echo/Actions/EditedEchoActionHandler.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System.Threading; -using System.Threading.Tasks; -using MediatR; -using Navigator.Actions; -using Navigator.Context; -using Navigator.Providers.Telegram; - -namespace Navigator.Samples.Echo.Actions -{ - public class EditedEchoActionHandler : ActionHandler - { - public EditedEchoActionHandler(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) - { - } - - public override async Task Handle(EditedEchoAction action, CancellationToken cancellationToken) - { - await NavigatorContext.Provider.GetTelegramClient().SendTextMessageAsync(NavigatorContext.GetTelegramChat(), - action.EditedMessage.Text, cancellationToken: cancellationToken); - - return Success(); - } - } -} \ No newline at end of file diff --git a/src/Navigator.Samples.Echo/Navigator.Samples.Echo.csproj b/src/Navigator.Samples.Echo/Navigator.Samples.Echo.csproj index 3676fe1..66c450d 100644 --- a/src/Navigator.Samples.Echo/Navigator.Samples.Echo.csproj +++ b/src/Navigator.Samples.Echo/Navigator.Samples.Echo.csproj @@ -1,21 +1,18 @@ - + - net5.0 + net6.0 enable - 9 + enable - - - - + - - + + - + diff --git a/src/Navigator.Samples.Echo/Program.cs b/src/Navigator.Samples.Echo/Program.cs index 44db3d3..96bd75b 100644 --- a/src/Navigator.Samples.Echo/Program.cs +++ b/src/Navigator.Samples.Echo/Program.cs @@ -1,47 +1,34 @@ -using System; -using System.IO; -using Ele.Extensions.Configuration; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.Hosting; -using Serilog; -using ConfigurationExtensions = Ele.Extensions.Configuration.ConfigurationExtensions; - -namespace Navigator.Samples.Echo +using Navigator; +using Navigator.Configuration; +using Navigator.Providers.Telegram; + +var builder = WebApplication.CreateBuilder(args); + +// Add services to the container. + +builder.Services.AddControllers(); +// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle +builder.Services.AddEndpointsApiExplorer(); +builder.Services.AddSwaggerGen(); + +builder.Services.AddNavigator(options => +{ + options.SetWebHookBaseUrl(builder.Configuration["BASE_WEBHOOK_URL"]); + options.RegisterActionsFromAssemblies(typeof(Program).Assembly); +}).WithProvider.Telegram(options => { options.SetTelegramToken(builder.Configuration["BOT_TOKEN"]); }); + +var app = builder.Build(); + +// Configure the HTTP request pipeline. +if (app.Environment.IsDevelopment()) { - public class Program - { - private static IConfiguration Configuration { get; } = ConfigurationExtensions.LoadConfiguration(Directory.GetCurrentDirectory()); - - - public static IHostBuilder CreateHostBuilder(string[] args) => - Host.CreateDefaultBuilder(args) - .ConfigureWebHostDefaults(webBuilder => - { - webBuilder.UseStartup(); - webBuilder.UseSerilog(); - }); - - public static void Main(string[] args) - { - Log.Logger = LoggingExtensions.LoadLogger(Configuration); - - try - { - var host = CreateHostBuilder(args).Build(); - - Log.Information("Starting WebApi"); - - host.Run(); - } - catch (Exception ex) - { - Log.Fatal(ex, "WebApi terminated unexpectedly"); - } - finally - { - Log.CloseAndFlush(); - } - } - } -} \ No newline at end of file + app.UseSwagger(); + app.UseSwaggerUI(); +} + +app.UseHttpsRedirection(); + +app.MapNavigator() + .ForProvider.Telegram(); + +app.Run(); \ No newline at end of file diff --git a/src/Navigator.Samples.Echo/Startup.cs b/src/Navigator.Samples.Echo/Startup.cs deleted file mode 100644 index fe16ad0..0000000 --- a/src/Navigator.Samples.Echo/Startup.cs +++ /dev/null @@ -1,54 +0,0 @@ -using MediatR; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Hosting; -using Navigator.Configuration; -using Navigator.Providers.Telegram; - -namespace Navigator.Samples.Echo -{ - public class Startup - { - public Startup(IConfiguration configuration) - { - Configuration = configuration; - } - - public IConfiguration Configuration { get; } - - // This method gets called by the runtime. Use this method to add services to the container. - public void ConfigureServices(IServiceCollection services) - { - services.AddControllers().AddNewtonsoftJson(); - - services.AddNavigator(options => - { - options.SetWebHookBaseUrl(Configuration["BASE_WEBHOOK_URL"]); - options.RegisterActionsFromAssemblies(typeof(Startup).Assembly); - }).WithProvider.Telegram(options => - { - options.SetTelegramToken(Configuration["BOT_TOKEN"]); - }); - } - - // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. - public void Configure(IApplicationBuilder app, IWebHostEnvironment env) - { - if (env.IsDevelopment()) - { - app.UseDeveloperExceptionPage(); - } - - app.UseRouting(); - - app.UseEndpoints(endpoints => - { - endpoints.MapControllers(); - endpoints.MapNavigator() - .ForProvider.Telegram(); - }); - } - } -} \ No newline at end of file diff --git a/src/Navigator.Samples.Echo/WeatherForecast.cs b/src/Navigator.Samples.Echo/WeatherForecast.cs new file mode 100644 index 0000000..e56a3d0 --- /dev/null +++ b/src/Navigator.Samples.Echo/WeatherForecast.cs @@ -0,0 +1,12 @@ +namespace Navigator.Samples.Echo; + +public class WeatherForecast +{ + public DateTime Date { get; set; } + + public int TemperatureC { get; set; } + + public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); + + public string? Summary { get; set; } +} \ No newline at end of file diff --git a/src/Navigator.Samples.Echo/appsettings.Development.json b/src/Navigator.Samples.Echo/appsettings.Development.json index 2c63c08..0c208ae 100644 --- a/src/Navigator.Samples.Echo/appsettings.Development.json +++ b/src/Navigator.Samples.Echo/appsettings.Development.json @@ -1,2 +1,8 @@ { + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } } diff --git a/src/Navigator.Samples.Echo/appsettings.json b/src/Navigator.Samples.Echo/appsettings.json index 0b50a2f..10f68b8 100644 --- a/src/Navigator.Samples.Echo/appsettings.json +++ b/src/Navigator.Samples.Echo/appsettings.json @@ -1,5 +1,9 @@ { - "ConnectionStrings": { - "DefaultConnection": "DataSource=app.db" - } + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" } diff --git a/src/Navigator.sln b/src/Navigator.sln index 618ec51..7bc4742 100644 --- a/src/Navigator.sln +++ b/src/Navigator.sln @@ -2,8 +2,6 @@ Microsoft Visual Studio Solution File, Format Version 12.00 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Navigator", "Navigator\Navigator.csproj", "{6DBAD041-6623-4903-9939-254FDC4EBD60}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Navigator.Samples.Echo", "Navigator.Samples.Echo\Navigator.Samples.Echo.csproj", "{7E8F867E-70E1-4C5B-AE65-A2C6822BFD6E}" -EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Navigator.Extensions.Store", "Navigator.Extensions.Store\Navigator.Extensions.Store.csproj", "{9DEA166A-AE92-438F-8F3D-7C2F777ABBDD}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Navigator.Extensions.Actions", "Navigator.Extensions.Actions\Navigator.Extensions.Actions.csproj", "{2711B76D-B24C-4A3A-A33F-5A0077C49CB6}" @@ -34,6 +32,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Providers", "Providers", "{ EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Navigator.Providers.Telegram", "Navigator.Providers.Telegram\Navigator.Providers.Telegram.csproj", "{8E0F6DCA-FAA4-4FA8-B9E0-75E9DC0F3573}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Navigator.Samples.Echo", "Navigator.Samples.Echo\Navigator.Samples.Echo.csproj", "{4F4CEC5E-5FAF-4914-8EC0-E6BC9EB1B975}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -44,10 +44,6 @@ Global {6DBAD041-6623-4903-9939-254FDC4EBD60}.Debug|Any CPU.Build.0 = Debug|Any CPU {6DBAD041-6623-4903-9939-254FDC4EBD60}.Release|Any CPU.ActiveCfg = Release|Any CPU {6DBAD041-6623-4903-9939-254FDC4EBD60}.Release|Any CPU.Build.0 = Release|Any CPU - {7E8F867E-70E1-4C5B-AE65-A2C6822BFD6E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {7E8F867E-70E1-4C5B-AE65-A2C6822BFD6E}.Debug|Any CPU.Build.0 = Debug|Any CPU - {7E8F867E-70E1-4C5B-AE65-A2C6822BFD6E}.Release|Any CPU.ActiveCfg = Release|Any CPU - {7E8F867E-70E1-4C5B-AE65-A2C6822BFD6E}.Release|Any CPU.Build.0 = Release|Any CPU {9DEA166A-AE92-438F-8F3D-7C2F777ABBDD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9DEA166A-AE92-438F-8F3D-7C2F777ABBDD}.Debug|Any CPU.Build.0 = Debug|Any CPU {9DEA166A-AE92-438F-8F3D-7C2F777ABBDD}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -76,9 +72,12 @@ Global {8E0F6DCA-FAA4-4FA8-B9E0-75E9DC0F3573}.Debug|Any CPU.Build.0 = Debug|Any CPU {8E0F6DCA-FAA4-4FA8-B9E0-75E9DC0F3573}.Release|Any CPU.ActiveCfg = Release|Any CPU {8E0F6DCA-FAA4-4FA8-B9E0-75E9DC0F3573}.Release|Any CPU.Build.0 = Release|Any CPU + {4F4CEC5E-5FAF-4914-8EC0-E6BC9EB1B975}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {4F4CEC5E-5FAF-4914-8EC0-E6BC9EB1B975}.Debug|Any CPU.Build.0 = Debug|Any CPU + {4F4CEC5E-5FAF-4914-8EC0-E6BC9EB1B975}.Release|Any CPU.ActiveCfg = Release|Any CPU + {4F4CEC5E-5FAF-4914-8EC0-E6BC9EB1B975}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(NestedProjects) = preSolution - {7E8F867E-70E1-4C5B-AE65-A2C6822BFD6E} = {6D6A8E40-8C40-49AA-BEAD-B046D43F511A} {F178DCF2-AD03-44C8-AF8F-95C60664DD10} = {895808DE-1CA6-406C-924A-7E43F293CF7D} {E6F24E3B-A066-4572-94F0-14665E19EFC7} = {895808DE-1CA6-406C-924A-7E43F293CF7D} {6DBAD041-6623-4903-9939-254FDC4EBD60} = {E6F24E3B-A066-4572-94F0-14665E19EFC7} @@ -93,5 +92,6 @@ Global {294C1716-C054-4585-B66E-C79D155AE684} = {E2FF61C3-F081-40C8-9CC3-BBE1F81543F6} {DAA22477-BB29-475C-AD2C-905F81B4AD8E} = {895808DE-1CA6-406C-924A-7E43F293CF7D} {8E0F6DCA-FAA4-4FA8-B9E0-75E9DC0F3573} = {DAA22477-BB29-475C-AD2C-905F81B4AD8E} + {4F4CEC5E-5FAF-4914-8EC0-E6BC9EB1B975} = {6D6A8E40-8C40-49AA-BEAD-B046D43F511A} EndGlobalSection EndGlobal From e94b902085d8ef434de974af9b99fbe4e1692bb4 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sun, 5 Dec 2021 12:56:17 +0100 Subject: [PATCH 164/304] feat: update GetMeAsync to GetProfile --- .../NavigatorTelegramClient.cs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/Navigator.Providers.Telegram/NavigatorTelegramClient.cs b/src/Navigator.Providers.Telegram/NavigatorTelegramClient.cs index cffd12a..dd4f10b 100644 --- a/src/Navigator.Providers.Telegram/NavigatorTelegramClient.cs +++ b/src/Navigator.Providers.Telegram/NavigatorTelegramClient.cs @@ -1,3 +1,4 @@ +using System; using System.Threading; using System.Threading.Tasks; using Navigator.Configuration; @@ -9,17 +10,17 @@ namespace Navigator.Providers.Telegram public class NavigatorTelegramClient : TelegramBotClient, INavigatorClient { public NavigatorTelegramClient(INavigatorOptions options) - : base(options.GetTelegramToken()) + : base(options.GetTelegramToken() ?? throw new ArgumentNullException()) { } public async Task GetProfile(CancellationToken cancellationToken = default) { - var bot = await GetMeAsync(cancellationToken); + var bot = await this.GetProfile(cancellationToken); return new BotUser { - Id = bot.Id.ToString(), + Id = bot.Id, Username = bot.Username }; } From 2c6c60283c174657e5607eee5d785b9b16cfdb11 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sun, 5 Dec 2021 14:17:40 +0100 Subject: [PATCH 165/304] feat: various changes --- .../ChannelCreatedAction.cs | 9 -------- .../Actions/Updates/ChannelCreatedAction.cs | 23 +++++++++++++++++++ .../Actions/Updates/ChannelPostAction.cs | 23 +++++++++++++++++++ .../Actions/Updates/PreCheckoutQueryAction.cs | 21 +++++++++++++++++ .../Actions/Updates/ShippingQueryAction.cs | 21 +++++++++++++++++ .../Updates/SupergroupCreatedAction.cs | 21 +++++++++++++++++ .../Navigator.Providers.Telegram.csproj | 4 ++++ ...torRouteProviderConfigurationExtensions.cs | 9 ++++---- .../TelegramMiddleware.cs | 5 ++-- .../Navigator.Samples.Echo.csproj | 5 ---- src/Navigator.Samples.Echo/Program.cs | 10 +++++--- src/Navigator.Samples.Echo/WeatherForecast.cs | 12 ---------- .../Context/NavigatorContextAccessor.cs | 9 +++++++- 13 files changed, 135 insertions(+), 37 deletions(-) delete mode 100644 src/Navigator.Extensions.Actions/ChannelCreatedAction.cs create mode 100644 src/Navigator.Providers.Telegram/Actions/Updates/ChannelCreatedAction.cs create mode 100644 src/Navigator.Providers.Telegram/Actions/Updates/ChannelPostAction.cs create mode 100644 src/Navigator.Providers.Telegram/Actions/Updates/PreCheckoutQueryAction.cs create mode 100644 src/Navigator.Providers.Telegram/Actions/Updates/ShippingQueryAction.cs create mode 100644 src/Navigator.Providers.Telegram/Actions/Updates/SupergroupCreatedAction.cs delete mode 100644 src/Navigator.Samples.Echo/WeatherForecast.cs diff --git a/src/Navigator.Extensions.Actions/ChannelCreatedAction.cs b/src/Navigator.Extensions.Actions/ChannelCreatedAction.cs deleted file mode 100644 index 63df302..0000000 --- a/src/Navigator.Extensions.Actions/ChannelCreatedAction.cs +++ /dev/null @@ -1,9 +0,0 @@ -using Navigator.Abstractions; - -namespace Navigator.Extensions.Actions -{ - public abstract class ChannelCreatedAction : Action - { - public override string Type => ActionType.ChannelCreated; - } -} \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/ChannelCreatedAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/ChannelCreatedAction.cs new file mode 100644 index 0000000..37f074e --- /dev/null +++ b/src/Navigator.Providers.Telegram/Actions/Updates/ChannelCreatedAction.cs @@ -0,0 +1,23 @@ +using Navigator.Actions; +using Navigator.Context; + +namespace Navigator.Providers.Telegram.Actions.Updates +{ + /// + /// TODO + /// + public abstract class ChannelCreatedAction : BaseAction + { + /// + public override string Type { get; protected set; } = typeof(ChannelCreatedAction).FullName!; + + /// + protected ChannelCreatedAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) + { + //TODO + } + + + + } +} \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/ChannelPostAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/ChannelPostAction.cs new file mode 100644 index 0000000..d35a697 --- /dev/null +++ b/src/Navigator.Providers.Telegram/Actions/Updates/ChannelPostAction.cs @@ -0,0 +1,23 @@ +using Navigator.Actions; +using Navigator.Context; + +namespace Navigator.Providers.Telegram.Actions.Updates +{ + /// + /// TODO + /// + public abstract class ChannelPostAction : BaseAction + { + /// + public override string Type { get; protected set; } = typeof(ChannelPostAction).FullName!; + + /// + protected ChannelPostAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) + { + //TODO + } + + + + } +} \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/PreCheckoutQueryAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/PreCheckoutQueryAction.cs new file mode 100644 index 0000000..3a9b8a2 --- /dev/null +++ b/src/Navigator.Providers.Telegram/Actions/Updates/PreCheckoutQueryAction.cs @@ -0,0 +1,21 @@ +using Navigator.Actions; +using Navigator.Context; + +namespace Navigator.Providers.Telegram.Actions.Updates +{ + /// + /// TODO + /// + public abstract class PreCheckoutQueryAction : BaseAction + { + /// + public override string Type { get; protected set; } = typeof(PreCheckoutQueryAction).FullName!; + + /// + protected PreCheckoutQueryAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) + { + //TODO + } + + } +} \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/ShippingQueryAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/ShippingQueryAction.cs new file mode 100644 index 0000000..5e1170f --- /dev/null +++ b/src/Navigator.Providers.Telegram/Actions/Updates/ShippingQueryAction.cs @@ -0,0 +1,21 @@ +using Navigator.Actions; +using Navigator.Context; + +namespace Navigator.Providers.Telegram.Actions.Updates +{ + /// + /// TODO + /// + public abstract class ShippingQueryAction : BaseAction + { + /// + public override string Type { get; protected set; } = typeof(ShippingQueryAction).FullName!; + + /// + protected ShippingQueryAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) + { + //TODO + } + + } +} \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/SupergroupCreatedAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/SupergroupCreatedAction.cs new file mode 100644 index 0000000..8835255 --- /dev/null +++ b/src/Navigator.Providers.Telegram/Actions/Updates/SupergroupCreatedAction.cs @@ -0,0 +1,21 @@ +using Navigator.Actions; +using Navigator.Context; + +namespace Navigator.Providers.Telegram.Actions.Updates +{ + /// + /// TODO + /// + public abstract class SupergroupCreatedAction : BaseAction + { + /// + public override string Type { get; protected set; } = typeof(SupergroupCreatedAction).FullName!; + + /// + protected SupergroupCreatedAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) + { + //TODO + } + + } +} \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/Navigator.Providers.Telegram.csproj b/src/Navigator.Providers.Telegram/Navigator.Providers.Telegram.csproj index f2b4683..deba361 100644 --- a/src/Navigator.Providers.Telegram/Navigator.Providers.Telegram.csproj +++ b/src/Navigator.Providers.Telegram/Navigator.Providers.Telegram.csproj @@ -15,6 +15,10 @@ Copyright © Lucas Maximiliano Marino 2021 https://raw.githubusercontent.com/navigatorframework/navigator/master/assets/logo.png + + + full + diff --git a/src/Navigator.Providers.Telegram/NavigatorRouteProviderConfigurationExtensions.cs b/src/Navigator.Providers.Telegram/NavigatorRouteProviderConfigurationExtensions.cs index 84d9543..1452ac3 100644 --- a/src/Navigator.Providers.Telegram/NavigatorRouteProviderConfigurationExtensions.cs +++ b/src/Navigator.Providers.Telegram/NavigatorRouteProviderConfigurationExtensions.cs @@ -37,11 +37,12 @@ private static async Task ProcessTelegramUpdate(HttpContext context) if (telegramUpdate is not null) { - using var scope = context.RequestServices.CreateScope(); + await using (var scope = context.RequestServices.CreateAsyncScope()) + { + var navigatorMiddleware = scope.ServiceProvider.GetRequiredService(); - var navigatorMiddleware = context.RequestServices.GetRequiredService(); - - await navigatorMiddleware.Process(telegramUpdate); + await navigatorMiddleware.Process(telegramUpdate); + } } } diff --git a/src/Navigator.Providers.Telegram/TelegramMiddleware.cs b/src/Navigator.Providers.Telegram/TelegramMiddleware.cs index 8472457..ae4ccb3 100644 --- a/src/Navigator.Providers.Telegram/TelegramMiddleware.cs +++ b/src/Navigator.Providers.Telegram/TelegramMiddleware.cs @@ -6,7 +6,6 @@ using Navigator.Providers.Telegram.Actions; using Navigator.Providers.Telegram.Actions.Messages; using Navigator.Providers.Telegram.Actions.Updates; -using Navigator.Providers.Telegram.Entities; using Navigator.Providers.Telegram.Extensions; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; @@ -14,7 +13,7 @@ namespace Navigator.Providers.Telegram { - internal class TelegramMiddleware + public class TelegramMiddleware { private readonly ILogger _logger; private readonly INavigatorContextFactory _navigatorContextFactory; @@ -51,7 +50,7 @@ await _navigatorContextFactory.Supply(builder => { return update.Type switch { - UpdateType.Message when update.Message.Entities?.First()?.Type == MessageEntityType.BotCommand => typeof(CommandAction).FullName, + UpdateType.Message when update.Message?.Entities?.First()?.Type == MessageEntityType.BotCommand => typeof(CommandAction).FullName, UpdateType.Message => update.Message.Type switch { MessageType.Document => typeof(DocumentAction).FullName, diff --git a/src/Navigator.Samples.Echo/Navigator.Samples.Echo.csproj b/src/Navigator.Samples.Echo/Navigator.Samples.Echo.csproj index 66c450d..0744581 100644 --- a/src/Navigator.Samples.Echo/Navigator.Samples.Echo.csproj +++ b/src/Navigator.Samples.Echo/Navigator.Samples.Echo.csproj @@ -3,13 +3,8 @@ net6.0 enable - enable - - - - diff --git a/src/Navigator.Samples.Echo/Program.cs b/src/Navigator.Samples.Echo/Program.cs index 96bd75b..fbd583b 100644 --- a/src/Navigator.Samples.Echo/Program.cs +++ b/src/Navigator.Samples.Echo/Program.cs @@ -1,6 +1,10 @@ +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Navigator; using Navigator.Configuration; using Navigator.Providers.Telegram; +using Navigator.Samples.Echo.Actions; var builder = WebApplication.CreateBuilder(args); @@ -14,7 +18,7 @@ builder.Services.AddNavigator(options => { options.SetWebHookBaseUrl(builder.Configuration["BASE_WEBHOOK_URL"]); - options.RegisterActionsFromAssemblies(typeof(Program).Assembly); + options.RegisterActionsFromAssemblies(typeof(EchoAction).Assembly); }).WithProvider.Telegram(options => { options.SetTelegramToken(builder.Configuration["BOT_TOKEN"]); }); var app = builder.Build(); @@ -22,8 +26,8 @@ // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { - app.UseSwagger(); - app.UseSwaggerUI(); + // app.UseSwagger(); + // app.UseSwaggerUI(); } app.UseHttpsRedirection(); diff --git a/src/Navigator.Samples.Echo/WeatherForecast.cs b/src/Navigator.Samples.Echo/WeatherForecast.cs deleted file mode 100644 index e56a3d0..0000000 --- a/src/Navigator.Samples.Echo/WeatherForecast.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace Navigator.Samples.Echo; - -public class WeatherForecast -{ - public DateTime Date { get; set; } - - public int TemperatureC { get; set; } - - public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); - - public string? Summary { get; set; } -} \ No newline at end of file diff --git a/src/Navigator/Context/NavigatorContextAccessor.cs b/src/Navigator/Context/NavigatorContextAccessor.cs index 94dd44f..1cef33d 100644 --- a/src/Navigator/Context/NavigatorContextAccessor.cs +++ b/src/Navigator/Context/NavigatorContextAccessor.cs @@ -9,6 +9,13 @@ public NavigatorContextAccessor(INavigatorContextFactory navigatorContextFactory _navigatorContextFactory = navigatorContextFactory; } - public INavigatorContext NavigatorContext => _navigatorContextFactory.Retrieve(); + public INavigatorContext NavigatorContext + { + get + { + var a = 1; + return _navigatorContextFactory.Retrieve(); + } + } } } \ No newline at end of file From faacad69bdad2998a9eebd01bc12269b5b2d290d Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sun, 5 Dec 2021 14:43:41 +0100 Subject: [PATCH 166/304] feat: delete swagger from sample --- src/Navigator.Samples.Echo/Program.cs | 6 ------ 1 file changed, 6 deletions(-) diff --git a/src/Navigator.Samples.Echo/Program.cs b/src/Navigator.Samples.Echo/Program.cs index fbd583b..f6db33c 100644 --- a/src/Navigator.Samples.Echo/Program.cs +++ b/src/Navigator.Samples.Echo/Program.cs @@ -9,12 +9,6 @@ var builder = WebApplication.CreateBuilder(args); // Add services to the container. - -builder.Services.AddControllers(); -// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle -builder.Services.AddEndpointsApiExplorer(); -builder.Services.AddSwaggerGen(); - builder.Services.AddNavigator(options => { options.SetWebHookBaseUrl(builder.Configuration["BASE_WEBHOOK_URL"]); From 0a640dbd29c500aebd1d8a44cc4b52afb76db65e Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 6 Dec 2021 11:21:46 +0100 Subject: [PATCH 167/304] feat: move action type outside of IAction --- src/Navigator/Actions/BaseAction.cs | 3 --- src/Navigator/Actions/IAction.cs | 5 ----- 2 files changed, 8 deletions(-) diff --git a/src/Navigator/Actions/BaseAction.cs b/src/Navigator/Actions/BaseAction.cs index d72ee5c..7209cd6 100644 --- a/src/Navigator/Actions/BaseAction.cs +++ b/src/Navigator/Actions/BaseAction.cs @@ -12,9 +12,6 @@ public abstract class BaseAction : IAction /// Used to access inside the action. /// protected readonly INavigatorContextAccessor NavigatorContextAccessor; - - /// - public abstract string Type { get; protected set; } /// public virtual ushort Priority { get; protected set; } = Actions.Priority.Default; diff --git a/src/Navigator/Actions/IAction.cs b/src/Navigator/Actions/IAction.cs index 38afad6..25d391b 100644 --- a/src/Navigator/Actions/IAction.cs +++ b/src/Navigator/Actions/IAction.cs @@ -8,11 +8,6 @@ namespace Navigator.Actions /// public interface IAction : IRequest { - /// - /// Type of the action. - /// - string Type { get; } - /// /// Priority of the action when launching multiple actions. /// From ad10d2165fe4e15aa268fbea1fd2aacc608a0d8a Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 6 Dec 2021 11:22:10 +0100 Subject: [PATCH 168/304] feat: adapt telegram actions to new IAction --- .../Actions/Messages/CommandAction.cs | 3 --- .../Actions/Messages/MessageAction.cs | 5 ++--- src/Navigator.Providers.Telegram/Actions/UnknownAction.cs | 5 +---- .../Actions/Updates/CallbackQueryAction.cs | 3 --- .../Actions/Updates/ChannelCreatedAction.cs | 3 --- .../Actions/Updates/ChannelPostAction.cs | 3 --- .../Actions/Updates/ChosenInlineResultAction.cs | 3 --- .../Actions/Updates/DocumentAction.cs | 2 -- .../Actions/Updates/EditedMessageAction.cs | 3 --- .../Actions/Updates/InlineQueryAction.cs | 3 --- .../Actions/Updates/PollAction.cs | 3 --- .../Actions/Updates/PreCheckoutQueryAction.cs | 3 --- .../Actions/Updates/ShippingQueryAction.cs | 3 --- .../Actions/Updates/SupergroupCreatedAction.cs | 3 --- 14 files changed, 3 insertions(+), 42 deletions(-) diff --git a/src/Navigator.Providers.Telegram/Actions/Messages/CommandAction.cs b/src/Navigator.Providers.Telegram/Actions/Messages/CommandAction.cs index 51b4909..d7562be 100644 --- a/src/Navigator.Providers.Telegram/Actions/Messages/CommandAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Messages/CommandAction.cs @@ -9,9 +9,6 @@ namespace Navigator.Providers.Telegram.Actions.Messages /// public abstract class CommandAction : MessageAction { - /// - public override string Type { get; protected set; } = typeof(CommandAction).FullName!; - /// /// Command. /// diff --git a/src/Navigator.Providers.Telegram/Actions/Messages/MessageAction.cs b/src/Navigator.Providers.Telegram/Actions/Messages/MessageAction.cs index 8eaa5db..672c0cd 100644 --- a/src/Navigator.Providers.Telegram/Actions/Messages/MessageAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Messages/MessageAction.cs @@ -1,3 +1,5 @@ +using System.ComponentModel; +using System.Reflection; using Navigator.Actions; using Navigator.Context; using Navigator.Context.Extensions; @@ -10,9 +12,6 @@ namespace Navigator.Providers.Telegram.Actions.Messages /// public abstract class MessageAction : BaseAction { - /// - public override string Type { get; protected set; } = typeof(MessageAction).FullName!; - /// /// The original Message. /// diff --git a/src/Navigator.Providers.Telegram/Actions/UnknownAction.cs b/src/Navigator.Providers.Telegram/Actions/UnknownAction.cs index 9bddbe1..bf33a40 100644 --- a/src/Navigator.Providers.Telegram/Actions/UnknownAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/UnknownAction.cs @@ -4,10 +4,7 @@ namespace Navigator.Providers.Telegram.Actions { public abstract class UnknownAction : BaseAction - { - /// - public override string Type { get; protected set; } = typeof(UnknownAction).FullName!; - + { /// protected UnknownAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) { diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/CallbackQueryAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/CallbackQueryAction.cs index c12606c..70326f5 100644 --- a/src/Navigator.Providers.Telegram/Actions/Updates/CallbackQueryAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/CallbackQueryAction.cs @@ -10,9 +10,6 @@ namespace Navigator.Providers.Telegram.Actions.Updates /// public abstract class CallbackQueryAction : BaseAction { - /// - public override string Type { get; protected set; } = typeof(CallbackQueryAction).FullName!; - /// /// The original /// diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/ChannelCreatedAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/ChannelCreatedAction.cs index 37f074e..80cfb54 100644 --- a/src/Navigator.Providers.Telegram/Actions/Updates/ChannelCreatedAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/ChannelCreatedAction.cs @@ -8,9 +8,6 @@ namespace Navigator.Providers.Telegram.Actions.Updates /// public abstract class ChannelCreatedAction : BaseAction { - /// - public override string Type { get; protected set; } = typeof(ChannelCreatedAction).FullName!; - /// protected ChannelCreatedAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) { diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/ChannelPostAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/ChannelPostAction.cs index d35a697..8b8f25d 100644 --- a/src/Navigator.Providers.Telegram/Actions/Updates/ChannelPostAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/ChannelPostAction.cs @@ -8,9 +8,6 @@ namespace Navigator.Providers.Telegram.Actions.Updates /// public abstract class ChannelPostAction : BaseAction { - /// - public override string Type { get; protected set; } = typeof(ChannelPostAction).FullName!; - /// protected ChannelPostAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) { diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/ChosenInlineResultAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/ChosenInlineResultAction.cs index 17e9fe7..30d0faf 100644 --- a/src/Navigator.Providers.Telegram/Actions/Updates/ChosenInlineResultAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/ChosenInlineResultAction.cs @@ -10,9 +10,6 @@ namespace Navigator.Providers.Telegram.Actions.Updates /// public abstract class ChosenInlineResultAction : BaseAction { - /// - public override string Type { get; protected set; } = typeof(ChosenInlineResultAction).FullName!; - /// /// The original chosen inline result. /// diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/DocumentAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/DocumentAction.cs index 2d4b24c..5892b5e 100644 --- a/src/Navigator.Providers.Telegram/Actions/Updates/DocumentAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/DocumentAction.cs @@ -9,8 +9,6 @@ namespace Navigator.Providers.Telegram.Actions.Updates /// public abstract class DocumentAction : BaseAction { - public override string Type { get; protected set; } = typeof(DocumentAction).FullName!; - /// public DocumentAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) { diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/EditedMessageAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/EditedMessageAction.cs index 27ced25..1cf212d 100644 --- a/src/Navigator.Providers.Telegram/Actions/Updates/EditedMessageAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/EditedMessageAction.cs @@ -10,9 +10,6 @@ namespace Navigator.Providers.Telegram.Actions.Updates /// public abstract class EditedMessageAction : BaseAction { - /// - public override string Type { get; protected set; } = typeof(EditedMessageAction).FullName!; - /// /// TODO /// diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/InlineQueryAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/InlineQueryAction.cs index 2fabb5d..c55e7cd 100644 --- a/src/Navigator.Providers.Telegram/Actions/Updates/InlineQueryAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/InlineQueryAction.cs @@ -10,9 +10,6 @@ namespace Navigator.Providers.Telegram.Actions.Updates /// public abstract class InlineQueryAction : BaseAction { - /// - public override string Type { get; protected set; } = typeof(InlineQueryAction).FullName!; - /// /// The original /// diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/PollAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/PollAction.cs index e8eb7a1..7ca6571 100644 --- a/src/Navigator.Providers.Telegram/Actions/Updates/PollAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/PollAction.cs @@ -10,9 +10,6 @@ namespace Navigator.Providers.Telegram.Actions.Updates /// public abstract class PollAction : BaseAction { - /// - public override string Type { get; protected set; } = typeof(PollAction).FullName!; - /// /// The original Poll. /// diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/PreCheckoutQueryAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/PreCheckoutQueryAction.cs index 3a9b8a2..f2c9a36 100644 --- a/src/Navigator.Providers.Telegram/Actions/Updates/PreCheckoutQueryAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/PreCheckoutQueryAction.cs @@ -8,9 +8,6 @@ namespace Navigator.Providers.Telegram.Actions.Updates /// public abstract class PreCheckoutQueryAction : BaseAction { - /// - public override string Type { get; protected set; } = typeof(PreCheckoutQueryAction).FullName!; - /// protected PreCheckoutQueryAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) { diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/ShippingQueryAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/ShippingQueryAction.cs index 5e1170f..9b3d82d 100644 --- a/src/Navigator.Providers.Telegram/Actions/Updates/ShippingQueryAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/ShippingQueryAction.cs @@ -8,9 +8,6 @@ namespace Navigator.Providers.Telegram.Actions.Updates /// public abstract class ShippingQueryAction : BaseAction { - /// - public override string Type { get; protected set; } = typeof(ShippingQueryAction).FullName!; - /// protected ShippingQueryAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) { diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/SupergroupCreatedAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/SupergroupCreatedAction.cs index 8835255..b602e7d 100644 --- a/src/Navigator.Providers.Telegram/Actions/Updates/SupergroupCreatedAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/SupergroupCreatedAction.cs @@ -8,9 +8,6 @@ namespace Navigator.Providers.Telegram.Actions.Updates /// public abstract class SupergroupCreatedAction : BaseAction { - /// - public override string Type { get; protected set; } = typeof(SupergroupCreatedAction).FullName!; - /// protected SupergroupCreatedAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) { From 9efe73868890befdf885aa222e7b95c9b4850434 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 6 Dec 2021 11:23:12 +0100 Subject: [PATCH 169/304] fix: correct client --- src/Navigator.Providers.Telegram/NavigatorTelegramClient.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Navigator.Providers.Telegram/NavigatorTelegramClient.cs b/src/Navigator.Providers.Telegram/NavigatorTelegramClient.cs index dd4f10b..917142e 100644 --- a/src/Navigator.Providers.Telegram/NavigatorTelegramClient.cs +++ b/src/Navigator.Providers.Telegram/NavigatorTelegramClient.cs @@ -16,11 +16,11 @@ public NavigatorTelegramClient(INavigatorOptions options) public async Task GetProfile(CancellationToken cancellationToken = default) { - var bot = await this.GetProfile(cancellationToken); + var bot = await this.GetMeAsync(cancellationToken); return new BotUser { - Id = bot.Id, + Id = bot.Id.ToString(), Username = bot.Username }; } From 1edeb87d673632ab45c73dbe13f9b781e7384311 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 6 Dec 2021 11:24:56 +0100 Subject: [PATCH 170/304] fix: correct NavigatorContextAccessor --- src/Navigator/Context/NavigatorContextAccessor.cs | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/src/Navigator/Context/NavigatorContextAccessor.cs b/src/Navigator/Context/NavigatorContextAccessor.cs index 1cef33d..94dd44f 100644 --- a/src/Navigator/Context/NavigatorContextAccessor.cs +++ b/src/Navigator/Context/NavigatorContextAccessor.cs @@ -9,13 +9,6 @@ public NavigatorContextAccessor(INavigatorContextFactory navigatorContextFactory _navigatorContextFactory = navigatorContextFactory; } - public INavigatorContext NavigatorContext - { - get - { - var a = 1; - return _navigatorContextFactory.Retrieve(); - } - } + public INavigatorContext NavigatorContext => _navigatorContextFactory.Retrieve(); } } \ No newline at end of file From 4a9128e1bfdca28894050ce230c48a9f0b699d91 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 6 Dec 2021 11:25:24 +0100 Subject: [PATCH 171/304] feat: new action discovery strategy --- src/Navigator/Actions/ActionLauncher.cs | 23 +++++---- src/Navigator/Actions/ActionTypeAttribute.cs | 11 +++++ .../Actions/Filters/CooldownActionFilter.cs | 2 +- .../Actions/NavigatorOptionsExtensions.cs | 49 +++++++++++++++++++ src/Navigator/ServiceCollectionExtensions.cs | 13 +++-- 5 files changed, 83 insertions(+), 15 deletions(-) create mode 100644 src/Navigator/Actions/ActionTypeAttribute.cs create mode 100644 src/Navigator/Actions/NavigatorOptionsExtensions.cs diff --git a/src/Navigator/Actions/ActionLauncher.cs b/src/Navigator/Actions/ActionLauncher.cs index 30b3bc8..a53c3f1 100644 --- a/src/Navigator/Actions/ActionLauncher.cs +++ b/src/Navigator/Actions/ActionLauncher.cs @@ -3,6 +3,7 @@ using System.Linq; using System.Threading.Tasks; using MediatR; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Navigator.Configuration; using Navigator.Context; @@ -11,20 +12,19 @@ namespace Navigator.Actions { internal class ActionLauncher : IActionLauncher { - private readonly INavigatorContextAccessor _navigatorContextAccessor; - private readonly IEnumerable _actions; + private readonly ILogger _logger; private readonly NavigatorOptions _navigatorOptions; + private readonly INavigatorContextAccessor _navigatorContextAccessor; + private readonly IServiceProvider _serviceProvider; private readonly ISender _sender; - private readonly ILogger _logger; - - public ActionLauncher(IEnumerable actions, NavigatorOptions navigatorOptions, - INavigatorContextAccessor navigatorContextAccessor, ISender sender, ILogger logger) + + public ActionLauncher(ILogger logger, NavigatorOptions navigatorOptions, INavigatorContextAccessor navigatorContextAccessor, IServiceProvider serviceProvider, ISender sender) { - _actions = actions; + _logger = logger; _navigatorOptions = navigatorOptions; _navigatorContextAccessor = navigatorContextAccessor; + _serviceProvider = serviceProvider; _sender = sender; - _logger = logger; } public async Task Launch() @@ -51,17 +51,20 @@ private IEnumerable GetActions() return Array.Empty(); } + var _actions = _navigatorOptions.RetrieveActions() + .Where(a => a.Key == _navigatorContextAccessor.NavigatorContext.ActionType); + if (_navigatorOptions.MultipleActionsUsageIsEnabled()) { return _actions - .Where(a => a.Type == _navigatorContextAccessor.NavigatorContext.ActionType) + .Select(pair => (IAction) _serviceProvider.GetService(pair.Value)!) .Where(a => a.CanHandleCurrentContext()) .OrderBy(a => a.Priority) .AsEnumerable(); } var action = _actions - .Where(a => a.Type == _navigatorContextAccessor.NavigatorContext.ActionType) + .Select(pair => (IAction) _serviceProvider.GetService(pair.Value)!) .OrderBy(a => a.Priority) .FirstOrDefault(a => a.CanHandleCurrentContext()); diff --git a/src/Navigator/Actions/ActionTypeAttribute.cs b/src/Navigator/Actions/ActionTypeAttribute.cs new file mode 100644 index 0000000..93e40c2 --- /dev/null +++ b/src/Navigator/Actions/ActionTypeAttribute.cs @@ -0,0 +1,11 @@ +namespace Navigator.Actions; + +[System.AttributeUsage(System.AttributeTargets.Class)] +public class ActionTypeAttribute : System.Attribute +{ + private string _action; + public ActionTypeAttribute(string action) + { + _action = action; + } +} \ No newline at end of file diff --git a/src/Navigator/Actions/Filters/CooldownActionFilter.cs b/src/Navigator/Actions/Filters/CooldownActionFilter.cs index f938fc0..da51fbd 100644 --- a/src/Navigator/Actions/Filters/CooldownActionFilter.cs +++ b/src/Navigator/Actions/Filters/CooldownActionFilter.cs @@ -39,7 +39,7 @@ public override async Task Handle(TAction action, CancellationToken canc private string GenerateKey(TAction action) { - return $"{action.Type}:{_navigatorContext.Conversation.Chat.Id}"; + return $"{action.GetType().GetActionType()}:{_navigatorContext.Conversation.Chat.Id}"; } } } \ No newline at end of file diff --git a/src/Navigator/Actions/NavigatorOptionsExtensions.cs b/src/Navigator/Actions/NavigatorOptionsExtensions.cs new file mode 100644 index 0000000..dd2133f --- /dev/null +++ b/src/Navigator/Actions/NavigatorOptionsExtensions.cs @@ -0,0 +1,49 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using Navigator.Configuration; + +namespace Navigator.Actions; + +internal static class NavigatorOptionsExtensions +{ + #region NavigatorActions + + private const string NavigatorActions = "_navigator.options.actions"; + + public static void RegisterActions(this NavigatorOptions navigatorOptions, IEnumerable actions) + { + navigatorOptions.TryRegisterOption(NavigatorActions, actions.ToImmutableDictionary( + type => type.GetActionType(), + type => type)); + } + + public static ImmutableDictionary RetrieveActions(this NavigatorOptions navigatorOptions) + { + return navigatorOptions.RetrieveOption>(NavigatorActions) ?? ImmutableDictionary.Empty; + } + + #endregion + + public static string GetActionType(this Type? type) + { + if (type?.CustomAttributes.Any(data => data.AttributeType == typeof(ActionTypeAttribute)) ?? false) + { + return type.Name; + } + + if (type?.BaseType is not null && !type.BaseType.IsInterface) + { + var action = GetActionType(type.BaseType); + + if (action != string.Empty) + { + return action; + } + } + + return type?.Name ?? string.Empty; + } + +} \ No newline at end of file diff --git a/src/Navigator/ServiceCollectionExtensions.cs b/src/Navigator/ServiceCollectionExtensions.cs index bb40897..5f610f0 100644 --- a/src/Navigator/ServiceCollectionExtensions.cs +++ b/src/Navigator/ServiceCollectionExtensions.cs @@ -1,4 +1,5 @@ using System; +using System.Linq; using MediatR; using Microsoft.Extensions.DependencyInjection; using Navigator.Actions; @@ -23,20 +24,24 @@ public static NavigatorConfiguration AddNavigator(this IServiceCollection servic services.AddNavigatorContextServices(); services.AddScoped(); - + services.AddScoped(); services.AddMediatR(navigatorBuilder.Options.GetActionsAssemblies()); - + services.Scan(scan => scan .FromAssemblies(navigatorBuilder.Options.GetActionsAssemblies()) .AddClasses(classes => classes.AssignableTo()) .UsingRegistrationStrategy(RegistrationStrategy.Append) .AsImplementedInterfaces() .WithScopedLifetime()); - + + navigatorBuilder.Options.RegisterActions(services + .Where(descriptor => descriptor.ImplementationType?.IsAssignableTo(typeof(IAction)) ?? false) + .Select(descriptor => descriptor.ImplementationType!)); + navigatorBuilder.RegisterOrReplaceOptions(); - + return navigatorBuilder; } From 622396aefa2085e119bb28987c313fbaac3034ee Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 6 Dec 2021 11:25:41 +0100 Subject: [PATCH 172/304] feat: simplify scope on route handler --- .../NavigatorRouteProviderConfigurationExtensions.cs | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/src/Navigator.Providers.Telegram/NavigatorRouteProviderConfigurationExtensions.cs b/src/Navigator.Providers.Telegram/NavigatorRouteProviderConfigurationExtensions.cs index 1452ac3..d458bc6 100644 --- a/src/Navigator.Providers.Telegram/NavigatorRouteProviderConfigurationExtensions.cs +++ b/src/Navigator.Providers.Telegram/NavigatorRouteProviderConfigurationExtensions.cs @@ -37,12 +37,9 @@ private static async Task ProcessTelegramUpdate(HttpContext context) if (telegramUpdate is not null) { - await using (var scope = context.RequestServices.CreateAsyncScope()) - { - var navigatorMiddleware = scope.ServiceProvider.GetRequiredService(); + var navigatorMiddleware = context.RequestServices.GetRequiredService(); - await navigatorMiddleware.Process(telegramUpdate); - } + await navigatorMiddleware.Process(telegramUpdate); } } From 3f88192f5cf46c204cbd69abcb55ef7048e1da91 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 6 Dec 2021 11:27:16 +0100 Subject: [PATCH 173/304] feat: improve logs --- src/Navigator/Actions/ActionLauncher.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Navigator/Actions/ActionLauncher.cs b/src/Navigator/Actions/ActionLauncher.cs index a53c3f1..456e818 100644 --- a/src/Navigator/Actions/ActionLauncher.cs +++ b/src/Navigator/Actions/ActionLauncher.cs @@ -39,7 +39,7 @@ public async Task Launch() } catch (Exception e) { - _logger.LogError(e, "Unhandled exception running {@Action}", action); + _logger.LogError(e, "Unhandled exception running {ActionName} ({@ActionData})", action.GetType().Name, action); } } } From 31bf1cbd2b5d0aaef6e5b6c7e89bf6684298c282 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 6 Dec 2021 11:30:22 +0100 Subject: [PATCH 174/304] feat: add ActionType to currently available telegram actions --- .../Actions/Messages/CommandAction.cs | 1 + .../Actions/Messages/MessageAction.cs | 1 + src/Navigator.Providers.Telegram/Actions/UnknownAction.cs | 1 + .../Actions/Updates/CallbackQueryAction.cs | 1 + .../Actions/Updates/ChannelCreatedAction.cs | 1 + .../Actions/Updates/ChannelPostAction.cs | 1 + .../Actions/Updates/ChosenInlineResultAction.cs | 1 + .../Actions/Updates/DocumentAction.cs | 1 + .../Actions/Updates/EditedMessageAction.cs | 1 + .../Actions/Updates/InlineQueryAction.cs | 1 + src/Navigator.Providers.Telegram/Actions/Updates/PollAction.cs | 1 + .../Actions/Updates/PreCheckoutQueryAction.cs | 1 + .../Actions/Updates/ShippingQueryAction.cs | 1 + .../Actions/Updates/SupergroupCreatedAction.cs | 1 + 14 files changed, 14 insertions(+) diff --git a/src/Navigator.Providers.Telegram/Actions/Messages/CommandAction.cs b/src/Navigator.Providers.Telegram/Actions/Messages/CommandAction.cs index d7562be..e5acbeb 100644 --- a/src/Navigator.Providers.Telegram/Actions/Messages/CommandAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Messages/CommandAction.cs @@ -7,6 +7,7 @@ namespace Navigator.Providers.Telegram.Actions.Messages /// /// Command based action. /// + [ActionType(nameof(CommandAction))] public abstract class CommandAction : MessageAction { /// diff --git a/src/Navigator.Providers.Telegram/Actions/Messages/MessageAction.cs b/src/Navigator.Providers.Telegram/Actions/Messages/MessageAction.cs index 672c0cd..e1f4ff7 100644 --- a/src/Navigator.Providers.Telegram/Actions/Messages/MessageAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Messages/MessageAction.cs @@ -10,6 +10,7 @@ namespace Navigator.Providers.Telegram.Actions.Messages /// /// A message based action. /// + [ActionType(nameof(MessageAction))] public abstract class MessageAction : BaseAction { /// diff --git a/src/Navigator.Providers.Telegram/Actions/UnknownAction.cs b/src/Navigator.Providers.Telegram/Actions/UnknownAction.cs index bf33a40..ab495cd 100644 --- a/src/Navigator.Providers.Telegram/Actions/UnknownAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/UnknownAction.cs @@ -3,6 +3,7 @@ namespace Navigator.Providers.Telegram.Actions { + [ActionType(nameof(UnknownAction))] public abstract class UnknownAction : BaseAction { /// diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/CallbackQueryAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/CallbackQueryAction.cs index 70326f5..0af55d2 100644 --- a/src/Navigator.Providers.Telegram/Actions/Updates/CallbackQueryAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/CallbackQueryAction.cs @@ -8,6 +8,7 @@ namespace Navigator.Providers.Telegram.Actions.Updates /// /// A callback query based action. /// + [ActionType(nameof(CallbackQueryAction))] public abstract class CallbackQueryAction : BaseAction { /// diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/ChannelCreatedAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/ChannelCreatedAction.cs index 80cfb54..6959478 100644 --- a/src/Navigator.Providers.Telegram/Actions/Updates/ChannelCreatedAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/ChannelCreatedAction.cs @@ -6,6 +6,7 @@ namespace Navigator.Providers.Telegram.Actions.Updates /// /// TODO /// + [ActionType(nameof(ChannelCreatedAction))] public abstract class ChannelCreatedAction : BaseAction { /// diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/ChannelPostAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/ChannelPostAction.cs index 8b8f25d..9a55e5c 100644 --- a/src/Navigator.Providers.Telegram/Actions/Updates/ChannelPostAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/ChannelPostAction.cs @@ -6,6 +6,7 @@ namespace Navigator.Providers.Telegram.Actions.Updates /// /// TODO /// + [ActionType(nameof(ChannelPostAction))] public abstract class ChannelPostAction : BaseAction { /// diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/ChosenInlineResultAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/ChosenInlineResultAction.cs index 30d0faf..d3c733a 100644 --- a/src/Navigator.Providers.Telegram/Actions/Updates/ChosenInlineResultAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/ChosenInlineResultAction.cs @@ -8,6 +8,7 @@ namespace Navigator.Providers.Telegram.Actions.Updates /// /// Inline result based action. /// + [ActionType(nameof(ChosenInlineResultAction))] public abstract class ChosenInlineResultAction : BaseAction { /// diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/DocumentAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/DocumentAction.cs index 5892b5e..8cd87fd 100644 --- a/src/Navigator.Providers.Telegram/Actions/Updates/DocumentAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/DocumentAction.cs @@ -7,6 +7,7 @@ namespace Navigator.Providers.Telegram.Actions.Updates /// /// TODO /// + [ActionType(nameof(DocumentAction))] public abstract class DocumentAction : BaseAction { /// diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/EditedMessageAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/EditedMessageAction.cs index 1cf212d..a3599a3 100644 --- a/src/Navigator.Providers.Telegram/Actions/Updates/EditedMessageAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/EditedMessageAction.cs @@ -8,6 +8,7 @@ namespace Navigator.Providers.Telegram.Actions.Updates /// /// TODO /// + [ActionType(nameof(EditedMessageAction))] public abstract class EditedMessageAction : BaseAction { /// diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/InlineQueryAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/InlineQueryAction.cs index c55e7cd..125ab85 100644 --- a/src/Navigator.Providers.Telegram/Actions/Updates/InlineQueryAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/InlineQueryAction.cs @@ -8,6 +8,7 @@ namespace Navigator.Providers.Telegram.Actions.Updates /// /// Inline query based action. /// + [ActionType(nameof(InlineQueryAction))] public abstract class InlineQueryAction : BaseAction { /// diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/PollAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/PollAction.cs index 7ca6571..aa0bece 100644 --- a/src/Navigator.Providers.Telegram/Actions/Updates/PollAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/PollAction.cs @@ -8,6 +8,7 @@ namespace Navigator.Providers.Telegram.Actions.Updates /// /// TODO /// + [ActionType(nameof(PollAction))] public abstract class PollAction : BaseAction { /// diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/PreCheckoutQueryAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/PreCheckoutQueryAction.cs index f2c9a36..5a08f5e 100644 --- a/src/Navigator.Providers.Telegram/Actions/Updates/PreCheckoutQueryAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/PreCheckoutQueryAction.cs @@ -6,6 +6,7 @@ namespace Navigator.Providers.Telegram.Actions.Updates /// /// TODO /// + [ActionType(nameof(PreCheckoutQueryAction))] public abstract class PreCheckoutQueryAction : BaseAction { /// diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/ShippingQueryAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/ShippingQueryAction.cs index 9b3d82d..97e520f 100644 --- a/src/Navigator.Providers.Telegram/Actions/Updates/ShippingQueryAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/ShippingQueryAction.cs @@ -6,6 +6,7 @@ namespace Navigator.Providers.Telegram.Actions.Updates /// /// TODO /// + [ActionType(nameof(ShippingQueryAction))] public abstract class ShippingQueryAction : BaseAction { /// diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/SupergroupCreatedAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/SupergroupCreatedAction.cs index b602e7d..0e9ddd3 100644 --- a/src/Navigator.Providers.Telegram/Actions/Updates/SupergroupCreatedAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/SupergroupCreatedAction.cs @@ -6,6 +6,7 @@ namespace Navigator.Providers.Telegram.Actions.Updates /// /// TODO /// + [ActionType(nameof(SupergroupCreatedAction))] public abstract class SupergroupCreatedAction : BaseAction { /// From c474f4746dca318e1eef7146695534696ffa0ea8 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 6 Dec 2021 11:33:50 +0100 Subject: [PATCH 175/304] feat: improve speed of action type discovery by using constants --- .../TelegramMiddleware.cs | 30 +++++++++---------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/src/Navigator.Providers.Telegram/TelegramMiddleware.cs b/src/Navigator.Providers.Telegram/TelegramMiddleware.cs index ae4ccb3..74ce614 100644 --- a/src/Navigator.Providers.Telegram/TelegramMiddleware.cs +++ b/src/Navigator.Providers.Telegram/TelegramMiddleware.cs @@ -50,10 +50,10 @@ await _navigatorContextFactory.Supply(builder => { return update.Type switch { - UpdateType.Message when update.Message?.Entities?.First()?.Type == MessageEntityType.BotCommand => typeof(CommandAction).FullName, - UpdateType.Message => update.Message.Type switch + UpdateType.Message when update.Message?.Entities?.First().Type == MessageEntityType.BotCommand => nameof(CommandAction), + UpdateType.Message => update.Message?.Type switch { - MessageType.Document => typeof(DocumentAction).FullName, + MessageType.Document => nameof(DocumentAction), // MessageType.Location => ActionType.ChatMembersAdded, // MessageType.Contact => ActionType.ChatMembersAdded, // MessageType.Game => ActionType.ChatMembersAdded, @@ -67,8 +67,8 @@ await _navigatorContextFactory.Supply(builder => // MessageType.MessagePinned => ActionType.MessagePinned, // MessageType.ChatPhotoDeleted => ActionType.ChatPhotoDeleted, // MessageType.GroupCreated => ActionType.GroupCreated, - MessageType.SupergroupCreated => typeof(SupergroupCreatedAction).FullName, - MessageType.ChannelCreated => typeof(ChannelCreatedAction).FullName, + MessageType.SupergroupCreated => nameof(SupergroupCreatedAction), + MessageType.ChannelCreated => nameof(ChannelCreatedAction), // MessageType.MigratedToSupergroup => ActionType.MigratedToSupergroup, // MessageType.MigratedFromGroup => ActionType.MigratedFromGroup, // MessageType.Dice => ActionType.MigratedFromGroup, @@ -78,21 +78,21 @@ await _navigatorContextFactory.Supply(builder => // MessageType.VoiceChatStarted => ActionType.MigratedFromGroup, // MessageType.VoiceChatEnded => ActionType.MigratedFromGroup, // MessageType.VoiceChatParticipantsInvited => ActionType.MigratedFromGroup, - _ => typeof(MessageAction).FullName, + _ => nameof(MessageAction), }, - UpdateType.InlineQuery => typeof(CommandAction).FullName, - UpdateType.ChosenInlineResult => typeof(ChosenInlineResultAction).FullName, - UpdateType.CallbackQuery => typeof(CallbackQueryAction).FullName, - UpdateType.EditedMessage => typeof(EditedMessageAction).FullName, - UpdateType.ChannelPost => typeof(ChannelPostAction).FullName, + UpdateType.InlineQuery => nameof(InlineQueryAction), + UpdateType.ChosenInlineResult => nameof(ChosenInlineResultAction), + UpdateType.CallbackQuery => nameof(CallbackQueryAction), + UpdateType.EditedMessage => nameof(EditedMessageAction), + UpdateType.ChannelPost => nameof(ChannelPostAction), // UpdateType.EditedChannelPost => ActionType.EditedChannelPost, - UpdateType.ShippingQuery => typeof(ShippingQueryAction).FullName, - UpdateType.PreCheckoutQuery => typeof(PreCheckoutQuery).FullName, - UpdateType.Poll => typeof(PollAction).FullName, + UpdateType.ShippingQuery => nameof(ShippingQueryAction), + UpdateType.PreCheckoutQuery => nameof(PreCheckoutQuery), + UpdateType.Poll => nameof(PollAction), // UpdateType.PollAnswer => typeof(PollAction).FullName, // UpdateType.MyChatMember => typeof(UnknownAction).FullName, // UpdateType.ChatMember => typeof(UnknownAction).FullName, - UpdateType.Unknown => typeof(UnknownAction).FullName, + UpdateType.Unknown => nameof(UnknownAction), _ => default }; } From 255a0d924825e87b53bd424de2840b93920e020d Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 6 Dec 2021 11:56:54 +0100 Subject: [PATCH 176/304] fix: make it work! --- .../Actions/Messages/MessageAction.cs | 4 ++-- src/Navigator/Actions/ActionLauncher.cs | 12 +++++++----- src/Navigator/ServiceCollectionExtensions.cs | 2 +- 3 files changed, 10 insertions(+), 8 deletions(-) diff --git a/src/Navigator.Providers.Telegram/Actions/Messages/MessageAction.cs b/src/Navigator.Providers.Telegram/Actions/Messages/MessageAction.cs index e1f4ff7..de80cee 100644 --- a/src/Navigator.Providers.Telegram/Actions/Messages/MessageAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Messages/MessageAction.cs @@ -33,8 +33,8 @@ protected MessageAction(INavigatorContextAccessor navigatorContextAccessor) : ba { var update = navigatorContextAccessor.NavigatorContext.GetOriginalEvent(); - Message = update.Message; - IsReply = update.Message.ReplyToMessage is not null; + Message = update.Message!; + IsReply = update.Message!.ReplyToMessage is not null; IsForwarded = update.Message.ForwardDate is not null; } } diff --git a/src/Navigator/Actions/ActionLauncher.cs b/src/Navigator/Actions/ActionLauncher.cs index 456e818..06fe9ca 100644 --- a/src/Navigator/Actions/ActionLauncher.cs +++ b/src/Navigator/Actions/ActionLauncher.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Collections.Immutable; using System.Linq; using System.Threading.Tasks; using MediatR; @@ -51,19 +52,20 @@ private IEnumerable GetActions() return Array.Empty(); } - var _actions = _navigatorOptions.RetrieveActions() - .Where(a => a.Key == _navigatorContextAccessor.NavigatorContext.ActionType); + var actions = _navigatorOptions.RetrieveActions() + .Where(a => a.Key == _navigatorContextAccessor.NavigatorContext.ActionType) + .ToImmutableList(); if (_navigatorOptions.MultipleActionsUsageIsEnabled()) { - return _actions + return actions .Select(pair => (IAction) _serviceProvider.GetService(pair.Value)!) .Where(a => a.CanHandleCurrentContext()) .OrderBy(a => a.Priority) .AsEnumerable(); } - - var action = _actions + + var action = actions .Select(pair => (IAction) _serviceProvider.GetService(pair.Value)!) .OrderBy(a => a.Priority) .FirstOrDefault(a => a.CanHandleCurrentContext()); diff --git a/src/Navigator/ServiceCollectionExtensions.cs b/src/Navigator/ServiceCollectionExtensions.cs index 5f610f0..ed6d8bc 100644 --- a/src/Navigator/ServiceCollectionExtensions.cs +++ b/src/Navigator/ServiceCollectionExtensions.cs @@ -33,7 +33,7 @@ public static NavigatorConfiguration AddNavigator(this IServiceCollection servic .FromAssemblies(navigatorBuilder.Options.GetActionsAssemblies()) .AddClasses(classes => classes.AssignableTo()) .UsingRegistrationStrategy(RegistrationStrategy.Append) - .AsImplementedInterfaces() + .AsSelf() .WithScopedLifetime()); navigatorBuilder.Options.RegisterActions(services From 879cf85a1546560576b18ebdc0be12529d3d3491 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 6 Dec 2021 12:38:10 +0100 Subject: [PATCH 177/304] chore: erase old project --- .../ChannelPostAction.cs | 21 ------------- .../ChatMemberLeftAction.cs | 9 ------ .../ChatMembersAddedAction.cs | 9 ------ .../ChatPhotoChangedAction.cs | 9 ------ .../ChatPhotoDeletedAction.cs | 9 ------ .../ChatTitleChangedAction.cs | 9 ------ .../EditedChannelPostAction.cs | 9 ------ .../GroupCreatedAction.cs | 9 ------ .../MessagePinnedAction.cs | 9 ------ .../MigratedFromGroupAction.cs | 9 ------ .../MigratedToSupergroupAction.cs | 9 ------ .../Navigator.Extensions.Actions.csproj | 31 ------------------- .../PreCheckoutQueryAction.cs | 9 ------ .../ShippingQueryAction.cs | 9 ------ .../SupergroupCreatedAction.cs | 9 ------ src/Navigator.sln | 10 ------ 16 files changed, 179 deletions(-) delete mode 100644 src/Navigator.Extensions.Actions/ChannelPostAction.cs delete mode 100644 src/Navigator.Extensions.Actions/ChatMemberLeftAction.cs delete mode 100644 src/Navigator.Extensions.Actions/ChatMembersAddedAction.cs delete mode 100644 src/Navigator.Extensions.Actions/ChatPhotoChangedAction.cs delete mode 100644 src/Navigator.Extensions.Actions/ChatPhotoDeletedAction.cs delete mode 100644 src/Navigator.Extensions.Actions/ChatTitleChangedAction.cs delete mode 100644 src/Navigator.Extensions.Actions/EditedChannelPostAction.cs delete mode 100644 src/Navigator.Extensions.Actions/GroupCreatedAction.cs delete mode 100644 src/Navigator.Extensions.Actions/MessagePinnedAction.cs delete mode 100644 src/Navigator.Extensions.Actions/MigratedFromGroupAction.cs delete mode 100644 src/Navigator.Extensions.Actions/MigratedToSupergroupAction.cs delete mode 100644 src/Navigator.Extensions.Actions/Navigator.Extensions.Actions.csproj delete mode 100644 src/Navigator.Extensions.Actions/PreCheckoutQueryAction.cs delete mode 100644 src/Navigator.Extensions.Actions/ShippingQueryAction.cs delete mode 100644 src/Navigator.Extensions.Actions/SupergroupCreatedAction.cs diff --git a/src/Navigator.Extensions.Actions/ChannelPostAction.cs b/src/Navigator.Extensions.Actions/ChannelPostAction.cs deleted file mode 100644 index facd2da..0000000 --- a/src/Navigator.Extensions.Actions/ChannelPostAction.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System; -using Navigator.Abstractions; - -namespace Navigator.Extensions.Actions -{ - public abstract class ChannelPostAction : Action - { - public override string Type => ActionType.ChannelPost; - public DateTime PostTimestamp { get; protected set; } - public int PostId { get; protected set; } - - public override IAction Init(INavigatorContext ctx) - { - PostTimestamp = ctx.Update.ChannelPost.Date; - PostId = ctx.Update.ChannelPost.MessageId; - - return this; - } - - } -} \ No newline at end of file diff --git a/src/Navigator.Extensions.Actions/ChatMemberLeftAction.cs b/src/Navigator.Extensions.Actions/ChatMemberLeftAction.cs deleted file mode 100644 index fc64e7b..0000000 --- a/src/Navigator.Extensions.Actions/ChatMemberLeftAction.cs +++ /dev/null @@ -1,9 +0,0 @@ -using Navigator.Abstractions; - -namespace Navigator.Extensions.Actions -{ - public abstract class ChatMemberLeftAction : Action - { - public override string Type => ActionType.ChatMemberLeft; - } -} \ No newline at end of file diff --git a/src/Navigator.Extensions.Actions/ChatMembersAddedAction.cs b/src/Navigator.Extensions.Actions/ChatMembersAddedAction.cs deleted file mode 100644 index 0d94879..0000000 --- a/src/Navigator.Extensions.Actions/ChatMembersAddedAction.cs +++ /dev/null @@ -1,9 +0,0 @@ -using Navigator.Abstractions; - -namespace Navigator.Extensions.Actions -{ - public abstract class ChatMembersAddedAction : Action - { - public override string Type => ActionType.ChatMembersAdded; - } -} \ No newline at end of file diff --git a/src/Navigator.Extensions.Actions/ChatPhotoChangedAction.cs b/src/Navigator.Extensions.Actions/ChatPhotoChangedAction.cs deleted file mode 100644 index 4553806..0000000 --- a/src/Navigator.Extensions.Actions/ChatPhotoChangedAction.cs +++ /dev/null @@ -1,9 +0,0 @@ -using Navigator.Abstractions; - -namespace Navigator.Extensions.Actions -{ - public abstract class ChatPhotoChangedAction : Action - { - public override string Type => ActionType.ChatPhotoChanged; - } -} \ No newline at end of file diff --git a/src/Navigator.Extensions.Actions/ChatPhotoDeletedAction.cs b/src/Navigator.Extensions.Actions/ChatPhotoDeletedAction.cs deleted file mode 100644 index 16f1aa2..0000000 --- a/src/Navigator.Extensions.Actions/ChatPhotoDeletedAction.cs +++ /dev/null @@ -1,9 +0,0 @@ -using Navigator.Abstractions; - -namespace Navigator.Extensions.Actions -{ - public abstract class ChatPhotoDeletedAction : Action - { - public override string Type => ActionType.ChatPhotoDeleted; - } -} \ No newline at end of file diff --git a/src/Navigator.Extensions.Actions/ChatTitleChangedAction.cs b/src/Navigator.Extensions.Actions/ChatTitleChangedAction.cs deleted file mode 100644 index 68dc234..0000000 --- a/src/Navigator.Extensions.Actions/ChatTitleChangedAction.cs +++ /dev/null @@ -1,9 +0,0 @@ -using Navigator.Abstractions; - -namespace Navigator.Extensions.Actions -{ - public abstract class ChatTitleChangedAction : Action - { - public override string Type => ActionType.ChatTitleChanged; - } -} \ No newline at end of file diff --git a/src/Navigator.Extensions.Actions/EditedChannelPostAction.cs b/src/Navigator.Extensions.Actions/EditedChannelPostAction.cs deleted file mode 100644 index eaca5be..0000000 --- a/src/Navigator.Extensions.Actions/EditedChannelPostAction.cs +++ /dev/null @@ -1,9 +0,0 @@ -using Navigator.Abstractions; - -namespace Navigator.Extensions.Actions -{ - public abstract class EditedChannelPostAction : ChannelPostAction - { - public override string Type => ActionType.EditedChannelPost; - } -} \ No newline at end of file diff --git a/src/Navigator.Extensions.Actions/GroupCreatedAction.cs b/src/Navigator.Extensions.Actions/GroupCreatedAction.cs deleted file mode 100644 index 9fe4135..0000000 --- a/src/Navigator.Extensions.Actions/GroupCreatedAction.cs +++ /dev/null @@ -1,9 +0,0 @@ -using Navigator.Abstractions; - -namespace Navigator.Extensions.Actions -{ - public abstract class GroupCreatedAction : Action - { - public override string Type => ActionType.GroupCreated; - } -} \ No newline at end of file diff --git a/src/Navigator.Extensions.Actions/MessagePinnedAction.cs b/src/Navigator.Extensions.Actions/MessagePinnedAction.cs deleted file mode 100644 index fd0d834..0000000 --- a/src/Navigator.Extensions.Actions/MessagePinnedAction.cs +++ /dev/null @@ -1,9 +0,0 @@ -using Navigator.Abstractions; - -namespace Navigator.Extensions.Actions -{ - public abstract class MessagePinnedAction : Action - { - public override string Type => ActionType.MessagePinned; - } -} \ No newline at end of file diff --git a/src/Navigator.Extensions.Actions/MigratedFromGroupAction.cs b/src/Navigator.Extensions.Actions/MigratedFromGroupAction.cs deleted file mode 100644 index 3c7e16a..0000000 --- a/src/Navigator.Extensions.Actions/MigratedFromGroupAction.cs +++ /dev/null @@ -1,9 +0,0 @@ -using Navigator.Abstractions; - -namespace Navigator.Extensions.Actions -{ - public abstract class MigratedFromGroupAction : Action - { - public override string Type => ActionType.MigratedFromGroup; - } -} \ No newline at end of file diff --git a/src/Navigator.Extensions.Actions/MigratedToSupergroupAction.cs b/src/Navigator.Extensions.Actions/MigratedToSupergroupAction.cs deleted file mode 100644 index e8734a5..0000000 --- a/src/Navigator.Extensions.Actions/MigratedToSupergroupAction.cs +++ /dev/null @@ -1,9 +0,0 @@ -using Navigator.Abstractions; - -namespace Navigator.Extensions.Actions -{ - public abstract class MigratedToSupergroupAction : Action - { - public override string Type => ActionType.MigratedToSupergroup; - } -} \ No newline at end of file diff --git a/src/Navigator.Extensions.Actions/Navigator.Extensions.Actions.csproj b/src/Navigator.Extensions.Actions/Navigator.Extensions.Actions.csproj deleted file mode 100644 index 17e60b6..0000000 --- a/src/Navigator.Extensions.Actions/Navigator.Extensions.Actions.csproj +++ /dev/null @@ -1,31 +0,0 @@ - - - - net5.0 - 9 - true - True - 0.9.100-beta - Navigator.Extensions.Actions - Navigator Extensions Actions - Lucas Maximiliano Marino - Common actions for Navigator Framework - https://github.com/navigatorframework/navigator - https://github.com/navigatorframework/navigator/blob/master/LICENSE - https://github.com/navigatorframework/navigator - Telegram, Bot, Framework, Navigator, Actions, Extension - true - Copyright © Lucas Maximiliano Marino 2020 - https://raw.githubusercontent.com/navigatorframework/navigator/master/assets/logo.png - enable - - - - - - - - - - - diff --git a/src/Navigator.Extensions.Actions/PreCheckoutQueryAction.cs b/src/Navigator.Extensions.Actions/PreCheckoutQueryAction.cs deleted file mode 100644 index 5845f26..0000000 --- a/src/Navigator.Extensions.Actions/PreCheckoutQueryAction.cs +++ /dev/null @@ -1,9 +0,0 @@ -using Navigator.Abstractions; - -namespace Navigator.Extensions.Actions -{ - public abstract class PreCheckoutQueryAction : Action - { - public override string Type => ActionType.PreCheckoutQuery; - } -} \ No newline at end of file diff --git a/src/Navigator.Extensions.Actions/ShippingQueryAction.cs b/src/Navigator.Extensions.Actions/ShippingQueryAction.cs deleted file mode 100644 index 70f3b96..0000000 --- a/src/Navigator.Extensions.Actions/ShippingQueryAction.cs +++ /dev/null @@ -1,9 +0,0 @@ -using Navigator.Abstractions; - -namespace Navigator.Extensions.Actions -{ - public abstract class ShippingQueryAction : Action - { - public override string Type => ActionType.ShippingQuery; - } -} \ No newline at end of file diff --git a/src/Navigator.Extensions.Actions/SupergroupCreatedAction.cs b/src/Navigator.Extensions.Actions/SupergroupCreatedAction.cs deleted file mode 100644 index ab8e3e0..0000000 --- a/src/Navigator.Extensions.Actions/SupergroupCreatedAction.cs +++ /dev/null @@ -1,9 +0,0 @@ -using Navigator.Abstractions; - -namespace Navigator.Extensions.Actions -{ - public abstract class SupergroupCreatedAction : Action - { - public override string Type => ActionType.SupergroupCreated; - } -} \ No newline at end of file diff --git a/src/Navigator.sln b/src/Navigator.sln index 7bc4742..7bd3304 100644 --- a/src/Navigator.sln +++ b/src/Navigator.sln @@ -4,14 +4,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Navigator", "Navigator\Navi EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Navigator.Extensions.Store", "Navigator.Extensions.Store\Navigator.Extensions.Store.csproj", "{9DEA166A-AE92-438F-8F3D-7C2F777ABBDD}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Navigator.Extensions.Actions", "Navigator.Extensions.Actions\Navigator.Extensions.Actions.csproj", "{2711B76D-B24C-4A3A-A33F-5A0077C49CB6}" -EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Samples", "Samples", "{6D6A8E40-8C40-49AA-BEAD-B046D43F511A}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Extensions", "Extensions", "{F178DCF2-AD03-44C8-AF8F-95C60664DD10}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Actions", "Actions", "{288F4B0C-9EF0-443B-B893-5FC34F9D032B}" -EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Packages", "Packages", "{895808DE-1CA6-406C-924A-7E43F293CF7D}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Navigator", "Navigator", "{E6F24E3B-A066-4572-94F0-14665E19EFC7}" @@ -48,10 +44,6 @@ Global {9DEA166A-AE92-438F-8F3D-7C2F777ABBDD}.Debug|Any CPU.Build.0 = Debug|Any CPU {9DEA166A-AE92-438F-8F3D-7C2F777ABBDD}.Release|Any CPU.ActiveCfg = Release|Any CPU {9DEA166A-AE92-438F-8F3D-7C2F777ABBDD}.Release|Any CPU.Build.0 = Release|Any CPU - {2711B76D-B24C-4A3A-A33F-5A0077C49CB6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {2711B76D-B24C-4A3A-A33F-5A0077C49CB6}.Debug|Any CPU.Build.0 = Debug|Any CPU - {2711B76D-B24C-4A3A-A33F-5A0077C49CB6}.Release|Any CPU.ActiveCfg = Release|Any CPU - {2711B76D-B24C-4A3A-A33F-5A0077C49CB6}.Release|Any CPU.Build.0 = Release|Any CPU {8E680AE7-33EC-4049-A9DC-0F42C6A03184}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {8E680AE7-33EC-4049-A9DC-0F42C6A03184}.Debug|Any CPU.Build.0 = Debug|Any CPU {8E680AE7-33EC-4049-A9DC-0F42C6A03184}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -81,8 +73,6 @@ Global {F178DCF2-AD03-44C8-AF8F-95C60664DD10} = {895808DE-1CA6-406C-924A-7E43F293CF7D} {E6F24E3B-A066-4572-94F0-14665E19EFC7} = {895808DE-1CA6-406C-924A-7E43F293CF7D} {6DBAD041-6623-4903-9939-254FDC4EBD60} = {E6F24E3B-A066-4572-94F0-14665E19EFC7} - {2711B76D-B24C-4A3A-A33F-5A0077C49CB6} = {288F4B0C-9EF0-443B-B893-5FC34F9D032B} - {288F4B0C-9EF0-443B-B893-5FC34F9D032B} = {F178DCF2-AD03-44C8-AF8F-95C60664DD10} {F26BD166-0ED4-4096-8841-47959645B3DE} = {F178DCF2-AD03-44C8-AF8F-95C60664DD10} {9DEA166A-AE92-438F-8F3D-7C2F777ABBDD} = {F26BD166-0ED4-4096-8841-47959645B3DE} {8E680AE7-33EC-4049-A9DC-0F42C6A03184} = {F26BD166-0ED4-4096-8841-47959645B3DE} From 7a201fba966c8b6edc72944825d6fceee2a248f9 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 6 Dec 2021 12:38:26 +0100 Subject: [PATCH 178/304] feat: rename filter to middleware --- src/Navigator/Actions/Filters/ActionFilter.cs | 11 ----------- .../Actions/Filters/CooldownActionFilter.cs | 4 ++-- src/Navigator/Actions/IActionMiddleware.cs | 12 ++++++++++++ 3 files changed, 14 insertions(+), 13 deletions(-) delete mode 100644 src/Navigator/Actions/Filters/ActionFilter.cs create mode 100644 src/Navigator/Actions/IActionMiddleware.cs diff --git a/src/Navigator/Actions/Filters/ActionFilter.cs b/src/Navigator/Actions/Filters/ActionFilter.cs deleted file mode 100644 index 4ce458a..0000000 --- a/src/Navigator/Actions/Filters/ActionFilter.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System.Threading; -using System.Threading.Tasks; -using MediatR; - -namespace Navigator.Actions.Filters -{ - public abstract class ActionFilter : IPipelineBehavior where TAction : IAction - { - public abstract Task Handle(TAction action, CancellationToken cancellationToken, RequestHandlerDelegate next); - } -} \ No newline at end of file diff --git a/src/Navigator/Actions/Filters/CooldownActionFilter.cs b/src/Navigator/Actions/Filters/CooldownActionFilter.cs index da51fbd..4ae7f97 100644 --- a/src/Navigator/Actions/Filters/CooldownActionFilter.cs +++ b/src/Navigator/Actions/Filters/CooldownActionFilter.cs @@ -6,7 +6,7 @@ namespace Navigator.Actions.Filters { - public class CooldownActionFilter : ActionFilter where TAction : IAction + public class CooldownActionFilter : IActionMiddleware where TAction : IAction { private readonly IDistributedCache _cache; private readonly INavigatorContext _navigatorContext; @@ -16,7 +16,7 @@ public CooldownActionFilter(IDistributedCache cache, INavigatorContextAccessor n _navigatorContext = navigatorContextAccessor.NavigatorContext; } - public override async Task Handle(TAction action, CancellationToken cancellationToken, RequestHandlerDelegate next) + public async Task Handle(TAction action, CancellationToken cancellationToken, RequestHandlerDelegate next) { var key = GenerateKey(action); diff --git a/src/Navigator/Actions/IActionMiddleware.cs b/src/Navigator/Actions/IActionMiddleware.cs new file mode 100644 index 0000000..f5653c6 --- /dev/null +++ b/src/Navigator/Actions/IActionMiddleware.cs @@ -0,0 +1,12 @@ +using MediatR; + +namespace Navigator.Actions +{ + /// + /// TODO + /// + /// + public interface IActionMiddleware : IPipelineBehavior where TAction : IAction + { + } +} \ No newline at end of file From 4e26a1c16df7895c51b6c2f7eb9800a747753ad5 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 6 Dec 2021 12:38:46 +0100 Subject: [PATCH 179/304] feat: add quality of life features --- .../ActionHandlerExtensions.cs | 17 ++++++++++++++++ .../NavigatorContextExtensions.cs | 20 ++++++++++++++----- .../Actions/EchoActionHandler.cs | 2 +- 3 files changed, 33 insertions(+), 6 deletions(-) create mode 100644 src/Navigator.Providers.Telegram/ActionHandlerExtensions.cs diff --git a/src/Navigator.Providers.Telegram/ActionHandlerExtensions.cs b/src/Navigator.Providers.Telegram/ActionHandlerExtensions.cs new file mode 100644 index 0000000..2dcbdf6 --- /dev/null +++ b/src/Navigator.Providers.Telegram/ActionHandlerExtensions.cs @@ -0,0 +1,17 @@ +using Navigator.Actions; +using Telegram.Bot.Types; + +namespace Navigator.Providers.Telegram; + +public static class ActionHandlerExtensions +{ + public static NavigatorTelegramClient GetTelegramClient(this ActionHandler actionHandler) where T : IAction + { + return actionHandler.NavigatorContext.Provider.GetTelegramClient(); + } + + public static Chat GetTelegramChat(this ActionHandler actionHandler) where T : IAction + { + return actionHandler.NavigatorContext.GetTelegramChat(); + } +} \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/NavigatorContextExtensions.cs b/src/Navigator.Providers.Telegram/NavigatorContextExtensions.cs index 469881f..0a62a82 100644 --- a/src/Navigator.Providers.Telegram/NavigatorContextExtensions.cs +++ b/src/Navigator.Providers.Telegram/NavigatorContextExtensions.cs @@ -11,6 +11,16 @@ namespace Navigator.Providers.Telegram /// public static class NavigatorContextExtensions { + /// + /// TODO + /// + /// + /// + public static NavigatorTelegramClient GetTelegramClient(this INavigatorContext context) + { + return context.Provider.GetTelegramClient(); + } + // #region User // // /// @@ -74,11 +84,11 @@ public static Chat GetTelegramChat(this INavigatorContext ctx) { return ctx.GetOriginalEventOrDefault()?.Type switch { - UpdateType.CallbackQuery => ctx.GetOriginalEvent().CallbackQuery.Message.Chat, - UpdateType.Message => ctx.GetOriginalEvent().Message.Chat, - UpdateType.EditedMessage => ctx.GetOriginalEvent().EditedMessage.Chat, - UpdateType.ChannelPost => ctx.GetOriginalEvent().ChannelPost.Chat, - UpdateType.EditedChannelPost => ctx.GetOriginalEvent().EditedChannelPost.Chat, + UpdateType.CallbackQuery => ctx.GetOriginalEvent().CallbackQuery?.Message?.Chat, + UpdateType.Message => ctx.GetOriginalEvent().Message?.Chat, + UpdateType.EditedMessage => ctx.GetOriginalEvent().EditedMessage?.Chat, + UpdateType.ChannelPost => ctx.GetOriginalEvent().ChannelPost?.Chat, + UpdateType.EditedChannelPost => ctx.GetOriginalEvent().EditedChannelPost?.Chat, _ => default }; } diff --git a/src/Navigator.Samples.Echo/Actions/EchoActionHandler.cs b/src/Navigator.Samples.Echo/Actions/EchoActionHandler.cs index 132cef9..dbbda89 100644 --- a/src/Navigator.Samples.Echo/Actions/EchoActionHandler.cs +++ b/src/Navigator.Samples.Echo/Actions/EchoActionHandler.cs @@ -16,7 +16,7 @@ public EchoActionHandler(INavigatorContextAccessor navigatorContextAccessor) : b public override async Task Handle(EchoAction action, CancellationToken cancellationToken) { - await NavigatorContext.Provider.GetTelegramClient().SendTextMessageAsync(NavigatorContext.GetTelegramChat(), + await this.GetTelegramClient().SendTextMessageAsync(this.GetTelegramChat().Id, action.MessageToEcho, cancellationToken: cancellationToken); return Success(); From fa15b60ea18d35cbac453129a1af159de7cf149f Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 6 Dec 2021 12:44:52 +0100 Subject: [PATCH 180/304] fix: correct namespace --- .../Actions/{Filters => MIddleware}/CooldownActionFilter.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename src/Navigator/Actions/{Filters => MIddleware}/CooldownActionFilter.cs (97%) diff --git a/src/Navigator/Actions/Filters/CooldownActionFilter.cs b/src/Navigator/Actions/MIddleware/CooldownActionFilter.cs similarity index 97% rename from src/Navigator/Actions/Filters/CooldownActionFilter.cs rename to src/Navigator/Actions/MIddleware/CooldownActionFilter.cs index 4ae7f97..54b8f2a 100644 --- a/src/Navigator/Actions/Filters/CooldownActionFilter.cs +++ b/src/Navigator/Actions/MIddleware/CooldownActionFilter.cs @@ -4,7 +4,7 @@ using Microsoft.Extensions.Caching.Distributed; using Navigator.Context; -namespace Navigator.Actions.Filters +namespace Navigator.Actions.MIddleware { public class CooldownActionFilter : IActionMiddleware where TAction : IAction { From 7b1a11300364481b8b4c70a16aa4902ff6c9d2a9 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 6 Dec 2021 12:47:40 +0100 Subject: [PATCH 181/304] chore: move file around --- .../Actions/Messages/CommandAction.cs | 1 + .../Actions/Messages/MessageAction.cs | 1 + src/Navigator.Providers.Telegram/Actions/UnknownAction.cs | 1 + .../Actions/Updates/CallbackQueryAction.cs | 1 + .../Actions/Updates/ChannelCreatedAction.cs | 1 + .../Actions/Updates/ChannelPostAction.cs | 1 + .../Actions/Updates/ChosenInlineResultAction.cs | 1 + .../Actions/Updates/DocumentAction.cs | 1 + .../Actions/Updates/EditedMessageAction.cs | 1 + .../Actions/Updates/InlineQueryAction.cs | 1 + src/Navigator.Providers.Telegram/Actions/Updates/PollAction.cs | 1 + .../Actions/Updates/PreCheckoutQueryAction.cs | 1 + .../Actions/Updates/ShippingQueryAction.cs | 1 + .../Actions/Updates/SupergroupCreatedAction.cs | 1 + src/Navigator/Actions/{ => Attributes}/ActionTypeAttribute.cs | 2 +- src/Navigator/Actions/NavigatorOptionsExtensions.cs | 1 + 16 files changed, 16 insertions(+), 1 deletion(-) rename src/Navigator/Actions/{ => Attributes}/ActionTypeAttribute.cs (84%) diff --git a/src/Navigator.Providers.Telegram/Actions/Messages/CommandAction.cs b/src/Navigator.Providers.Telegram/Actions/Messages/CommandAction.cs index e5acbeb..c282d9c 100644 --- a/src/Navigator.Providers.Telegram/Actions/Messages/CommandAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Messages/CommandAction.cs @@ -1,4 +1,5 @@ using Navigator.Actions; +using Navigator.Actions.Attributes; using Navigator.Context; using Navigator.Providers.Telegram.Extensions; diff --git a/src/Navigator.Providers.Telegram/Actions/Messages/MessageAction.cs b/src/Navigator.Providers.Telegram/Actions/Messages/MessageAction.cs index de80cee..7e67aa4 100644 --- a/src/Navigator.Providers.Telegram/Actions/Messages/MessageAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Messages/MessageAction.cs @@ -1,6 +1,7 @@ using System.ComponentModel; using System.Reflection; using Navigator.Actions; +using Navigator.Actions.Attributes; using Navigator.Context; using Navigator.Context.Extensions; using Telegram.Bot.Types; diff --git a/src/Navigator.Providers.Telegram/Actions/UnknownAction.cs b/src/Navigator.Providers.Telegram/Actions/UnknownAction.cs index ab495cd..7affb43 100644 --- a/src/Navigator.Providers.Telegram/Actions/UnknownAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/UnknownAction.cs @@ -1,4 +1,5 @@ using Navigator.Actions; +using Navigator.Actions.Attributes; using Navigator.Context; namespace Navigator.Providers.Telegram.Actions diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/CallbackQueryAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/CallbackQueryAction.cs index 0af55d2..49f7d19 100644 --- a/src/Navigator.Providers.Telegram/Actions/Updates/CallbackQueryAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/CallbackQueryAction.cs @@ -1,4 +1,5 @@ using Navigator.Actions; +using Navigator.Actions.Attributes; using Navigator.Context; using Navigator.Context.Extensions; using Telegram.Bot.Types; diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/ChannelCreatedAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/ChannelCreatedAction.cs index 6959478..f4db172 100644 --- a/src/Navigator.Providers.Telegram/Actions/Updates/ChannelCreatedAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/ChannelCreatedAction.cs @@ -1,4 +1,5 @@ using Navigator.Actions; +using Navigator.Actions.Attributes; using Navigator.Context; namespace Navigator.Providers.Telegram.Actions.Updates diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/ChannelPostAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/ChannelPostAction.cs index 9a55e5c..7b522a5 100644 --- a/src/Navigator.Providers.Telegram/Actions/Updates/ChannelPostAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/ChannelPostAction.cs @@ -1,4 +1,5 @@ using Navigator.Actions; +using Navigator.Actions.Attributes; using Navigator.Context; namespace Navigator.Providers.Telegram.Actions.Updates diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/ChosenInlineResultAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/ChosenInlineResultAction.cs index d3c733a..c71bbf3 100644 --- a/src/Navigator.Providers.Telegram/Actions/Updates/ChosenInlineResultAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/ChosenInlineResultAction.cs @@ -1,4 +1,5 @@ using Navigator.Actions; +using Navigator.Actions.Attributes; using Navigator.Context; using Navigator.Context.Extensions; using Telegram.Bot.Types; diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/DocumentAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/DocumentAction.cs index 8cd87fd..5fe74a5 100644 --- a/src/Navigator.Providers.Telegram/Actions/Updates/DocumentAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/DocumentAction.cs @@ -1,5 +1,6 @@ using System; using Navigator.Actions; +using Navigator.Actions.Attributes; using Navigator.Context; namespace Navigator.Providers.Telegram.Actions.Updates diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/EditedMessageAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/EditedMessageAction.cs index a3599a3..ea7c9b0 100644 --- a/src/Navigator.Providers.Telegram/Actions/Updates/EditedMessageAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/EditedMessageAction.cs @@ -1,4 +1,5 @@ using Navigator.Actions; +using Navigator.Actions.Attributes; using Navigator.Context; using Navigator.Context.Extensions; using Telegram.Bot.Types; diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/InlineQueryAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/InlineQueryAction.cs index 125ab85..96cea79 100644 --- a/src/Navigator.Providers.Telegram/Actions/Updates/InlineQueryAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/InlineQueryAction.cs @@ -1,4 +1,5 @@ using Navigator.Actions; +using Navigator.Actions.Attributes; using Navigator.Context; using Navigator.Context.Extensions; using Telegram.Bot.Types; diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/PollAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/PollAction.cs index aa0bece..ce78520 100644 --- a/src/Navigator.Providers.Telegram/Actions/Updates/PollAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/PollAction.cs @@ -1,4 +1,5 @@ using Navigator.Actions; +using Navigator.Actions.Attributes; using Navigator.Context; using Navigator.Context.Extensions; using Telegram.Bot.Types; diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/PreCheckoutQueryAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/PreCheckoutQueryAction.cs index 5a08f5e..ecc362c 100644 --- a/src/Navigator.Providers.Telegram/Actions/Updates/PreCheckoutQueryAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/PreCheckoutQueryAction.cs @@ -1,4 +1,5 @@ using Navigator.Actions; +using Navigator.Actions.Attributes; using Navigator.Context; namespace Navigator.Providers.Telegram.Actions.Updates diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/ShippingQueryAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/ShippingQueryAction.cs index 97e520f..26f4359 100644 --- a/src/Navigator.Providers.Telegram/Actions/Updates/ShippingQueryAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/ShippingQueryAction.cs @@ -1,4 +1,5 @@ using Navigator.Actions; +using Navigator.Actions.Attributes; using Navigator.Context; namespace Navigator.Providers.Telegram.Actions.Updates diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/SupergroupCreatedAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/SupergroupCreatedAction.cs index 0e9ddd3..1e5bc99 100644 --- a/src/Navigator.Providers.Telegram/Actions/Updates/SupergroupCreatedAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/SupergroupCreatedAction.cs @@ -1,4 +1,5 @@ using Navigator.Actions; +using Navigator.Actions.Attributes; using Navigator.Context; namespace Navigator.Providers.Telegram.Actions.Updates diff --git a/src/Navigator/Actions/ActionTypeAttribute.cs b/src/Navigator/Actions/Attributes/ActionTypeAttribute.cs similarity index 84% rename from src/Navigator/Actions/ActionTypeAttribute.cs rename to src/Navigator/Actions/Attributes/ActionTypeAttribute.cs index 93e40c2..6e9fa88 100644 --- a/src/Navigator/Actions/ActionTypeAttribute.cs +++ b/src/Navigator/Actions/Attributes/ActionTypeAttribute.cs @@ -1,4 +1,4 @@ -namespace Navigator.Actions; +namespace Navigator.Actions.Attributes; [System.AttributeUsage(System.AttributeTargets.Class)] public class ActionTypeAttribute : System.Attribute diff --git a/src/Navigator/Actions/NavigatorOptionsExtensions.cs b/src/Navigator/Actions/NavigatorOptionsExtensions.cs index dd2133f..d429179 100644 --- a/src/Navigator/Actions/NavigatorOptionsExtensions.cs +++ b/src/Navigator/Actions/NavigatorOptionsExtensions.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; +using Navigator.Actions.Attributes; using Navigator.Configuration; namespace Navigator.Actions; From 9eb0f0491c6822b73b863d3c9bd76aa825434932 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 6 Dec 2021 12:47:58 +0100 Subject: [PATCH 182/304] feat: add ActionPriority attribute --- .../Actions/Attributes/ActionPriorityAttribute.cs | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 src/Navigator/Actions/Attributes/ActionPriorityAttribute.cs diff --git a/src/Navigator/Actions/Attributes/ActionPriorityAttribute.cs b/src/Navigator/Actions/Attributes/ActionPriorityAttribute.cs new file mode 100644 index 0000000..1c1792d --- /dev/null +++ b/src/Navigator/Actions/Attributes/ActionPriorityAttribute.cs @@ -0,0 +1,11 @@ +namespace Navigator.Actions.Attributes; + +[System.AttributeUsage(System.AttributeTargets.Class)] +public class ActionPriorityAttribute : System.Attribute +{ + private ushort _priority; + public ActionPriorityAttribute(ushort priority) + { + _priority = priority; + } +} \ No newline at end of file From 226b8d0db2f7dc29cfb57eccf99315ebbe189be9 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 6 Dec 2021 12:51:22 +0100 Subject: [PATCH 183/304] feat: move priority out of action type to attribute --- src/Navigator/Actions/Attributes/ActionPriorityAttribute.cs | 3 +++ src/Navigator/Actions/BaseAction.cs | 2 ++ src/Navigator/Actions/IAction.cs | 5 ----- src/Navigator/Actions/Priority.cs | 6 +++--- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/Navigator/Actions/Attributes/ActionPriorityAttribute.cs b/src/Navigator/Actions/Attributes/ActionPriorityAttribute.cs index 1c1792d..778914f 100644 --- a/src/Navigator/Actions/Attributes/ActionPriorityAttribute.cs +++ b/src/Navigator/Actions/Attributes/ActionPriorityAttribute.cs @@ -1,5 +1,8 @@ namespace Navigator.Actions.Attributes; +/// +/// Sets the priority of an action when multiple actions are available for the same trigger. +/// [System.AttributeUsage(System.AttributeTargets.Class)] public class ActionPriorityAttribute : System.Attribute { diff --git a/src/Navigator/Actions/BaseAction.cs b/src/Navigator/Actions/BaseAction.cs index 7209cd6..daa2bba 100644 --- a/src/Navigator/Actions/BaseAction.cs +++ b/src/Navigator/Actions/BaseAction.cs @@ -1,4 +1,5 @@ using System; +using Navigator.Actions.Attributes; using Navigator.Context; namespace Navigator.Actions @@ -6,6 +7,7 @@ namespace Navigator.Actions /// /// Base action to use for any action. /// + [ActionPriority(Actions.Priority.Default)] public abstract class BaseAction : IAction { /// diff --git a/src/Navigator/Actions/IAction.cs b/src/Navigator/Actions/IAction.cs index 25d391b..0b2fa50 100644 --- a/src/Navigator/Actions/IAction.cs +++ b/src/Navigator/Actions/IAction.cs @@ -8,11 +8,6 @@ namespace Navigator.Actions /// public interface IAction : IRequest { - /// - /// Priority of the action when launching multiple actions. - /// - ushort Priority { get; } - /// /// This function must return true when the incoming update can be handled by this action. /// diff --git a/src/Navigator/Actions/Priority.cs b/src/Navigator/Actions/Priority.cs index 81a3665..8a0fa65 100644 --- a/src/Navigator/Actions/Priority.cs +++ b/src/Navigator/Actions/Priority.cs @@ -2,8 +2,8 @@ namespace Navigator.Actions { public static class Priority { - public static ushort Low = 15000; - public static ushort Default = 10000; - public static ushort High = 5000; + public const ushort Low = 15000; + public const ushort Default = 10000; + public const ushort High = 5000; } } \ No newline at end of file From 375c778bf323d87ef06cf28a8c7dc512afc66e13 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 6 Dec 2021 21:17:29 +0100 Subject: [PATCH 184/304] feat: adapt priority attribute into ActionLauncher strategies --- src/Navigator/Actions/ActionLauncher.cs | 22 ++++--- .../Attributes/ActionPriorityAttribute.cs | 5 +- .../Actions/Attributes/ActionTypeAttribute.cs | 5 +- .../Actions/NavigatorOptionsExtensions.cs | 57 +++++++++++++++++-- 4 files changed, 71 insertions(+), 18 deletions(-) diff --git a/src/Navigator/Actions/ActionLauncher.cs b/src/Navigator/Actions/ActionLauncher.cs index 06fe9ca..eab947a 100644 --- a/src/Navigator/Actions/ActionLauncher.cs +++ b/src/Navigator/Actions/ActionLauncher.cs @@ -14,18 +14,22 @@ namespace Navigator.Actions internal class ActionLauncher : IActionLauncher { private readonly ILogger _logger; - private readonly NavigatorOptions _navigatorOptions; private readonly INavigatorContextAccessor _navigatorContextAccessor; private readonly IServiceProvider _serviceProvider; private readonly ISender _sender; + private readonly NavigatorOptions _navigatorOptions; + private readonly ImmutableDictionary _actions; + private readonly ImmutableDictionary _priorities; public ActionLauncher(ILogger logger, NavigatorOptions navigatorOptions, INavigatorContextAccessor navigatorContextAccessor, IServiceProvider serviceProvider, ISender sender) { _logger = logger; - _navigatorOptions = navigatorOptions; _navigatorContextAccessor = navigatorContextAccessor; _serviceProvider = serviceProvider; _sender = sender; + _navigatorOptions = navigatorOptions; + _actions = _navigatorOptions.RetrieveActions(); + _priorities = _navigatorOptions.RetrievePriorities(); } public async Task Launch() @@ -52,22 +56,24 @@ private IEnumerable GetActions() return Array.Empty(); } - var actions = _navigatorOptions.RetrieveActions() + var actions = _actions .Where(a => a.Key == _navigatorContextAccessor.NavigatorContext.ActionType) .ToImmutableList(); if (_navigatorOptions.MultipleActionsUsageIsEnabled()) { return actions - .Select(pair => (IAction) _serviceProvider.GetService(pair.Value)!) - .Where(a => a.CanHandleCurrentContext()) - .OrderBy(a => a.Priority) + .Select(pair => ((IAction) _serviceProvider.GetService(pair.Value)!, pair.Value.FullName)) + .Where(a => a.Item1.CanHandleCurrentContext()) + .OrderBy(a => _priorities.GetValueOrDefault(a.FullName ?? string.Empty, Priority.Default)) + .Select(a => a.Item1) .AsEnumerable(); } var action = actions - .Select(pair => (IAction) _serviceProvider.GetService(pair.Value)!) - .OrderBy(a => a.Priority) + .Select(pair => ((IAction) _serviceProvider.GetService(pair.Value)!, pair.Value.FullName)) + .OrderBy(a => _priorities.GetValueOrDefault(a.FullName ?? string.Empty, Priority.Default)) + .Select(a => a.Item1) .FirstOrDefault(a => a.CanHandleCurrentContext()); return action is not null ? new[] {action} : Array.Empty(); diff --git a/src/Navigator/Actions/Attributes/ActionPriorityAttribute.cs b/src/Navigator/Actions/Attributes/ActionPriorityAttribute.cs index 778914f..fb2ee3b 100644 --- a/src/Navigator/Actions/Attributes/ActionPriorityAttribute.cs +++ b/src/Navigator/Actions/Attributes/ActionPriorityAttribute.cs @@ -6,9 +6,10 @@ namespace Navigator.Actions.Attributes; [System.AttributeUsage(System.AttributeTargets.Class)] public class ActionPriorityAttribute : System.Attribute { - private ushort _priority; + public readonly ushort Priority; + public ActionPriorityAttribute(ushort priority) { - _priority = priority; + Priority = priority; } } \ No newline at end of file diff --git a/src/Navigator/Actions/Attributes/ActionTypeAttribute.cs b/src/Navigator/Actions/Attributes/ActionTypeAttribute.cs index 6e9fa88..3383e7e 100644 --- a/src/Navigator/Actions/Attributes/ActionTypeAttribute.cs +++ b/src/Navigator/Actions/Attributes/ActionTypeAttribute.cs @@ -3,9 +3,10 @@ namespace Navigator.Actions.Attributes; [System.AttributeUsage(System.AttributeTargets.Class)] public class ActionTypeAttribute : System.Attribute { - private string _action; + public string ActionType; + public ActionTypeAttribute(string action) { - _action = action; + ActionType = action; } } \ No newline at end of file diff --git a/src/Navigator/Actions/NavigatorOptionsExtensions.cs b/src/Navigator/Actions/NavigatorOptionsExtensions.cs index d429179..8ad25ab 100644 --- a/src/Navigator/Actions/NavigatorOptionsExtensions.cs +++ b/src/Navigator/Actions/NavigatorOptionsExtensions.cs @@ -9,29 +9,51 @@ namespace Navigator.Actions; internal static class NavigatorOptionsExtensions { - #region NavigatorActions + #region NavigatorActionTypeCollection - private const string NavigatorActions = "_navigator.options.actions"; + private const string NavigatorActionTypeCollection = "_navigator.options.action_type_collection"; public static void RegisterActions(this NavigatorOptions navigatorOptions, IEnumerable actions) { - navigatorOptions.TryRegisterOption(NavigatorActions, actions.ToImmutableDictionary( + navigatorOptions.TryRegisterOption(NavigatorActionTypeCollection, actions.ToImmutableDictionary( type => type.GetActionType(), type => type)); } public static ImmutableDictionary RetrieveActions(this NavigatorOptions navigatorOptions) { - return navigatorOptions.RetrieveOption>(NavigatorActions) ?? ImmutableDictionary.Empty; + return navigatorOptions.RetrieveOption>(NavigatorActionTypeCollection) ?? ImmutableDictionary.Empty; } #endregion + + #region NavigatorActionPriorityCollection + + private const string NavigatorActionPriorityCollection = "_navigator.options.action_priority_collection"; + public static void RegisterPriority(this NavigatorOptions navigatorOptions, IEnumerable actions) + { + navigatorOptions.TryRegisterOption(NavigatorActionPriorityCollection, actions.ToImmutableDictionary( + type => type.FullName ?? string.Empty, + type => type.GetActionPriority())); + } + + public static ImmutableDictionary RetrievePriorities(this NavigatorOptions navigatorOptions) + { + return navigatorOptions.RetrieveOption>(NavigatorActionPriorityCollection) ?? ImmutableDictionary.Empty; + } + + #endregion + public static string GetActionType(this Type? type) { + ActionTypeAttribute? actionTypeAttribute = default; + if (type?.CustomAttributes.Any(data => data.AttributeType == typeof(ActionTypeAttribute)) ?? false) { - return type.Name; + actionTypeAttribute = Attribute.GetCustomAttribute(type, typeof(ActionTypeAttribute)) as ActionTypeAttribute; + + return actionTypeAttribute?.ActionType ?? string.Empty; } if (type?.BaseType is not null && !type.BaseType.IsInterface) @@ -44,7 +66,30 @@ public static string GetActionType(this Type? type) } } - return type?.Name ?? string.Empty; + if (type is not null) + { + actionTypeAttribute = Attribute.GetCustomAttribute(type, typeof(ActionTypeAttribute)) as ActionTypeAttribute; + } + + return actionTypeAttribute?.ActionType ?? string.Empty; + } + public static ushort GetActionPriority(this Type? type) + { + if (type?.CustomAttributes.Any(data => data.AttributeType == typeof(ActionPriorityAttribute)) ?? false) + { + var priorityAttribute = (ActionPriorityAttribute) Attribute.GetCustomAttribute(type, typeof(ActionPriorityAttribute))!; + + return priorityAttribute.Priority; + } + + if (type?.BaseType is not null && !type.BaseType.IsInterface) + { + var priority = GetActionPriority(type.BaseType); + + return priority; + } + + return Priority.Default; } } \ No newline at end of file From 93dff254202d76f5fe1eac529023fcc670a6917d Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 6 Dec 2021 23:24:01 +0100 Subject: [PATCH 185/304] feat: move cooldown logic to new extension project --- .../CooldownActionMiddleware.cs | 45 +++++++++++++++++++ .../CooldownAttribute.cs | 7 +++ .../Extensions/DistributedCacheExtensions.cs | 14 ++++++ .../Extensions/TypeExtensions.cs | 14 ++++++ .../Navigator.Extensions.Cooldown.csproj | 13 ++++++ .../Actions/CooldownAction.cs | 18 ++++++++ .../Actions/EchoAction.cs | 13 ++---- .../Navigator.Samples.Echo.csproj | 1 + src/Navigator.sln | 7 +++ .../MIddleware/CooldownActionFilter.cs | 45 ------------------- src/Navigator/DistributedCacheExtensions.cs | 17 ------- src/Navigator/Navigator.csproj | 4 ++ 12 files changed, 126 insertions(+), 72 deletions(-) create mode 100644 src/Navigator.Extensions.Cooldown/CooldownActionMiddleware.cs create mode 100644 src/Navigator.Extensions.Cooldown/CooldownAttribute.cs create mode 100644 src/Navigator.Extensions.Cooldown/Extensions/DistributedCacheExtensions.cs create mode 100644 src/Navigator.Extensions.Cooldown/Extensions/TypeExtensions.cs create mode 100644 src/Navigator.Extensions.Cooldown/Navigator.Extensions.Cooldown.csproj create mode 100644 src/Navigator.Samples.Echo/Actions/CooldownAction.cs delete mode 100644 src/Navigator/Actions/MIddleware/CooldownActionFilter.cs delete mode 100644 src/Navigator/DistributedCacheExtensions.cs diff --git a/src/Navigator.Extensions.Cooldown/CooldownActionMiddleware.cs b/src/Navigator.Extensions.Cooldown/CooldownActionMiddleware.cs new file mode 100644 index 0000000..ca0742f --- /dev/null +++ b/src/Navigator.Extensions.Cooldown/CooldownActionMiddleware.cs @@ -0,0 +1,45 @@ +using MediatR; +using Microsoft.Extensions.Caching.Distributed; +using Navigator.Actions; +using Navigator.Context; +using Navigator.Extensions.Cooldown.Extensions; + +namespace Navigator.Extensions.Cooldown; + +internal class CooldownActionMiddleware : IActionMiddleware where TAction : IAction +{ + private readonly IDistributedCache _cache; + private readonly INavigatorContext _navigatorContext; + + public CooldownActionMiddleware(IDistributedCache cache, INavigatorContextAccessor navigatorContextAccessor) + { + _cache = cache; + _navigatorContext = navigatorContextAccessor.NavigatorContext; + } + + public async Task Handle(TAction action, CancellationToken cancellationToken, RequestHandlerDelegate next) + { + var key = GenerateKey(action); + + var cooldownStatus = await _cache.GetAsync(key, cancellationToken); + + if (cooldownStatus is not null) + { + return new Status(true); + } + + var status = await next(); + + if (status.IsSuccess && typeof(TAction).GetCooldown() is { } cooldown) + { + await _cache.SetStringAsync(key, key, new DistributedCacheEntryOptions().SetAbsoluteExpiration(cooldown), cancellationToken); + } + + return status; + } + + private string GenerateKey(TAction action) + { + return $"{action.GetType().FullName}:{_navigatorContext.Conversation.Chat.Id}"; + } +} \ No newline at end of file diff --git a/src/Navigator.Extensions.Cooldown/CooldownAttribute.cs b/src/Navigator.Extensions.Cooldown/CooldownAttribute.cs new file mode 100644 index 0000000..62922aa --- /dev/null +++ b/src/Navigator.Extensions.Cooldown/CooldownAttribute.cs @@ -0,0 +1,7 @@ +namespace Navigator.Extensions.Cooldown; + +[AttributeUsage(AttributeTargets.Class)] +public class CooldownAttribute : Attribute +{ + public int Seconds { get; set; } = 300; +} diff --git a/src/Navigator.Extensions.Cooldown/Extensions/DistributedCacheExtensions.cs b/src/Navigator.Extensions.Cooldown/Extensions/DistributedCacheExtensions.cs new file mode 100644 index 0000000..c3ae7ac --- /dev/null +++ b/src/Navigator.Extensions.Cooldown/Extensions/DistributedCacheExtensions.cs @@ -0,0 +1,14 @@ +using System.Text.Json; +using Microsoft.Extensions.Caching.Distributed; + +namespace Navigator.Extensions.Cooldown.Extensions; + +internal static class DistributedCacheExtensions +{ + public static async Task GetAsync(this IDistributedCache distributedCache, string key, CancellationToken cancellationToken = default) + { + var cachedItem = await distributedCache.GetAsync(key, cancellationToken); + + return cachedItem is not null ? JsonSerializer.Deserialize(cachedItem) : default; + } +} \ No newline at end of file diff --git a/src/Navigator.Extensions.Cooldown/Extensions/TypeExtensions.cs b/src/Navigator.Extensions.Cooldown/Extensions/TypeExtensions.cs new file mode 100644 index 0000000..3b04dd6 --- /dev/null +++ b/src/Navigator.Extensions.Cooldown/Extensions/TypeExtensions.cs @@ -0,0 +1,14 @@ +namespace Navigator.Extensions.Cooldown.Extensions; + +internal static class TypeExtensions +{ + public static TimeSpan? GetCooldown(this Type type) + { + if (Attribute.GetCustomAttribute(type, typeof(CooldownAttribute)) is CooldownAttribute cooldownAttribute) + { + return TimeSpan.FromSeconds(cooldownAttribute.Seconds); + } + + return default; + } +} \ No newline at end of file diff --git a/src/Navigator.Extensions.Cooldown/Navigator.Extensions.Cooldown.csproj b/src/Navigator.Extensions.Cooldown/Navigator.Extensions.Cooldown.csproj new file mode 100644 index 0000000..ca35656 --- /dev/null +++ b/src/Navigator.Extensions.Cooldown/Navigator.Extensions.Cooldown.csproj @@ -0,0 +1,13 @@ + + + + net6.0 + enable + enable + + + + + + + diff --git a/src/Navigator.Samples.Echo/Actions/CooldownAction.cs b/src/Navigator.Samples.Echo/Actions/CooldownAction.cs new file mode 100644 index 0000000..8fbe14f --- /dev/null +++ b/src/Navigator.Samples.Echo/Actions/CooldownAction.cs @@ -0,0 +1,18 @@ +using Navigator.Context; +using Navigator.Extensions.Cooldown; +using Navigator.Providers.Telegram.Actions.Messages; + +namespace Navigator.Samples.Echo.Actions; + +[Cooldown] +public class CooldownAction : CommandAction +{ + public CooldownAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) + { + } + + public override bool CanHandleCurrentContext() + { + return Command == "/cooldown"; + } +} \ No newline at end of file diff --git a/src/Navigator.Samples.Echo/Actions/EchoAction.cs b/src/Navigator.Samples.Echo/Actions/EchoAction.cs index bd416bd..8493c63 100644 --- a/src/Navigator.Samples.Echo/Actions/EchoAction.cs +++ b/src/Navigator.Samples.Echo/Actions/EchoAction.cs @@ -1,22 +1,15 @@ -using Navigator.Actions; -using Navigator.Context; -using Navigator.Providers.Telegram.Actions; +using Navigator.Context; using Navigator.Providers.Telegram.Actions.Messages; namespace Navigator.Samples.Echo.Actions { public class EchoAction : MessageAction { - public override ushort Priority { get; protected set; } = Navigator.Actions.Priority.High; - - public string MessageToEcho { get; protected set; } = string.Empty; + public readonly string MessageToEcho; public EchoAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) { - if (!string.IsNullOrWhiteSpace(Message.Text)) - { - MessageToEcho = Message.Text; - } + MessageToEcho = !string.IsNullOrWhiteSpace(Message.Text) ? Message.Text : string.Empty; } public override bool CanHandleCurrentContext() diff --git a/src/Navigator.Samples.Echo/Navigator.Samples.Echo.csproj b/src/Navigator.Samples.Echo/Navigator.Samples.Echo.csproj index 0744581..ed9f8e7 100644 --- a/src/Navigator.Samples.Echo/Navigator.Samples.Echo.csproj +++ b/src/Navigator.Samples.Echo/Navigator.Samples.Echo.csproj @@ -6,6 +6,7 @@ + diff --git a/src/Navigator.sln b/src/Navigator.sln index 7bd3304..280a289 100644 --- a/src/Navigator.sln +++ b/src/Navigator.sln @@ -30,6 +30,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Navigator.Providers.Telegra EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Navigator.Samples.Echo", "Navigator.Samples.Echo\Navigator.Samples.Echo.csproj", "{4F4CEC5E-5FAF-4914-8EC0-E6BC9EB1B975}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Navigator.Extensions.Cooldown", "Navigator.Extensions.Cooldown\Navigator.Extensions.Cooldown.csproj", "{B7013C91-C736-4041-9952-5AC2471D9E9A}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -68,6 +70,10 @@ Global {4F4CEC5E-5FAF-4914-8EC0-E6BC9EB1B975}.Debug|Any CPU.Build.0 = Debug|Any CPU {4F4CEC5E-5FAF-4914-8EC0-E6BC9EB1B975}.Release|Any CPU.ActiveCfg = Release|Any CPU {4F4CEC5E-5FAF-4914-8EC0-E6BC9EB1B975}.Release|Any CPU.Build.0 = Release|Any CPU + {B7013C91-C736-4041-9952-5AC2471D9E9A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B7013C91-C736-4041-9952-5AC2471D9E9A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B7013C91-C736-4041-9952-5AC2471D9E9A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B7013C91-C736-4041-9952-5AC2471D9E9A}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(NestedProjects) = preSolution {F178DCF2-AD03-44C8-AF8F-95C60664DD10} = {895808DE-1CA6-406C-924A-7E43F293CF7D} @@ -83,5 +89,6 @@ Global {DAA22477-BB29-475C-AD2C-905F81B4AD8E} = {895808DE-1CA6-406C-924A-7E43F293CF7D} {8E0F6DCA-FAA4-4FA8-B9E0-75E9DC0F3573} = {DAA22477-BB29-475C-AD2C-905F81B4AD8E} {4F4CEC5E-5FAF-4914-8EC0-E6BC9EB1B975} = {6D6A8E40-8C40-49AA-BEAD-B046D43F511A} + {B7013C91-C736-4041-9952-5AC2471D9E9A} = {E6F24E3B-A066-4572-94F0-14665E19EFC7} EndGlobalSection EndGlobal diff --git a/src/Navigator/Actions/MIddleware/CooldownActionFilter.cs b/src/Navigator/Actions/MIddleware/CooldownActionFilter.cs deleted file mode 100644 index 54b8f2a..0000000 --- a/src/Navigator/Actions/MIddleware/CooldownActionFilter.cs +++ /dev/null @@ -1,45 +0,0 @@ -using System.Threading; -using System.Threading.Tasks; -using MediatR; -using Microsoft.Extensions.Caching.Distributed; -using Navigator.Context; - -namespace Navigator.Actions.MIddleware -{ - public class CooldownActionFilter : IActionMiddleware where TAction : IAction - { - private readonly IDistributedCache _cache; - private readonly INavigatorContext _navigatorContext; - public CooldownActionFilter(IDistributedCache cache, INavigatorContextAccessor navigatorContextAccessor) - { - _cache = cache; - _navigatorContext = navigatorContextAccessor.NavigatorContext; - } - - public async Task Handle(TAction action, CancellationToken cancellationToken, RequestHandlerDelegate next) - { - var key = GenerateKey(action); - - var cooldownStatus = await _cache.GetAsync(key, cancellationToken); - - if (cooldownStatus is not null) - { - return new Status(true); - } - - var status = await next(); - - if (status.IsSuccess) - { - await _cache.SetStringAsync(key, key); //TODO add timer with attribute; - } - - return status; - } - - private string GenerateKey(TAction action) - { - return $"{action.GetType().GetActionType()}:{_navigatorContext.Conversation.Chat.Id}"; - } - } -} \ No newline at end of file diff --git a/src/Navigator/DistributedCacheExtensions.cs b/src/Navigator/DistributedCacheExtensions.cs deleted file mode 100644 index 6d77c30..0000000 --- a/src/Navigator/DistributedCacheExtensions.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.Extensions.Caching.Distributed; - -namespace Navigator -{ - internal static class DistributedCacheExtensions - { - public static async Task GetAsync(this IDistributedCache distributedCache, string key, CancellationToken cancellationToken = default) - { - var cachedItem = await distributedCache.GetAsync(key, cancellationToken); - - return cachedItem is not null ? JsonSerializer.Deserialize(cachedItem) : default; - } - } -} \ No newline at end of file diff --git a/src/Navigator/Navigator.csproj b/src/Navigator/Navigator.csproj index 99a0901..bb7794d 100644 --- a/src/Navigator/Navigator.csproj +++ b/src/Navigator/Navigator.csproj @@ -28,4 +28,8 @@ + + + + From 760b5fc55cd2d08446a1a28f17c5d11a408f4128 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 6 Dec 2021 23:26:28 +0100 Subject: [PATCH 186/304] chore: simplify sample project --- .../Actions/EchoAction.cs | 23 +++++++++---------- .../Actions/EchoActionHandler.cs | 22 ++++++++---------- src/Navigator.Samples.Echo/Program.cs | 3 --- 3 files changed, 21 insertions(+), 27 deletions(-) diff --git a/src/Navigator.Samples.Echo/Actions/EchoAction.cs b/src/Navigator.Samples.Echo/Actions/EchoAction.cs index 8493c63..5546372 100644 --- a/src/Navigator.Samples.Echo/Actions/EchoAction.cs +++ b/src/Navigator.Samples.Echo/Actions/EchoAction.cs @@ -1,20 +1,19 @@ using Navigator.Context; using Navigator.Providers.Telegram.Actions.Messages; -namespace Navigator.Samples.Echo.Actions +namespace Navigator.Samples.Echo.Actions; + +public class EchoAction : MessageAction { - public class EchoAction : MessageAction - { - public readonly string MessageToEcho; + public readonly string MessageToEcho; - public EchoAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) - { - MessageToEcho = !string.IsNullOrWhiteSpace(Message.Text) ? Message.Text : string.Empty; - } + public EchoAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) + { + MessageToEcho = !string.IsNullOrWhiteSpace(Message.Text) ? Message.Text : string.Empty; + } - public override bool CanHandleCurrentContext() - { - return !string.IsNullOrWhiteSpace(MessageToEcho); - } + public override bool CanHandleCurrentContext() + { + return !string.IsNullOrWhiteSpace(MessageToEcho); } } \ No newline at end of file diff --git a/src/Navigator.Samples.Echo/Actions/EchoActionHandler.cs b/src/Navigator.Samples.Echo/Actions/EchoActionHandler.cs index dbbda89..120329d 100644 --- a/src/Navigator.Samples.Echo/Actions/EchoActionHandler.cs +++ b/src/Navigator.Samples.Echo/Actions/EchoActionHandler.cs @@ -1,25 +1,23 @@ using System.Threading; using System.Threading.Tasks; -using MediatR; using Navigator.Actions; using Navigator.Context; using Navigator.Providers.Telegram; using Telegram.Bot; -namespace Navigator.Samples.Echo.Actions +namespace Navigator.Samples.Echo.Actions; + +public class EchoActionHandler : ActionHandler { - public class EchoActionHandler : ActionHandler + public EchoActionHandler(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) { - public EchoActionHandler(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) - { - } + } - public override async Task Handle(EchoAction action, CancellationToken cancellationToken) - { - await this.GetTelegramClient().SendTextMessageAsync(this.GetTelegramChat().Id, - action.MessageToEcho, cancellationToken: cancellationToken); + public override async Task Handle(EchoAction action, CancellationToken cancellationToken) + { + await this.GetTelegramClient().SendTextMessageAsync(this.GetTelegramChat().Id, + action.MessageToEcho, cancellationToken: cancellationToken); - return Success(); - } + return Success(); } } \ No newline at end of file diff --git a/src/Navigator.Samples.Echo/Program.cs b/src/Navigator.Samples.Echo/Program.cs index f6db33c..bd65c88 100644 --- a/src/Navigator.Samples.Echo/Program.cs +++ b/src/Navigator.Samples.Echo/Program.cs @@ -1,5 +1,4 @@ using Microsoft.AspNetCore.Builder; -using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Navigator; using Navigator.Configuration; @@ -20,8 +19,6 @@ // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { - // app.UseSwagger(); - // app.UseSwaggerUI(); } app.UseHttpsRedirection(); From 4faddf9fa87fe19242b9d4d1f94904dbf85a1791 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 7 Dec 2021 09:17:53 +0100 Subject: [PATCH 187/304] chore: update solution structure --- src/Navigator.sln | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/src/Navigator.sln b/src/Navigator.sln index 280a289..e8a6c96 100644 --- a/src/Navigator.sln +++ b/src/Navigator.sln @@ -1,4 +1,4 @@ - + Microsoft Visual Studio Solution File, Format Version 12.00 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Navigator", "Navigator\Navigator.csproj", "{6DBAD041-6623-4903-9939-254FDC4EBD60}" EndProject @@ -8,7 +8,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Samples", "Samples", "{6D6A EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Extensions", "Extensions", "{F178DCF2-AD03-44C8-AF8F-95C60664DD10}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Packages", "Packages", "{895808DE-1CA6-406C-924A-7E43F293CF7D}" +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Old", "Old", "{895808DE-1CA6-406C-924A-7E43F293CF7D}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Navigator", "Navigator", "{E6F24E3B-A066-4572-94F0-14665E19EFC7}" EndProject @@ -32,6 +32,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Navigator.Samples.Echo", "N EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Navigator.Extensions.Cooldown", "Navigator.Extensions.Cooldown\Navigator.Extensions.Cooldown.csproj", "{B7013C91-C736-4041-9952-5AC2471D9E9A}" EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Extensions", "Extensions", "{A6DF6F5F-F784-4EF1-97D1-C3DDD2E66B5E}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -77,7 +79,6 @@ Global EndGlobalSection GlobalSection(NestedProjects) = preSolution {F178DCF2-AD03-44C8-AF8F-95C60664DD10} = {895808DE-1CA6-406C-924A-7E43F293CF7D} - {E6F24E3B-A066-4572-94F0-14665E19EFC7} = {895808DE-1CA6-406C-924A-7E43F293CF7D} {6DBAD041-6623-4903-9939-254FDC4EBD60} = {E6F24E3B-A066-4572-94F0-14665E19EFC7} {F26BD166-0ED4-4096-8841-47959645B3DE} = {F178DCF2-AD03-44C8-AF8F-95C60664DD10} {9DEA166A-AE92-438F-8F3D-7C2F777ABBDD} = {F26BD166-0ED4-4096-8841-47959645B3DE} @@ -86,9 +87,10 @@ Global {E2FF61C3-F081-40C8-9CC3-BBE1F81543F6} = {F178DCF2-AD03-44C8-AF8F-95C60664DD10} {90E6A9A5-BD73-4C9D-97A3-FA8021D16921} = {E2FF61C3-F081-40C8-9CC3-BBE1F81543F6} {294C1716-C054-4585-B66E-C79D155AE684} = {E2FF61C3-F081-40C8-9CC3-BBE1F81543F6} - {DAA22477-BB29-475C-AD2C-905F81B4AD8E} = {895808DE-1CA6-406C-924A-7E43F293CF7D} {8E0F6DCA-FAA4-4FA8-B9E0-75E9DC0F3573} = {DAA22477-BB29-475C-AD2C-905F81B4AD8E} {4F4CEC5E-5FAF-4914-8EC0-E6BC9EB1B975} = {6D6A8E40-8C40-49AA-BEAD-B046D43F511A} - {B7013C91-C736-4041-9952-5AC2471D9E9A} = {E6F24E3B-A066-4572-94F0-14665E19EFC7} + {B7013C91-C736-4041-9952-5AC2471D9E9A} = {A6DF6F5F-F784-4EF1-97D1-C3DDD2E66B5E} + {DAA22477-BB29-475C-AD2C-905F81B4AD8E} = {E6F24E3B-A066-4572-94F0-14665E19EFC7} + {A6DF6F5F-F784-4EF1-97D1-C3DDD2E66B5E} = {E6F24E3B-A066-4572-94F0-14665E19EFC7} EndGlobalSection -EndGlobal +EndGlobal \ No newline at end of file From b679b7d7d9717b28b7c9f4c6159ed0f2f38ab352 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 7 Dec 2021 15:47:43 +0100 Subject: [PATCH 188/304] feat: update IActionMiddleware --- src/Navigator/Actions/IActionMiddleware.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Navigator/Actions/IActionMiddleware.cs b/src/Navigator/Actions/IActionMiddleware.cs index f5653c6..12d64d5 100644 --- a/src/Navigator/Actions/IActionMiddleware.cs +++ b/src/Navigator/Actions/IActionMiddleware.cs @@ -6,7 +6,8 @@ namespace Navigator.Actions /// TODO /// /// - public interface IActionMiddleware : IPipelineBehavior where TAction : IAction + /// + public interface IActionMiddleware : IPipelineBehavior where TAction : IAction { } } \ No newline at end of file From fd75a5a7f89c3659f5bb3cb42523f8b673a8e498 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 7 Dec 2021 15:48:25 +0100 Subject: [PATCH 189/304] feat: add configuration for Cooldown extension --- .../CooldownActionMiddleware.cs | 4 +-- ...vigatorExtensionConfigurationExtensions.cs | 29 +++++++++++++++++++ 2 files changed, 31 insertions(+), 2 deletions(-) create mode 100644 src/Navigator.Extensions.Cooldown/NavigatorExtensionConfigurationExtensions.cs diff --git a/src/Navigator.Extensions.Cooldown/CooldownActionMiddleware.cs b/src/Navigator.Extensions.Cooldown/CooldownActionMiddleware.cs index ca0742f..a13a3d7 100644 --- a/src/Navigator.Extensions.Cooldown/CooldownActionMiddleware.cs +++ b/src/Navigator.Extensions.Cooldown/CooldownActionMiddleware.cs @@ -6,7 +6,7 @@ namespace Navigator.Extensions.Cooldown; -internal class CooldownActionMiddleware : IActionMiddleware where TAction : IAction +internal class CooldownActionMiddleware : IActionMiddleware where TAction : IAction { private readonly IDistributedCache _cache; private readonly INavigatorContext _navigatorContext; @@ -21,7 +21,7 @@ public async Task Handle(TAction action, CancellationToken cancellationT { var key = GenerateKey(action); - var cooldownStatus = await _cache.GetAsync(key, cancellationToken); + var cooldownStatus = await _cache.GetAsync(key, cancellationToken); if (cooldownStatus is not null) { diff --git a/src/Navigator.Extensions.Cooldown/NavigatorExtensionConfigurationExtensions.cs b/src/Navigator.Extensions.Cooldown/NavigatorExtensionConfigurationExtensions.cs new file mode 100644 index 0000000..641f92b --- /dev/null +++ b/src/Navigator.Extensions.Cooldown/NavigatorExtensionConfigurationExtensions.cs @@ -0,0 +1,29 @@ +using MediatR; +using Microsoft.Extensions.DependencyInjection; +using Navigator.Actions; +using Navigator.Configuration; +using Navigator.Configuration.Extension; +using Scrutor; + +namespace Navigator.Extensions.Cooldown; + +public static class NavigatorExtensionConfigurationExtensions +{ + public static NavigatorConfiguration Cooldown(this NavigatorExtensionConfiguration providerConfiguration) + { + + return providerConfiguration.Extension( + _ => {}, + services => + { + // services.Scan(source => source + // .FromAssemblyOf() + // .AddClasses(filter => filter.AssignableTo(typeof(IPipelineBehavior<,>))) + // .UsingRegistrationStrategy(RegistrationStrategy.Append) + // .AsImplementedInterfaces() + // .WithScopedLifetime()); + + services.AddScoped(typeof(IPipelineBehavior<,>), typeof(CooldownActionMiddleware<,>)); + }); + } +} \ No newline at end of file From 8fecca6a7a22ef50a4dc96d2830f189e2dd537d2 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 7 Dec 2021 15:48:37 +0100 Subject: [PATCH 190/304] feat: update sample to use cooldown --- .../Actions/CooldownAction.cs | 4 ++-- .../Actions/CooldownActionHandler.cs | 23 +++++++++++++++++++ src/Navigator.Samples.Echo/Program.cs | 19 +++++++++++---- 3 files changed, 39 insertions(+), 7 deletions(-) create mode 100644 src/Navigator.Samples.Echo/Actions/CooldownActionHandler.cs diff --git a/src/Navigator.Samples.Echo/Actions/CooldownAction.cs b/src/Navigator.Samples.Echo/Actions/CooldownAction.cs index 8fbe14f..776c81e 100644 --- a/src/Navigator.Samples.Echo/Actions/CooldownAction.cs +++ b/src/Navigator.Samples.Echo/Actions/CooldownAction.cs @@ -4,7 +4,7 @@ namespace Navigator.Samples.Echo.Actions; -[Cooldown] +[Cooldown(Seconds = 10)] public class CooldownAction : CommandAction { public CooldownAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) @@ -13,6 +13,6 @@ public CooldownAction(INavigatorContextAccessor navigatorContextAccessor) : base public override bool CanHandleCurrentContext() { - return Command == "/cooldown"; + return Command.StartsWith("/cooldown", true, default); } } \ No newline at end of file diff --git a/src/Navigator.Samples.Echo/Actions/CooldownActionHandler.cs b/src/Navigator.Samples.Echo/Actions/CooldownActionHandler.cs new file mode 100644 index 0000000..573e08c --- /dev/null +++ b/src/Navigator.Samples.Echo/Actions/CooldownActionHandler.cs @@ -0,0 +1,23 @@ +using System.Threading; +using System.Threading.Tasks; +using Navigator.Actions; +using Navigator.Context; +using Navigator.Providers.Telegram; +using Telegram.Bot; + +namespace Navigator.Samples.Echo.Actions; + +public class CooldownActionHandler : ActionHandler +{ + public CooldownActionHandler(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) + { + } + + public override async Task Handle(CooldownAction action, CancellationToken cancellationToken) + { + await this.GetTelegramClient().SendTextMessageAsync(this.GetTelegramChat().Id, + "not in cooldown", cancellationToken: cancellationToken); + + return Success(); + } +} \ No newline at end of file diff --git a/src/Navigator.Samples.Echo/Program.cs b/src/Navigator.Samples.Echo/Program.cs index bd65c88..19eb0f8 100644 --- a/src/Navigator.Samples.Echo/Program.cs +++ b/src/Navigator.Samples.Echo/Program.cs @@ -1,18 +1,27 @@ using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Navigator; using Navigator.Configuration; +using Navigator.Extensions.Cooldown; using Navigator.Providers.Telegram; using Navigator.Samples.Echo.Actions; var builder = WebApplication.CreateBuilder(args); // Add services to the container. -builder.Services.AddNavigator(options => -{ - options.SetWebHookBaseUrl(builder.Configuration["BASE_WEBHOOK_URL"]); - options.RegisterActionsFromAssemblies(typeof(EchoAction).Assembly); -}).WithProvider.Telegram(options => { options.SetTelegramToken(builder.Configuration["BOT_TOKEN"]); }); + +// For Extensions.Cooldown +builder.Services.AddDistributedMemoryCache(); + +builder.Services + .AddNavigator(options => + { + options.SetWebHookBaseUrl(builder.Configuration["BASE_WEBHOOK_URL"]); + options.RegisterActionsFromAssemblies(typeof(EchoAction).Assembly); + }) + .WithExtension.Cooldown() + .WithProvider.Telegram(options => { options.SetTelegramToken(builder.Configuration["BOT_TOKEN"]); }); var app = builder.Build(); From 1431d75b2fda89947454b5ad0ba8aaf1804978c9 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 7 Dec 2021 16:30:33 +0100 Subject: [PATCH 191/304] feat: update project metadata --- .../Navigator.Providers.Telegram.csproj | 5 +---- src/Navigator/Navigator.csproj | 4 ---- 2 files changed, 1 insertion(+), 8 deletions(-) diff --git a/src/Navigator.Providers.Telegram/Navigator.Providers.Telegram.csproj b/src/Navigator.Providers.Telegram/Navigator.Providers.Telegram.csproj index deba361..380430d 100644 --- a/src/Navigator.Providers.Telegram/Navigator.Providers.Telegram.csproj +++ b/src/Navigator.Providers.Telegram/Navigator.Providers.Telegram.csproj @@ -15,10 +15,7 @@ Copyright © Lucas Maximiliano Marino 2021 https://raw.githubusercontent.com/navigatorframework/navigator/master/assets/logo.png - - - full - + diff --git a/src/Navigator/Navigator.csproj b/src/Navigator/Navigator.csproj index bb7794d..99a0901 100644 --- a/src/Navigator/Navigator.csproj +++ b/src/Navigator/Navigator.csproj @@ -28,8 +28,4 @@ - - - - From 41527bb4c9e61367cfbffefcf92ae32e81a13735 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 7 Dec 2021 16:48:03 +0100 Subject: [PATCH 192/304] feat: create new Extension package for Store --- src/Navigator.sln | 14 ++++++++++---- .../Navigator.Extensions.Store.csproj | 17 +++++++++++++++++ .../ConversationEntityTypeConfiguration.cs | 4 ++-- .../Context/NavigatorDbContext.cs | 6 +++--- .../DefaultChatMapper.cs | 6 +++--- .../DefaultEntityManager.cs | 12 ++++++------ .../DefaultUserMapper.cs | 6 +++--- .../NavigatorOptionsCollectionExtensions.cs | 4 ++-- .../NavigatorServiceCollectionExtensions.cs | 10 +++++----- .../Old.Navigator.Extensions.Store.csproj} | 2 +- .../Provider/DefaultChatContextProvider.cs | 10 +++++----- .../Provider/DefaultUserContextProvider.cs | 10 +++++----- .../Provider/UpdateDataContextProvider.cs | 8 ++++---- 13 files changed, 66 insertions(+), 43 deletions(-) create mode 100644 src/Navigator/Navigator.Extensions.Store/Navigator.Extensions.Store.csproj rename src/{Navigator.Extensions.Store => Old.Navigator.Extensions.Store}/Context/Configuration/ConversationEntityTypeConfiguration.cs (84%) rename src/{Navigator.Extensions.Store => Old.Navigator.Extensions.Store}/Context/NavigatorDbContext.cs (84%) rename src/{Navigator.Extensions.Store => Old.Navigator.Extensions.Store}/DefaultChatMapper.cs (72%) rename src/{Navigator.Extensions.Store => Old.Navigator.Extensions.Store}/DefaultEntityManager.cs (94%) rename src/{Navigator.Extensions.Store => Old.Navigator.Extensions.Store}/DefaultUserMapper.cs (70%) rename src/{Navigator.Extensions.Store => Old.Navigator.Extensions.Store}/NavigatorOptionsCollectionExtensions.cs (95%) rename src/{Navigator.Extensions.Store => Old.Navigator.Extensions.Store}/NavigatorServiceCollectionExtensions.cs (94%) rename src/{Navigator.Extensions.Store/Navigator.Extensions.Store.csproj => Old.Navigator.Extensions.Store/Old.Navigator.Extensions.Store.csproj} (97%) rename src/{Navigator.Extensions.Store => Old.Navigator.Extensions.Store}/Provider/DefaultChatContextProvider.cs (88%) rename src/{Navigator.Extensions.Store => Old.Navigator.Extensions.Store}/Provider/DefaultUserContextProvider.cs (92%) rename src/{Navigator.Extensions.Store => Old.Navigator.Extensions.Store}/Provider/UpdateDataContextProvider.cs (89%) diff --git a/src/Navigator.sln b/src/Navigator.sln index e8a6c96..93cd799 100644 --- a/src/Navigator.sln +++ b/src/Navigator.sln @@ -1,8 +1,7 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 +Microsoft Visual Studio Solution File, Format Version 12.00 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Navigator", "Navigator\Navigator.csproj", "{6DBAD041-6623-4903-9939-254FDC4EBD60}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Navigator.Extensions.Store", "Navigator.Extensions.Store\Navigator.Extensions.Store.csproj", "{9DEA166A-AE92-438F-8F3D-7C2F777ABBDD}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Old.Navigator.Extensions.Store", "Old.Navigator.Extensions.Store\Old.Navigator.Extensions.Store.csproj", "{9DEA166A-AE92-438F-8F3D-7C2F777ABBDD}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Samples", "Samples", "{6D6A8E40-8C40-49AA-BEAD-B046D43F511A}" EndProject @@ -34,6 +33,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Navigator.Extensions.Cooldo EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Extensions", "Extensions", "{A6DF6F5F-F784-4EF1-97D1-C3DDD2E66B5E}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Navigator.Extensions.Store", "Navigator\Navigator.Extensions.Store\Navigator.Extensions.Store.csproj", "{E7D6F33B-C30E-4ED2-878C-B2F899CF1805}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -76,6 +77,10 @@ Global {B7013C91-C736-4041-9952-5AC2471D9E9A}.Debug|Any CPU.Build.0 = Debug|Any CPU {B7013C91-C736-4041-9952-5AC2471D9E9A}.Release|Any CPU.ActiveCfg = Release|Any CPU {B7013C91-C736-4041-9952-5AC2471D9E9A}.Release|Any CPU.Build.0 = Release|Any CPU + {E7D6F33B-C30E-4ED2-878C-B2F899CF1805}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E7D6F33B-C30E-4ED2-878C-B2F899CF1805}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E7D6F33B-C30E-4ED2-878C-B2F899CF1805}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E7D6F33B-C30E-4ED2-878C-B2F899CF1805}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(NestedProjects) = preSolution {F178DCF2-AD03-44C8-AF8F-95C60664DD10} = {895808DE-1CA6-406C-924A-7E43F293CF7D} @@ -92,5 +97,6 @@ Global {B7013C91-C736-4041-9952-5AC2471D9E9A} = {A6DF6F5F-F784-4EF1-97D1-C3DDD2E66B5E} {DAA22477-BB29-475C-AD2C-905F81B4AD8E} = {E6F24E3B-A066-4572-94F0-14665E19EFC7} {A6DF6F5F-F784-4EF1-97D1-C3DDD2E66B5E} = {E6F24E3B-A066-4572-94F0-14665E19EFC7} + {E7D6F33B-C30E-4ED2-878C-B2F899CF1805} = {A6DF6F5F-F784-4EF1-97D1-C3DDD2E66B5E} EndGlobalSection -EndGlobal \ No newline at end of file +EndGlobal diff --git a/src/Navigator/Navigator.Extensions.Store/Navigator.Extensions.Store.csproj b/src/Navigator/Navigator.Extensions.Store/Navigator.Extensions.Store.csproj new file mode 100644 index 0000000..f1b9b36 --- /dev/null +++ b/src/Navigator/Navigator.Extensions.Store/Navigator.Extensions.Store.csproj @@ -0,0 +1,17 @@ + + + + net6.0 + enable + enable + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + diff --git a/src/Navigator.Extensions.Store/Context/Configuration/ConversationEntityTypeConfiguration.cs b/src/Old.Navigator.Extensions.Store/Context/Configuration/ConversationEntityTypeConfiguration.cs similarity index 84% rename from src/Navigator.Extensions.Store/Context/Configuration/ConversationEntityTypeConfiguration.cs rename to src/Old.Navigator.Extensions.Store/Context/Configuration/ConversationEntityTypeConfiguration.cs index 0008eed..fd0d64d 100644 --- a/src/Navigator.Extensions.Store/Context/Configuration/ConversationEntityTypeConfiguration.cs +++ b/src/Old.Navigator.Extensions.Store/Context/Configuration/ConversationEntityTypeConfiguration.cs @@ -1,8 +1,8 @@ using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; -using Navigator.Extensions.Store.Abstractions.Entity; +using Old.Navigator.Extensions.Store.Abstractions.Entity; -namespace Navigator.Extensions.Store.Context.Configuration +namespace Old.Navigator.Extensions.Store.Context.Configuration { /// public class ConversationEntityTypeConfiguration : IEntityTypeConfiguration diff --git a/src/Navigator.Extensions.Store/Context/NavigatorDbContext.cs b/src/Old.Navigator.Extensions.Store/Context/NavigatorDbContext.cs similarity index 84% rename from src/Navigator.Extensions.Store/Context/NavigatorDbContext.cs rename to src/Old.Navigator.Extensions.Store/Context/NavigatorDbContext.cs index 92ccfab..a4a6173 100644 --- a/src/Navigator.Extensions.Store/Context/NavigatorDbContext.cs +++ b/src/Old.Navigator.Extensions.Store/Context/NavigatorDbContext.cs @@ -1,8 +1,8 @@ using Microsoft.EntityFrameworkCore; -using Navigator.Extensions.Store.Abstractions.Entity; -using Navigator.Extensions.Store.Context.Configuration; +using Old.Navigator.Extensions.Store.Abstractions.Entity; +using Old.Navigator.Extensions.Store.Context.Configuration; -namespace Navigator.Extensions.Store.Context +namespace Old.Navigator.Extensions.Store.Context { public class NavigatorDbContext : NavigatorDbContext { diff --git a/src/Navigator.Extensions.Store/DefaultChatMapper.cs b/src/Old.Navigator.Extensions.Store/DefaultChatMapper.cs similarity index 72% rename from src/Navigator.Extensions.Store/DefaultChatMapper.cs rename to src/Old.Navigator.Extensions.Store/DefaultChatMapper.cs index 5396606..2cd8bc2 100644 --- a/src/Navigator.Extensions.Store/DefaultChatMapper.cs +++ b/src/Old.Navigator.Extensions.Store/DefaultChatMapper.cs @@ -1,8 +1,8 @@ using System; -using Navigator.Extensions.Store.Abstractions; -using Navigator.Extensions.Store.Abstractions.Entity; +using Old.Navigator.Extensions.Store.Abstractions; +using Old.Navigator.Extensions.Store.Abstractions.Entity; -namespace Navigator.Extensions.Store +namespace Old.Navigator.Extensions.Store { public class DefaultChatMapper : IChatMapper { diff --git a/src/Navigator.Extensions.Store/DefaultEntityManager.cs b/src/Old.Navigator.Extensions.Store/DefaultEntityManager.cs similarity index 94% rename from src/Navigator.Extensions.Store/DefaultEntityManager.cs rename to src/Old.Navigator.Extensions.Store/DefaultEntityManager.cs index 128ac1a..5c0eff0 100644 --- a/src/Navigator.Extensions.Store/DefaultEntityManager.cs +++ b/src/Old.Navigator.Extensions.Store/DefaultEntityManager.cs @@ -4,14 +4,14 @@ using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; -using Navigator.Extensions.Store.Abstractions; -using Navigator.Extensions.Store.Abstractions.Entity; -using Navigator.Extensions.Store.Context; +using Old.Navigator.Extensions.Store.Abstractions; +using Old.Navigator.Extensions.Store.Abstractions.Entity; +using Old.Navigator.Extensions.Store.Context; using Telegram.Bot.Types; -using Chat = Navigator.Extensions.Store.Abstractions.Entity.Chat; -using User = Navigator.Extensions.Store.Abstractions.Entity.User; +using Chat = Old.Navigator.Extensions.Store.Abstractions.Entity.Chat; +using User = Old.Navigator.Extensions.Store.Abstractions.Entity.User; -namespace Navigator.Extensions.Store +namespace Old.Navigator.Extensions.Store { public class DefaultEntityManager : IEntityManager where TContext : NavigatorDbContext where TUser : User diff --git a/src/Navigator.Extensions.Store/DefaultUserMapper.cs b/src/Old.Navigator.Extensions.Store/DefaultUserMapper.cs similarity index 70% rename from src/Navigator.Extensions.Store/DefaultUserMapper.cs rename to src/Old.Navigator.Extensions.Store/DefaultUserMapper.cs index 0d6f893..45cfc71 100644 --- a/src/Navigator.Extensions.Store/DefaultUserMapper.cs +++ b/src/Old.Navigator.Extensions.Store/DefaultUserMapper.cs @@ -1,7 +1,7 @@ -using Navigator.Extensions.Store.Abstractions; -using Navigator.Extensions.Store.Abstractions.Entity; +using Old.Navigator.Extensions.Store.Abstractions; +using Old.Navigator.Extensions.Store.Abstractions.Entity; -namespace Navigator.Extensions.Store +namespace Old.Navigator.Extensions.Store { public class DefaultUserMapper : IUserMapper { diff --git a/src/Navigator.Extensions.Store/NavigatorOptionsCollectionExtensions.cs b/src/Old.Navigator.Extensions.Store/NavigatorOptionsCollectionExtensions.cs similarity index 95% rename from src/Navigator.Extensions.Store/NavigatorOptionsCollectionExtensions.cs rename to src/Old.Navigator.Extensions.Store/NavigatorOptionsCollectionExtensions.cs index 84a4e7d..39698e9 100644 --- a/src/Navigator.Extensions.Store/NavigatorOptionsCollectionExtensions.cs +++ b/src/Old.Navigator.Extensions.Store/NavigatorOptionsCollectionExtensions.cs @@ -1,8 +1,8 @@ using System; using Navigator.Abstractions; -using Navigator.Extensions.Store.Abstractions.Entity; +using Old.Navigator.Extensions.Store.Abstractions.Entity; -namespace Navigator.Extensions.Store +namespace Old.Navigator.Extensions.Store { public static class NavigatorOptionsCollectionExtensions { diff --git a/src/Navigator.Extensions.Store/NavigatorServiceCollectionExtensions.cs b/src/Old.Navigator.Extensions.Store/NavigatorServiceCollectionExtensions.cs similarity index 94% rename from src/Navigator.Extensions.Store/NavigatorServiceCollectionExtensions.cs rename to src/Old.Navigator.Extensions.Store/NavigatorServiceCollectionExtensions.cs index 2ae9024..b8c2232 100644 --- a/src/Navigator.Extensions.Store/NavigatorServiceCollectionExtensions.cs +++ b/src/Old.Navigator.Extensions.Store/NavigatorServiceCollectionExtensions.cs @@ -3,12 +3,12 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Navigator.Abstractions; -using Navigator.Extensions.Store.Abstractions; -using Navigator.Extensions.Store.Abstractions.Entity; -using Navigator.Extensions.Store.Context; -using Navigator.Extensions.Store.Provider; +using Old.Navigator.Extensions.Store.Abstractions; +using Old.Navigator.Extensions.Store.Abstractions.Entity; +using Old.Navigator.Extensions.Store.Context; +using Old.Navigator.Extensions.Store.Provider; - namespace Navigator.Extensions.Store +namespace Old.Navigator.Extensions.Store { public static class NavigatorServiceCollectionExtensions { diff --git a/src/Navigator.Extensions.Store/Navigator.Extensions.Store.csproj b/src/Old.Navigator.Extensions.Store/Old.Navigator.Extensions.Store.csproj similarity index 97% rename from src/Navigator.Extensions.Store/Navigator.Extensions.Store.csproj rename to src/Old.Navigator.Extensions.Store/Old.Navigator.Extensions.Store.csproj index b5e6ecc..a57d629 100644 --- a/src/Navigator.Extensions.Store/Navigator.Extensions.Store.csproj +++ b/src/Old.Navigator.Extensions.Store/Old.Navigator.Extensions.Store.csproj @@ -6,7 +6,7 @@ true true 0.9.100-beta - Navigator.Extensions.Store + Old.Navigator.Extensions.Store Navigator Extensions Store Lucas Maximiliano Marino Store extension for Navigator Framework. diff --git a/src/Navigator.Extensions.Store/Provider/DefaultChatContextProvider.cs b/src/Old.Navigator.Extensions.Store/Provider/DefaultChatContextProvider.cs similarity index 88% rename from src/Navigator.Extensions.Store/Provider/DefaultChatContextProvider.cs rename to src/Old.Navigator.Extensions.Store/Provider/DefaultChatContextProvider.cs index d62e73a..6116c4f 100644 --- a/src/Navigator.Extensions.Store/Provider/DefaultChatContextProvider.cs +++ b/src/Old.Navigator.Extensions.Store/Provider/DefaultChatContextProvider.cs @@ -1,14 +1,14 @@ using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Navigator.Abstractions; -using Navigator.Extensions.Store.Abstractions; -using Navigator.Extensions.Store.Abstractions.Extensions; +using Old.Navigator.Extensions.Store.Abstractions; +using Old.Navigator.Extensions.Store.Abstractions.Extensions; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; -using Chat = Navigator.Extensions.Store.Abstractions.Entity.Chat; -using User = Navigator.Extensions.Store.Abstractions.Entity.User; +using Chat = Old.Navigator.Extensions.Store.Abstractions.Entity.Chat; +using User = Old.Navigator.Extensions.Store.Abstractions.Entity.User; -namespace Navigator.Extensions.Store.Provider +namespace Old.Navigator.Extensions.Store.Provider { public class DefaultChatContextProvider : INavigatorContextExtensionProvider where TUser : User diff --git a/src/Navigator.Extensions.Store/Provider/DefaultUserContextProvider.cs b/src/Old.Navigator.Extensions.Store/Provider/DefaultUserContextProvider.cs similarity index 92% rename from src/Navigator.Extensions.Store/Provider/DefaultUserContextProvider.cs rename to src/Old.Navigator.Extensions.Store/Provider/DefaultUserContextProvider.cs index 3b41d3a..91d033f 100644 --- a/src/Navigator.Extensions.Store/Provider/DefaultUserContextProvider.cs +++ b/src/Old.Navigator.Extensions.Store/Provider/DefaultUserContextProvider.cs @@ -1,14 +1,14 @@ using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Navigator.Abstractions; -using Navigator.Extensions.Store.Abstractions; -using Navigator.Extensions.Store.Abstractions.Extensions; +using Old.Navigator.Extensions.Store.Abstractions; +using Old.Navigator.Extensions.Store.Abstractions.Extensions; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; -using Chat = Navigator.Extensions.Store.Abstractions.Entity.Chat; -using User = Navigator.Extensions.Store.Abstractions.Entity.User; +using Chat = Old.Navigator.Extensions.Store.Abstractions.Entity.Chat; +using User = Old.Navigator.Extensions.Store.Abstractions.Entity.User; -namespace Navigator.Extensions.Store.Provider +namespace Old.Navigator.Extensions.Store.Provider { public class DefaultUserContextProvider : INavigatorContextExtensionProvider where TUser : User diff --git a/src/Navigator.Extensions.Store/Provider/UpdateDataContextProvider.cs b/src/Old.Navigator.Extensions.Store/Provider/UpdateDataContextProvider.cs similarity index 89% rename from src/Navigator.Extensions.Store/Provider/UpdateDataContextProvider.cs rename to src/Old.Navigator.Extensions.Store/Provider/UpdateDataContextProvider.cs index d00af98..7b3531f 100644 --- a/src/Navigator.Extensions.Store/Provider/UpdateDataContextProvider.cs +++ b/src/Old.Navigator.Extensions.Store/Provider/UpdateDataContextProvider.cs @@ -1,13 +1,13 @@ using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Navigator.Abstractions; -using Navigator.Extensions.Store.Abstractions; +using Old.Navigator.Extensions.Store.Abstractions; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; -using Chat = Navigator.Extensions.Store.Abstractions.Entity.Chat; -using User = Navigator.Extensions.Store.Abstractions.Entity.User; +using Chat = Old.Navigator.Extensions.Store.Abstractions.Entity.Chat; +using User = Old.Navigator.Extensions.Store.Abstractions.Entity.User; -namespace Navigator.Extensions.Store.Provider +namespace Old.Navigator.Extensions.Store.Provider { public class UpdateDataContextProvider : INavigatorContextExtensionProvider where TUser : User From d8e2f5507b49aec8ec50ab6773a0d0ce219c16a4 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 7 Dec 2021 18:34:13 +0100 Subject: [PATCH 193/304] feat: delete unused class --- .../Extensions/DistributedCacheExtensions.cs | 14 -------------- 1 file changed, 14 deletions(-) delete mode 100644 src/Navigator.Extensions.Cooldown/Extensions/DistributedCacheExtensions.cs diff --git a/src/Navigator.Extensions.Cooldown/Extensions/DistributedCacheExtensions.cs b/src/Navigator.Extensions.Cooldown/Extensions/DistributedCacheExtensions.cs deleted file mode 100644 index c3ae7ac..0000000 --- a/src/Navigator.Extensions.Cooldown/Extensions/DistributedCacheExtensions.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System.Text.Json; -using Microsoft.Extensions.Caching.Distributed; - -namespace Navigator.Extensions.Cooldown.Extensions; - -internal static class DistributedCacheExtensions -{ - public static async Task GetAsync(this IDistributedCache distributedCache, string key, CancellationToken cancellationToken = default) - { - var cachedItem = await distributedCache.GetAsync(key, cancellationToken); - - return cachedItem is not null ? JsonSerializer.Deserialize(cachedItem) : default; - } -} \ No newline at end of file From 9c631a71576545b7a88c984b41c693a898dead3d Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 7 Dec 2021 19:56:35 +0100 Subject: [PATCH 194/304] chore: correct solution project path --- src/Navigator.sln | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Navigator.sln b/src/Navigator.sln index 93cd799..9f20dd4 100644 --- a/src/Navigator.sln +++ b/src/Navigator.sln @@ -33,7 +33,7 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Navigator.Extensions.Cooldo EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Extensions", "Extensions", "{A6DF6F5F-F784-4EF1-97D1-C3DDD2E66B5E}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Navigator.Extensions.Store", "Navigator\Navigator.Extensions.Store\Navigator.Extensions.Store.csproj", "{E7D6F33B-C30E-4ED2-878C-B2F899CF1805}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Navigator.Extensions.Store", "Navigator.Extensions.Store\Navigator.Extensions.Store.csproj", "{E7D6F33B-C30E-4ED2-878C-B2F899CF1805}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution From 2851fe4cddf357387b0b392cdf23cf251a278529 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 7 Dec 2021 19:57:03 +0100 Subject: [PATCH 195/304] feat: convert chat entities from interface to records --- src/Navigator/Entities/Bot.cs | 12 +++++++++ src/Navigator/Entities/BotUser.cs | 8 ------ src/Navigator/Entities/Chat.cs | 33 +++++++++++++++++++++++++ src/Navigator/Entities/Conversation.cs | 11 +++++++++ src/Navigator/Entities/IConversation.cs | 16 ------------ src/Navigator/Entities/IUser.cs | 18 -------------- src/Navigator/Entities/User.cs | 25 +++++++++++++++++++ 7 files changed, 81 insertions(+), 42 deletions(-) create mode 100644 src/Navigator/Entities/Bot.cs delete mode 100644 src/Navigator/Entities/BotUser.cs create mode 100644 src/Navigator/Entities/Chat.cs create mode 100644 src/Navigator/Entities/Conversation.cs delete mode 100644 src/Navigator/Entities/IConversation.cs delete mode 100644 src/Navigator/Entities/IUser.cs create mode 100644 src/Navigator/Entities/User.cs diff --git a/src/Navigator/Entities/Bot.cs b/src/Navigator/Entities/Bot.cs new file mode 100644 index 0000000..fe1e23b --- /dev/null +++ b/src/Navigator/Entities/Bot.cs @@ -0,0 +1,12 @@ +using System; + +namespace Navigator.Entities +{ + public record Bot : User + { + /// + protected Bot(string input) : base(input) + { + } + } +} \ No newline at end of file diff --git a/src/Navigator/Entities/BotUser.cs b/src/Navigator/Entities/BotUser.cs deleted file mode 100644 index e603313..0000000 --- a/src/Navigator/Entities/BotUser.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace Navigator.Entities -{ - public class BotUser : IUser - { - public string Id { get; init; } - public string Username { get; init; } - } -} \ No newline at end of file diff --git a/src/Navigator/Entities/Chat.cs b/src/Navigator/Entities/Chat.cs new file mode 100644 index 0000000..2cdc65b --- /dev/null +++ b/src/Navigator/Entities/Chat.cs @@ -0,0 +1,33 @@ +using System; +using System.Linq; +using System.Security.Cryptography; +using System.Text; + +namespace Navigator.Entities; + +/// +/// Represents a chat. +/// +public abstract record Chat +{ + protected Chat(string input) + { + Id = new Guid(SHA256.HashData(Encoding.UTF8.GetBytes(input)).Take(16).ToArray()); + } + + /// + /// Id of the chat. + /// + /// Generally a deterministic Guid based on some kind of input. + /// + /// + Guid Id { get; init; } + + /// + /// Title of the chat, if any. + /// + /// Optional. + /// + /// + string? Title { get; init; } +} \ No newline at end of file diff --git a/src/Navigator/Entities/Conversation.cs b/src/Navigator/Entities/Conversation.cs new file mode 100644 index 0000000..0d27410 --- /dev/null +++ b/src/Navigator/Entities/Conversation.cs @@ -0,0 +1,11 @@ +namespace Navigator.Entities; + +/// +/// Represents an interaction between a user and chat. +/// +public abstract record Conversation +{ + User User { get; init; } + + Chat Chat { get; init; } +} \ No newline at end of file diff --git a/src/Navigator/Entities/IConversation.cs b/src/Navigator/Entities/IConversation.cs deleted file mode 100644 index addfbf5..0000000 --- a/src/Navigator/Entities/IConversation.cs +++ /dev/null @@ -1,16 +0,0 @@ -using System.Collections.Generic; - -namespace Navigator.Entities -{ - public interface IConversation - { - IUser User { get; init; } - IChat Chat { get; init; } - } - - public interface IChat - { - string Id { get; init; } - string? Title { get; init; } - } -} \ No newline at end of file diff --git a/src/Navigator/Entities/IUser.cs b/src/Navigator/Entities/IUser.cs deleted file mode 100644 index 309ba66..0000000 --- a/src/Navigator/Entities/IUser.cs +++ /dev/null @@ -1,18 +0,0 @@ -namespace Navigator.Entities -{ - /// - /// User - /// - public interface IUser - { - /// - /// Id of the user. - /// - string Id { get; init; } - - /// - /// Username of the user, if any. - /// - string? Username { get; init; } - } -} \ No newline at end of file diff --git a/src/Navigator/Entities/User.cs b/src/Navigator/Entities/User.cs new file mode 100644 index 0000000..96a27e5 --- /dev/null +++ b/src/Navigator/Entities/User.cs @@ -0,0 +1,25 @@ +using System; +using System.Linq; +using System.Security.Cryptography; +using System.Text; + +namespace Navigator.Entities; + +/// +/// Represents a user. +/// +public abstract record User +{ + protected User(string input) + { + Id = new Guid(SHA256.HashData(Encoding.UTF8.GetBytes(input)).Take(16).ToArray()); + } + + /// + /// Id of the user. + /// + /// Generally a deterministic Guid based on some kind of input. + /// + /// + Guid Id { get; init; } +} \ No newline at end of file From 77e9d3a5d4bd1fff939561b5c67e6aaccf419cc6 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 7 Dec 2021 20:00:33 +0100 Subject: [PATCH 196/304] chore: move project to correct path --- .../Navigator.Extensions.Store.csproj | 0 .../NavigatorDbContext.cs | 33 +++++++++++++++++++ 2 files changed, 33 insertions(+) rename src/{Navigator => }/Navigator.Extensions.Store/Navigator.Extensions.Store.csproj (100%) create mode 100644 src/Navigator.Extensions.Store/NavigatorDbContext.cs diff --git a/src/Navigator/Navigator.Extensions.Store/Navigator.Extensions.Store.csproj b/src/Navigator.Extensions.Store/Navigator.Extensions.Store.csproj similarity index 100% rename from src/Navigator/Navigator.Extensions.Store/Navigator.Extensions.Store.csproj rename to src/Navigator.Extensions.Store/Navigator.Extensions.Store.csproj diff --git a/src/Navigator.Extensions.Store/NavigatorDbContext.cs b/src/Navigator.Extensions.Store/NavigatorDbContext.cs new file mode 100644 index 0000000..bc9755f --- /dev/null +++ b/src/Navigator.Extensions.Store/NavigatorDbContext.cs @@ -0,0 +1,33 @@ +namespace Navigator.Extensions.Store; + +public class NavigatorDbContext : NavigatorDbContext +{ + public NavigatorDbContext(DbContextOptions options) : base(options) + { + } +} + +public class NavigatorDbContext : DbContext + where TUser : User + where TChat : Chat +{ + public DbSet Users { get; set; } + public DbSet Chats { get; set; } + public DbSet Conversations { get; set; } + + protected NavigatorDbContext() + { + } + + public NavigatorDbContext(DbContextOptions options) : base(options) + { + } + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + base.OnModelCreating(modelBuilder); + + modelBuilder.ApplyConfiguration(new ConversationEntityTypeConfiguration()); + + } +} \ No newline at end of file From 4775cf48b5db97f49c511aa694d9a77a23a872d4 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 7 Dec 2021 20:26:37 +0100 Subject: [PATCH 197/304] feat: adapt Navigator and related projects to new entities --- .../Actions/Messages/CommandAction.cs | 5 ++- .../Entities/Conversation.cs | 23 +++++------ .../Entities/TelegramBot.cs | 16 ++++++++ .../Entities/TelegramChat.cs | 17 ++++++++ .../Entities/TelegramUser.cs | 19 +++++++++ .../Extensions/TelegramUpdateExtensions.cs | 39 ++++++++----------- .../NavigatorContextExtensions.cs | 2 +- .../NavigatorTelegramClient.cs | 8 ++-- src/Navigator/Context/INavigatorContext.cs | 4 +- src/Navigator/Context/NavigatorContext.cs | 6 +-- ...avigatorContextBuilderOptionsExtensions.cs | 6 +-- src/Navigator/Entities/Bot.cs | 3 +- src/Navigator/Entities/Chat.cs | 10 +---- src/Navigator/Entities/Conversation.cs | 12 ++++-- src/Navigator/Entities/User.cs | 2 +- src/Navigator/INavigatorClient.cs | 2 +- 16 files changed, 107 insertions(+), 67 deletions(-) create mode 100644 src/Navigator.Providers.Telegram/Entities/TelegramBot.cs create mode 100644 src/Navigator.Providers.Telegram/Entities/TelegramChat.cs create mode 100644 src/Navigator.Providers.Telegram/Entities/TelegramUser.cs diff --git a/src/Navigator.Providers.Telegram/Actions/Messages/CommandAction.cs b/src/Navigator.Providers.Telegram/Actions/Messages/CommandAction.cs index c282d9c..2401a31 100644 --- a/src/Navigator.Providers.Telegram/Actions/Messages/CommandAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Messages/CommandAction.cs @@ -1,6 +1,7 @@ using Navigator.Actions; using Navigator.Actions.Attributes; using Navigator.Context; +using Navigator.Providers.Telegram.Entities; using Navigator.Providers.Telegram.Extensions; namespace Navigator.Providers.Telegram.Actions.Messages @@ -26,8 +27,8 @@ protected CommandAction(INavigatorContextAccessor navigatorContextAccessor) : ba { var botProfile = NavigatorContextAccessor.NavigatorContext.BotProfile; - Command = Message.ExtractCommand(botProfile.Username) ?? string.Empty; - Arguments = Message.ExtractArguments(botProfile.Username); + Command = Message.ExtractCommand((botProfile as TelegramBot)?.Username) ?? string.Empty; + Arguments = Message.ExtractArguments(); } } } \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/Entities/Conversation.cs b/src/Navigator.Providers.Telegram/Entities/Conversation.cs index d16a24f..d83019a 100644 --- a/src/Navigator.Providers.Telegram/Entities/Conversation.cs +++ b/src/Navigator.Providers.Telegram/Entities/Conversation.cs @@ -2,21 +2,16 @@ namespace Navigator.Providers.Telegram.Entities { - public class Conversation : IConversation + public record TelegramConversation : Conversation { - public IUser User { get; init; } - public IChat Chat { get; init; } - } + /// + /// Telegram user. + /// + public new TelegramUser User { get; init; } - public class User : IUser - { - public string Id { get; init; } - public string? Username { get; init; } - } - - public class Chat : IChat - { - public string Id { get; init; } - public string? Title { get; init; } + /// + /// Telegram chat. + /// + public new TelegramChat Chat { get; init; } } } \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/Entities/TelegramBot.cs b/src/Navigator.Providers.Telegram/Entities/TelegramBot.cs new file mode 100644 index 0000000..b01b916 --- /dev/null +++ b/src/Navigator.Providers.Telegram/Entities/TelegramBot.cs @@ -0,0 +1,16 @@ +using Navigator.Entities; + +namespace Navigator.Providers.Telegram.Entities; + +public record TelegramBot(long ExternalIdentifier) : Bot(ExternalIdentifier.ToString()) +{ + /// + /// Telegram identifier for the bot. + /// + public long ExternalIdentifier { get; init; } = ExternalIdentifier; + + /// + /// Username of the bot. + /// + public string Username { get; init; } +} \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/Entities/TelegramChat.cs b/src/Navigator.Providers.Telegram/Entities/TelegramChat.cs new file mode 100644 index 0000000..eac83ac --- /dev/null +++ b/src/Navigator.Providers.Telegram/Entities/TelegramChat.cs @@ -0,0 +1,17 @@ +using System; +using Navigator.Entities; + +namespace Navigator.Providers.Telegram.Entities; + +public record TelegramChat(long ExternalIdentifier) : Chat(ExternalIdentifier.ToString()) +{ + /// + /// Telegram identifier for the user. + /// + public long ExternalIdentifier { get; init; } = ExternalIdentifier; + + /// + /// Title of the chat, if any. + /// + public string? Title { get; init; } +} \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/Entities/TelegramUser.cs b/src/Navigator.Providers.Telegram/Entities/TelegramUser.cs new file mode 100644 index 0000000..42e3d37 --- /dev/null +++ b/src/Navigator.Providers.Telegram/Entities/TelegramUser.cs @@ -0,0 +1,19 @@ +using Navigator.Entities; + +namespace Navigator.Providers.Telegram.Entities; + +public record TelegramUser(long ExternalIdentifier) : User(ExternalIdentifier.ToString()) +{ + /// + /// Telegram identifier for the user. + /// + public long ExternalIdentifier { get; init; } = ExternalIdentifier; + + /// + /// Username of the user, if any. + /// + /// Optional. + /// + /// + public string? Username { get; init; } +} \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/Extensions/TelegramUpdateExtensions.cs b/src/Navigator.Providers.Telegram/Extensions/TelegramUpdateExtensions.cs index c9bb204..78a8ea5 100644 --- a/src/Navigator.Providers.Telegram/Extensions/TelegramUpdateExtensions.cs +++ b/src/Navigator.Providers.Telegram/Extensions/TelegramUpdateExtensions.cs @@ -1,8 +1,5 @@ using System; using System.Linq; -using Navigator.Context; -using Navigator.Context.Extensions; -using Navigator.Entities; using Navigator.Providers.Telegram.Entities; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; @@ -13,28 +10,28 @@ namespace Navigator.Providers.Telegram.Extensions { internal static class TelegramUpdateExtensions { - public static string? ExtractCommand(this Message message, string botName) + public static string? ExtractCommand(this Message message, string? botName) { - if (message.Entities?.First()?.Type != MessageEntityType.BotCommand) return default; + if (message.Entities?.First().Type != MessageEntityType.BotCommand) return default; - var command = message.EntityValues.First(); + var command = message.EntityValues?.First(); - if (!command.Contains('@')) return command; + if (command?.Contains('@') == false) return command; - if (!command.Contains(botName)) return default; + if (botName is not null && !command?.Contains(botName) == false) return default; - command = command.Substring(0, command.IndexOf('@')); + command = command?[..command.IndexOf('@')]; return command; } - - public static string? ExtractArguments(this Message message, string botName) + + public static string? ExtractArguments(this Message message) { - return message.Text.Contains(' ') + return message.Text is not null && message.Text.Contains(' ') ? message.Text.Remove(0, message.Text.IndexOf(' ') + 1) : default; } - + public static User? GetUserOrDefault(this Update update) { return update.Type switch @@ -51,7 +48,7 @@ internal static class TelegramUpdateExtensions _ => default }; } - + public static Chat? GetChatOrDefault(this Update update) { return update.Type switch @@ -65,7 +62,7 @@ internal static class TelegramUpdateExtensions }; } - public static IConversation GetConversation(this Update update) + public static TelegramConversation GetConversation(this Update update) { var user = update.GetUserOrDefault(); var chat = update.GetChatOrDefault(); @@ -75,17 +72,15 @@ public static IConversation GetConversation(this Update update) throw new Exception("TODO NAvigator exception no conversation could be built."); } - return new Conversation + return new TelegramConversation { - User = new Entities.User + User = new TelegramUser(user.Id) { - Id = user.Id.ToString(), - Username = string.IsNullOrWhiteSpace(user.Username) ? chat.FirstName : user.Username + Username = user.Username }, - Chat = new Entities.Chat + Chat = new TelegramChat(chat.Id) { - Id = chat.Id.ToString(), - Title = string.IsNullOrWhiteSpace(chat.Title) ? chat.Username : chat.Title + Title = chat.Title } }; } diff --git a/src/Navigator.Providers.Telegram/NavigatorContextExtensions.cs b/src/Navigator.Providers.Telegram/NavigatorContextExtensions.cs index 0a62a82..bb68947 100644 --- a/src/Navigator.Providers.Telegram/NavigatorContextExtensions.cs +++ b/src/Navigator.Providers.Telegram/NavigatorContextExtensions.cs @@ -21,7 +21,7 @@ public static NavigatorTelegramClient GetTelegramClient(this INavigatorContext c return context.Provider.GetTelegramClient(); } - // #region User + // #region TelegramUser // // /// // /// Get a Telegram user. diff --git a/src/Navigator.Providers.Telegram/NavigatorTelegramClient.cs b/src/Navigator.Providers.Telegram/NavigatorTelegramClient.cs index 917142e..cafbb38 100644 --- a/src/Navigator.Providers.Telegram/NavigatorTelegramClient.cs +++ b/src/Navigator.Providers.Telegram/NavigatorTelegramClient.cs @@ -3,6 +3,7 @@ using System.Threading.Tasks; using Navigator.Configuration; using Navigator.Entities; +using Navigator.Providers.Telegram.Entities; using Telegram.Bot; namespace Navigator.Providers.Telegram @@ -14,14 +15,13 @@ public NavigatorTelegramClient(INavigatorOptions options) { } - public async Task GetProfile(CancellationToken cancellationToken = default) + public async Task GetProfile(CancellationToken cancellationToken = default) { var bot = await this.GetMeAsync(cancellationToken); - return new BotUser + return new TelegramBot(bot.Id) { - Id = bot.Id.ToString(), - Username = bot.Username + Username = bot.Username! }; } } diff --git a/src/Navigator/Context/INavigatorContext.cs b/src/Navigator/Context/INavigatorContext.cs index b0ea141..2075380 100644 --- a/src/Navigator/Context/INavigatorContext.cs +++ b/src/Navigator/Context/INavigatorContext.cs @@ -13,7 +13,7 @@ public interface INavigatorContext /// /// /// - BotUser BotProfile { get; } + Bot BotProfile { get; } /// /// @@ -30,6 +30,6 @@ public interface INavigatorContext /// public string ActionType { get; } - public IConversation Conversation { get; } + public Conversation Conversation { get; } } } \ No newline at end of file diff --git a/src/Navigator/Context/NavigatorContext.cs b/src/Navigator/Context/NavigatorContext.cs index 84c13ad..f3f518b 100644 --- a/src/Navigator/Context/NavigatorContext.cs +++ b/src/Navigator/Context/NavigatorContext.cs @@ -16,7 +16,7 @@ public class NavigatorContext : INavigatorContext /// /// /// - public BotUser BotProfile { get; } + public Bot BotProfile { get; } public Dictionary Extensions { get; } @@ -24,12 +24,12 @@ public class NavigatorContext : INavigatorContext public string ActionType { get; } - public IConversation Conversation { get; } + public Conversation Conversation { get; } /// /// Builds a new Navigator Context. /// - public NavigatorContext(INavigatorProvider provider, BotUser botProfile, string actionType, IConversation conversation) + public NavigatorContext(INavigatorProvider provider, Bot botProfile, string actionType, Conversation conversation) { Provider = provider; BotProfile = botProfile; diff --git a/src/Navigator/Context/NavigatorContextBuilderOptionsExtensions.cs b/src/Navigator/Context/NavigatorContextBuilderOptionsExtensions.cs index 366b10d..97b9fb4 100644 --- a/src/Navigator/Context/NavigatorContextBuilderOptionsExtensions.cs +++ b/src/Navigator/Context/NavigatorContextBuilderOptionsExtensions.cs @@ -60,15 +60,15 @@ public static void SetOriginalEvent(this INavigatorContextBuilderOptions context private const string ConversationKey = "_navigator.context.options.conversation"; - public static void SetConversation(this INavigatorContextBuilderOptions contextBuilderOptions, IConversation conversation) + public static void SetConversation(this INavigatorContextBuilderOptions contextBuilderOptions, Conversation conversation) { contextBuilderOptions.TryRegisterOption(ConversationKey, conversation); } - public static IConversation? GetConversationOrDefault(this INavigatorContextBuilderOptions contextBuilderOptions) + public static Conversation? GetConversationOrDefault(this INavigatorContextBuilderOptions contextBuilderOptions) { - return contextBuilderOptions.RetrieveOption(ConversationKey); + return contextBuilderOptions.RetrieveOption(ConversationKey); } #endregion diff --git a/src/Navigator/Entities/Bot.cs b/src/Navigator/Entities/Bot.cs index fe1e23b..681be41 100644 --- a/src/Navigator/Entities/Bot.cs +++ b/src/Navigator/Entities/Bot.cs @@ -2,9 +2,8 @@ namespace Navigator.Entities { - public record Bot : User + public abstract record Bot : User { - /// protected Bot(string input) : base(input) { } diff --git a/src/Navigator/Entities/Chat.cs b/src/Navigator/Entities/Chat.cs index 2cdc65b..090ad9c 100644 --- a/src/Navigator/Entities/Chat.cs +++ b/src/Navigator/Entities/Chat.cs @@ -21,13 +21,5 @@ protected Chat(string input) /// Generally a deterministic Guid based on some kind of input. /// /// - Guid Id { get; init; } - - /// - /// Title of the chat, if any. - /// - /// Optional. - /// - /// - string? Title { get; init; } + public Guid Id { get; init; } } \ No newline at end of file diff --git a/src/Navigator/Entities/Conversation.cs b/src/Navigator/Entities/Conversation.cs index 0d27410..edd109f 100644 --- a/src/Navigator/Entities/Conversation.cs +++ b/src/Navigator/Entities/Conversation.cs @@ -5,7 +5,13 @@ namespace Navigator.Entities; /// public abstract record Conversation { - User User { get; init; } - - Chat Chat { get; init; } + /// + /// User + /// + public User User { get; init; } + + /// + /// Chat + /// + public Chat Chat { get; init; } } \ No newline at end of file diff --git a/src/Navigator/Entities/User.cs b/src/Navigator/Entities/User.cs index 96a27e5..94cefc4 100644 --- a/src/Navigator/Entities/User.cs +++ b/src/Navigator/Entities/User.cs @@ -21,5 +21,5 @@ protected User(string input) /// Generally a deterministic Guid based on some kind of input. /// /// - Guid Id { get; init; } + public Guid Id { get; init; } } \ No newline at end of file diff --git a/src/Navigator/INavigatorClient.cs b/src/Navigator/INavigatorClient.cs index 5aabf86..6fb545f 100644 --- a/src/Navigator/INavigatorClient.cs +++ b/src/Navigator/INavigatorClient.cs @@ -11,6 +11,6 @@ public interface INavigatorClient /// /// /// - Task GetProfile(CancellationToken cancellationToken = default); + Task GetProfile(CancellationToken cancellationToken = default); } } \ No newline at end of file From c761b19587ea5998e68250aea73704731711bb39 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 7 Dec 2021 20:37:15 +0100 Subject: [PATCH 198/304] docs: improve class documentation for NavigatorContext --- src/Navigator/Context/NavigatorContext.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Navigator/Context/NavigatorContext.cs b/src/Navigator/Context/NavigatorContext.cs index f3f518b..6a685ad 100644 --- a/src/Navigator/Context/NavigatorContext.cs +++ b/src/Navigator/Context/NavigatorContext.cs @@ -14,7 +14,7 @@ public class NavigatorContext : INavigatorContext public INavigatorProvider Provider { get; } /// - /// + /// Profile of the bot running in this context. /// public Bot BotProfile { get; } From 9fc506ffbffe813b6fc8cc495aa9c86ac91d4b82 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 7 Dec 2021 20:37:35 +0100 Subject: [PATCH 199/304] feat: add more fields to TelegramUser --- .../Entities/TelegramUser.cs | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/src/Navigator.Providers.Telegram/Entities/TelegramUser.cs b/src/Navigator.Providers.Telegram/Entities/TelegramUser.cs index 42e3d37..378ef1f 100644 --- a/src/Navigator.Providers.Telegram/Entities/TelegramUser.cs +++ b/src/Navigator.Providers.Telegram/Entities/TelegramUser.cs @@ -16,4 +16,25 @@ public record TelegramUser(long ExternalIdentifier) : User(ExternalIdentifier.To /// /// public string? Username { get; init; } + + /// + /// First name of the user. + /// + public string FirstName { get; init; } = default!; + + /// + /// Last name of the user. + /// + /// Optional. + /// + /// + public string? LastName { get; init; } + + /// + /// Language code of the user. + /// + /// Optional. + /// + /// + public string? LanguageCode { get; init; } } \ No newline at end of file From 2a6bdcca2972765fa609c5fb0004c901e27b1e7f Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 7 Dec 2021 20:37:53 +0100 Subject: [PATCH 200/304] feat: add more fields to TelegramBot --- .../Entities/TelegramBot.cs | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/src/Navigator.Providers.Telegram/Entities/TelegramBot.cs b/src/Navigator.Providers.Telegram/Entities/TelegramBot.cs index b01b916..eafc63f 100644 --- a/src/Navigator.Providers.Telegram/Entities/TelegramBot.cs +++ b/src/Navigator.Providers.Telegram/Entities/TelegramBot.cs @@ -1,3 +1,4 @@ +using Navigator.Context; using Navigator.Entities; namespace Navigator.Providers.Telegram.Entities; @@ -13,4 +14,42 @@ public record TelegramBot(long ExternalIdentifier) : Bot(ExternalIdentifier.ToSt /// Username of the bot. /// public string Username { get; init; } + + /// + /// First name of the bot. + /// + public string FirstName { get; init; } = default!; + + /// + /// Last name of the bot. + /// + /// Optional. + /// + /// + public string? LastName { get; init; } + + /// + /// Whether the bot can join groups or not. + /// + /// Optional. Only available on + /// + /// + public bool? CanJoinGroups { get; set; } + + /// + /// Whether the bot can read all group messages or not. + /// + /// Optional. Only available on + /// + /// + public bool? CanReadAllGroupMessages { get; set; } + + /// + /// Whether the bot supports inline queries or not. + /// + /// Optional. Only available on + /// + /// + public bool? SupportsInlineQueries { get; set; } + } \ No newline at end of file From b2bb37423cc4ea97ce670b715836f68b761bf94c Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 7 Dec 2021 20:40:35 +0100 Subject: [PATCH 201/304] feat: improve GetProfile to use new parameters in TelegramBot --- .../NavigatorTelegramClient.cs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/src/Navigator.Providers.Telegram/NavigatorTelegramClient.cs b/src/Navigator.Providers.Telegram/NavigatorTelegramClient.cs index cafbb38..bc815e3 100644 --- a/src/Navigator.Providers.Telegram/NavigatorTelegramClient.cs +++ b/src/Navigator.Providers.Telegram/NavigatorTelegramClient.cs @@ -10,18 +10,28 @@ namespace Navigator.Providers.Telegram { public class NavigatorTelegramClient : TelegramBotClient, INavigatorClient { + /// + /// Builds a . + /// + /// public NavigatorTelegramClient(INavigatorOptions options) : base(options.GetTelegramToken() ?? throw new ArgumentNullException()) { } + /// public async Task GetProfile(CancellationToken cancellationToken = default) { var bot = await this.GetMeAsync(cancellationToken); return new TelegramBot(bot.Id) { - Username = bot.Username! + Username = bot.Username!, + FirstName = bot.FirstName, + LastName = bot.LastName, + CanJoinGroups = bot.CanJoinGroups, + CanReadAllGroupMessages = bot.CanReadAllGroupMessages, + SupportsInlineQueries = bot.SupportsInlineQueries }; } } From 7b735016805bfd5f1f2b0f12f0ff84be1591c0d3 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 7 Dec 2021 21:23:13 +0100 Subject: [PATCH 202/304] fix: correct Conversation implementation --- .../Entities/Conversation.cs | 6 +++--- .../Extensions/TelegramUpdateExtensions.cs | 19 ++++++++++--------- src/Navigator/Entities/Conversation.cs | 6 +++--- 3 files changed, 16 insertions(+), 15 deletions(-) diff --git a/src/Navigator.Providers.Telegram/Entities/Conversation.cs b/src/Navigator.Providers.Telegram/Entities/Conversation.cs index d83019a..cb56f6a 100644 --- a/src/Navigator.Providers.Telegram/Entities/Conversation.cs +++ b/src/Navigator.Providers.Telegram/Entities/Conversation.cs @@ -2,16 +2,16 @@ namespace Navigator.Providers.Telegram.Entities { - public record TelegramConversation : Conversation + public record TelegramConversation(TelegramUser User, TelegramChat Chat) : Conversation(User, Chat) { /// /// Telegram user. /// - public new TelegramUser User { get; init; } + public new TelegramUser User { get; init; } = User; /// /// Telegram chat. /// - public new TelegramChat Chat { get; init; } + public new TelegramChat Chat { get; init; } = Chat; } } \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/Extensions/TelegramUpdateExtensions.cs b/src/Navigator.Providers.Telegram/Extensions/TelegramUpdateExtensions.cs index 78a8ea5..ff0b221 100644 --- a/src/Navigator.Providers.Telegram/Extensions/TelegramUpdateExtensions.cs +++ b/src/Navigator.Providers.Telegram/Extensions/TelegramUpdateExtensions.cs @@ -18,7 +18,7 @@ internal static class TelegramUpdateExtensions if (command?.Contains('@') == false) return command; - if (botName is not null && !command?.Contains(botName) == false) return default; + if (botName is not null && !command?.Contains(botName) == true) return default; command = command?[..command.IndexOf('@')]; @@ -72,17 +72,18 @@ public static TelegramConversation GetConversation(this Update update) throw new Exception("TODO NAvigator exception no conversation could be built."); } - return new TelegramConversation - { - User = new TelegramUser(user.Id) + return new TelegramConversation( + new TelegramUser(user.Id) { - Username = user.Username - }, - Chat = new TelegramChat(chat.Id) + Username = user.Username, + FirstName = user.FirstName, + LastName = user.LastName, + LanguageCode = user.LanguageCode + }, + new TelegramChat(chat.Id) { Title = chat.Title - } - }; + }); } } } \ No newline at end of file diff --git a/src/Navigator/Entities/Conversation.cs b/src/Navigator/Entities/Conversation.cs index edd109f..70a96f0 100644 --- a/src/Navigator/Entities/Conversation.cs +++ b/src/Navigator/Entities/Conversation.cs @@ -3,15 +3,15 @@ namespace Navigator.Entities; /// /// Represents an interaction between a user and chat. /// -public abstract record Conversation +public abstract record Conversation(User User, Chat Chat) { /// /// User /// - public User User { get; init; } + public User User { get; init; } = User; /// /// Chat /// - public Chat Chat { get; init; } + public Chat Chat { get; init; } = Chat; } \ No newline at end of file From eee5e822161657545c305e832a5152f5228bc7ea Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 7 Dec 2021 21:48:09 +0100 Subject: [PATCH 203/304] feat: change entities from record to class --- .../Entities/Conversation.cs | 17 -------------- .../Entities/TelegramBot.cs | 12 ++++++---- .../Entities/TelegramChat.cs | 9 ++++++-- .../Entities/TelegramConversation.cs | 23 +++++++++++++++++++ .../Entities/TelegramUser.cs | 11 ++++++--- src/Navigator/Entities/Bot.cs | 22 ++++++++++++++---- src/Navigator/Entities/Chat.cs | 2 +- src/Navigator/Entities/Conversation.cs | 12 +++++++--- src/Navigator/Entities/User.cs | 2 +- 9 files changed, 74 insertions(+), 36 deletions(-) delete mode 100644 src/Navigator.Providers.Telegram/Entities/Conversation.cs create mode 100644 src/Navigator.Providers.Telegram/Entities/TelegramConversation.cs diff --git a/src/Navigator.Providers.Telegram/Entities/Conversation.cs b/src/Navigator.Providers.Telegram/Entities/Conversation.cs deleted file mode 100644 index cb56f6a..0000000 --- a/src/Navigator.Providers.Telegram/Entities/Conversation.cs +++ /dev/null @@ -1,17 +0,0 @@ -using Navigator.Entities; - -namespace Navigator.Providers.Telegram.Entities -{ - public record TelegramConversation(TelegramUser User, TelegramChat Chat) : Conversation(User, Chat) - { - /// - /// Telegram user. - /// - public new TelegramUser User { get; init; } = User; - - /// - /// Telegram chat. - /// - public new TelegramChat Chat { get; init; } = Chat; - } -} \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/Entities/TelegramBot.cs b/src/Navigator.Providers.Telegram/Entities/TelegramBot.cs index eafc63f..495cd3f 100644 --- a/src/Navigator.Providers.Telegram/Entities/TelegramBot.cs +++ b/src/Navigator.Providers.Telegram/Entities/TelegramBot.cs @@ -3,12 +3,17 @@ namespace Navigator.Providers.Telegram.Entities; -public record TelegramBot(long ExternalIdentifier) : Bot(ExternalIdentifier.ToString()) +public class TelegramBot : Bot { + public TelegramBot(long externalIdentifier) : base(externalIdentifier.ToString()) + { + ExternalIdentifier = externalIdentifier; + } + /// /// Telegram identifier for the bot. /// - public long ExternalIdentifier { get; init; } = ExternalIdentifier; + public long ExternalIdentifier { get; init; } /// /// Username of the bot. @@ -18,7 +23,7 @@ public record TelegramBot(long ExternalIdentifier) : Bot(ExternalIdentifier.ToSt /// /// First name of the bot. /// - public string FirstName { get; init; } = default!; + public string FirstName { get; init; } /// /// Last name of the bot. @@ -51,5 +56,4 @@ public record TelegramBot(long ExternalIdentifier) : Bot(ExternalIdentifier.ToSt /// /// public bool? SupportsInlineQueries { get; set; } - } \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/Entities/TelegramChat.cs b/src/Navigator.Providers.Telegram/Entities/TelegramChat.cs index eac83ac..3102064 100644 --- a/src/Navigator.Providers.Telegram/Entities/TelegramChat.cs +++ b/src/Navigator.Providers.Telegram/Entities/TelegramChat.cs @@ -3,12 +3,17 @@ namespace Navigator.Providers.Telegram.Entities; -public record TelegramChat(long ExternalIdentifier) : Chat(ExternalIdentifier.ToString()) +public class TelegramChat : Chat { + public TelegramChat(long externalIdentifier) : base(externalIdentifier.ToString()) + { + ExternalIdentifier = externalIdentifier; + } + /// /// Telegram identifier for the user. /// - public long ExternalIdentifier { get; init; } = ExternalIdentifier; + public long ExternalIdentifier { get; init; } /// /// Title of the chat, if any. diff --git a/src/Navigator.Providers.Telegram/Entities/TelegramConversation.cs b/src/Navigator.Providers.Telegram/Entities/TelegramConversation.cs new file mode 100644 index 0000000..a770024 --- /dev/null +++ b/src/Navigator.Providers.Telegram/Entities/TelegramConversation.cs @@ -0,0 +1,23 @@ +using Navigator.Entities; + +namespace Navigator.Providers.Telegram.Entities +{ + public class TelegramConversation : Conversation + { + public TelegramConversation(TelegramUser user, TelegramChat chat) : base(user, chat) + { + User = user; + Chat = chat; + } + + /// + /// Telegram user. + /// + public new TelegramUser User { get; init; } + + /// + /// Telegram chat. + /// + public new TelegramChat Chat { get; init; } + } +} \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/Entities/TelegramUser.cs b/src/Navigator.Providers.Telegram/Entities/TelegramUser.cs index 378ef1f..1bca159 100644 --- a/src/Navigator.Providers.Telegram/Entities/TelegramUser.cs +++ b/src/Navigator.Providers.Telegram/Entities/TelegramUser.cs @@ -2,12 +2,17 @@ namespace Navigator.Providers.Telegram.Entities; -public record TelegramUser(long ExternalIdentifier) : User(ExternalIdentifier.ToString()) +public class TelegramUser : User { + public TelegramUser(long externalIdentifier) : base(externalIdentifier.ToString()) + { + ExternalIdentifier = externalIdentifier; + } + /// /// Telegram identifier for the user. /// - public long ExternalIdentifier { get; init; } = ExternalIdentifier; + public long ExternalIdentifier { get; init; } /// /// Username of the user, if any. @@ -20,7 +25,7 @@ public record TelegramUser(long ExternalIdentifier) : User(ExternalIdentifier.To /// /// First name of the user. /// - public string FirstName { get; init; } = default!; + public string FirstName { get; init; } /// /// Last name of the user. diff --git a/src/Navigator/Entities/Bot.cs b/src/Navigator/Entities/Bot.cs index 681be41..b58b958 100644 --- a/src/Navigator/Entities/Bot.cs +++ b/src/Navigator/Entities/Bot.cs @@ -1,11 +1,23 @@ using System; +using System.Linq; +using System.Security.Cryptography; +using System.Text; -namespace Navigator.Entities +namespace Navigator.Entities; + +public abstract class Bot { - public abstract record Bot : User + + protected Bot(string input) { - protected Bot(string input) : base(input) - { - } + Id = new Guid(SHA256.HashData(Encoding.UTF8.GetBytes(input)).Take(16).ToArray()); } + + /// + /// Id of the bot. + /// + /// Generally a deterministic Guid based on some kind of input. + /// + /// + public Guid Id { get; init; } } \ No newline at end of file diff --git a/src/Navigator/Entities/Chat.cs b/src/Navigator/Entities/Chat.cs index 090ad9c..79d1e39 100644 --- a/src/Navigator/Entities/Chat.cs +++ b/src/Navigator/Entities/Chat.cs @@ -8,7 +8,7 @@ namespace Navigator.Entities; /// /// Represents a chat. /// -public abstract record Chat +public abstract class Chat { protected Chat(string input) { diff --git a/src/Navigator/Entities/Conversation.cs b/src/Navigator/Entities/Conversation.cs index 70a96f0..a2bbf94 100644 --- a/src/Navigator/Entities/Conversation.cs +++ b/src/Navigator/Entities/Conversation.cs @@ -3,15 +3,21 @@ namespace Navigator.Entities; /// /// Represents an interaction between a user and chat. /// -public abstract record Conversation(User User, Chat Chat) +public abstract class Conversation { + protected Conversation(User user, Chat chat) + { + User = user; + Chat = chat; + } + /// /// User /// - public User User { get; init; } = User; + public User User { get; init; } /// /// Chat /// - public Chat Chat { get; init; } = Chat; + public Chat Chat { get; init; } } \ No newline at end of file diff --git a/src/Navigator/Entities/User.cs b/src/Navigator/Entities/User.cs index 94cefc4..9f58746 100644 --- a/src/Navigator/Entities/User.cs +++ b/src/Navigator/Entities/User.cs @@ -8,7 +8,7 @@ namespace Navigator.Entities; /// /// Represents a user. /// -public abstract record User +public abstract class User { protected User(string input) { From 53be1b8e8deea90a405826ea977559836c56a19b Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Fri, 10 Dec 2021 15:10:58 +0100 Subject: [PATCH 204/304] feat: moved OriginalEventContextExtension to Bundled --- .../OriginalEvent}/NavigatorContextExtensions.cs | 7 +++++-- .../OriginalEvent}/OriginalEventContextExtension.cs | 4 ++-- 2 files changed, 7 insertions(+), 4 deletions(-) rename src/Navigator/Context/Extensions/{ => Bundled/OriginalEvent}/NavigatorContextExtensions.cs (88%) rename src/Navigator/Context/Extensions/{ => Bundled/OriginalEvent}/OriginalEventContextExtension.cs (76%) diff --git a/src/Navigator/Context/Extensions/NavigatorContextExtensions.cs b/src/Navigator/Context/Extensions/Bundled/OriginalEvent/NavigatorContextExtensions.cs similarity index 88% rename from src/Navigator/Context/Extensions/NavigatorContextExtensions.cs rename to src/Navigator/Context/Extensions/Bundled/OriginalEvent/NavigatorContextExtensions.cs index a07738d..4dab057 100644 --- a/src/Navigator/Context/Extensions/NavigatorContextExtensions.cs +++ b/src/Navigator/Context/Extensions/Bundled/OriginalEvent/NavigatorContextExtensions.cs @@ -1,10 +1,11 @@ -using System; using System.Collections.Generic; -namespace Navigator.Context.Extensions +namespace Navigator.Context.Extensions.Bundled.OriginalEvent { public static class NavigatorContextExtensions { + #region OriginalEvent + public static TEvent GetOriginalEvent(this INavigatorContext navigatorContext) where TEvent : class { var update = navigatorContext.GetOriginalEventOrDefault(); @@ -23,5 +24,7 @@ public static TEvent GetOriginalEvent(this INavigatorContext navigatorCo return default; } + + #endregion } } \ No newline at end of file diff --git a/src/Navigator/Context/Extensions/OriginalEventContextExtension.cs b/src/Navigator/Context/Extensions/Bundled/OriginalEvent/OriginalEventContextExtension.cs similarity index 76% rename from src/Navigator/Context/Extensions/OriginalEventContextExtension.cs rename to src/Navigator/Context/Extensions/Bundled/OriginalEvent/OriginalEventContextExtension.cs index 38aca08..895ec40 100644 --- a/src/Navigator/Context/Extensions/OriginalEventContextExtension.cs +++ b/src/Navigator/Context/Extensions/Bundled/OriginalEvent/OriginalEventContextExtension.cs @@ -1,8 +1,8 @@ using System.Threading.Tasks; -namespace Navigator.Context.Extensions +namespace Navigator.Context.Extensions.Bundled.OriginalEvent { - public class OriginalEventContextExtension : INavigatorContextExtension + internal class OriginalEventContextExtension : INavigatorContextExtension { public const string OriginalEventKey = "_navigator.extensions.original_event"; From f65af0180070f3efe8407f1744f1c69ec835946b Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Fri, 10 Dec 2021 15:12:06 +0100 Subject: [PATCH 205/304] feat: update references to OriginalEvent to new namespace --- .../Actions/Messages/MessageAction.cs | 2 ++ .../Actions/Updates/CallbackQueryAction.cs | 2 ++ .../Actions/Updates/ChosenInlineResultAction.cs | 2 ++ .../Actions/Updates/EditedMessageAction.cs | 2 ++ .../Actions/Updates/InlineQueryAction.cs | 2 ++ .../Actions/Updates/PollAction.cs | 2 ++ .../NavigatorContextExtensions.cs | 2 ++ src/Navigator/Navigator.csproj | 4 ++++ src/Navigator/ServiceCollectionExtensions.cs | 2 ++ 9 files changed, 20 insertions(+) diff --git a/src/Navigator.Providers.Telegram/Actions/Messages/MessageAction.cs b/src/Navigator.Providers.Telegram/Actions/Messages/MessageAction.cs index 7e67aa4..1f08805 100644 --- a/src/Navigator.Providers.Telegram/Actions/Messages/MessageAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Messages/MessageAction.cs @@ -4,6 +4,8 @@ using Navigator.Actions.Attributes; using Navigator.Context; using Navigator.Context.Extensions; +using Navigator.Context.Extensions.Bundled; +using Navigator.Context.Extensions.Bundled.OriginalEvent; using Telegram.Bot.Types; namespace Navigator.Providers.Telegram.Actions.Messages diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/CallbackQueryAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/CallbackQueryAction.cs index 49f7d19..cc17a45 100644 --- a/src/Navigator.Providers.Telegram/Actions/Updates/CallbackQueryAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/CallbackQueryAction.cs @@ -2,6 +2,8 @@ using Navigator.Actions.Attributes; using Navigator.Context; using Navigator.Context.Extensions; +using Navigator.Context.Extensions.Bundled; +using Navigator.Context.Extensions.Bundled.OriginalEvent; using Telegram.Bot.Types; namespace Navigator.Providers.Telegram.Actions.Updates diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/ChosenInlineResultAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/ChosenInlineResultAction.cs index c71bbf3..c3aa02c 100644 --- a/src/Navigator.Providers.Telegram/Actions/Updates/ChosenInlineResultAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/ChosenInlineResultAction.cs @@ -2,6 +2,8 @@ using Navigator.Actions.Attributes; using Navigator.Context; using Navigator.Context.Extensions; +using Navigator.Context.Extensions.Bundled; +using Navigator.Context.Extensions.Bundled.OriginalEvent; using Telegram.Bot.Types; namespace Navigator.Providers.Telegram.Actions.Updates diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/EditedMessageAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/EditedMessageAction.cs index ea7c9b0..ded6dfe 100644 --- a/src/Navigator.Providers.Telegram/Actions/Updates/EditedMessageAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/EditedMessageAction.cs @@ -2,6 +2,8 @@ using Navigator.Actions.Attributes; using Navigator.Context; using Navigator.Context.Extensions; +using Navigator.Context.Extensions.Bundled; +using Navigator.Context.Extensions.Bundled.OriginalEvent; using Telegram.Bot.Types; namespace Navigator.Providers.Telegram.Actions.Updates diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/InlineQueryAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/InlineQueryAction.cs index 96cea79..be6cc06 100644 --- a/src/Navigator.Providers.Telegram/Actions/Updates/InlineQueryAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/InlineQueryAction.cs @@ -2,6 +2,8 @@ using Navigator.Actions.Attributes; using Navigator.Context; using Navigator.Context.Extensions; +using Navigator.Context.Extensions.Bundled; +using Navigator.Context.Extensions.Bundled.OriginalEvent; using Telegram.Bot.Types; namespace Navigator.Providers.Telegram.Actions.Updates diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/PollAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/PollAction.cs index ce78520..7cebfe0 100644 --- a/src/Navigator.Providers.Telegram/Actions/Updates/PollAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/PollAction.cs @@ -2,6 +2,8 @@ using Navigator.Actions.Attributes; using Navigator.Context; using Navigator.Context.Extensions; +using Navigator.Context.Extensions.Bundled; +using Navigator.Context.Extensions.Bundled.OriginalEvent; using Telegram.Bot.Types; namespace Navigator.Providers.Telegram.Actions.Updates diff --git a/src/Navigator.Providers.Telegram/NavigatorContextExtensions.cs b/src/Navigator.Providers.Telegram/NavigatorContextExtensions.cs index bb68947..9bbe198 100644 --- a/src/Navigator.Providers.Telegram/NavigatorContextExtensions.cs +++ b/src/Navigator.Providers.Telegram/NavigatorContextExtensions.cs @@ -1,6 +1,8 @@ using System; using Navigator.Context; using Navigator.Context.Extensions; +using Navigator.Context.Extensions.Bundled; +using Navigator.Context.Extensions.Bundled.OriginalEvent; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; diff --git a/src/Navigator/Navigator.csproj b/src/Navigator/Navigator.csproj index 99a0901..3fa0be4 100644 --- a/src/Navigator/Navigator.csproj +++ b/src/Navigator/Navigator.csproj @@ -28,4 +28,8 @@ + + + + diff --git a/src/Navigator/ServiceCollectionExtensions.cs b/src/Navigator/ServiceCollectionExtensions.cs index ed6d8bc..9cfba06 100644 --- a/src/Navigator/ServiceCollectionExtensions.cs +++ b/src/Navigator/ServiceCollectionExtensions.cs @@ -6,6 +6,8 @@ using Navigator.Configuration; using Navigator.Context; using Navigator.Context.Extensions; +using Navigator.Context.Extensions.Bundled; +using Navigator.Context.Extensions.Bundled.OriginalEvent; using Scrutor; namespace Navigator From 0a95639bde12387be6eb900282f3b96184b5b3ef Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Fri, 10 Dec 2021 15:13:22 +0100 Subject: [PATCH 206/304] feat: add INavigatorContextBuilderConversationSource This interface defines a source to use while building a NavigatorContext for filling Conversation parameters --- ...avigatorContextBuilderConversationSource.cs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 src/Navigator/Context/INavigatorContextBuilderConversationSource.cs diff --git a/src/Navigator/Context/INavigatorContextBuilderConversationSource.cs b/src/Navigator/Context/INavigatorContextBuilderConversationSource.cs new file mode 100644 index 0000000..e272b68 --- /dev/null +++ b/src/Navigator/Context/INavigatorContextBuilderConversationSource.cs @@ -0,0 +1,18 @@ +using System.Threading.Tasks; +using Navigator.Entities; + +namespace Navigator.Context; + +/// +/// Defines a source for to use +/// while building a . +/// +public interface INavigatorContextBuilderConversationSource +{ + /// + /// Returns a in accordance to the original event that spawned this context. + /// + /// + /// + Task GetConversationAsync(object? originalEvent); +} \ No newline at end of file From 9c1e400c36d0bfddc031aa2154fe42682845a194 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Fri, 10 Dec 2021 15:15:54 +0100 Subject: [PATCH 207/304] feat: add first implementation of conversation source for context builder --- src/Navigator/Context/NavigatorContextBuilder.cs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/Navigator/Context/NavigatorContextBuilder.cs b/src/Navigator/Context/NavigatorContextBuilder.cs index 3b40b2f..7cdc1c9 100644 --- a/src/Navigator/Context/NavigatorContextBuilder.cs +++ b/src/Navigator/Context/NavigatorContextBuilder.cs @@ -14,13 +14,15 @@ public class NavigatorContextBuilder : INavigatorContextBuilder private readonly IEnumerable _navigatorProviders; private readonly IEnumerable _navigatorContextExtensions; private readonly INavigatorContextBuilderOptions _options; + private readonly INavigatorContextBuilderConversationSource _conversationSource; - public NavigatorContextBuilder(ILogger logger, IEnumerable navigatorClients, IEnumerable navigatorContextExtensions) + public NavigatorContextBuilder(ILogger logger, IEnumerable navigatorClients, IEnumerable navigatorContextExtensions, INavigatorContextBuilderConversationSource conversationSource) { _logger = logger; _navigatorProviders = navigatorClients; _navigatorContextExtensions = navigatorContextExtensions; - + _conversationSource = conversationSource; + _options = new NavigatorContextBuilderOptions(); } @@ -38,7 +40,8 @@ public async Task Build(Action Date: Fri, 10 Dec 2021 15:23:48 +0100 Subject: [PATCH 208/304] fix: correct call to GetOriginalEventOrDefault --- src/Navigator/Context/NavigatorContextBuilder.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Navigator/Context/NavigatorContextBuilder.cs b/src/Navigator/Context/NavigatorContextBuilder.cs index 7cdc1c9..f9a9379 100644 --- a/src/Navigator/Context/NavigatorContextBuilder.cs +++ b/src/Navigator/Context/NavigatorContextBuilder.cs @@ -41,7 +41,7 @@ public async Task Build(Action Date: Fri, 10 Dec 2021 15:24:30 +0100 Subject: [PATCH 209/304] feat: add implementation for conversation source for telegram provider TelegramNavigatorContextBuilderConversationSource --- ...mNavigatorContextBuilderConversationSource.cs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 src/Navigator.Providers.Telegram/TelegramNavigatorContextBuilderConversationSource.cs diff --git a/src/Navigator.Providers.Telegram/TelegramNavigatorContextBuilderConversationSource.cs b/src/Navigator.Providers.Telegram/TelegramNavigatorContextBuilderConversationSource.cs new file mode 100644 index 0000000..55898c3 --- /dev/null +++ b/src/Navigator.Providers.Telegram/TelegramNavigatorContextBuilderConversationSource.cs @@ -0,0 +1,16 @@ +using System; +using System.Threading.Tasks; +using Navigator.Context; +using Navigator.Entities; +using Navigator.Providers.Telegram.Extensions; +using Telegram.Bot.Types; + +namespace Navigator.Providers.Telegram; + +internal class TelegramNavigatorContextBuilderConversationSource : INavigatorContextBuilderConversationSource +{ + public async Task GetConversationAsync(object? originalEvent) + { + return await Task.FromResult((originalEvent as Update ?? throw new InvalidOperationException()).GetConversation()); + } +} \ No newline at end of file From b3b4eff396988ce219f769fca44b81b3445453c6 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Fri, 10 Dec 2021 15:25:16 +0100 Subject: [PATCH 210/304] feat: update provider DI Add Telegram implementation for conversation source --- .../NavigatorProviderConfigurationExtensions.cs | 3 +++ src/Navigator.Providers.Telegram/TelegramMiddleware.cs | 1 - src/Navigator/Navigator.csproj | 4 ---- 3 files changed, 3 insertions(+), 5 deletions(-) diff --git a/src/Navigator.Providers.Telegram/NavigatorProviderConfigurationExtensions.cs b/src/Navigator.Providers.Telegram/NavigatorProviderConfigurationExtensions.cs index cdf19bf..50a50fa 100644 --- a/src/Navigator.Providers.Telegram/NavigatorProviderConfigurationExtensions.cs +++ b/src/Navigator.Providers.Telegram/NavigatorProviderConfigurationExtensions.cs @@ -2,6 +2,7 @@ using Microsoft.Extensions.DependencyInjection; using Navigator.Configuration; using Navigator.Configuration.Provider; +using Navigator.Context; using Navigator.Providers.Telegram.Hosted; namespace Navigator.Providers.Telegram @@ -22,6 +23,8 @@ public static NavigatorConfiguration Telegram(this NavigatorProviderConfiguratio services.AddSingleton(sp => sp.GetRequiredService()); services.AddScoped(); + + services.AddScoped(); services.AddScoped(); diff --git a/src/Navigator.Providers.Telegram/TelegramMiddleware.cs b/src/Navigator.Providers.Telegram/TelegramMiddleware.cs index 74ce614..e87efa3 100644 --- a/src/Navigator.Providers.Telegram/TelegramMiddleware.cs +++ b/src/Navigator.Providers.Telegram/TelegramMiddleware.cs @@ -40,7 +40,6 @@ await _navigatorContextFactory.Supply(builder => builder.SetProvider(); builder.SetActionType(actionType); builder.SetOriginalEvent(update); - builder.SetConversation(update.GetConversation()); }); await _actionLauncher.Launch(); diff --git a/src/Navigator/Navigator.csproj b/src/Navigator/Navigator.csproj index 3fa0be4..99a0901 100644 --- a/src/Navigator/Navigator.csproj +++ b/src/Navigator/Navigator.csproj @@ -28,8 +28,4 @@ - - - - From b5c92ad60cb621655f078f1ac7ad101d16f88b46 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Fri, 10 Dec 2021 15:34:42 +0100 Subject: [PATCH 211/304] feat: delete old extensions --- .../NavigatorContextBuilderOptionsExtensions.cs | 17 ----------------- 1 file changed, 17 deletions(-) diff --git a/src/Navigator/Context/NavigatorContextBuilderOptionsExtensions.cs b/src/Navigator/Context/NavigatorContextBuilderOptionsExtensions.cs index 97b9fb4..51b03c1 100644 --- a/src/Navigator/Context/NavigatorContextBuilderOptionsExtensions.cs +++ b/src/Navigator/Context/NavigatorContextBuilderOptionsExtensions.cs @@ -55,22 +55,5 @@ public static void SetOriginalEvent(this INavigatorContextBuilderOptions context } #endregion - - #region Conversation - - private const string ConversationKey = "_navigator.context.options.conversation"; - - public static void SetConversation(this INavigatorContextBuilderOptions contextBuilderOptions, Conversation conversation) - { - contextBuilderOptions.TryRegisterOption(ConversationKey, conversation); - - } - - public static Conversation? GetConversationOrDefault(this INavigatorContextBuilderOptions contextBuilderOptions) - { - return contextBuilderOptions.RetrieveOption(ConversationKey); - } - - #endregion } } \ No newline at end of file From 99329afb4354a7f34cc86303f0310c30ffb5a886 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Fri, 10 Dec 2021 16:26:28 +0100 Subject: [PATCH 212/304] feat: add Store entities for Navigator --- .../Entities/Chat.cs | 31 +++++++++++++++++++ .../Entities/Conversation.cs | 13 ++++++++ .../Entities/User.cs | 30 ++++++++++++++++++ 3 files changed, 74 insertions(+) create mode 100644 src/Navigator.Extensions.Store/Entities/Chat.cs create mode 100644 src/Navigator.Extensions.Store/Entities/Conversation.cs create mode 100644 src/Navigator.Extensions.Store/Entities/User.cs diff --git a/src/Navigator.Extensions.Store/Entities/Chat.cs b/src/Navigator.Extensions.Store/Entities/Chat.cs new file mode 100644 index 0000000..078409d --- /dev/null +++ b/src/Navigator.Extensions.Store/Entities/Chat.cs @@ -0,0 +1,31 @@ +using Navigator.Extensions.Store.Entities; + +public class Chat +{ + public Chat() + { + ProviderEntities = new List(); + Users = new List(); + } + + public Guid Id { get; set; } + + public IList ProviderEntities { get; set; } + + /// + /// Users related to the chat. + /// + public ICollection Users { get; set; } + + public ICollection Conversations { get; set; } + + /// + /// Date of first interaction for this chat. + /// + public DateTime FirstInteractionAt { get; set; } +} + +public interface INavigatorProviderChatEntity +{ + public Guid Id { get; set; } +} \ No newline at end of file diff --git a/src/Navigator.Extensions.Store/Entities/Conversation.cs b/src/Navigator.Extensions.Store/Entities/Conversation.cs new file mode 100644 index 0000000..1fe0eef --- /dev/null +++ b/src/Navigator.Extensions.Store/Entities/Conversation.cs @@ -0,0 +1,13 @@ +namespace Navigator.Extensions.Store.Entities; + +public class Conversation +{ + public Chat Chat { get; set; } + + public User User { get; set; } + + /// + /// Date of first interaction for this chat. + /// + public DateTime FirstInteractionAt { get; set; } +} \ No newline at end of file diff --git a/src/Navigator.Extensions.Store/Entities/User.cs b/src/Navigator.Extensions.Store/Entities/User.cs new file mode 100644 index 0000000..eeec838 --- /dev/null +++ b/src/Navigator.Extensions.Store/Entities/User.cs @@ -0,0 +1,30 @@ +namespace Navigator.Extensions.Store.Entities; + +public class User +{ + public User() + { + ProviderEntities = new List(); + Chats = new List(); + } + public Guid Id { get; set; } + + public IList ProviderEntities { get; set; } + + /// + /// Chats related to the user. + /// + public IList Chats { get; set; } + + public ICollection Conversations { get; set; } + + /// + /// Date of first interaction for this chat. + /// + public DateTime FirstInteractionAt { get; set; } +} + +public interface INavigatorProviderUserEntity +{ + public Guid Id { get; set; } +} \ No newline at end of file From 7b260039c8bcf0f4d397fd4f20a634d177150afe Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Fri, 10 Dec 2021 17:03:10 +0100 Subject: [PATCH 213/304] feat: update main entities across all Navigator --- src/Navigator.Extensions.Store/Entities/Chat.cs | 2 +- src/Navigator.Extensions.Store/Entities/Conversation.cs | 2 +- src/Navigator.Extensions.Store/Entities/User.cs | 2 +- src/Navigator.Providers.Telegram/Entities/TelegramBot.cs | 2 +- src/Navigator.Providers.Telegram/Entities/TelegramChat.cs | 2 +- src/Navigator.Providers.Telegram/Entities/TelegramUser.cs | 2 +- src/Navigator/Entities/Bot.cs | 2 +- src/Navigator/Entities/Chat.cs | 4 ++++ src/Navigator/Entities/Conversation.cs | 4 ++++ src/Navigator/Entities/User.cs | 4 ++++ 10 files changed, 19 insertions(+), 7 deletions(-) diff --git a/src/Navigator.Extensions.Store/Entities/Chat.cs b/src/Navigator.Extensions.Store/Entities/Chat.cs index 078409d..85c1c69 100644 --- a/src/Navigator.Extensions.Store/Entities/Chat.cs +++ b/src/Navigator.Extensions.Store/Entities/Chat.cs @@ -1,6 +1,6 @@ using Navigator.Extensions.Store.Entities; -public class Chat +public class Chat : Navigator.Entities.Chat { public Chat() { diff --git a/src/Navigator.Extensions.Store/Entities/Conversation.cs b/src/Navigator.Extensions.Store/Entities/Conversation.cs index 1fe0eef..d73e1d7 100644 --- a/src/Navigator.Extensions.Store/Entities/Conversation.cs +++ b/src/Navigator.Extensions.Store/Entities/Conversation.cs @@ -1,6 +1,6 @@ namespace Navigator.Extensions.Store.Entities; -public class Conversation +public class Conversation : Navigator.Entities.Conversation { public Chat Chat { get; set; } diff --git a/src/Navigator.Extensions.Store/Entities/User.cs b/src/Navigator.Extensions.Store/Entities/User.cs index eeec838..9bef4a6 100644 --- a/src/Navigator.Extensions.Store/Entities/User.cs +++ b/src/Navigator.Extensions.Store/Entities/User.cs @@ -1,6 +1,6 @@ namespace Navigator.Extensions.Store.Entities; -public class User +public class User : Navigator.Entities.User { public User() { diff --git a/src/Navigator.Providers.Telegram/Entities/TelegramBot.cs b/src/Navigator.Providers.Telegram/Entities/TelegramBot.cs index 495cd3f..ac59a62 100644 --- a/src/Navigator.Providers.Telegram/Entities/TelegramBot.cs +++ b/src/Navigator.Providers.Telegram/Entities/TelegramBot.cs @@ -5,7 +5,7 @@ namespace Navigator.Providers.Telegram.Entities; public class TelegramBot : Bot { - public TelegramBot(long externalIdentifier) : base(externalIdentifier.ToString()) + public TelegramBot(long externalIdentifier) : base($"{nameof(TelegramBot)}.{externalIdentifier.ToString()}") { ExternalIdentifier = externalIdentifier; } diff --git a/src/Navigator.Providers.Telegram/Entities/TelegramChat.cs b/src/Navigator.Providers.Telegram/Entities/TelegramChat.cs index 3102064..210d7dd 100644 --- a/src/Navigator.Providers.Telegram/Entities/TelegramChat.cs +++ b/src/Navigator.Providers.Telegram/Entities/TelegramChat.cs @@ -5,7 +5,7 @@ namespace Navigator.Providers.Telegram.Entities; public class TelegramChat : Chat { - public TelegramChat(long externalIdentifier) : base(externalIdentifier.ToString()) + public TelegramChat(long externalIdentifier) : base($"{nameof(TelegramChat)}.{externalIdentifier.ToString()}") { ExternalIdentifier = externalIdentifier; } diff --git a/src/Navigator.Providers.Telegram/Entities/TelegramUser.cs b/src/Navigator.Providers.Telegram/Entities/TelegramUser.cs index 1bca159..85b774d 100644 --- a/src/Navigator.Providers.Telegram/Entities/TelegramUser.cs +++ b/src/Navigator.Providers.Telegram/Entities/TelegramUser.cs @@ -4,7 +4,7 @@ namespace Navigator.Providers.Telegram.Entities; public class TelegramUser : User { - public TelegramUser(long externalIdentifier) : base(externalIdentifier.ToString()) + public TelegramUser(long externalIdentifier) : base($"{nameof(TelegramUser)}.{externalIdentifier.ToString()}") { ExternalIdentifier = externalIdentifier; } diff --git a/src/Navigator/Entities/Bot.cs b/src/Navigator/Entities/Bot.cs index b58b958..3184ca2 100644 --- a/src/Navigator/Entities/Bot.cs +++ b/src/Navigator/Entities/Bot.cs @@ -5,7 +5,7 @@ namespace Navigator.Entities; -public abstract class Bot +public abstract class Bot : User { protected Bot(string input) diff --git a/src/Navigator/Entities/Chat.cs b/src/Navigator/Entities/Chat.cs index 79d1e39..f4bb710 100644 --- a/src/Navigator/Entities/Chat.cs +++ b/src/Navigator/Entities/Chat.cs @@ -10,6 +10,10 @@ namespace Navigator.Entities; /// public abstract class Chat { + protected Chat() + { + } + protected Chat(string input) { Id = new Guid(SHA256.HashData(Encoding.UTF8.GetBytes(input)).Take(16).ToArray()); diff --git a/src/Navigator/Entities/Conversation.cs b/src/Navigator/Entities/Conversation.cs index a2bbf94..fc41df2 100644 --- a/src/Navigator/Entities/Conversation.cs +++ b/src/Navigator/Entities/Conversation.cs @@ -5,6 +5,10 @@ namespace Navigator.Entities; /// public abstract class Conversation { + protected Conversation() + { + } + protected Conversation(User user, Chat chat) { User = user; diff --git a/src/Navigator/Entities/User.cs b/src/Navigator/Entities/User.cs index 9f58746..93373ab 100644 --- a/src/Navigator/Entities/User.cs +++ b/src/Navigator/Entities/User.cs @@ -10,6 +10,10 @@ namespace Navigator.Entities; /// public abstract class User { + protected User() + { + } + protected User(string input) { Id = new Guid(SHA256.HashData(Encoding.UTF8.GetBytes(input)).Take(16).ToArray()); From 544f146e0a61a3f25206d67ecb053045e53c77c1 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Fri, 10 Dec 2021 17:04:46 +0100 Subject: [PATCH 214/304] feat: add ChatEntityTypeConfiguration --- .../ChatEntityTypeConfiguration.cs | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 src/Navigator.Extensions.Store/Configuration/ChatEntityTypeConfiguration.cs diff --git a/src/Navigator.Extensions.Store/Configuration/ChatEntityTypeConfiguration.cs b/src/Navigator.Extensions.Store/Configuration/ChatEntityTypeConfiguration.cs new file mode 100644 index 0000000..7f08fd1 --- /dev/null +++ b/src/Navigator.Extensions.Store/Configuration/ChatEntityTypeConfiguration.cs @@ -0,0 +1,27 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; +using Navigator.Extensions.Store.Entities; + +namespace Navigator.Extensions.Store.Configuration; + +public class ChatEntityTypeConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder builder) + { + builder.HasKey(e => e.Id); + + builder.HasMany(e => e.ProviderEntities) + .WithOne(); + + builder.HasMany(e => e.Users) + .WithMany(e => e.Chats) + .UsingEntity( + e => e.HasOne(e => e.User) + .WithMany(e => e.Conversations), + e=> e.HasOne(e => e.Chat) + .WithMany(e => e.Conversations)); + + builder.Property(e => e.FirstInteractionAt) + .IsRequired(); + } +} \ No newline at end of file From 8139454e8e3010b7c09f73b16c28f4b1234df799 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Fri, 10 Dec 2021 17:04:58 +0100 Subject: [PATCH 215/304] feat: add ConversationEntityTypeConfiguration --- .../ConversationEntityTypeConfiguration.cs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 src/Navigator.Extensions.Store/Configuration/ConversationEntityTypeConfiguration.cs diff --git a/src/Navigator.Extensions.Store/Configuration/ConversationEntityTypeConfiguration.cs b/src/Navigator.Extensions.Store/Configuration/ConversationEntityTypeConfiguration.cs new file mode 100644 index 0000000..245f1d1 --- /dev/null +++ b/src/Navigator.Extensions.Store/Configuration/ConversationEntityTypeConfiguration.cs @@ -0,0 +1,14 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; +using Navigator.Extensions.Store.Entities; + +namespace Navigator.Extensions.Store.Configuration; + +public class ConversationEntityTypeConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder builder) + { + builder.Property(e => e.FirstInteractionAt) + .IsRequired(); + } +} \ No newline at end of file From 10c6ea1796bc7604e9917437cb741766738011d5 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Fri, 10 Dec 2021 17:05:16 +0100 Subject: [PATCH 216/304] feat: add UserEntityTypeConfiguration --- .../UserEntityTypeConfiguration.cs | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 src/Navigator.Extensions.Store/Configuration/UserEntityTypeConfiguration.cs diff --git a/src/Navigator.Extensions.Store/Configuration/UserEntityTypeConfiguration.cs b/src/Navigator.Extensions.Store/Configuration/UserEntityTypeConfiguration.cs new file mode 100644 index 0000000..58b92b4 --- /dev/null +++ b/src/Navigator.Extensions.Store/Configuration/UserEntityTypeConfiguration.cs @@ -0,0 +1,27 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; +using Navigator.Extensions.Store.Entities; + +namespace Navigator.Extensions.Store.Configuration; + +public class UserEntityTypeConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder builder) + { + builder.HasKey(e => e.Id); + + builder.HasMany(e => e.ProviderEntities) + .WithOne(); + + builder.HasMany(e => e.Chats) + .WithMany(e => e.Users) + .UsingEntity( + e => e.HasOne(e => e.Chat) + .WithMany(e => e.Conversations), + e=> e.HasOne(e => e.User) + .WithMany(e => e.Conversations)); + + builder.Property(e => e.FirstInteractionAt) + .IsRequired(); + } +} \ No newline at end of file From cd52b5bb7260fb934cf139503060921a37183d51 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Fri, 10 Dec 2021 17:05:36 +0100 Subject: [PATCH 217/304] feat: add NavigatorProviderChatEntity and NavigatorProviderUserEntity --- .../Configuration/NavigatorProviderChatEntity.cs | 12 ++++++++++++ .../Configuration/NavigatorProviderUserEntity.cs | 13 +++++++++++++ 2 files changed, 25 insertions(+) create mode 100644 src/Navigator.Extensions.Store/Configuration/NavigatorProviderChatEntity.cs create mode 100644 src/Navigator.Extensions.Store/Configuration/NavigatorProviderUserEntity.cs diff --git a/src/Navigator.Extensions.Store/Configuration/NavigatorProviderChatEntity.cs b/src/Navigator.Extensions.Store/Configuration/NavigatorProviderChatEntity.cs new file mode 100644 index 0000000..6c301b3 --- /dev/null +++ b/src/Navigator.Extensions.Store/Configuration/NavigatorProviderChatEntity.cs @@ -0,0 +1,12 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace Navigator.Extensions.Store.Configuration; + +public class NavigatorProviderChatEntity : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder builder) + { + builder.HasKey(e => e.Id); + } +} \ No newline at end of file diff --git a/src/Navigator.Extensions.Store/Configuration/NavigatorProviderUserEntity.cs b/src/Navigator.Extensions.Store/Configuration/NavigatorProviderUserEntity.cs new file mode 100644 index 0000000..33a2368 --- /dev/null +++ b/src/Navigator.Extensions.Store/Configuration/NavigatorProviderUserEntity.cs @@ -0,0 +1,13 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; +using Navigator.Extensions.Store.Entities; + +namespace Navigator.Extensions.Store.Configuration; + +public class NavigatorProviderUserEntity : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder builder) + { + builder.HasKey(e => e.Id); + } +} \ No newline at end of file From 51a7fa5f9cab3244ef60be65e472cff2bd4acc66 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Fri, 10 Dec 2021 17:05:56 +0100 Subject: [PATCH 218/304] feat: update NavigatorDbContext --- .../Navigator.Extensions.Store.csproj | 4 ++++ .../NavigatorDbContext.cs | 13 ++++++++++--- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/src/Navigator.Extensions.Store/Navigator.Extensions.Store.csproj b/src/Navigator.Extensions.Store/Navigator.Extensions.Store.csproj index f1b9b36..aecea51 100644 --- a/src/Navigator.Extensions.Store/Navigator.Extensions.Store.csproj +++ b/src/Navigator.Extensions.Store/Navigator.Extensions.Store.csproj @@ -14,4 +14,8 @@ + + + + diff --git a/src/Navigator.Extensions.Store/NavigatorDbContext.cs b/src/Navigator.Extensions.Store/NavigatorDbContext.cs index bc9755f..0ad9f88 100644 --- a/src/Navigator.Extensions.Store/NavigatorDbContext.cs +++ b/src/Navigator.Extensions.Store/NavigatorDbContext.cs @@ -1,3 +1,7 @@ +using Microsoft.EntityFrameworkCore; +using Navigator.Extensions.Store.Configuration; +using Navigator.Extensions.Store.Entities; + namespace Navigator.Extensions.Store; public class NavigatorDbContext : NavigatorDbContext @@ -6,14 +10,16 @@ public NavigatorDbContext(DbContextOptions options) : base(options) { } } - + public class NavigatorDbContext : DbContext where TUser : User where TChat : Chat { public DbSet Users { get; set; } public DbSet Chats { get; set; } - public DbSet Conversations { get; set; } + + protected DbSet NavigatorProviderUserEntities { get; set; } + protected DbSet NavigatorProviderChatEntities { get; set; } protected NavigatorDbContext() { @@ -27,7 +33,8 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); + modelBuilder.ApplyConfiguration(new ChatEntityTypeConfiguration()); + modelBuilder.ApplyConfiguration(new UserEntityTypeConfiguration()); modelBuilder.ApplyConfiguration(new ConversationEntityTypeConfiguration()); - } } \ No newline at end of file From e2e47ede10b6b0e0939fb2536b6211a827f52e48 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sun, 12 Dec 2021 19:15:07 +0100 Subject: [PATCH 219/304] chore: delete old files and classes --- .../IBotManagementService.cs | 15 -- .../Model/BotCommands.cs | 15 -- .../Model/BotInfo.cs | 49 ------ .../Model/BotPic.cs | 20 --- ...or.Extensions.Shipyard.Abstractions.csproj | 30 ---- .../BotManagementService.cs | 108 ------------ .../Controllers/BotController.cs | 66 ------- .../Controllers/ConversationController.cs | 102 ----------- .../GenericControllerFeatureProvider.cs | 33 ---- .../ShipyardApiKeyAuthenticationHandler.cs | 47 ----- .../Navigator.Extensions.Shipyard.csproj | 40 ----- .../NavigatorOptionsCollectionExtensions.cs | 25 --- .../NavigatorServiceCollectionExtensions.cs | 47 ----- .../INavigatorContextExtensions.cs | 40 ----- ...sions.Store.Abstractions.Extensions.csproj | 30 ---- .../Entity/Chat.cs | 47 ----- .../Entity/Conversation.cs | 18 -- .../Entity/User.cs | 39 ---- .../IChatMapper.cs | 9 - .../IEntityManager.cs | 25 --- .../IUserMapper.cs | 9 - ...gator.Extensions.Store.Abstractions.csproj | 30 ---- src/Navigator.sln | 46 ----- src/Navigator/Provider.cs | 10 -- .../ConversationEntityTypeConfiguration.cs | 24 --- .../Context/NavigatorDbContext.cs | 38 ---- .../DefaultChatMapper.cs | 20 --- .../DefaultEntityManager.cs | 166 ------------------ .../DefaultUserMapper.cs | 19 -- .../NavigatorOptionsCollectionExtensions.cs | 73 -------- .../NavigatorServiceCollectionExtensions.cs | 91 ---------- .../Old.Navigator.Extensions.Store.csproj | 42 ----- .../Provider/DefaultChatContextProvider.cs | 59 ------- .../Provider/DefaultUserContextProvider.cs | 79 --------- .../Provider/UpdateDataContextProvider.cs | 62 ------- 35 files changed, 1573 deletions(-) delete mode 100644 src/Navigator.Extensions.Shipyard.Abstractions/IBotManagementService.cs delete mode 100644 src/Navigator.Extensions.Shipyard.Abstractions/Model/BotCommands.cs delete mode 100644 src/Navigator.Extensions.Shipyard.Abstractions/Model/BotInfo.cs delete mode 100644 src/Navigator.Extensions.Shipyard.Abstractions/Model/BotPic.cs delete mode 100644 src/Navigator.Extensions.Shipyard.Abstractions/Navigator.Extensions.Shipyard.Abstractions.csproj delete mode 100644 src/Navigator.Extensions.Shipyard/BotManagementService.cs delete mode 100644 src/Navigator.Extensions.Shipyard/Controllers/BotController.cs delete mode 100644 src/Navigator.Extensions.Shipyard/Controllers/ConversationController.cs delete mode 100644 src/Navigator.Extensions.Shipyard/GenericControllerFeatureProvider.cs delete mode 100644 src/Navigator.Extensions.Shipyard/Middleware/ShipyardApiKeyAuthenticationHandler.cs delete mode 100644 src/Navigator.Extensions.Shipyard/Navigator.Extensions.Shipyard.csproj delete mode 100644 src/Navigator.Extensions.Shipyard/NavigatorOptionsCollectionExtensions.cs delete mode 100644 src/Navigator.Extensions.Shipyard/NavigatorServiceCollectionExtensions.cs delete mode 100644 src/Navigator.Extensions.Store.Abstractions.Extensions/INavigatorContextExtensions.cs delete mode 100644 src/Navigator.Extensions.Store.Abstractions.Extensions/Navigator.Extensions.Store.Abstractions.Extensions.csproj delete mode 100644 src/Navigator.Extensions.Store.Abstractions/Entity/Chat.cs delete mode 100644 src/Navigator.Extensions.Store.Abstractions/Entity/Conversation.cs delete mode 100644 src/Navigator.Extensions.Store.Abstractions/Entity/User.cs delete mode 100644 src/Navigator.Extensions.Store.Abstractions/IChatMapper.cs delete mode 100644 src/Navigator.Extensions.Store.Abstractions/IEntityManager.cs delete mode 100644 src/Navigator.Extensions.Store.Abstractions/IUserMapper.cs delete mode 100644 src/Navigator.Extensions.Store.Abstractions/Navigator.Extensions.Store.Abstractions.csproj delete mode 100644 src/Navigator/Provider.cs delete mode 100644 src/Old.Navigator.Extensions.Store/Context/Configuration/ConversationEntityTypeConfiguration.cs delete mode 100644 src/Old.Navigator.Extensions.Store/Context/NavigatorDbContext.cs delete mode 100644 src/Old.Navigator.Extensions.Store/DefaultChatMapper.cs delete mode 100644 src/Old.Navigator.Extensions.Store/DefaultEntityManager.cs delete mode 100644 src/Old.Navigator.Extensions.Store/DefaultUserMapper.cs delete mode 100644 src/Old.Navigator.Extensions.Store/NavigatorOptionsCollectionExtensions.cs delete mode 100644 src/Old.Navigator.Extensions.Store/NavigatorServiceCollectionExtensions.cs delete mode 100644 src/Old.Navigator.Extensions.Store/Old.Navigator.Extensions.Store.csproj delete mode 100644 src/Old.Navigator.Extensions.Store/Provider/DefaultChatContextProvider.cs delete mode 100644 src/Old.Navigator.Extensions.Store/Provider/DefaultUserContextProvider.cs delete mode 100644 src/Old.Navigator.Extensions.Store/Provider/UpdateDataContextProvider.cs diff --git a/src/Navigator.Extensions.Shipyard.Abstractions/IBotManagementService.cs b/src/Navigator.Extensions.Shipyard.Abstractions/IBotManagementService.cs deleted file mode 100644 index 61607d2..0000000 --- a/src/Navigator.Extensions.Shipyard.Abstractions/IBotManagementService.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System.Threading; -using System.Threading.Tasks; -using Navigator.Extensions.Shipyard.Abstractions.Model; - -namespace Navigator.Extensions.Shipyard.Abstractions -{ - public interface IBotManagementService - { - Task GetBotInfo(CancellationToken cancellationToken = default); - Task GetBotPic(CancellationToken cancellationToken = default); - Task GetBotCommands(CancellationToken cancellationToken = default); - Task UpdateBotCommands(BotCommands botCommands, CancellationToken cancellationToken = default); - - } -} \ No newline at end of file diff --git a/src/Navigator.Extensions.Shipyard.Abstractions/Model/BotCommands.cs b/src/Navigator.Extensions.Shipyard.Abstractions/Model/BotCommands.cs deleted file mode 100644 index dea35e7..0000000 --- a/src/Navigator.Extensions.Shipyard.Abstractions/Model/BotCommands.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System.Collections.Generic; - -namespace Navigator.Extensions.Shipyard.Abstractions.Model -{ - /// - /// Bot commands. - /// - public class BotCommands - { - /// - /// List of commands. - /// - public Dictionary Commands { get; init; } - } -} \ No newline at end of file diff --git a/src/Navigator.Extensions.Shipyard.Abstractions/Model/BotInfo.cs b/src/Navigator.Extensions.Shipyard.Abstractions/Model/BotInfo.cs deleted file mode 100644 index b79320f..0000000 --- a/src/Navigator.Extensions.Shipyard.Abstractions/Model/BotInfo.cs +++ /dev/null @@ -1,49 +0,0 @@ -namespace Navigator.Extensions.Shipyard.Abstractions.Model -{ - /// - /// Bot information. - /// - public class BotInfo - { - /// - /// Bot id. - /// - public long Id { get; init; } - - /// - /// Bot username. - /// - public string Username { get; init; } - - /// - /// Bot name. - /// - public string Name { get; init; } - - /// - /// Bot permissions. - /// - public BotPermissions Permissions { get; init; } - - /// - /// Bot permissions. - /// - public class BotPermissions - { - /// - /// CanJoinGroups - /// - public bool CanJoinGroups { get; init; } - - /// - /// CanReadAllGroupMessages - /// - public bool CanReadAllGroupMessages { get; init; } - - /// - /// SupportsInlineQueries - /// - public bool SupportsInlineQueries { get; init; } - } - } -} \ No newline at end of file diff --git a/src/Navigator.Extensions.Shipyard.Abstractions/Model/BotPic.cs b/src/Navigator.Extensions.Shipyard.Abstractions/Model/BotPic.cs deleted file mode 100644 index 310a420..0000000 --- a/src/Navigator.Extensions.Shipyard.Abstractions/Model/BotPic.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System.IO; - -namespace Navigator.Extensions.Shipyard.Abstractions.Model -{ - /// - /// Bot Picture. - /// - public class BotPic - { - /// - /// Picture in stream format. - /// - public MemoryStream File { get; init; } - - /// - /// Mime type of the picture. - /// - public string MimeType { get; init; } = "image/png"; - } -} \ No newline at end of file diff --git a/src/Navigator.Extensions.Shipyard.Abstractions/Navigator.Extensions.Shipyard.Abstractions.csproj b/src/Navigator.Extensions.Shipyard.Abstractions/Navigator.Extensions.Shipyard.Abstractions.csproj deleted file mode 100644 index 864fe98..0000000 --- a/src/Navigator.Extensions.Shipyard.Abstractions/Navigator.Extensions.Shipyard.Abstractions.csproj +++ /dev/null @@ -1,30 +0,0 @@ - - - - net5.0 - enable - true - true - 0.9.100-beta - Navigator.Extensions.Shipyard.Abstractions - Navigator Extensions Shipyard Abstractions - Lucas Maximiliano Marino - A highly opinionated telegram bot framework, mainly based on Telegram.Bot. - https://github.com/navigatorframework/navigator - https://github.com/navigatorframework/navigator/blob/master/LICENSE - https://github.com/navigatorframework/navigator - Telegram, Bot, Framework, Navigator - true - Copyright © Lucas Maximiliano Marino 2021 - https://raw.githubusercontent.com/navigatorframework/navigator/master/assets/logo.png - - - - - - - - - - - diff --git a/src/Navigator.Extensions.Shipyard/BotManagementService.cs b/src/Navigator.Extensions.Shipyard/BotManagementService.cs deleted file mode 100644 index a45ffc4..0000000 --- a/src/Navigator.Extensions.Shipyard/BotManagementService.cs +++ /dev/null @@ -1,108 +0,0 @@ -using System; -using System.IO; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.Extensions.Logging; -using Navigator.Abstractions; -using Navigator.Extensions.Shipyard.Abstractions; -using Navigator.Extensions.Shipyard.Abstractions.Model; - -namespace Navigator.Extensions.Shipyard -{ - /// - public class BotManagementService : IBotManagementService - { - private readonly ILogger _logger; - private readonly IBotClient _botClient; - - /// - /// Default constructor. - /// - /// - /// - public BotManagementService(ILogger logger, IBotClient botClient) - { - _logger = logger; - _botClient = botClient; - } - - /// - public async Task GetBotInfo(CancellationToken cancellationToken = default) - { - try - { - var info = await _botClient.GetMeAsync(cancellationToken); - - return new BotInfo - { - Id = info.Id, - Username = info.Username, - Name = info.FirstName, - Permissions = new BotInfo.BotPermissions - { - CanJoinGroups = info.CanJoinGroups ?? false, - CanReadAllGroupMessages = info.CanReadAllGroupMessages ?? false, - SupportsInlineQueries = info.SupportsInlineQueries ?? false - } - }; - } - catch (Exception e) - { - _logger.LogError(e, "Unhandled exception requesting bot information."); - - return default; - } - } - - /// - public async Task GetBotPic(CancellationToken cancellationToken = default) - { - try - { - var photos = await _botClient.GetUserProfilePhotosAsync(_botClient.BotId, cancellationToken: cancellationToken); - - if (photos.TotalCount > 0) - { - var botPicId = photos.Photos.FirstOrDefault()? - .OrderByDescending(x => x.FileSize).FirstOrDefault() - ?.FileId; - - if (!string.IsNullOrWhiteSpace(botPicId)) - { - var pictureStream = new MemoryStream(); - await _botClient.GetInfoAndDownloadFileAsync(botPicId, pictureStream, cancellationToken); - - return new BotPic - { - File = pictureStream - }; - } - } - } - catch (Exception e) - { - _logger.LogError(e, "Unhandled exception requesting bot pic."); - } - - return default; - } - - /// - public async Task GetBotCommands(CancellationToken cancellationToken = default) - { - var commands = await _botClient.GetMyCommandsAsync(cancellationToken); - - return new BotCommands - { - Commands = commands.ToDictionary(command => command.Command, command => command.Description) - }; - } - - /// - public Task UpdateBotCommands(BotCommands botCommands, CancellationToken cancellationToken = default) - { - throw new System.NotImplementedException(); - } - } -} \ No newline at end of file diff --git a/src/Navigator.Extensions.Shipyard/Controllers/BotController.cs b/src/Navigator.Extensions.Shipyard/Controllers/BotController.cs deleted file mode 100644 index 389cdd6..0000000 --- a/src/Navigator.Extensions.Shipyard/Controllers/BotController.cs +++ /dev/null @@ -1,66 +0,0 @@ -using System; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; -using Navigator.Extensions.Shipyard.Abstractions; -using Navigator.Extensions.Shipyard.Middleware; - -namespace Navigator.Extensions.Shipyard.Controllers -{ - /// - /// Bot controller. - /// - [Authorize(AuthenticationSchemes = nameof(ShipyardApiKeyAuthenticationHandler))] - [ApiController] - [ApiVersion("1")] - [Route("shipyard/api/v{v:apiVersion}/[controller]")] - public class BotController : ControllerBase - { - private readonly IBotManagementService _botManagementService; - - /// - /// Default constructor. - /// - /// - public BotController(IBotManagementService botManagementService) - { - _botManagementService = botManagementService; - } - - [HttpGet("information")] - public async Task GetBotInformation(CancellationToken cancellationToken) - { - var information = await _botManagementService.GetBotInfo(cancellationToken); - - return Ok(information); - } - - [HttpGet("pic")] - public async Task GetBotPic(CancellationToken cancellationToken) - { - var botPic = await _botManagementService.GetBotPic(cancellationToken); - - if (botPic is not null) - { - return File(botPic.File, botPic.MimeType); - } - return NotFound("BotPic not found"); - } - - [HttpGet("commands")] - public async Task GetBotCommands(CancellationToken cancellationToken) - { - var botCommands = await _botManagementService.GetBotCommands(cancellationToken); - - return Ok(botCommands); - } - - [HttpPut("commands")] - public async Task UpdateBotCommands() - { - throw new NotImplementedException(); - } - - } -} \ No newline at end of file diff --git a/src/Navigator.Extensions.Shipyard/Controllers/ConversationController.cs b/src/Navigator.Extensions.Shipyard/Controllers/ConversationController.cs deleted file mode 100644 index 0e0090f..0000000 --- a/src/Navigator.Extensions.Shipyard/Controllers/ConversationController.cs +++ /dev/null @@ -1,102 +0,0 @@ -using System; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; -using Navigator.Abstractions; -using Navigator.Extensions.Shipyard.Middleware; -using Navigator.Extensions.Store.Abstractions; -using Navigator.Extensions.Store.Abstractions.Entity; -using Telegram.Bot.Types.Enums; - -namespace Navigator.Extensions.Shipyard.Controllers -{ - /// - /// Conversation controller. - /// - /// - /// - [Authorize(AuthenticationSchemes = nameof(ShipyardApiKeyAuthenticationHandler))] - [ApiController] - [ApiVersion("1")] - [Route("shipyard/api/v{v:apiVersion}/conversation")] - public class ConversationController : ControllerBase where TUser : User where TChat : Chat - { - private readonly IEntityManager _entityManager; - private readonly IBotClient _botClient; - - /// - /// Default constructor. - /// - /// - /// - public ConversationController(IEntityManager entityManager, IBotClient botClient) - { - _entityManager = entityManager; - _botClient = botClient; - } - - /// - /// Gets all the users. - /// - /// - /// - [HttpGet("user")] - public IActionResult GetUsers(CancellationToken cancellationToken) - { - try - { - var users = _entityManager.FindAllUsersAsync(cancellationToken); - - if (users is not null) - { - return Ok(users); - } - } - catch (Exception) - { - // ignored - } - - return NotFound(); - } - - /// - /// Gets all the chats. - /// - /// - /// - [HttpGet("chat")] - public IActionResult GetChats(CancellationToken cancellationToken) - { - try - { - var chats = _entityManager.FindAllChatsAsync(cancellationToken); - - if (chats is not null) - { - return Ok(chats); - } - } - catch (Exception) - { - // ignored - } - - return NotFound(); - } - - [HttpPost("chat/{chatId}")] - public async Task SendMessage([FromRoute] long chatId, [FromBody] string message, CancellationToken cancellationToken) - { - if (await _entityManager.FindChatAsync(chatId, cancellationToken) is null) - { - return NotFound(); - } - - await _botClient.SendTextMessageAsync(chatId, message, ParseMode.MarkdownV2, cancellationToken: cancellationToken); - - return Ok(); - } - } -} \ No newline at end of file diff --git a/src/Navigator.Extensions.Shipyard/GenericControllerFeatureProvider.cs b/src/Navigator.Extensions.Shipyard/GenericControllerFeatureProvider.cs deleted file mode 100644 index 9efcac3..0000000 --- a/src/Navigator.Extensions.Shipyard/GenericControllerFeatureProvider.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using Microsoft.AspNetCore.Mvc.ApplicationParts; -using Microsoft.AspNetCore.Mvc.Controllers; -using Navigator.Extensions.Shipyard.Controllers; - -namespace Navigator.Extensions.Shipyard -{ - public class GenericControllerFeatureProvider : IApplicationFeatureProvider - { - private Type UserType { get; } - private Type ChatType { get; } - - public GenericControllerFeatureProvider(Type userType, Type chatType) - { - UserType = userType; - ChatType = chatType; - } - - public void PopulateFeature(IEnumerable parts, ControllerFeature feature) - { - // Check to see if there is a "real" controller for this class - if (!feature.Controllers.Any(t => t.GenericTypeParameters.Any(gp => gp == UserType) && t.GenericTypeParameters.Any(gp => gp == ChatType))) - { - // Create a generic controller for this type - var controllerType = typeof(ConversationController<,>).MakeGenericType(UserType, ChatType).GetTypeInfo(); - feature.Controllers.Add(controllerType); - } - } - } -} \ No newline at end of file diff --git a/src/Navigator.Extensions.Shipyard/Middleware/ShipyardApiKeyAuthenticationHandler.cs b/src/Navigator.Extensions.Shipyard/Middleware/ShipyardApiKeyAuthenticationHandler.cs deleted file mode 100644 index 39784db..0000000 --- a/src/Navigator.Extensions.Shipyard/Middleware/ShipyardApiKeyAuthenticationHandler.cs +++ /dev/null @@ -1,47 +0,0 @@ -using System.Collections.Generic; -using System.Security.Claims; -using System.Text.Encodings.Web; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Authentication; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Options; - -namespace Navigator.Extensions.Shipyard.Middleware -{ - internal class ShipyardApiKeyAuthenticationHandler : AuthenticationHandler - { - private readonly NavigatorOptions _navigatorOptions; - - public ShipyardApiKeyAuthenticationHandler(IOptionsMonitor options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock, NavigatorOptions navigatorOptions) : base(options, logger, encoder, clock) - { - _navigatorOptions = navigatorOptions; - } - - /// - protected override Task HandleAuthenticateAsync() - { - if (_navigatorOptions.GetShipyardApiKey() is null) - { - return Task.FromResult(AuthenticateResult.Fail("Navigator Shipyard is not configured. Please configure an API KEY.")); - } - - if (Context.Request.Headers.TryGetValue("SHIPYARD-API-KEY", out var headerApiKey) && headerApiKey == _navigatorOptions.GetShipyardApiKey()) - { - const string username = "manager"; - var claims = new[] - { - new Claim(ClaimTypes.NameIdentifier, username, ClaimValueTypes.String, Options.ClaimsIssuer), - new Claim(ClaimTypes.Name, username, ClaimValueTypes.String, Options.ClaimsIssuer) - }; - - ClaimsPrincipal principal = new ClaimsPrincipal(new ClaimsIdentity(claims, Scheme.Name)); - - AuthenticationTicket ticket = new(principal, Scheme.Name); - return Task.FromResult(AuthenticateResult.Success(ticket)); - } - - return Task.FromResult(AuthenticateResult.Fail("Unauthorized")); - } - } -} \ No newline at end of file diff --git a/src/Navigator.Extensions.Shipyard/Navigator.Extensions.Shipyard.csproj b/src/Navigator.Extensions.Shipyard/Navigator.Extensions.Shipyard.csproj deleted file mode 100644 index 1669592..0000000 --- a/src/Navigator.Extensions.Shipyard/Navigator.Extensions.Shipyard.csproj +++ /dev/null @@ -1,40 +0,0 @@ - - - - net5.0 - enable - true - true - 0.9.100-beta - Navigator.Extensions.Shipyard - Navigator Extensions Shipyard - Lucas Maximiliano Marino - A highly opinionated telegram bot framework, mainly based on Telegram.Bot. - https://github.com/navigatorframework/navigator - https://github.com/navigatorframework/navigator/blob/master/LICENSE - https://github.com/navigatorframework/navigator - Telegram, Bot, Framework, Navigator - true - Copyright © Lucas Maximiliano Marino 2021 - https://raw.githubusercontent.com/navigatorframework/navigator/master/assets/logo.png - - - - - - - - - - - - - - - - - - - - - diff --git a/src/Navigator.Extensions.Shipyard/NavigatorOptionsCollectionExtensions.cs b/src/Navigator.Extensions.Shipyard/NavigatorOptionsCollectionExtensions.cs deleted file mode 100644 index 66a39fb..0000000 --- a/src/Navigator.Extensions.Shipyard/NavigatorOptionsCollectionExtensions.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System; -using Navigator.Abstractions; -using Navigator.Extensions.Store.Abstractions.Entity; - -namespace Navigator.Extensions.Shipyard -{ - public static class NavigatorOptionsCollectionExtensions - { - #region ShipyardApiKey - - private const string ShipyardApiKeyKey = "_navigator.extensions.shipyard.options.api_key"; - - public static void SetShipyardApiKey(this INavigatorOptions navigatorOptions, string apiKey) - { - navigatorOptions.TryRegisterOption(ShipyardApiKeyKey, apiKey); - } - - public static string? GetShipyardApiKey(this INavigatorOptions navigatorOptions) - { - return navigatorOptions.RetrieveOption(ShipyardApiKeyKey); - } - - #endregion - } -} \ No newline at end of file diff --git a/src/Navigator.Extensions.Shipyard/NavigatorServiceCollectionExtensions.cs b/src/Navigator.Extensions.Shipyard/NavigatorServiceCollectionExtensions.cs deleted file mode 100644 index 3c9b797..0000000 --- a/src/Navigator.Extensions.Shipyard/NavigatorServiceCollectionExtensions.cs +++ /dev/null @@ -1,47 +0,0 @@ -using System; -using System.Linq; -using Microsoft.AspNetCore.Authentication; -using Microsoft.Extensions.DependencyInjection; -using Navigator.Extensions.Shipyard.Abstractions; -using Navigator.Extensions.Shipyard.Middleware; -using Navigator.Extensions.Store; -using Navigator.Extensions.Store.Abstractions; -using Navigator.Extensions.Store.Abstractions.Entity; - -namespace Navigator.Extensions.Shipyard -{ - /// - /// Navigator Shipyard Services - /// - public static class NavigatorServiceCollectionExtensions - { - /// - /// Registers all the necessary navigatorBuilder for shipyard to work. - /// - /// - /// - /// - public static NavigatorBuilder AddShipyard(this NavigatorBuilder navigatorBuilder, Action? options = default) - { - if (options is null) - { - throw new ArgumentException("Please configure shipyard options."); - } - - options.Invoke(navigatorBuilder.Options); - - navigatorBuilder.RegisterOrReplaceOptions(); - - navigatorBuilder.Services.AddControllers().ConfigureApplicationPartManager(m => - m.FeatureProviders.Add( - new GenericControllerFeatureProvider(navigatorBuilder.Options.GetUserType()!, navigatorBuilder.Options.GetChatType()!) - )); - navigatorBuilder.Services.AddAuthentication().AddScheme( - nameof(ShipyardApiKeyAuthenticationHandler), o => { }); - - navigatorBuilder.Services.AddScoped(); - - return navigatorBuilder; - } - } -} \ No newline at end of file diff --git a/src/Navigator.Extensions.Store.Abstractions.Extensions/INavigatorContextExtensions.cs b/src/Navigator.Extensions.Store.Abstractions.Extensions/INavigatorContextExtensions.cs deleted file mode 100644 index 56431c3..0000000 --- a/src/Navigator.Extensions.Store.Abstractions.Extensions/INavigatorContextExtensions.cs +++ /dev/null @@ -1,40 +0,0 @@ -using System; -using Navigator.Abstractions; -using Navigator.Extensions.Store.Abstractions.Entity; - -namespace Navigator.Extensions.Store.Abstractions.Extensions -{ - public static class INavigatorContextExtensions - { - public static string DefaultUserKey => "navigator.extensions.store.user"; - public static string DefaultChatKey => "navigator.extensions.store.chat"; - - #region User - - public static TUser GetUser(this INavigatorContext ctx) where TUser : User - { - return ctx.GetUserOrDefault() ?? throw new Exception("User not found"); - } - - public static TUser? GetUserOrDefault(this INavigatorContext ctx, TUser defaultValue = default) where TUser : User - { - return ctx.Get(DefaultUserKey) ?? defaultValue; - } - - #endregion - - #region Chat - - public static TChat GetChat(this INavigatorContext ctx) where TChat : Chat - { - return ctx.GetChatOrDefault() ?? throw new Exception("User not found"); - } - - public static TChat? GetChatOrDefault(this INavigatorContext ctx, TChat defaultValue = default) where TChat : Chat - { - return ctx.Get(DefaultChatKey) ?? defaultValue; - } - - #endregion - } -} \ No newline at end of file diff --git a/src/Navigator.Extensions.Store.Abstractions.Extensions/Navigator.Extensions.Store.Abstractions.Extensions.csproj b/src/Navigator.Extensions.Store.Abstractions.Extensions/Navigator.Extensions.Store.Abstractions.Extensions.csproj deleted file mode 100644 index f5b247d..0000000 --- a/src/Navigator.Extensions.Store.Abstractions.Extensions/Navigator.Extensions.Store.Abstractions.Extensions.csproj +++ /dev/null @@ -1,30 +0,0 @@ - - - - net5.0 - enable - true - true - 0.9.99-beta - Navigator.Extensions.Store.Abstractions.Extensions - Navigator Extensions Store Abstractions Extensions - Lucas Maximiliano Marino - Store extension for Navigator Framework. - https://github.com/navigatorframework/navigator - https://github.com/navigatorframework/navigator/blob/master/LICENSE - https://github.com/navigatorframework/navigator - Telegram, Bot, Framework, Navigator, EF Core, Store, Database, Extension - true - Copyright © Lucas Maximiliano Marino 2021 - https://raw.githubusercontent.com/navigatorframework/navigator/master/assets/logo.png - - - - - - - - - - - diff --git a/src/Navigator.Extensions.Store.Abstractions/Entity/Chat.cs b/src/Navigator.Extensions.Store.Abstractions/Entity/Chat.cs deleted file mode 100644 index e6dc1f4..0000000 --- a/src/Navigator.Extensions.Store.Abstractions/Entity/Chat.cs +++ /dev/null @@ -1,47 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace Navigator.Extensions.Store.Abstractions.Entity -{ - public class Chat - { - public Chat() - { - Conversations = new List(); - CreatedAt = DateTime.UtcNow; - } - - /// - /// Id of the chat. - /// - public long Id { get; set; } - /// - /// Optional, available when the type of the chat is private. - /// - public string? Username { get; set; } - /// - /// Optional, available when the type of the chat is a group, supergroup or channel. - /// - public string? Title { get; set; } - /// - /// Type of the chat. - /// - public ChatType Type { get; set; } - /// - /// List of conversations that this chat has. - /// - public List Conversations { get; set; } - /// - /// Date of first interaction with the chat. - /// - public DateTime CreatedAt { get; set; } - - public enum ChatType - { - Private, - Group, - Channel, - Supergroup, - } - } -} \ No newline at end of file diff --git a/src/Navigator.Extensions.Store.Abstractions/Entity/Conversation.cs b/src/Navigator.Extensions.Store.Abstractions/Entity/Conversation.cs deleted file mode 100644 index ff0efd4..0000000 --- a/src/Navigator.Extensions.Store.Abstractions/Entity/Conversation.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System; - -namespace Navigator.Extensions.Store.Abstractions.Entity -{ - public class Conversation - { - public Conversation() - { - CreatedAt = DateTime.UtcNow; - } - - public long ChatId { get; set; } - public Chat Chat { get; set; } - public int UserId { get; set; } - public User User { get; set; } - public DateTime CreatedAt { get; set; } - } -} \ No newline at end of file diff --git a/src/Navigator.Extensions.Store.Abstractions/Entity/User.cs b/src/Navigator.Extensions.Store.Abstractions/Entity/User.cs deleted file mode 100644 index 5f3c025..0000000 --- a/src/Navigator.Extensions.Store.Abstractions/Entity/User.cs +++ /dev/null @@ -1,39 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace Navigator.Extensions.Store.Abstractions.Entity -{ - public class User - { - public User() - { - Conversations = new List(); - CreatedAt = DateTime.UtcNow; - } - - /// - /// Id of the user. - /// - public int Id { get; set; } - /// - /// Specifies if the user is a bot or not. - /// - public bool IsBot { get; set; } - /// - /// Language code of the user client. - /// - public string? LanguageCode { get; set; } - /// - /// Username of the user. - /// - public string? Username { get; set; } - /// - /// List of conversations that this user has. - /// - public List Conversations { get; set; } - /// - /// Date of first interaction with the user. - /// - public DateTime CreatedAt { get; set; } - } -} \ No newline at end of file diff --git a/src/Navigator.Extensions.Store.Abstractions/IChatMapper.cs b/src/Navigator.Extensions.Store.Abstractions/IChatMapper.cs deleted file mode 100644 index 4c7091a..0000000 --- a/src/Navigator.Extensions.Store.Abstractions/IChatMapper.cs +++ /dev/null @@ -1,9 +0,0 @@ -using Telegram.Bot.Types; - -namespace Navigator.Extensions.Store.Abstractions -{ - public interface IChatMapper - { - TChat Parse(Chat chat); - } -} \ No newline at end of file diff --git a/src/Navigator.Extensions.Store.Abstractions/IEntityManager.cs b/src/Navigator.Extensions.Store.Abstractions/IEntityManager.cs deleted file mode 100644 index 772eac3..0000000 --- a/src/Navigator.Extensions.Store.Abstractions/IEntityManager.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using Navigator.Extensions.Store.Abstractions.Entity; - -namespace Navigator.Extensions.Store.Abstractions -{ - public interface IEntityManager - where TUser : User - where TChat : Chat - { - Task Handle(Telegram.Bot.Types.User telegramUser, CancellationToken cancellationToken = default); - Task Handle(Telegram.Bot.Types.User telegramUser, Telegram.Bot.Types.Chat telegramChat, CancellationToken cancellationToken = default); - TUser? FindUser(int id); - Task FindUserAsync(int id, CancellationToken cancellationToken = default); - IEnumerable FindAllUsersAsync(CancellationToken cancellationToken = default); - TChat? FindChat(long id); - Task FindChatAsync(long id, CancellationToken cancellationToken = default); - IEnumerable FindAllChatsAsync(CancellationToken cancellationToken = default); - Task MigrateFromGroup(Telegram.Bot.Types.Message telegramMessage, CancellationToken cancellationToken = default); - Task MigrateToSupergroup(Telegram.Bot.Types.Message telegramMessage, CancellationToken cancellationToken = default); - Task ChatTitleChanged(Telegram.Bot.Types.Message telegramMessage, CancellationToken cancellationToken = default); - Task ChatMemberLeft(Telegram.Bot.Types.Message telegramMessage, CancellationToken cancellationToken = default); - } -} \ No newline at end of file diff --git a/src/Navigator.Extensions.Store.Abstractions/IUserMapper.cs b/src/Navigator.Extensions.Store.Abstractions/IUserMapper.cs deleted file mode 100644 index dd11aef..0000000 --- a/src/Navigator.Extensions.Store.Abstractions/IUserMapper.cs +++ /dev/null @@ -1,9 +0,0 @@ -using Telegram.Bot.Types; - -namespace Navigator.Extensions.Store.Abstractions -{ - public interface IUserMapper - { - TUser Parse(User user); - } -} \ No newline at end of file diff --git a/src/Navigator.Extensions.Store.Abstractions/Navigator.Extensions.Store.Abstractions.csproj b/src/Navigator.Extensions.Store.Abstractions/Navigator.Extensions.Store.Abstractions.csproj deleted file mode 100644 index 215aa22..0000000 --- a/src/Navigator.Extensions.Store.Abstractions/Navigator.Extensions.Store.Abstractions.csproj +++ /dev/null @@ -1,30 +0,0 @@ - - - - net5.0 - enable - true - true - 0.9.100-beta - Navigator.Extensions.Store.Abstractions - Navigator Extensions Store Abstractions - Lucas Maximiliano Marino - Store extension for Navigator Framework. - https://github.com/navigatorframework/navigator - https://github.com/navigatorframework/navigator/blob/master/LICENSE - https://github.com/navigatorframework/navigator - Telegram, Bot, Framework, Navigator, EF Core, Store, Database, Extension - true - Copyright © Lucas Maximiliano Marino 2021 - https://raw.githubusercontent.com/navigatorframework/navigator/master/assets/logo.png - - - - - - - - - - - diff --git a/src/Navigator.sln b/src/Navigator.sln index 9f20dd4..81a6e2c 100644 --- a/src/Navigator.sln +++ b/src/Navigator.sln @@ -1,28 +1,10 @@ Microsoft Visual Studio Solution File, Format Version 12.00 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Navigator", "Navigator\Navigator.csproj", "{6DBAD041-6623-4903-9939-254FDC4EBD60}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Old.Navigator.Extensions.Store", "Old.Navigator.Extensions.Store\Old.Navigator.Extensions.Store.csproj", "{9DEA166A-AE92-438F-8F3D-7C2F777ABBDD}" -EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Samples", "Samples", "{6D6A8E40-8C40-49AA-BEAD-B046D43F511A}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Extensions", "Extensions", "{F178DCF2-AD03-44C8-AF8F-95C60664DD10}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Old", "Old", "{895808DE-1CA6-406C-924A-7E43F293CF7D}" -EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Navigator", "Navigator", "{E6F24E3B-A066-4572-94F0-14665E19EFC7}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Store", "Store", "{F26BD166-0ED4-4096-8841-47959645B3DE}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Navigator.Extensions.Store.Abstractions", "Navigator.Extensions.Store.Abstractions\Navigator.Extensions.Store.Abstractions.csproj", "{8E680AE7-33EC-4049-A9DC-0F42C6A03184}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Navigator.Extensions.Store.Abstractions.Extensions", "Navigator.Extensions.Store.Abstractions.Extensions\Navigator.Extensions.Store.Abstractions.Extensions.csproj", "{DB8B0A37-3CE6-4B84-8796-819D04D6C70E}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Shipyard", "Shipyard", "{E2FF61C3-F081-40C8-9CC3-BBE1F81543F6}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Navigator.Extensions.Shipyard", "Navigator.Extensions.Shipyard\Navigator.Extensions.Shipyard.csproj", "{90E6A9A5-BD73-4C9D-97A3-FA8021D16921}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Navigator.Extensions.Shipyard.Abstractions", "Navigator.Extensions.Shipyard.Abstractions\Navigator.Extensions.Shipyard.Abstractions.csproj", "{294C1716-C054-4585-B66E-C79D155AE684}" -EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Providers", "Providers", "{DAA22477-BB29-475C-AD2C-905F81B4AD8E}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Navigator.Providers.Telegram", "Navigator.Providers.Telegram\Navigator.Providers.Telegram.csproj", "{8E0F6DCA-FAA4-4FA8-B9E0-75E9DC0F3573}" @@ -45,26 +27,6 @@ Global {6DBAD041-6623-4903-9939-254FDC4EBD60}.Debug|Any CPU.Build.0 = Debug|Any CPU {6DBAD041-6623-4903-9939-254FDC4EBD60}.Release|Any CPU.ActiveCfg = Release|Any CPU {6DBAD041-6623-4903-9939-254FDC4EBD60}.Release|Any CPU.Build.0 = Release|Any CPU - {9DEA166A-AE92-438F-8F3D-7C2F777ABBDD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {9DEA166A-AE92-438F-8F3D-7C2F777ABBDD}.Debug|Any CPU.Build.0 = Debug|Any CPU - {9DEA166A-AE92-438F-8F3D-7C2F777ABBDD}.Release|Any CPU.ActiveCfg = Release|Any CPU - {9DEA166A-AE92-438F-8F3D-7C2F777ABBDD}.Release|Any CPU.Build.0 = Release|Any CPU - {8E680AE7-33EC-4049-A9DC-0F42C6A03184}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {8E680AE7-33EC-4049-A9DC-0F42C6A03184}.Debug|Any CPU.Build.0 = Debug|Any CPU - {8E680AE7-33EC-4049-A9DC-0F42C6A03184}.Release|Any CPU.ActiveCfg = Release|Any CPU - {8E680AE7-33EC-4049-A9DC-0F42C6A03184}.Release|Any CPU.Build.0 = Release|Any CPU - {DB8B0A37-3CE6-4B84-8796-819D04D6C70E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {DB8B0A37-3CE6-4B84-8796-819D04D6C70E}.Debug|Any CPU.Build.0 = Debug|Any CPU - {DB8B0A37-3CE6-4B84-8796-819D04D6C70E}.Release|Any CPU.ActiveCfg = Release|Any CPU - {DB8B0A37-3CE6-4B84-8796-819D04D6C70E}.Release|Any CPU.Build.0 = Release|Any CPU - {90E6A9A5-BD73-4C9D-97A3-FA8021D16921}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {90E6A9A5-BD73-4C9D-97A3-FA8021D16921}.Debug|Any CPU.Build.0 = Debug|Any CPU - {90E6A9A5-BD73-4C9D-97A3-FA8021D16921}.Release|Any CPU.ActiveCfg = Release|Any CPU - {90E6A9A5-BD73-4C9D-97A3-FA8021D16921}.Release|Any CPU.Build.0 = Release|Any CPU - {294C1716-C054-4585-B66E-C79D155AE684}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {294C1716-C054-4585-B66E-C79D155AE684}.Debug|Any CPU.Build.0 = Debug|Any CPU - {294C1716-C054-4585-B66E-C79D155AE684}.Release|Any CPU.ActiveCfg = Release|Any CPU - {294C1716-C054-4585-B66E-C79D155AE684}.Release|Any CPU.Build.0 = Release|Any CPU {8E0F6DCA-FAA4-4FA8-B9E0-75E9DC0F3573}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {8E0F6DCA-FAA4-4FA8-B9E0-75E9DC0F3573}.Debug|Any CPU.Build.0 = Debug|Any CPU {8E0F6DCA-FAA4-4FA8-B9E0-75E9DC0F3573}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -83,15 +45,7 @@ Global {E7D6F33B-C30E-4ED2-878C-B2F899CF1805}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(NestedProjects) = preSolution - {F178DCF2-AD03-44C8-AF8F-95C60664DD10} = {895808DE-1CA6-406C-924A-7E43F293CF7D} {6DBAD041-6623-4903-9939-254FDC4EBD60} = {E6F24E3B-A066-4572-94F0-14665E19EFC7} - {F26BD166-0ED4-4096-8841-47959645B3DE} = {F178DCF2-AD03-44C8-AF8F-95C60664DD10} - {9DEA166A-AE92-438F-8F3D-7C2F777ABBDD} = {F26BD166-0ED4-4096-8841-47959645B3DE} - {8E680AE7-33EC-4049-A9DC-0F42C6A03184} = {F26BD166-0ED4-4096-8841-47959645B3DE} - {DB8B0A37-3CE6-4B84-8796-819D04D6C70E} = {F26BD166-0ED4-4096-8841-47959645B3DE} - {E2FF61C3-F081-40C8-9CC3-BBE1F81543F6} = {F178DCF2-AD03-44C8-AF8F-95C60664DD10} - {90E6A9A5-BD73-4C9D-97A3-FA8021D16921} = {E2FF61C3-F081-40C8-9CC3-BBE1F81543F6} - {294C1716-C054-4585-B66E-C79D155AE684} = {E2FF61C3-F081-40C8-9CC3-BBE1F81543F6} {8E0F6DCA-FAA4-4FA8-B9E0-75E9DC0F3573} = {DAA22477-BB29-475C-AD2C-905F81B4AD8E} {4F4CEC5E-5FAF-4914-8EC0-E6BC9EB1B975} = {6D6A8E40-8C40-49AA-BEAD-B046D43F511A} {B7013C91-C736-4041-9952-5AC2471D9E9A} = {A6DF6F5F-F784-4EF1-97D1-C3DDD2E66B5E} diff --git a/src/Navigator/Provider.cs b/src/Navigator/Provider.cs deleted file mode 100644 index d400459..0000000 --- a/src/Navigator/Provider.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace Navigator -{ - public static class Provider - { - public static TProvider For() where TProvider : INavigatorProvider, new() - { - return new(); - } - } -} \ No newline at end of file diff --git a/src/Old.Navigator.Extensions.Store/Context/Configuration/ConversationEntityTypeConfiguration.cs b/src/Old.Navigator.Extensions.Store/Context/Configuration/ConversationEntityTypeConfiguration.cs deleted file mode 100644 index fd0d64d..0000000 --- a/src/Old.Navigator.Extensions.Store/Context/Configuration/ConversationEntityTypeConfiguration.cs +++ /dev/null @@ -1,24 +0,0 @@ -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Metadata.Builders; -using Old.Navigator.Extensions.Store.Abstractions.Entity; - -namespace Old.Navigator.Extensions.Store.Context.Configuration -{ - /// - public class ConversationEntityTypeConfiguration : IEntityTypeConfiguration - { - /// - public void Configure(EntityTypeBuilder builder) - { - builder.HasKey(e => new {e.ChatId, e.UserId}); - - builder.HasOne(e => e.User) - .WithMany(e => e.Conversations) - .HasForeignKey(e => e.UserId); - - builder.HasOne(e => e.Chat) - .WithMany(e => e.Conversations) - .HasForeignKey(e => e.ChatId); - } - } -} \ No newline at end of file diff --git a/src/Old.Navigator.Extensions.Store/Context/NavigatorDbContext.cs b/src/Old.Navigator.Extensions.Store/Context/NavigatorDbContext.cs deleted file mode 100644 index a4a6173..0000000 --- a/src/Old.Navigator.Extensions.Store/Context/NavigatorDbContext.cs +++ /dev/null @@ -1,38 +0,0 @@ -using Microsoft.EntityFrameworkCore; -using Old.Navigator.Extensions.Store.Abstractions.Entity; -using Old.Navigator.Extensions.Store.Context.Configuration; - -namespace Old.Navigator.Extensions.Store.Context -{ - public class NavigatorDbContext : NavigatorDbContext - { - public NavigatorDbContext(DbContextOptions options) : base(options) - { - } - } - - public class NavigatorDbContext : DbContext - where TUser : User - where TChat : Chat - { - public DbSet Users { get; set; } - public DbSet Chats { get; set; } - public DbSet Conversations { get; set; } - - protected NavigatorDbContext() - { - } - - public NavigatorDbContext(DbContextOptions options) : base(options) - { - } - - protected override void OnModelCreating(ModelBuilder modelBuilder) - { - base.OnModelCreating(modelBuilder); - - modelBuilder.ApplyConfiguration(new ConversationEntityTypeConfiguration()); - - } - } -} \ No newline at end of file diff --git a/src/Old.Navigator.Extensions.Store/DefaultChatMapper.cs b/src/Old.Navigator.Extensions.Store/DefaultChatMapper.cs deleted file mode 100644 index 2cd8bc2..0000000 --- a/src/Old.Navigator.Extensions.Store/DefaultChatMapper.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System; -using Old.Navigator.Extensions.Store.Abstractions; -using Old.Navigator.Extensions.Store.Abstractions.Entity; - -namespace Old.Navigator.Extensions.Store -{ - public class DefaultChatMapper : IChatMapper - { - public Chat Parse(Telegram.Bot.Types.Chat chat) - { - return new Chat - { - Id = chat.Id, - Username = chat.Username, - Title = chat.Title, - Type = Enum.Parse(chat.Type.ToString()) - }; - } - } -} \ No newline at end of file diff --git a/src/Old.Navigator.Extensions.Store/DefaultEntityManager.cs b/src/Old.Navigator.Extensions.Store/DefaultEntityManager.cs deleted file mode 100644 index 5c0eff0..0000000 --- a/src/Old.Navigator.Extensions.Store/DefaultEntityManager.cs +++ /dev/null @@ -1,166 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Logging; -using Old.Navigator.Extensions.Store.Abstractions; -using Old.Navigator.Extensions.Store.Abstractions.Entity; -using Old.Navigator.Extensions.Store.Context; -using Telegram.Bot.Types; -using Chat = Old.Navigator.Extensions.Store.Abstractions.Entity.Chat; -using User = Old.Navigator.Extensions.Store.Abstractions.Entity.User; - -namespace Old.Navigator.Extensions.Store -{ - public class DefaultEntityManager : IEntityManager where TContext : NavigatorDbContext - where TUser : User - where TChat : Chat - { - private readonly ILogger> _logger; - private readonly TContext _navigatorDbContext; - private readonly IUserMapper _userMapper; - private readonly IChatMapper _chatMapper; - - public DefaultEntityManager(ILogger> logger, TContext navigatorDbContext, - IUserMapper userMapper, IChatMapper chatMapper) - { - _logger = logger; - _navigatorDbContext = navigatorDbContext; - _userMapper = userMapper; - _chatMapper = chatMapper; - } - - public async Task Handle(Telegram.Bot.Types.User telegramUser, CancellationToken cancellationToken = default) - { - _logger.LogDebug("Handling user {@UserId}", telegramUser.Id); - - var user = await _navigatorDbContext.Users.Include(u => u.Conversations) - .FirstOrDefaultAsync(u => u.Id == telegramUser.Id, cancellationToken); - - if (user == null) - { - user = _userMapper.Parse(telegramUser); - - await _navigatorDbContext.AddAsync(user, cancellationToken); - await _navigatorDbContext.SaveChangesAsync(cancellationToken); - } - } - - public async Task Handle(Telegram.Bot.Types.User telegramUser, Telegram.Bot.Types.Chat telegramChat, - CancellationToken cancellationToken = default) - { - _logger.LogDebug("Handling user {@UserId} and chat {@ChatId}", telegramUser.Id, telegramChat.Id); - - var userIsNew = false; - var chatIsNew = false; - var conversationIsNew = false; - - var user = await _navigatorDbContext.Users.Include(u => u.Conversations) - .FirstOrDefaultAsync(u => u.Id == telegramUser.Id, cancellationToken); - - var chat = await _navigatorDbContext.Chats.Include(u => u.Conversations) - .FirstOrDefaultAsync(u => u.Id == telegramChat.Id, cancellationToken); - - if (user == null) - { - userIsNew = true; - user = _userMapper.Parse(telegramUser); - await _navigatorDbContext.Users.AddAsync(user, cancellationToken); - } - - if (chat == null) - { - chatIsNew = true; - chat = _chatMapper.Parse(telegramChat); - await _navigatorDbContext.Chats.AddAsync(chat, cancellationToken); - } - - if (chat.Conversations.FirstOrDefault(cv => cv.UserId == user.Id) == null) - { - conversationIsNew = true; - var conversation = new Conversation - { - UserId = user.Id, - ChatId = chat.Id - }; - await _navigatorDbContext.Conversations.AddAsync(conversation, cancellationToken); - } - - if (userIsNew || chatIsNew || conversationIsNew) - { - await _navigatorDbContext.SaveChangesAsync(cancellationToken); - } - } - - public TUser FindUser(int id) - { - return _navigatorDbContext.Users.Find(id); - } - - public async Task FindUserAsync(int id, CancellationToken cancellationToken = default) - { - return await _navigatorDbContext.Users.FindAsync(id); - } - - public IEnumerable FindAllUsersAsync(CancellationToken cancellationToken = default) - { - return _navigatorDbContext.Users.AsEnumerable(); - } - - public TChat FindChat(long id) - { - return _navigatorDbContext.Chats.Find(id); - } - - public async Task FindChatAsync(long id, CancellationToken cancellationToken = default) - { - return await _navigatorDbContext.Chats.FindAsync(id); - } - - public IEnumerable FindAllChatsAsync(CancellationToken cancellationToken = default) - { - return _navigatorDbContext.Chats.AsEnumerable(); - } - - public async Task MigrateFromGroup(Telegram.Bot.Types.Message telegramMessage, CancellationToken cancellationToken = default) - { - var chat = await FindChatAsync(telegramMessage.Chat.Id, cancellationToken); - - chat.Id = telegramMessage.MigrateToChatId; - chat.Type = Chat.ChatType.Supergroup; - - await _navigatorDbContext.SaveChangesAsync(cancellationToken); - } - - public async Task MigrateToSupergroup(Telegram.Bot.Types.Message telegramMessage, CancellationToken cancellationToken = default) - { - var chat = await FindChatAsync(telegramMessage.MigrateFromChatId, cancellationToken); - - chat.Id = telegramMessage.Chat.Id; - chat.Type = Chat.ChatType.Supergroup; - - await _navigatorDbContext.SaveChangesAsync(cancellationToken); - } - - public async Task ChatTitleChanged(Message telegramMessage, CancellationToken cancellationToken = default) - { - var chat = await FindChatAsync(telegramMessage.MigrateFromChatId, cancellationToken); - - chat.Title = telegramMessage.NewChatTitle; - - await _navigatorDbContext.SaveChangesAsync(cancellationToken); - } - - public async Task ChatMemberLeft(Message telegramMessage, CancellationToken cancellationToken = default) - { - var conversation = await _navigatorDbContext.Conversations - .Where(c => c.ChatId == telegramMessage.Chat.Id && c.UserId == telegramMessage.From.Id) - .SingleOrDefaultAsync(cancellationToken); - - _navigatorDbContext.Remove(conversation); - - await _navigatorDbContext.SaveChangesAsync(cancellationToken); - } - } -} \ No newline at end of file diff --git a/src/Old.Navigator.Extensions.Store/DefaultUserMapper.cs b/src/Old.Navigator.Extensions.Store/DefaultUserMapper.cs deleted file mode 100644 index 45cfc71..0000000 --- a/src/Old.Navigator.Extensions.Store/DefaultUserMapper.cs +++ /dev/null @@ -1,19 +0,0 @@ -using Old.Navigator.Extensions.Store.Abstractions; -using Old.Navigator.Extensions.Store.Abstractions.Entity; - -namespace Old.Navigator.Extensions.Store -{ - public class DefaultUserMapper : IUserMapper - { - public User Parse(Telegram.Bot.Types.User user) - { - return new User - { - Id = user.Id, - IsBot = user.IsBot, - LanguageCode = user.LanguageCode, - Username = user.Username - }; - } - } -} \ No newline at end of file diff --git a/src/Old.Navigator.Extensions.Store/NavigatorOptionsCollectionExtensions.cs b/src/Old.Navigator.Extensions.Store/NavigatorOptionsCollectionExtensions.cs deleted file mode 100644 index 39698e9..0000000 --- a/src/Old.Navigator.Extensions.Store/NavigatorOptionsCollectionExtensions.cs +++ /dev/null @@ -1,73 +0,0 @@ -using System; -using Navigator.Abstractions; -using Old.Navigator.Extensions.Store.Abstractions.Entity; - -namespace Old.Navigator.Extensions.Store -{ - public static class NavigatorOptionsCollectionExtensions - { - #region UserMapper - - private const string UserTypeKey = "_navigator.extensions.store.options.user_type"; - - public static void SetUserType(this INavigatorOptions navigatorOptions) where TUser : User - { - navigatorOptions.TryRegisterOption(UserTypeKey, typeof(TUser)); - } - - public static Type? GetUserType(this INavigatorOptions navigatorOptions) - { - return navigatorOptions.RetrieveOption(UserTypeKey); - } - - #endregion - - #region ChatMapper - - private const string ChatTypeKey = "_navigator.extensions.store.options.chat_type"; - - public static void SetChatType(this INavigatorOptions navigatorOptions) - { - navigatorOptions.TryRegisterOption(ChatTypeKey, typeof(TChat)); - } - - public static Type? GetChatType(this INavigatorOptions navigatorOptions) - { - return navigatorOptions.RetrieveOption(ChatTypeKey); - } - - #endregion - - #region UserMapper - - private const string UserMapperKey = "_navigator.extensions.store.options.user_mapper"; - - public static void SetUserMapper(this INavigatorOptions navigatorOptions) - { - navigatorOptions.ForceRegisterOption(UserMapperKey, typeof(TUserMapper)); - } - - public static Type? GetUserMapper(this INavigatorOptions navigatorOptions) - { - return navigatorOptions.RetrieveOption(UserMapperKey); - } - - #endregion - - #region ChatMapper - - private const string ChatMapperKey = "_navigator.extensions.store.options.chat_mapper"; - - public static void SetChatMapper(this INavigatorOptions navigatorOptions) - { - navigatorOptions.ForceRegisterOption(ChatMapperKey, typeof(TChatMapper)); - } - - public static Type? GetChatMapper(this INavigatorOptions navigatorOptions) - { - return navigatorOptions.RetrieveOption(ChatMapperKey); - } - - #endregion - } -} \ No newline at end of file diff --git a/src/Old.Navigator.Extensions.Store/NavigatorServiceCollectionExtensions.cs b/src/Old.Navigator.Extensions.Store/NavigatorServiceCollectionExtensions.cs deleted file mode 100644 index b8c2232..0000000 --- a/src/Old.Navigator.Extensions.Store/NavigatorServiceCollectionExtensions.cs +++ /dev/null @@ -1,91 +0,0 @@ -using System; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.DependencyInjection; - using Microsoft.Extensions.DependencyInjection.Extensions; -using Navigator.Abstractions; -using Old.Navigator.Extensions.Store.Abstractions; -using Old.Navigator.Extensions.Store.Abstractions.Entity; -using Old.Navigator.Extensions.Store.Context; -using Old.Navigator.Extensions.Store.Provider; - -namespace Old.Navigator.Extensions.Store -{ - public static class NavigatorServiceCollectionExtensions - { - #region Default Implementation - - public static NavigatorBuilder AddNavigatorStore(this NavigatorBuilder navigatorBuilder, Action dbContextOptions = default, - Action options = default) - { - navigatorBuilder.Options.SetUserMapper(); - navigatorBuilder.Options.SetChatMapper(); - - navigatorBuilder.AddNavigatorStore(dbContextOptions, options); - - return navigatorBuilder; - } - - #endregion - - public static NavigatorBuilder AddNavigatorStore(this NavigatorBuilder navigatorBuilder, Action dbContextOptions = default, - Action options = default) - where TContext : NavigatorDbContext - where TUser : User - { - navigatorBuilder.Options.SetChatMapper(); - - return navigatorBuilder.AddNavigatorStore(dbContextOptions, options); - } - - public static NavigatorBuilder AddNavigatorStore(this NavigatorBuilder navigatorBuilder, Action? dbContextOptions = default, - Action? options = default) - where TContext : NavigatorDbContext - where TUser : User - where TChat : Chat - { - navigatorBuilder.Options.SetUserType(); - navigatorBuilder.Options.SetChatType(); - - options?.Invoke(navigatorBuilder.Options); - - navigatorBuilder.Services.AddDbContext(dbContextOptions); - - RegisterUserMapper(navigatorBuilder); - - RegisterChatMapper(navigatorBuilder); - - navigatorBuilder.Services.AddScoped, DefaultEntityManager>(); - navigatorBuilder.Services.TryAddEnumerable(ServiceDescriptor.Scoped>()); - navigatorBuilder.Services.TryAddEnumerable(ServiceDescriptor.Scoped>()); - navigatorBuilder.Services.TryAddEnumerable(ServiceDescriptor.Scoped>()); - - navigatorBuilder.RegisterOrReplaceOptions(); - - return navigatorBuilder; - } - - private static void RegisterUserMapper(NavigatorBuilder navigatorBuilder) where TUser : User - { - if (navigatorBuilder.Options.GetUserMapper() is not null && typeof(IUserMapper).IsAssignableFrom(navigatorBuilder.Options.GetUserMapper())) - { - navigatorBuilder.Services.AddScoped(typeof(IUserMapper), navigatorBuilder.Options.GetUserMapper()!); - } - else - { - throw new ArgumentException("TODO"); - } - } - - private static void RegisterChatMapper(NavigatorBuilder navigatorBuilder) where TChat : Chat - { - if (navigatorBuilder.Options.GetChatMapper() is not null && typeof(IChatMapper).IsAssignableFrom(navigatorBuilder.Options.GetChatMapper())) - { - navigatorBuilder.Services.AddScoped(typeof(IChatMapper), navigatorBuilder.Options.GetChatMapper()!); - } - else - { - throw new ArgumentException("TODO"); - } - } - } -} \ No newline at end of file diff --git a/src/Old.Navigator.Extensions.Store/Old.Navigator.Extensions.Store.csproj b/src/Old.Navigator.Extensions.Store/Old.Navigator.Extensions.Store.csproj deleted file mode 100644 index a57d629..0000000 --- a/src/Old.Navigator.Extensions.Store/Old.Navigator.Extensions.Store.csproj +++ /dev/null @@ -1,42 +0,0 @@ - - - - net5.0 - enable - true - true - 0.9.100-beta - Old.Navigator.Extensions.Store - Navigator Extensions Store - Lucas Maximiliano Marino - Store extension for Navigator Framework. - https://github.com/navigatorframework/navigator - https://github.com/navigatorframework/navigator/blob/master/LICENSE - https://github.com/navigatorframework/navigator - Telegram, Bot, Framework, Navigator, EF Core, Store, Database, Extension - true - Copyright © Lucas Maximiliano Marino 2021 - https://raw.githubusercontent.com/navigatorframework/navigator/master/assets/logo.png - - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - - - - - - - - - - - diff --git a/src/Old.Navigator.Extensions.Store/Provider/DefaultChatContextProvider.cs b/src/Old.Navigator.Extensions.Store/Provider/DefaultChatContextProvider.cs deleted file mode 100644 index 6116c4f..0000000 --- a/src/Old.Navigator.Extensions.Store/Provider/DefaultChatContextProvider.cs +++ /dev/null @@ -1,59 +0,0 @@ -using System.Threading.Tasks; -using Microsoft.Extensions.Logging; -using Navigator.Abstractions; -using Old.Navigator.Extensions.Store.Abstractions; -using Old.Navigator.Extensions.Store.Abstractions.Extensions; -using Telegram.Bot.Types; -using Telegram.Bot.Types.Enums; -using Chat = Old.Navigator.Extensions.Store.Abstractions.Entity.Chat; -using User = Old.Navigator.Extensions.Store.Abstractions.Entity.User; - -namespace Old.Navigator.Extensions.Store.Provider -{ - public class DefaultChatContextProvider : INavigatorContextExtensionProvider - where TUser : User - where TChat : Chat - { - public int Order => 500; - - private readonly ILogger> _logger; - private readonly IEntityManager _entityManager; - - public DefaultChatContextProvider(ILogger> logger, IEntityManager entityManager) - { - _logger = logger; - _entityManager = entityManager; - } - - public async Task<(string?, object?)> Process(Update update) - { - _logger.LogDebug("Processing update {UpdateId} of type {UpdateType} from {Provider}", update.Id, update.Type.ToString(), nameof(DefaultChatContextProvider)); - - TChat chat; - - switch (update.Type) - { - case UpdateType.Message: - await _entityManager.Handle(update.Message.From, update.Message.Chat); - chat = await _entityManager.FindChatAsync(update.Message.Chat.Id); - break; - case UpdateType.EditedMessage: - await _entityManager.Handle(update.EditedMessage.From, update.EditedMessage.Chat); - chat = await _entityManager.FindChatAsync(update.EditedMessage.Chat.Id); - break; - case UpdateType.ChannelPost: - await _entityManager.Handle(update.ChannelPost.From, update.ChannelPost.Chat); - chat = await _entityManager.FindChatAsync(update.ChannelPost.Chat.Id); - break; - case UpdateType.EditedChannelPost: - await _entityManager.Handle(update.EditedChannelPost.From, update.EditedChannelPost.Chat); - chat = await _entityManager.FindChatAsync(update.EditedChannelPost.Chat.Id); - break; - default: - return default; - } - - return (INavigatorContextExtensions.DefaultChatKey, chat); - } - } -} \ No newline at end of file diff --git a/src/Old.Navigator.Extensions.Store/Provider/DefaultUserContextProvider.cs b/src/Old.Navigator.Extensions.Store/Provider/DefaultUserContextProvider.cs deleted file mode 100644 index 91d033f..0000000 --- a/src/Old.Navigator.Extensions.Store/Provider/DefaultUserContextProvider.cs +++ /dev/null @@ -1,79 +0,0 @@ -using System.Threading.Tasks; -using Microsoft.Extensions.Logging; -using Navigator.Abstractions; -using Old.Navigator.Extensions.Store.Abstractions; -using Old.Navigator.Extensions.Store.Abstractions.Extensions; -using Telegram.Bot.Types; -using Telegram.Bot.Types.Enums; -using Chat = Old.Navigator.Extensions.Store.Abstractions.Entity.Chat; -using User = Old.Navigator.Extensions.Store.Abstractions.Entity.User; - -namespace Old.Navigator.Extensions.Store.Provider -{ - public class DefaultUserContextProvider : INavigatorContextExtensionProvider - where TUser : User - where TChat : Chat - { - public int Order => 500; - - private readonly ILogger> _logger; - private readonly IEntityManager _entityManager; - - public DefaultUserContextProvider(ILogger> logger, IEntityManager entityManager) - { - _logger = logger; - _entityManager = entityManager; - } - - public async Task<(string?, object?)> Process(Update update) - { - _logger.LogDebug("Processing update {UpdateId} of type {UpdateType} from {Provider}", update.Id, update.Type.ToString(), nameof(DefaultChatContextProvider)); - - TUser user; - - switch (update.Type) - { - case UpdateType.Message: - await _entityManager.Handle(update.Message.From, update.Message.Chat); - user = await _entityManager.FindUserAsync(update.Message.From.Id); - break; - case UpdateType.InlineQuery: - await _entityManager.Handle(update.InlineQuery.From); - user = await _entityManager.FindUserAsync(update.InlineQuery.From.Id); - break; - case UpdateType.ChosenInlineResult: - await _entityManager.Handle(update.ChosenInlineResult.From); - user = await _entityManager.FindUserAsync(update.ChosenInlineResult.From.Id); - break; - case UpdateType.CallbackQuery: - await _entityManager.Handle(update.CallbackQuery.From); - user = await _entityManager.FindUserAsync(update.CallbackQuery.From.Id); - break; - case UpdateType.EditedMessage: - await _entityManager.Handle(update.EditedMessage.From, update.EditedMessage.Chat); - user = await _entityManager.FindUserAsync(update.EditedMessage.From.Id); - break; - case UpdateType.ChannelPost: - await _entityManager.Handle(update.ChannelPost.From, update.ChannelPost.Chat); - user = await _entityManager.FindUserAsync(update.ChannelPost.From.Id); - break; - case UpdateType.EditedChannelPost: - await _entityManager.Handle(update.EditedChannelPost.From, update.EditedChannelPost.Chat); - user = await _entityManager.FindUserAsync(update.EditedChannelPost.From.Id); - break; - case UpdateType.ShippingQuery: - await _entityManager.Handle(update.ShippingQuery.From); - user = await _entityManager.FindUserAsync(update.ShippingQuery.From.Id); - break; - case UpdateType.PreCheckoutQuery: - await _entityManager.Handle(update.PreCheckoutQuery.From); - user = await _entityManager.FindUserAsync(update.PreCheckoutQuery.From.Id); - break; - default: - return default; - } - - return (INavigatorContextExtensions.DefaultUserKey, user); - } - } -} \ No newline at end of file diff --git a/src/Old.Navigator.Extensions.Store/Provider/UpdateDataContextProvider.cs b/src/Old.Navigator.Extensions.Store/Provider/UpdateDataContextProvider.cs deleted file mode 100644 index 7b3531f..0000000 --- a/src/Old.Navigator.Extensions.Store/Provider/UpdateDataContextProvider.cs +++ /dev/null @@ -1,62 +0,0 @@ -using System.Threading.Tasks; -using Microsoft.Extensions.Logging; -using Navigator.Abstractions; -using Old.Navigator.Extensions.Store.Abstractions; -using Telegram.Bot.Types; -using Telegram.Bot.Types.Enums; -using Chat = Old.Navigator.Extensions.Store.Abstractions.Entity.Chat; -using User = Old.Navigator.Extensions.Store.Abstractions.Entity.User; - -namespace Old.Navigator.Extensions.Store.Provider -{ - public class UpdateDataContextProvider : INavigatorContextExtensionProvider - where TUser : User - where TChat : Chat - { - public int Order => 250; - - private readonly ILogger> _logger; - private readonly IEntityManager _entityManager; - - public UpdateDataContextProvider(ILogger> logger, IEntityManager entityManager) - { - _logger = logger; - _entityManager = entityManager; - } - - public async Task<(string?, object?)> Process(Update update) - { - if (update.Type == UpdateType.Message || update.Type == UpdateType.ChannelPost) - { - switch (update.Message.Type) - { - case MessageType.ChatMembersAdded: - await AddMembers(update); - break; - case MessageType.ChatMemberLeft: - await _entityManager.ChatMemberLeft(update.Message); - break; - case MessageType.ChatTitleChanged: - await _entityManager.ChatTitleChanged(update.Message); - break; - case MessageType.MigratedToSupergroup: - await _entityManager.MigrateToSupergroup(update.Message); - break; - case MessageType.MigratedFromGroup: - await _entityManager.MigrateFromGroup(update.Message); - break; - } - } - - return default; - } - - private async Task AddMembers(Update update) - { - foreach (var newUser in update.Message.NewChatMembers) - { - await _entityManager.Handle(newUser, update.Message.Chat); - } - } - } -} \ No newline at end of file From 538600cf31b13cee1eff6fd7bd6d8f6b88bc9cd4 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sun, 12 Dec 2021 19:15:31 +0100 Subject: [PATCH 220/304] style: correct namespace styles --- .../Actions/Messages/CommandAction.cs | 39 +- .../Actions/Messages/MessageAction.cs | 49 +- .../Actions/UnknownAction.cs | 17 +- .../Actions/Updates/CallbackQueryAction.cs | 59 ++- .../Actions/Updates/ChannelCreatedAction.cs | 23 +- .../Actions/Updates/ChannelPostAction.cs | 23 +- .../Updates/ChosenInlineResultAction.cs | 49 +- .../Actions/Updates/DocumentAction.cs | 21 +- .../Actions/Updates/EditedMessageAction.cs | 37 +- .../Actions/Updates/InlineQueryAction.cs | 49 +- .../Actions/Updates/PollAction.cs | 29 +- .../Actions/Updates/PreCheckoutQueryAction.cs | 23 +- .../Actions/Updates/ShippingQueryAction.cs | 23 +- .../Updates/SupergroupCreatedAction.cs | 23 +- .../Entities/TelegramConversation.cs | 31 +- .../Extensions/TelegramUpdateExtensions.cs | 125 +++-- .../SetTelegramBotWebHookHostedService.cs | 71 ++- .../NavigatorContextExtensions.cs | 485 +++++++++--------- ...avigatorProviderConfigurationExtensions.cs | 37 +- .../NavigatorProviderExtensions.cs | 41 +- ...torRouteProviderConfigurationExtensions.cs | 69 ++- .../NavigatorTelegramClient.cs | 47 +- .../NavigatorTelegramProviderOptions.cs | 7 +- ...igatorTelegramProviderOptionsExtensions.cs | 61 ++- .../TelegramMiddleware.cs | 147 +++--- .../TelegramNavigatorProvider.cs | 31 +- src/Navigator/Actions/ActionHandler.cs | 33 +- .../Actions/ActionHandlerExtensions.cs | 7 +- src/Navigator/Actions/ActionLauncher.cs | 107 ++-- src/Navigator/Actions/BaseAction.cs | 51 +- src/Navigator/Actions/IAction.cs | 19 +- src/Navigator/Actions/IActionLauncher.cs | 9 +- src/Navigator/Actions/IActionMiddleware.cs | 17 +- src/Navigator/Actions/Priority.cs | 13 +- src/Navigator/Actions/Status.cs | 19 +- .../EndpointRouteBuilderExtensions.cs | 21 +- .../NavigatorExtensionConfiguration.cs | 51 +- .../Configuration/INavigatorOptions.cs | 23 +- .../Configuration/NavigatorConfiguration.cs | 79 ++- .../Configuration/NavigatorOptions.cs | 81 ++- .../NavigatorOptionsCollectionExtensions.cs | 93 ++-- .../NavigatorRouteConfiguration.cs | 19 +- .../NavigatorProviderConfiguration.cs | 51 +- .../NavigatorRouteProviderConfiguration.cs | 25 +- .../NavigatorContextExtensions.cs | 37 +- .../OriginalEventContextExtension.cs | 17 +- .../Extensions/INavigatorContextExtension.cs | 9 +- src/Navigator/Context/INavigatorContext.cs | 49 +- .../Context/INavigatorContextAccessor.cs | 9 +- .../Context/INavigatorContextBuilder.cs | 9 +- .../INavigatorContextBuilderOptions.cs | 15 +- .../Context/INavigatorContextFactory.cs | 14 +- src/Navigator/Context/NavigatorContext.cs | 52 +- .../Context/NavigatorContextAccessor.cs | 19 +- .../Context/NavigatorContextBuilder.cs | 69 ++- .../Context/NavigatorContextBuilderOptions.cs | 55 +- ...avigatorContextBuilderOptionsExtensions.cs | 73 ++- .../Context/NavigatorContextFactory.cs | 49 +- src/Navigator/Entities/Bot.cs | 9 - src/Navigator/INavigatorClient.cs | 19 +- src/Navigator/INavigatorProvider.cs | 19 +- src/Navigator/NavigatorException.cs | 41 +- src/Navigator/Replies/ReplyBuilderOptions.cs | 7 +- src/Navigator/ServiceCollectionExtensions.cs | 59 ++- 64 files changed, 1439 insertions(+), 1525 deletions(-) diff --git a/src/Navigator.Providers.Telegram/Actions/Messages/CommandAction.cs b/src/Navigator.Providers.Telegram/Actions/Messages/CommandAction.cs index 2401a31..3c3e940 100644 --- a/src/Navigator.Providers.Telegram/Actions/Messages/CommandAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Messages/CommandAction.cs @@ -4,31 +4,30 @@ using Navigator.Providers.Telegram.Entities; using Navigator.Providers.Telegram.Extensions; -namespace Navigator.Providers.Telegram.Actions.Messages +namespace Navigator.Providers.Telegram.Actions.Messages; + +/// +/// Command based action. +/// +[ActionType(nameof(CommandAction))] +public abstract class CommandAction : MessageAction { /// - /// Command based action. + /// Command. /// - [ActionType(nameof(CommandAction))] - public abstract class CommandAction : MessageAction - { - /// - /// Command. - /// - public readonly string Command; + public readonly string Command; - /// - /// Any arguments passed with the command. If no arguments were passed, it will be null. - /// - public readonly string? Arguments; + /// + /// Any arguments passed with the command. If no arguments were passed, it will be null. + /// + public readonly string? Arguments; - /// - protected CommandAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) - { - var botProfile = NavigatorContextAccessor.NavigatorContext.BotProfile; + /// + protected CommandAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) + { + var botProfile = NavigatorContextAccessor.NavigatorContext.BotProfile; - Command = Message.ExtractCommand((botProfile as TelegramBot)?.Username) ?? string.Empty; - Arguments = Message.ExtractArguments(); - } + Command = Message.ExtractCommand((botProfile as TelegramBot)?.Username) ?? string.Empty; + Arguments = Message.ExtractArguments(); } } \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/Actions/Messages/MessageAction.cs b/src/Navigator.Providers.Telegram/Actions/Messages/MessageAction.cs index 1f08805..1d1cb91 100644 --- a/src/Navigator.Providers.Telegram/Actions/Messages/MessageAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Messages/MessageAction.cs @@ -8,37 +8,36 @@ using Navigator.Context.Extensions.Bundled.OriginalEvent; using Telegram.Bot.Types; -namespace Navigator.Providers.Telegram.Actions.Messages +namespace Navigator.Providers.Telegram.Actions.Messages; + +/// +/// A message based action. +/// +[ActionType(nameof(MessageAction))] +public abstract class MessageAction : BaseAction { /// - /// A message based action. + /// The original Message. /// - [ActionType(nameof(MessageAction))] - public abstract class MessageAction : BaseAction - { - /// - /// The original Message. - /// - public Message Message { get; protected set; } + public Message Message { get; protected set; } - /// - /// Determines if this message is a reply to another message. - /// - public bool IsReply { get; protected set; } + /// + /// Determines if this message is a reply to another message. + /// + public bool IsReply { get; protected set; } - /// - /// Determines if this message is a forwarded message. - /// - public bool IsForwarded { get; protected set; } + /// + /// Determines if this message is a forwarded message. + /// + public bool IsForwarded { get; protected set; } - /// - protected MessageAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) - { - var update = navigatorContextAccessor.NavigatorContext.GetOriginalEvent(); + /// + protected MessageAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) + { + var update = navigatorContextAccessor.NavigatorContext.GetOriginalEvent(); - Message = update.Message!; - IsReply = update.Message!.ReplyToMessage is not null; - IsForwarded = update.Message.ForwardDate is not null; - } + Message = update.Message!; + IsReply = update.Message!.ReplyToMessage is not null; + IsForwarded = update.Message.ForwardDate is not null; } } \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/Actions/UnknownAction.cs b/src/Navigator.Providers.Telegram/Actions/UnknownAction.cs index 7affb43..23a568b 100644 --- a/src/Navigator.Providers.Telegram/Actions/UnknownAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/UnknownAction.cs @@ -2,14 +2,13 @@ using Navigator.Actions.Attributes; using Navigator.Context; -namespace Navigator.Providers.Telegram.Actions -{ - [ActionType(nameof(UnknownAction))] - public abstract class UnknownAction : BaseAction - { - /// - protected UnknownAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) - { - } +namespace Navigator.Providers.Telegram.Actions; + +[ActionType(nameof(UnknownAction))] +public abstract class UnknownAction : BaseAction +{ + /// + protected UnknownAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) + { } } \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/CallbackQueryAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/CallbackQueryAction.cs index cc17a45..5944f3d 100644 --- a/src/Navigator.Providers.Telegram/Actions/Updates/CallbackQueryAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/CallbackQueryAction.cs @@ -6,43 +6,42 @@ using Navigator.Context.Extensions.Bundled.OriginalEvent; using Telegram.Bot.Types; -namespace Navigator.Providers.Telegram.Actions.Updates +namespace Navigator.Providers.Telegram.Actions.Updates; + +/// +/// A callback query based action. +/// +[ActionType(nameof(CallbackQueryAction))] +public abstract class CallbackQueryAction : BaseAction { /// - /// A callback query based action. + /// The original /// - [ActionType(nameof(CallbackQueryAction))] - public abstract class CallbackQueryAction : BaseAction - { - /// - /// The original - /// - public CallbackQuery CallbackQuery { get; protected set; } + public CallbackQuery CallbackQuery { get; protected set; } - /// - /// The message that originated the callback query. Iy may be null if the message is too old. - /// - public Message? OriginalMessage { get; protected set; } + /// + /// The message that originated the callback query. Iy may be null if the message is too old. + /// + public Message? OriginalMessage { get; protected set; } - /// - /// Any data present on the callback query. - /// - public string? Data { get; protected set; } + /// + /// Any data present on the callback query. + /// + public string? Data { get; protected set; } - /// - /// True if the callback query is from a game. - /// - public bool IsGameQuery { get; protected set; } + /// + /// True if the callback query is from a game. + /// + public bool IsGameQuery { get; protected set; } - /// - protected CallbackQueryAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) - { - var update = NavigatorContextAccessor.NavigatorContext.GetOriginalEvent(); + /// + protected CallbackQueryAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) + { + var update = NavigatorContextAccessor.NavigatorContext.GetOriginalEvent(); - CallbackQuery = update.CallbackQuery; - OriginalMessage = update.CallbackQuery.Message; - Data = string.IsNullOrWhiteSpace(update.CallbackQuery.Data) ? update.CallbackQuery.Data : default; - IsGameQuery = update.CallbackQuery.IsGameQuery; - } + CallbackQuery = update.CallbackQuery; + OriginalMessage = update.CallbackQuery.Message; + Data = string.IsNullOrWhiteSpace(update.CallbackQuery.Data) ? update.CallbackQuery.Data : default; + IsGameQuery = update.CallbackQuery.IsGameQuery; } } \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/ChannelCreatedAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/ChannelCreatedAction.cs index f4db172..0293ad2 100644 --- a/src/Navigator.Providers.Telegram/Actions/Updates/ChannelCreatedAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/ChannelCreatedAction.cs @@ -2,21 +2,20 @@ using Navigator.Actions.Attributes; using Navigator.Context; -namespace Navigator.Providers.Telegram.Actions.Updates +namespace Navigator.Providers.Telegram.Actions.Updates; + +/// +/// TODO +/// +[ActionType(nameof(ChannelCreatedAction))] +public abstract class ChannelCreatedAction : BaseAction { - /// - /// TODO - /// - [ActionType(nameof(ChannelCreatedAction))] - public abstract class ChannelCreatedAction : BaseAction + /// + protected ChannelCreatedAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) { - /// - protected ChannelCreatedAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) - { - //TODO - } + //TODO + } - } } \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/ChannelPostAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/ChannelPostAction.cs index 7b522a5..2e1a5e7 100644 --- a/src/Navigator.Providers.Telegram/Actions/Updates/ChannelPostAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/ChannelPostAction.cs @@ -2,21 +2,20 @@ using Navigator.Actions.Attributes; using Navigator.Context; -namespace Navigator.Providers.Telegram.Actions.Updates +namespace Navigator.Providers.Telegram.Actions.Updates; + +/// +/// TODO +/// +[ActionType(nameof(ChannelPostAction))] +public abstract class ChannelPostAction : BaseAction { - /// - /// TODO - /// - [ActionType(nameof(ChannelPostAction))] - public abstract class ChannelPostAction : BaseAction + /// + protected ChannelPostAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) { - /// - protected ChannelPostAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) - { - //TODO - } + //TODO + } - } } \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/ChosenInlineResultAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/ChosenInlineResultAction.cs index c3aa02c..8e5a00b 100644 --- a/src/Navigator.Providers.Telegram/Actions/Updates/ChosenInlineResultAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/ChosenInlineResultAction.cs @@ -6,37 +6,36 @@ using Navigator.Context.Extensions.Bundled.OriginalEvent; using Telegram.Bot.Types; -namespace Navigator.Providers.Telegram.Actions.Updates +namespace Navigator.Providers.Telegram.Actions.Updates; + +/// +/// Inline result based action. +/// +[ActionType(nameof(ChosenInlineResultAction))] +public abstract class ChosenInlineResultAction : BaseAction { /// - /// Inline result based action. + /// The original chosen inline result. /// - [ActionType(nameof(ChosenInlineResultAction))] - public abstract class ChosenInlineResultAction : BaseAction - { - /// - /// The original chosen inline result. - /// - public ChosenInlineResult ChosenInlineResult { get; protected set; } + public ChosenInlineResult ChosenInlineResult { get; protected set; } - /// - /// The chosen result id. - /// - public string ResultId { get; protected set; } + /// + /// The chosen result id. + /// + public string ResultId { get; protected set; } - /// - /// The original query. - /// - public string Query { get; protected set; } + /// + /// The original query. + /// + public string Query { get; protected set; } - /// - protected ChosenInlineResultAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) - { - var update = NavigatorContextAccessor.NavigatorContext.GetOriginalEvent(); + /// + protected ChosenInlineResultAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) + { + var update = NavigatorContextAccessor.NavigatorContext.GetOriginalEvent(); - ChosenInlineResult = update.ChosenInlineResult; - ResultId = update.ChosenInlineResult.ResultId; - Query = update.ChosenInlineResult.Query; - } + ChosenInlineResult = update.ChosenInlineResult; + ResultId = update.ChosenInlineResult.ResultId; + Query = update.ChosenInlineResult.Query; } } \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/DocumentAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/DocumentAction.cs index 5fe74a5..d3c8e7a 100644 --- a/src/Navigator.Providers.Telegram/Actions/Updates/DocumentAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/DocumentAction.cs @@ -3,18 +3,17 @@ using Navigator.Actions.Attributes; using Navigator.Context; -namespace Navigator.Providers.Telegram.Actions.Updates +namespace Navigator.Providers.Telegram.Actions.Updates; + +/// +/// TODO +/// +[ActionType(nameof(DocumentAction))] +public abstract class DocumentAction : BaseAction { - /// - /// TODO - /// - [ActionType(nameof(DocumentAction))] - public abstract class DocumentAction : BaseAction + /// + public DocumentAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) { - /// - public DocumentAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) - { - //TODO - } + //TODO } } \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/EditedMessageAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/EditedMessageAction.cs index ded6dfe..022711b 100644 --- a/src/Navigator.Providers.Telegram/Actions/Updates/EditedMessageAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/EditedMessageAction.cs @@ -6,31 +6,30 @@ using Navigator.Context.Extensions.Bundled.OriginalEvent; using Telegram.Bot.Types; -namespace Navigator.Providers.Telegram.Actions.Updates +namespace Navigator.Providers.Telegram.Actions.Updates; + +/// +/// TODO +/// +[ActionType(nameof(EditedMessageAction))] +public abstract class EditedMessageAction : BaseAction { /// /// TODO /// - [ActionType(nameof(EditedMessageAction))] - public abstract class EditedMessageAction : BaseAction - { - /// - /// TODO - /// - public Message OriginalMessage { get; protected set; } + public Message OriginalMessage { get; protected set; } - /// - /// TODO - /// - public Message EditedMessage { get; protected set; } + /// + /// TODO + /// + public Message EditedMessage { get; protected set; } - /// - protected EditedMessageAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) - { - var update = NavigatorContextAccessor.NavigatorContext.GetOriginalEvent(); + /// + protected EditedMessageAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) + { + var update = NavigatorContextAccessor.NavigatorContext.GetOriginalEvent(); - OriginalMessage = update.Message; - EditedMessage = update.EditedMessage; - } + OriginalMessage = update.Message; + EditedMessage = update.EditedMessage; } } \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/InlineQueryAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/InlineQueryAction.cs index be6cc06..b2e7e3f 100644 --- a/src/Navigator.Providers.Telegram/Actions/Updates/InlineQueryAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/InlineQueryAction.cs @@ -6,37 +6,36 @@ using Navigator.Context.Extensions.Bundled.OriginalEvent; using Telegram.Bot.Types; -namespace Navigator.Providers.Telegram.Actions.Updates +namespace Navigator.Providers.Telegram.Actions.Updates; + +/// +/// Inline query based action. +/// +[ActionType(nameof(InlineQueryAction))] +public abstract class InlineQueryAction : BaseAction { /// - /// Inline query based action. + /// The original /// - [ActionType(nameof(InlineQueryAction))] - public abstract class InlineQueryAction : BaseAction - { - /// - /// The original - /// - public InlineQuery InlineQuery { get; protected set; } = null!; + public InlineQuery InlineQuery { get; protected set; } = null!; - /// - /// The query from the user. - /// - public string Query { get; protected set; } = string.Empty; + /// + /// The query from the user. + /// + public string Query { get; protected set; } = string.Empty; - /// - /// The offset. - /// - public string Offset { get; protected set; } = string.Empty; + /// + /// The offset. + /// + public string Offset { get; protected set; } = string.Empty; - /// - protected InlineQueryAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) - { - var update = NavigatorContextAccessor.NavigatorContext.GetOriginalEvent(); + /// + protected InlineQueryAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) + { + var update = NavigatorContextAccessor.NavigatorContext.GetOriginalEvent(); - InlineQuery = update.InlineQuery; - Query = update.InlineQuery.Query; - Offset = update.InlineQuery.Offset; - } + InlineQuery = update.InlineQuery; + Query = update.InlineQuery.Query; + Offset = update.InlineQuery.Offset; } } \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/PollAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/PollAction.cs index 7cebfe0..cda0755 100644 --- a/src/Navigator.Providers.Telegram/Actions/Updates/PollAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/PollAction.cs @@ -6,25 +6,24 @@ using Navigator.Context.Extensions.Bundled.OriginalEvent; using Telegram.Bot.Types; -namespace Navigator.Providers.Telegram.Actions.Updates +namespace Navigator.Providers.Telegram.Actions.Updates; + +/// +/// TODO +/// +[ActionType(nameof(PollAction))] +public abstract class PollAction : BaseAction { /// - /// TODO + /// The original Poll. /// - [ActionType(nameof(PollAction))] - public abstract class PollAction : BaseAction - { - /// - /// The original Poll. - /// - public Poll Poll { get; protected set; } + public Poll Poll { get; protected set; } - /// - protected PollAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) - { - var update = NavigatorContextAccessor.NavigatorContext.GetOriginalEvent(); + /// + protected PollAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) + { + var update = NavigatorContextAccessor.NavigatorContext.GetOriginalEvent(); - Poll = update.Poll; - } + Poll = update.Poll; } } \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/PreCheckoutQueryAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/PreCheckoutQueryAction.cs index ecc362c..aa973e8 100644 --- a/src/Navigator.Providers.Telegram/Actions/Updates/PreCheckoutQueryAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/PreCheckoutQueryAction.cs @@ -2,19 +2,18 @@ using Navigator.Actions.Attributes; using Navigator.Context; -namespace Navigator.Providers.Telegram.Actions.Updates +namespace Navigator.Providers.Telegram.Actions.Updates; + +/// +/// TODO +/// +[ActionType(nameof(PreCheckoutQueryAction))] +public abstract class PreCheckoutQueryAction : BaseAction { - /// - /// TODO - /// - [ActionType(nameof(PreCheckoutQueryAction))] - public abstract class PreCheckoutQueryAction : BaseAction + /// + protected PreCheckoutQueryAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) { - /// - protected PreCheckoutQueryAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) - { - //TODO - } - + //TODO } + } \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/ShippingQueryAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/ShippingQueryAction.cs index 26f4359..a8c6438 100644 --- a/src/Navigator.Providers.Telegram/Actions/Updates/ShippingQueryAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/ShippingQueryAction.cs @@ -2,19 +2,18 @@ using Navigator.Actions.Attributes; using Navigator.Context; -namespace Navigator.Providers.Telegram.Actions.Updates +namespace Navigator.Providers.Telegram.Actions.Updates; + +/// +/// TODO +/// +[ActionType(nameof(ShippingQueryAction))] +public abstract class ShippingQueryAction : BaseAction { - /// - /// TODO - /// - [ActionType(nameof(ShippingQueryAction))] - public abstract class ShippingQueryAction : BaseAction + /// + protected ShippingQueryAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) { - /// - protected ShippingQueryAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) - { - //TODO - } - + //TODO } + } \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/SupergroupCreatedAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/SupergroupCreatedAction.cs index 1e5bc99..d9d4a1e 100644 --- a/src/Navigator.Providers.Telegram/Actions/Updates/SupergroupCreatedAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/SupergroupCreatedAction.cs @@ -2,19 +2,18 @@ using Navigator.Actions.Attributes; using Navigator.Context; -namespace Navigator.Providers.Telegram.Actions.Updates +namespace Navigator.Providers.Telegram.Actions.Updates; + +/// +/// TODO +/// +[ActionType(nameof(SupergroupCreatedAction))] +public abstract class SupergroupCreatedAction : BaseAction { - /// - /// TODO - /// - [ActionType(nameof(SupergroupCreatedAction))] - public abstract class SupergroupCreatedAction : BaseAction + /// + protected SupergroupCreatedAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) { - /// - protected SupergroupCreatedAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) - { - //TODO - } - + //TODO } + } \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/Entities/TelegramConversation.cs b/src/Navigator.Providers.Telegram/Entities/TelegramConversation.cs index a770024..c50bc13 100644 --- a/src/Navigator.Providers.Telegram/Entities/TelegramConversation.cs +++ b/src/Navigator.Providers.Telegram/Entities/TelegramConversation.cs @@ -1,23 +1,22 @@ using Navigator.Entities; -namespace Navigator.Providers.Telegram.Entities +namespace Navigator.Providers.Telegram.Entities; + +public class TelegramConversation : Conversation { - public class TelegramConversation : Conversation + public TelegramConversation(TelegramUser user, TelegramChat chat) : base(user, chat) { - public TelegramConversation(TelegramUser user, TelegramChat chat) : base(user, chat) - { - User = user; - Chat = chat; - } + User = user; + Chat = chat; + } - /// - /// Telegram user. - /// - public new TelegramUser User { get; init; } + /// + /// Telegram user. + /// + public new TelegramUser User { get; init; } - /// - /// Telegram chat. - /// - public new TelegramChat Chat { get; init; } - } + /// + /// Telegram chat. + /// + public new TelegramChat Chat { get; init; } } \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/Extensions/TelegramUpdateExtensions.cs b/src/Navigator.Providers.Telegram/Extensions/TelegramUpdateExtensions.cs index ff0b221..3795653 100644 --- a/src/Navigator.Providers.Telegram/Extensions/TelegramUpdateExtensions.cs +++ b/src/Navigator.Providers.Telegram/Extensions/TelegramUpdateExtensions.cs @@ -6,84 +6,83 @@ using Chat = Telegram.Bot.Types.Chat; using User = Telegram.Bot.Types.User; -namespace Navigator.Providers.Telegram.Extensions +namespace Navigator.Providers.Telegram.Extensions; + +internal static class TelegramUpdateExtensions { - internal static class TelegramUpdateExtensions + public static string? ExtractCommand(this Message message, string? botName) { - public static string? ExtractCommand(this Message message, string? botName) - { - if (message.Entities?.First().Type != MessageEntityType.BotCommand) return default; + if (message.Entities?.First().Type != MessageEntityType.BotCommand) return default; - var command = message.EntityValues?.First(); + var command = message.EntityValues?.First(); - if (command?.Contains('@') == false) return command; + if (command?.Contains('@') == false) return command; - if (botName is not null && !command?.Contains(botName) == true) return default; + if (botName is not null && !command?.Contains(botName) == true) return default; - command = command?[..command.IndexOf('@')]; + command = command?[..command.IndexOf('@')]; - return command; - } + return command; + } - public static string? ExtractArguments(this Message message) - { - return message.Text is not null && message.Text.Contains(' ') - ? message.Text.Remove(0, message.Text.IndexOf(' ') + 1) - : default; - } + public static string? ExtractArguments(this Message message) + { + return message.Text is not null && message.Text.Contains(' ') + ? message.Text.Remove(0, message.Text.IndexOf(' ') + 1) + : default; + } - public static User? GetUserOrDefault(this Update update) + public static User? GetUserOrDefault(this Update update) + { + return update.Type switch { - return update.Type switch - { - UpdateType.Message => update.Message.From, - UpdateType.InlineQuery => update.InlineQuery.From, - UpdateType.ChosenInlineResult => update.ChosenInlineResult.From, - UpdateType.CallbackQuery => update.CallbackQuery.From, - UpdateType.EditedMessage => update.EditedMessage.From, - UpdateType.ChannelPost => update.ChannelPost.From, - UpdateType.EditedChannelPost => update.EditedChannelPost.From, - UpdateType.ShippingQuery => update.ShippingQuery.From, - UpdateType.PreCheckoutQuery => update.PreCheckoutQuery.From, - _ => default - }; - } + UpdateType.Message => update.Message.From, + UpdateType.InlineQuery => update.InlineQuery.From, + UpdateType.ChosenInlineResult => update.ChosenInlineResult.From, + UpdateType.CallbackQuery => update.CallbackQuery.From, + UpdateType.EditedMessage => update.EditedMessage.From, + UpdateType.ChannelPost => update.ChannelPost.From, + UpdateType.EditedChannelPost => update.EditedChannelPost.From, + UpdateType.ShippingQuery => update.ShippingQuery.From, + UpdateType.PreCheckoutQuery => update.PreCheckoutQuery.From, + _ => default + }; + } - public static Chat? GetChatOrDefault(this Update update) + public static Chat? GetChatOrDefault(this Update update) + { + return update.Type switch { - return update.Type switch - { - UpdateType.CallbackQuery => update.CallbackQuery.Message.Chat, - UpdateType.Message => update.Message.Chat, - UpdateType.EditedMessage => update.EditedMessage.Chat, - UpdateType.ChannelPost => update.ChannelPost.Chat, - UpdateType.EditedChannelPost => update.EditedChannelPost.Chat, - _ => default - }; - } + UpdateType.CallbackQuery => update.CallbackQuery.Message.Chat, + UpdateType.Message => update.Message.Chat, + UpdateType.EditedMessage => update.EditedMessage.Chat, + UpdateType.ChannelPost => update.ChannelPost.Chat, + UpdateType.EditedChannelPost => update.EditedChannelPost.Chat, + _ => default + }; + } - public static TelegramConversation GetConversation(this Update update) + public static TelegramConversation GetConversation(this Update update) + { + var user = update.GetUserOrDefault(); + var chat = update.GetChatOrDefault(); + + if (chat is null || user is null) { - var user = update.GetUserOrDefault(); - var chat = update.GetChatOrDefault(); + throw new Exception("TODO NAvigator exception no conversation could be built."); + } - if (chat is null || user is null) + return new TelegramConversation( + new TelegramUser(user.Id) { - throw new Exception("TODO NAvigator exception no conversation could be built."); - } - - return new TelegramConversation( - new TelegramUser(user.Id) - { - Username = user.Username, - FirstName = user.FirstName, - LastName = user.LastName, - LanguageCode = user.LanguageCode - }, - new TelegramChat(chat.Id) - { - Title = chat.Title - }); - } + Username = user.Username, + FirstName = user.FirstName, + LastName = user.LastName, + LanguageCode = user.LanguageCode + }, + new TelegramChat(chat.Id) + { + Title = chat.Title + }); } } \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/Hosted/SetTelegramBotWebHookHostedService.cs b/src/Navigator.Providers.Telegram/Hosted/SetTelegramBotWebHookHostedService.cs index 797f202..938c550 100644 --- a/src/Navigator.Providers.Telegram/Hosted/SetTelegramBotWebHookHostedService.cs +++ b/src/Navigator.Providers.Telegram/Hosted/SetTelegramBotWebHookHostedService.cs @@ -7,53 +7,52 @@ using Navigator.Configuration; using Telegram.Bot; -namespace Navigator.Providers.Telegram.Hosted +namespace Navigator.Providers.Telegram.Hosted; + +/// +/// WebHook service for navigator's telegram provider. +/// +public class SetTelegramBotWebHookHostedService : BackgroundService { + private readonly ILogger _logger; + private readonly IServiceScopeFactory _serviceScopeFactory; + private readonly string _webHookUrl; + /// - /// WebHook service for navigator's telegram provider. + /// Default constructor. /// - public class SetTelegramBotWebHookHostedService : BackgroundService + /// + /// + /// + /// + public SetTelegramBotWebHookHostedService(ILogger logger, IServiceScopeFactory serviceScopeFactory, + NavigatorOptions navigatorOptions) { - private readonly ILogger _logger; - private readonly IServiceScopeFactory _serviceScopeFactory; - private readonly string _webHookUrl; - - /// - /// Default constructor. - /// - /// - /// - /// - /// - public SetTelegramBotWebHookHostedService(ILogger logger, IServiceScopeFactory serviceScopeFactory, - NavigatorOptions navigatorOptions) - { - _logger = logger; - _serviceScopeFactory = serviceScopeFactory; + _logger = logger; + _serviceScopeFactory = serviceScopeFactory; - if (string.IsNullOrWhiteSpace(navigatorOptions.GetWebHookBaseUrl())) - { - throw new ArgumentNullException(nameof(navigatorOptions), "An URL for WebHook is required."); - } - - _webHookUrl = $"{navigatorOptions.GetWebHookBaseUrl()}/{navigatorOptions.GetWebHookEndpointOrDefault()}"; + if (string.IsNullOrWhiteSpace(navigatorOptions.GetWebHookBaseUrl())) + { + throw new ArgumentNullException(nameof(navigatorOptions), "An URL for WebHook is required."); } + + _webHookUrl = $"{navigatorOptions.GetWebHookBaseUrl()}/{navigatorOptions.GetWebHookEndpointOrDefault()}"; + } - /// - protected override async Task ExecuteAsync(CancellationToken stoppingToken) - { - _logger.LogTrace("Starting with setup of webhook."); - _logger.LogTrace("Using webHook url {WebHookUrl}", _webHookUrl); + /// + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + _logger.LogTrace("Starting with setup of webhook."); + _logger.LogTrace("Using webHook url {WebHookUrl}", _webHookUrl); - using var scope = _serviceScopeFactory.CreateScope(); + using var scope = _serviceScopeFactory.CreateScope(); - var navigatorClient = scope.ServiceProvider.GetRequiredService(); + var navigatorClient = scope.ServiceProvider.GetRequiredService(); - await navigatorClient.SetWebhookAsync(_webHookUrl, cancellationToken: stoppingToken); + await navigatorClient.SetWebhookAsync(_webHookUrl, cancellationToken: stoppingToken); - var me = await navigatorClient.GetMeAsync(stoppingToken); + var me = await navigatorClient.GetMeAsync(stoppingToken); - _logger.LogInformation($"Telegram Bot Client is receiving updates for bot: @{me.Username} at the url: {_webHookUrl}"); - } + _logger.LogInformation($"Telegram Bot Client is receiving updates for bot: @{me.Username} at the url: {_webHookUrl}"); } } \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/NavigatorContextExtensions.cs b/src/Navigator.Providers.Telegram/NavigatorContextExtensions.cs index 9bbe198..d7bf0ae 100644 --- a/src/Navigator.Providers.Telegram/NavigatorContextExtensions.cs +++ b/src/Navigator.Providers.Telegram/NavigatorContextExtensions.cs @@ -6,257 +6,256 @@ using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; -namespace Navigator.Providers.Telegram +namespace Navigator.Providers.Telegram; + +/// +/// Useful extensions for Navigator Context. +/// +public static class NavigatorContextExtensions { /// - /// Useful extensions for Navigator Context. + /// TODO /// - public static class NavigatorContextExtensions + /// + /// + public static NavigatorTelegramClient GetTelegramClient(this INavigatorContext context) { - /// - /// TODO - /// - /// - /// - public static NavigatorTelegramClient GetTelegramClient(this INavigatorContext context) - { - return context.Provider.GetTelegramClient(); - } + return context.Provider.GetTelegramClient(); + } - // #region TelegramUser - // - // /// - // /// Get a Telegram user. - // /// - // /// - // /// When user is not found. - // /// - // public static User GetTelegramUser(this INavigatorContext ctx) - // { - // var user = ctx.GetTelegramUserOrDefault(); - // - // return user ?? throw new Exception("User not found in update."); - // } - // - // /// - // /// Get a Telegram user or default if not found. - // /// - // /// - // /// - // public static User? GetTelegramUserOrDefault(this INavigatorContext ctx) - // { - // return ctx.Update.Type switch - // { - // UpdateType.Message => ctx.Update.Message.From, - // UpdateType.InlineQuery => ctx.Update.InlineQuery.From, - // UpdateType.ChosenInlineResult => ctx.Update.ChosenInlineResult.From, - // UpdateType.CallbackQuery => ctx.Update.CallbackQuery.From, - // UpdateType.EditedMessage => ctx.Update.EditedMessage.From, - // UpdateType.ChannelPost => ctx.Update.ChannelPost.From, - // UpdateType.EditedChannelPost => ctx.Update.EditedChannelPost.From, - // UpdateType.ShippingQuery => ctx.Update.ShippingQuery.From, - // UpdateType.PreCheckoutQuery => ctx.Update.PreCheckoutQuery.From, - // _ => default - // }; - // } - // - // #endregion - // - #region Chat + // #region TelegramUser + // + // /// + // /// Get a Telegram user. + // /// + // /// + // /// When user is not found. + // /// + // public static User GetTelegramUser(this INavigatorContext ctx) + // { + // var user = ctx.GetTelegramUserOrDefault(); + // + // return user ?? throw new Exception("User not found in update."); + // } + // + // /// + // /// Get a Telegram user or default if not found. + // /// + // /// + // /// + // public static User? GetTelegramUserOrDefault(this INavigatorContext ctx) + // { + // return ctx.Update.Type switch + // { + // UpdateType.Message => ctx.Update.Message.From, + // UpdateType.InlineQuery => ctx.Update.InlineQuery.From, + // UpdateType.ChosenInlineResult => ctx.Update.ChosenInlineResult.From, + // UpdateType.CallbackQuery => ctx.Update.CallbackQuery.From, + // UpdateType.EditedMessage => ctx.Update.EditedMessage.From, + // UpdateType.ChannelPost => ctx.Update.ChannelPost.From, + // UpdateType.EditedChannelPost => ctx.Update.EditedChannelPost.From, + // UpdateType.ShippingQuery => ctx.Update.ShippingQuery.From, + // UpdateType.PreCheckoutQuery => ctx.Update.PreCheckoutQuery.From, + // _ => default + // }; + // } + // + // #endregion + // + #region Chat - /// - /// Gets a . - /// - /// - /// When chat is not found. - /// - public static Chat GetTelegramChat(this INavigatorContext ctx) - { - var chat = ctx.GetTelegramChatOrDefault(); + /// + /// Gets a . + /// + /// + /// When chat is not found. + /// + public static Chat GetTelegramChat(this INavigatorContext ctx) + { + var chat = ctx.GetTelegramChatOrDefault(); - return chat ?? throw new Exception("Chat was not found."); - } + return chat ?? throw new Exception("Chat was not found."); + } - /// - /// Get a Telegram chat or default if not found. - /// - /// - /// Telegram Chat - public static Chat? GetTelegramChatOrDefault(this INavigatorContext ctx) + /// + /// Get a Telegram chat or default if not found. + /// + /// + /// Telegram Chat + public static Chat? GetTelegramChatOrDefault(this INavigatorContext ctx) + { + return ctx.GetOriginalEventOrDefault()?.Type switch { - return ctx.GetOriginalEventOrDefault()?.Type switch - { - UpdateType.CallbackQuery => ctx.GetOriginalEvent().CallbackQuery?.Message?.Chat, - UpdateType.Message => ctx.GetOriginalEvent().Message?.Chat, - UpdateType.EditedMessage => ctx.GetOriginalEvent().EditedMessage?.Chat, - UpdateType.ChannelPost => ctx.GetOriginalEvent().ChannelPost?.Chat, - UpdateType.EditedChannelPost => ctx.GetOriginalEvent().EditedChannelPost?.Chat, - _ => default - }; - } - - #endregion - // - // #region Message - // - // /// - // /// Get a Telegram message. - // /// - // /// - // /// When message is not found. - // /// - // public static Message GetMessage(this INavigatorContext ctx) - // { - // return ctx.GetMessageOrDefault() ?? throw new Exception("Message not found in update."); - // } - // - // /// - // /// Get a Telegram message or default if not found. - // /// - // /// - // /// - // public static Message? GetMessageOrDefault(this INavigatorContext ctx) - // { - // return ctx.Update.Type == UpdateType.Message ? ctx.Update.Message : default; - // } - // - // #endregion - // - // #region InlineQuery - // - // /// - // /// Get a Telegram inline query - // /// - // /// - // /// When inline query is not found. - // /// - // public static InlineQuery GetInlineQuery(this INavigatorContext ctx) - // { - // return ctx.GetInlineQueryOrDefault() ?? throw new Exception("InlineQuery not found in update."); - // } - // - // /// - // /// Get a Telegram inline query or default if not found. - // /// - // /// - // /// - // public static InlineQuery? GetInlineQueryOrDefault(this INavigatorContext ctx) - // { - // return ctx.Update.Type == UpdateType.InlineQuery ? ctx.Update.InlineQuery : default; - // } - // - // #endregion - // - // #region ChosenInlineResult - // - // public static ChosenInlineResult GetChosenInlineResult(this INavigatorContext ctx) - // { - // return ctx.GetChosenInlineResultOrDefault() ?? throw new Exception("ChosenInlineResult not found in update."); - // } - // - // public static ChosenInlineResult? GetChosenInlineResultOrDefault(this INavigatorContext ctx) - // { - // return ctx.Update.Type == UpdateType.ChosenInlineResult ? ctx.Update.ChosenInlineResult : default; - // } - // - // #endregion - // - // #region CallbackQuery - // - // public static CallbackQuery GetCallbackQuery(this INavigatorContext ctx) - // { - // return ctx.GetCallbackQueryOrDefault() ?? throw new Exception("CallbackQuery not found in update."); - // } - // - // public static CallbackQuery? GetCallbackQueryOrDefault(this INavigatorContext ctx) - // { - // return ctx.Update.Type == UpdateType.CallbackQuery ? ctx.Update.CallbackQuery : default; - // } - // - // #endregion - // - // #region EditedMessage - // - // public static Message GetEditedMessage(this INavigatorContext ctx) - // { - // return ctx.GetEditedMessageOrDefault() ?? throw new Exception("EditedMessage not found in update."); - // } - // - // public static Message? GetEditedMessageOrDefault(this INavigatorContext ctx) - // { - // return ctx.Update.Type == UpdateType.EditedMessage ? ctx.Update.EditedMessage : default; - // } - // - // #endregion - // - // #region ChannelPost - // - // public static Message GetChannelPost(this INavigatorContext ctx) - // { - // return ctx.GetChannelPostOrDefault() ?? throw new Exception("ChannelPost not found in update."); - // } - // - // public static Message? GetChannelPostOrDefault(this INavigatorContext ctx) - // { - // return ctx.Update.Type == UpdateType.ChannelPost ? ctx.Update.ChannelPost : default; - // } - // - // #endregion - // - // #region EditedChannelPost - // - // public static Message GetEditedChannelPost(this INavigatorContext ctx) - // { - // return ctx.GetEditedChannelPostOrDefault() ?? throw new Exception("EditedChannelPost not found in update."); - // } - // - // public static Message? GetEditedChannelPostOrDefault(this INavigatorContext ctx) - // { - // return ctx.Update.Type == UpdateType.EditedChannelPost ? ctx.Update.EditedChannelPost : default; - // } - // - // #endregion - // - // #region ShippingQuery - // - // public static ShippingQuery GetShippingQuery(this INavigatorContext ctx) - // { - // return ctx.GetShippingQueryOrDefault() ?? throw new Exception("ShippingQuery not found in update."); - // } - // - // public static ShippingQuery? GetShippingQueryOrDefault(this INavigatorContext ctx) - // { - // return ctx.Update.Type == UpdateType.ShippingQuery ? ctx.Update.ShippingQuery : default; - // } - // - // #endregion - // - // #region PreCheckoutQuery - // - // public static PreCheckoutQuery GetPreCheckoutQuery(this INavigatorContext ctx) - // { - // return ctx.GetPreCheckoutQueryOrDefault() ?? throw new Exception("PreCheckoutQuery not found in update."); - // } - // - // public static PreCheckoutQuery? GetPreCheckoutQueryOrDefault(this INavigatorContext ctx) - // { - // return ctx.Update.Type == UpdateType.PreCheckoutQuery ? ctx.Update.PreCheckoutQuery : default; - // } - // - // #endregion - // - // #region Poll - // - // public static Poll GetPoll(this INavigatorContext ctx) - // { - // return ctx.GetPollOrDefault() ?? throw new Exception("Poll not found in update."); - // } - // - // public static Poll? GetPollOrDefault(this INavigatorContext ctx) - // { - // return ctx.Update.Type == UpdateType.Poll ? ctx.Update.Poll : default; - // } - // - // #endregion + UpdateType.CallbackQuery => ctx.GetOriginalEvent().CallbackQuery?.Message?.Chat, + UpdateType.Message => ctx.GetOriginalEvent().Message?.Chat, + UpdateType.EditedMessage => ctx.GetOriginalEvent().EditedMessage?.Chat, + UpdateType.ChannelPost => ctx.GetOriginalEvent().ChannelPost?.Chat, + UpdateType.EditedChannelPost => ctx.GetOriginalEvent().EditedChannelPost?.Chat, + _ => default + }; } + + #endregion + // + // #region Message + // + // /// + // /// Get a Telegram message. + // /// + // /// + // /// When message is not found. + // /// + // public static Message GetMessage(this INavigatorContext ctx) + // { + // return ctx.GetMessageOrDefault() ?? throw new Exception("Message not found in update."); + // } + // + // /// + // /// Get a Telegram message or default if not found. + // /// + // /// + // /// + // public static Message? GetMessageOrDefault(this INavigatorContext ctx) + // { + // return ctx.Update.Type == UpdateType.Message ? ctx.Update.Message : default; + // } + // + // #endregion + // + // #region InlineQuery + // + // /// + // /// Get a Telegram inline query + // /// + // /// + // /// When inline query is not found. + // /// + // public static InlineQuery GetInlineQuery(this INavigatorContext ctx) + // { + // return ctx.GetInlineQueryOrDefault() ?? throw new Exception("InlineQuery not found in update."); + // } + // + // /// + // /// Get a Telegram inline query or default if not found. + // /// + // /// + // /// + // public static InlineQuery? GetInlineQueryOrDefault(this INavigatorContext ctx) + // { + // return ctx.Update.Type == UpdateType.InlineQuery ? ctx.Update.InlineQuery : default; + // } + // + // #endregion + // + // #region ChosenInlineResult + // + // public static ChosenInlineResult GetChosenInlineResult(this INavigatorContext ctx) + // { + // return ctx.GetChosenInlineResultOrDefault() ?? throw new Exception("ChosenInlineResult not found in update."); + // } + // + // public static ChosenInlineResult? GetChosenInlineResultOrDefault(this INavigatorContext ctx) + // { + // return ctx.Update.Type == UpdateType.ChosenInlineResult ? ctx.Update.ChosenInlineResult : default; + // } + // + // #endregion + // + // #region CallbackQuery + // + // public static CallbackQuery GetCallbackQuery(this INavigatorContext ctx) + // { + // return ctx.GetCallbackQueryOrDefault() ?? throw new Exception("CallbackQuery not found in update."); + // } + // + // public static CallbackQuery? GetCallbackQueryOrDefault(this INavigatorContext ctx) + // { + // return ctx.Update.Type == UpdateType.CallbackQuery ? ctx.Update.CallbackQuery : default; + // } + // + // #endregion + // + // #region EditedMessage + // + // public static Message GetEditedMessage(this INavigatorContext ctx) + // { + // return ctx.GetEditedMessageOrDefault() ?? throw new Exception("EditedMessage not found in update."); + // } + // + // public static Message? GetEditedMessageOrDefault(this INavigatorContext ctx) + // { + // return ctx.Update.Type == UpdateType.EditedMessage ? ctx.Update.EditedMessage : default; + // } + // + // #endregion + // + // #region ChannelPost + // + // public static Message GetChannelPost(this INavigatorContext ctx) + // { + // return ctx.GetChannelPostOrDefault() ?? throw new Exception("ChannelPost not found in update."); + // } + // + // public static Message? GetChannelPostOrDefault(this INavigatorContext ctx) + // { + // return ctx.Update.Type == UpdateType.ChannelPost ? ctx.Update.ChannelPost : default; + // } + // + // #endregion + // + // #region EditedChannelPost + // + // public static Message GetEditedChannelPost(this INavigatorContext ctx) + // { + // return ctx.GetEditedChannelPostOrDefault() ?? throw new Exception("EditedChannelPost not found in update."); + // } + // + // public static Message? GetEditedChannelPostOrDefault(this INavigatorContext ctx) + // { + // return ctx.Update.Type == UpdateType.EditedChannelPost ? ctx.Update.EditedChannelPost : default; + // } + // + // #endregion + // + // #region ShippingQuery + // + // public static ShippingQuery GetShippingQuery(this INavigatorContext ctx) + // { + // return ctx.GetShippingQueryOrDefault() ?? throw new Exception("ShippingQuery not found in update."); + // } + // + // public static ShippingQuery? GetShippingQueryOrDefault(this INavigatorContext ctx) + // { + // return ctx.Update.Type == UpdateType.ShippingQuery ? ctx.Update.ShippingQuery : default; + // } + // + // #endregion + // + // #region PreCheckoutQuery + // + // public static PreCheckoutQuery GetPreCheckoutQuery(this INavigatorContext ctx) + // { + // return ctx.GetPreCheckoutQueryOrDefault() ?? throw new Exception("PreCheckoutQuery not found in update."); + // } + // + // public static PreCheckoutQuery? GetPreCheckoutQueryOrDefault(this INavigatorContext ctx) + // { + // return ctx.Update.Type == UpdateType.PreCheckoutQuery ? ctx.Update.PreCheckoutQuery : default; + // } + // + // #endregion + // + // #region Poll + // + // public static Poll GetPoll(this INavigatorContext ctx) + // { + // return ctx.GetPollOrDefault() ?? throw new Exception("Poll not found in update."); + // } + // + // public static Poll? GetPollOrDefault(this INavigatorContext ctx) + // { + // return ctx.Update.Type == UpdateType.Poll ? ctx.Update.Poll : default; + // } + // + // #endregion } \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/NavigatorProviderConfigurationExtensions.cs b/src/Navigator.Providers.Telegram/NavigatorProviderConfigurationExtensions.cs index 50a50fa..108b416 100644 --- a/src/Navigator.Providers.Telegram/NavigatorProviderConfigurationExtensions.cs +++ b/src/Navigator.Providers.Telegram/NavigatorProviderConfigurationExtensions.cs @@ -5,32 +5,31 @@ using Navigator.Context; using Navigator.Providers.Telegram.Hosted; -namespace Navigator.Providers.Telegram +namespace Navigator.Providers.Telegram; + +public static class NavigatorProviderConfigurationExtensions { - public static class NavigatorProviderConfigurationExtensions + public static NavigatorConfiguration Telegram(this NavigatorProviderConfiguration providerConfiguration, + Action options) { - public static NavigatorConfiguration Telegram(this NavigatorProviderConfiguration providerConfiguration, - Action options) - { - var telegramProviderOptions = new NavigatorTelegramProviderOptions(); - options.Invoke(telegramProviderOptions); + var telegramProviderOptions = new NavigatorTelegramProviderOptions(); + options.Invoke(telegramProviderOptions); - return providerConfiguration.Provider( - optionsAction => optionsAction.Import(telegramProviderOptions.RetrieveAllOptions()), - services => - { - services.AddSingleton(); - services.AddSingleton(sp => sp.GetRequiredService()); + return providerConfiguration.Provider( + optionsAction => optionsAction.Import(telegramProviderOptions.RetrieveAllOptions()), + services => + { + services.AddSingleton(); + services.AddSingleton(sp => sp.GetRequiredService()); - services.AddScoped(); + services.AddScoped(); - services.AddScoped(); + services.AddScoped(); - services.AddScoped(); + services.AddScoped(); - services.AddHostedService(); + services.AddHostedService(); - }); - } + }); } } \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/NavigatorProviderExtensions.cs b/src/Navigator.Providers.Telegram/NavigatorProviderExtensions.cs index 2fbbc51..642f2ea 100644 --- a/src/Navigator.Providers.Telegram/NavigatorProviderExtensions.cs +++ b/src/Navigator.Providers.Telegram/NavigatorProviderExtensions.cs @@ -1,35 +1,34 @@ using System; -namespace Navigator.Providers.Telegram +namespace Navigator.Providers.Telegram; + +public static class NavigatorProviderExtensions { - public static class NavigatorProviderExtensions + public static NavigatorTelegramClient GetTelegramClient(this INavigatorProvider provider) { - public static NavigatorTelegramClient GetTelegramClient(this INavigatorProvider provider) - { - var client = provider.GetTelegramClientOrDefault(); - - if (client is not null) - { - return client; - } + var client = provider.GetTelegramClientOrDefault(); - throw new Exception($"Navigator client was not of type {nameof(NavigatorTelegramClient)}") - { - Data = - { - {nameof(Type), provider.GetClient().GetType()} - } - }; + if (client is not null) + { + return client; } - public static NavigatorTelegramClient? GetTelegramClientOrDefault(this INavigatorProvider provider) + throw new Exception($"Navigator client was not of type {nameof(NavigatorTelegramClient)}") { - if (provider.GetClient() is NavigatorTelegramClient navigatorTelegramClient) + Data = { - return navigatorTelegramClient; + {nameof(Type), provider.GetClient().GetType()} } + }; + } - return default; + public static NavigatorTelegramClient? GetTelegramClientOrDefault(this INavigatorProvider provider) + { + if (provider.GetClient() is NavigatorTelegramClient navigatorTelegramClient) + { + return navigatorTelegramClient; } + + return default; } } \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/NavigatorRouteProviderConfigurationExtensions.cs b/src/Navigator.Providers.Telegram/NavigatorRouteProviderConfigurationExtensions.cs index d458bc6..0891d02 100644 --- a/src/Navigator.Providers.Telegram/NavigatorRouteProviderConfigurationExtensions.cs +++ b/src/Navigator.Providers.Telegram/NavigatorRouteProviderConfigurationExtensions.cs @@ -8,54 +8,53 @@ using Newtonsoft.Json; using Telegram.Bot.Types; -namespace Navigator.Providers.Telegram +namespace Navigator.Providers.Telegram; + +public static class NavigatorRouteProviderConfigurationExtensions { - public static class NavigatorRouteProviderConfigurationExtensions + public static NavigatorRouteConfiguration Telegram(this NavigatorRouteProviderConfiguration routeProviderConfiguration) { - public static NavigatorRouteConfiguration Telegram(this NavigatorRouteProviderConfiguration routeProviderConfiguration) + return routeProviderConfiguration.Provider(builder => { - return routeProviderConfiguration.Provider(builder => - { - using var scope = builder.ServiceProvider.CreateScope(); + using var scope = builder.ServiceProvider.CreateScope(); - var options = scope.ServiceProvider.GetRequiredService(); + var options = scope.ServiceProvider.GetRequiredService(); - builder.MapPost(options.GetWebHookEndpointOrDefault(), ProcessTelegramUpdate); - }); - } + builder.MapPost(options.GetWebHookEndpointOrDefault(), ProcessTelegramUpdate); + }); + } - private static async Task ProcessTelegramUpdate(HttpContext context) - { - context.Response.StatusCode = 200; + private static async Task ProcessTelegramUpdate(HttpContext context) + { + context.Response.StatusCode = 200; - if (context.Request.ContentType != "application/json") - { - return; - } + if (context.Request.ContentType != "application/json") + { + return; + } - var telegramUpdate = await ParseTelegramUpdate(context.Request.Body); + var telegramUpdate = await ParseTelegramUpdate(context.Request.Body); - if (telegramUpdate is not null) - { - var navigatorMiddleware = context.RequestServices.GetRequiredService(); + if (telegramUpdate is not null) + { + var navigatorMiddleware = context.RequestServices.GetRequiredService(); - await navigatorMiddleware.Process(telegramUpdate); - } + await navigatorMiddleware.Process(telegramUpdate); } + } - private static async Task ParseTelegramUpdate(Stream stream) + private static async Task ParseTelegramUpdate(Stream stream) + { + try + { + var reader = new StreamReader(stream); + var update = JsonConvert.DeserializeObject(await reader.ReadToEndAsync()); + + return update.Id == default ? default : update; + } + catch { - try - { - var reader = new StreamReader(stream); - var update = JsonConvert.DeserializeObject(await reader.ReadToEndAsync()); - - return update.Id == default ? default : update; - } - catch - { - return default; - } + return default; } } } \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/NavigatorTelegramClient.cs b/src/Navigator.Providers.Telegram/NavigatorTelegramClient.cs index bc815e3..0137232 100644 --- a/src/Navigator.Providers.Telegram/NavigatorTelegramClient.cs +++ b/src/Navigator.Providers.Telegram/NavigatorTelegramClient.cs @@ -6,33 +6,32 @@ using Navigator.Providers.Telegram.Entities; using Telegram.Bot; -namespace Navigator.Providers.Telegram +namespace Navigator.Providers.Telegram; + +public class NavigatorTelegramClient : TelegramBotClient, INavigatorClient { - public class NavigatorTelegramClient : TelegramBotClient, INavigatorClient + /// + /// Builds a . + /// + /// + public NavigatorTelegramClient(INavigatorOptions options) + : base(options.GetTelegramToken() ?? throw new ArgumentNullException()) { - /// - /// Builds a . - /// - /// - public NavigatorTelegramClient(INavigatorOptions options) - : base(options.GetTelegramToken() ?? throw new ArgumentNullException()) - { - } + } - /// - public async Task GetProfile(CancellationToken cancellationToken = default) - { - var bot = await this.GetMeAsync(cancellationToken); + /// + public async Task GetProfile(CancellationToken cancellationToken = default) + { + var bot = await this.GetMeAsync(cancellationToken); - return new TelegramBot(bot.Id) - { - Username = bot.Username!, - FirstName = bot.FirstName, - LastName = bot.LastName, - CanJoinGroups = bot.CanJoinGroups, - CanReadAllGroupMessages = bot.CanReadAllGroupMessages, - SupportsInlineQueries = bot.SupportsInlineQueries - }; - } + return new TelegramBot(bot.Id) + { + Username = bot.Username!, + FirstName = bot.FirstName, + LastName = bot.LastName, + CanJoinGroups = bot.CanJoinGroups, + CanReadAllGroupMessages = bot.CanReadAllGroupMessages, + SupportsInlineQueries = bot.SupportsInlineQueries + }; } } \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/NavigatorTelegramProviderOptions.cs b/src/Navigator.Providers.Telegram/NavigatorTelegramProviderOptions.cs index bbcf8c2..007f5f5 100644 --- a/src/Navigator.Providers.Telegram/NavigatorTelegramProviderOptions.cs +++ b/src/Navigator.Providers.Telegram/NavigatorTelegramProviderOptions.cs @@ -1,9 +1,8 @@ using Navigator.Configuration; -namespace Navigator.Providers.Telegram +namespace Navigator.Providers.Telegram; + +public class NavigatorTelegramProviderOptions : NavigatorOptions { - public class NavigatorTelegramProviderOptions : NavigatorOptions - { - } } \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/NavigatorTelegramProviderOptionsExtensions.cs b/src/Navigator.Providers.Telegram/NavigatorTelegramProviderOptionsExtensions.cs index 05197c4..c4a88aa 100644 --- a/src/Navigator.Providers.Telegram/NavigatorTelegramProviderOptionsExtensions.cs +++ b/src/Navigator.Providers.Telegram/NavigatorTelegramProviderOptionsExtensions.cs @@ -1,48 +1,47 @@ using System; using Navigator.Configuration; -namespace Navigator.Providers.Telegram +namespace Navigator.Providers.Telegram; + +public static class NavigatorTelegramProviderOptionsExtensions { - public static class NavigatorTelegramProviderOptionsExtensions - { - #region TelegramToken + #region TelegramToken - private const string TelegramTokenKey = "_navigator.options.telegram.telegram_token"; + private const string TelegramTokenKey = "_navigator.options.telegram.telegram_token"; - public static void SetTelegramToken(this NavigatorTelegramProviderOptions navigatorOptions, string telegramToken) - { - navigatorOptions.TryRegisterOption(TelegramTokenKey, telegramToken); + public static void SetTelegramToken(this NavigatorTelegramProviderOptions navigatorOptions, string telegramToken) + { + navigatorOptions.TryRegisterOption(TelegramTokenKey, telegramToken); - } + } - public static string? GetTelegramToken(this INavigatorOptions navigatorOptions) - { - return navigatorOptions.RetrieveOption(TelegramTokenKey); - } + public static string? GetTelegramToken(this INavigatorOptions navigatorOptions) + { + return navigatorOptions.RetrieveOption(TelegramTokenKey); + } - #endregion + #endregion - #region WebHookEndpoint + #region WebHookEndpoint - private const string WebHookEndpointKey = "_navigator.options.telegram.webhook_endpoint"; + private const string WebHookEndpointKey = "_navigator.options.telegram.webhook_endpoint"; - public static void SetWebHookEndpoint(this NavigatorTelegramProviderOptions navigatorOptions, string webHookEndpoint) - { - navigatorOptions.TryRegisterOption(WebHookEndpointKey, webHookEndpoint); - } + public static void SetWebHookEndpoint(this NavigatorTelegramProviderOptions navigatorOptions, string webHookEndpoint) + { + navigatorOptions.TryRegisterOption(WebHookEndpointKey, webHookEndpoint); + } - public static string GetWebHookEndpointOrDefault(this INavigatorOptions navigatorOptions) - { - var webHookEndpoint = navigatorOptions.RetrieveOption(WebHookEndpointKey); + public static string GetWebHookEndpointOrDefault(this INavigatorOptions navigatorOptions) + { + var webHookEndpoint = navigatorOptions.RetrieveOption(WebHookEndpointKey); - if (webHookEndpoint is null) - { - navigatorOptions.TryRegisterOption(WebHookEndpointKey,$"telegram/bot/{Guid.NewGuid()}"); - } - - return navigatorOptions.RetrieveOption(WebHookEndpointKey)!; + if (webHookEndpoint is null) + { + navigatorOptions.TryRegisterOption(WebHookEndpointKey,$"telegram/bot/{Guid.NewGuid()}"); } - - #endregion + + return navigatorOptions.RetrieveOption(WebHookEndpointKey)!; } + + #endregion } \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/TelegramMiddleware.cs b/src/Navigator.Providers.Telegram/TelegramMiddleware.cs index e87efa3..3538b9e 100644 --- a/src/Navigator.Providers.Telegram/TelegramMiddleware.cs +++ b/src/Navigator.Providers.Telegram/TelegramMiddleware.cs @@ -11,89 +11,88 @@ using Telegram.Bot.Types.Enums; using Telegram.Bot.Types.Payments; -namespace Navigator.Providers.Telegram +namespace Navigator.Providers.Telegram; + +public class TelegramMiddleware { - public class TelegramMiddleware + private readonly ILogger _logger; + private readonly INavigatorContextFactory _navigatorContextFactory; + private readonly IActionLauncher _actionLauncher; + + public TelegramMiddleware(ILogger logger, INavigatorContextFactory navigatorContextFactory, IActionLauncher actionLauncher) { - private readonly ILogger _logger; - private readonly INavigatorContextFactory _navigatorContextFactory; - private readonly IActionLauncher _actionLauncher; + _logger = logger; + _navigatorContextFactory = navigatorContextFactory; + _actionLauncher = actionLauncher; + } - public TelegramMiddleware(ILogger logger, INavigatorContextFactory navigatorContextFactory, IActionLauncher actionLauncher) - { - _logger = logger; - _navigatorContextFactory = navigatorContextFactory; - _actionLauncher = actionLauncher; - } + public async Task Process(Update update) + { + var actionType = DefineActionType(update); - public async Task Process(Update update) + if (actionType is null) { - var actionType = DefineActionType(update); - - if (actionType is null) - { - return; - } + return; + } - await _navigatorContextFactory.Supply(builder => - { - builder.SetProvider(); - builder.SetActionType(actionType); - builder.SetOriginalEvent(update); - }); + await _navigatorContextFactory.Supply(builder => + { + builder.SetProvider(); + builder.SetActionType(actionType); + builder.SetOriginalEvent(update); + }); - await _actionLauncher.Launch(); - } + await _actionLauncher.Launch(); + } - private static string? DefineActionType(Update update) + private static string? DefineActionType(Update update) + { + return update.Type switch { - return update.Type switch + UpdateType.Message when update.Message?.Entities?.First().Type == MessageEntityType.BotCommand => nameof(CommandAction), + UpdateType.Message => update.Message?.Type switch { - UpdateType.Message when update.Message?.Entities?.First().Type == MessageEntityType.BotCommand => nameof(CommandAction), - UpdateType.Message => update.Message?.Type switch - { - MessageType.Document => nameof(DocumentAction), - // MessageType.Location => ActionType.ChatMembersAdded, - // MessageType.Contact => ActionType.ChatMembersAdded, - // MessageType.Game => ActionType.ChatMembersAdded, - // MessageType.Invoice => ActionType.ChatMembersAdded, - // MessageType.SuccessfulPayment => ActionType.ChatMembersAdded, - // MessageType.WebsiteConnected => ActionType.ChatMembersAdded, - // MessageType.ChatMembersAdded => ActionType.ChatMembersAdded, - // MessageType.ChatMemberLeft => ActionType.ChatMemberLeft, - // MessageType.ChatTitleChanged => ActionType.ChatTitleChanged, - // MessageType.ChatPhotoChanged => ActionType.ChatPhotoChanged, - // MessageType.MessagePinned => ActionType.MessagePinned, - // MessageType.ChatPhotoDeleted => ActionType.ChatPhotoDeleted, - // MessageType.GroupCreated => ActionType.GroupCreated, - MessageType.SupergroupCreated => nameof(SupergroupCreatedAction), - MessageType.ChannelCreated => nameof(ChannelCreatedAction), - // MessageType.MigratedToSupergroup => ActionType.MigratedToSupergroup, - // MessageType.MigratedFromGroup => ActionType.MigratedFromGroup, - // MessageType.Dice => ActionType.MigratedFromGroup, - // MessageType.MessageAutoDeleteTimerChanged => ActionType.MigratedFromGroup, - // MessageType.ProximityAlertTriggered => ActionType.MigratedFromGroup, - // MessageType.VoiceChatScheduled => ActionType.MigratedFromGroup, - // MessageType.VoiceChatStarted => ActionType.MigratedFromGroup, - // MessageType.VoiceChatEnded => ActionType.MigratedFromGroup, - // MessageType.VoiceChatParticipantsInvited => ActionType.MigratedFromGroup, - _ => nameof(MessageAction), - }, - UpdateType.InlineQuery => nameof(InlineQueryAction), - UpdateType.ChosenInlineResult => nameof(ChosenInlineResultAction), - UpdateType.CallbackQuery => nameof(CallbackQueryAction), - UpdateType.EditedMessage => nameof(EditedMessageAction), - UpdateType.ChannelPost => nameof(ChannelPostAction), - // UpdateType.EditedChannelPost => ActionType.EditedChannelPost, - UpdateType.ShippingQuery => nameof(ShippingQueryAction), - UpdateType.PreCheckoutQuery => nameof(PreCheckoutQuery), - UpdateType.Poll => nameof(PollAction), - // UpdateType.PollAnswer => typeof(PollAction).FullName, - // UpdateType.MyChatMember => typeof(UnknownAction).FullName, - // UpdateType.ChatMember => typeof(UnknownAction).FullName, - UpdateType.Unknown => nameof(UnknownAction), - _ => default - }; - } + MessageType.Document => nameof(DocumentAction), + // MessageType.Location => ActionType.ChatMembersAdded, + // MessageType.Contact => ActionType.ChatMembersAdded, + // MessageType.Game => ActionType.ChatMembersAdded, + // MessageType.Invoice => ActionType.ChatMembersAdded, + // MessageType.SuccessfulPayment => ActionType.ChatMembersAdded, + // MessageType.WebsiteConnected => ActionType.ChatMembersAdded, + // MessageType.ChatMembersAdded => ActionType.ChatMembersAdded, + // MessageType.ChatMemberLeft => ActionType.ChatMemberLeft, + // MessageType.ChatTitleChanged => ActionType.ChatTitleChanged, + // MessageType.ChatPhotoChanged => ActionType.ChatPhotoChanged, + // MessageType.MessagePinned => ActionType.MessagePinned, + // MessageType.ChatPhotoDeleted => ActionType.ChatPhotoDeleted, + // MessageType.GroupCreated => ActionType.GroupCreated, + MessageType.SupergroupCreated => nameof(SupergroupCreatedAction), + MessageType.ChannelCreated => nameof(ChannelCreatedAction), + // MessageType.MigratedToSupergroup => ActionType.MigratedToSupergroup, + // MessageType.MigratedFromGroup => ActionType.MigratedFromGroup, + // MessageType.Dice => ActionType.MigratedFromGroup, + // MessageType.MessageAutoDeleteTimerChanged => ActionType.MigratedFromGroup, + // MessageType.ProximityAlertTriggered => ActionType.MigratedFromGroup, + // MessageType.VoiceChatScheduled => ActionType.MigratedFromGroup, + // MessageType.VoiceChatStarted => ActionType.MigratedFromGroup, + // MessageType.VoiceChatEnded => ActionType.MigratedFromGroup, + // MessageType.VoiceChatParticipantsInvited => ActionType.MigratedFromGroup, + _ => nameof(MessageAction), + }, + UpdateType.InlineQuery => nameof(InlineQueryAction), + UpdateType.ChosenInlineResult => nameof(ChosenInlineResultAction), + UpdateType.CallbackQuery => nameof(CallbackQueryAction), + UpdateType.EditedMessage => nameof(EditedMessageAction), + UpdateType.ChannelPost => nameof(ChannelPostAction), + // UpdateType.EditedChannelPost => ActionType.EditedChannelPost, + UpdateType.ShippingQuery => nameof(ShippingQueryAction), + UpdateType.PreCheckoutQuery => nameof(PreCheckoutQuery), + UpdateType.Poll => nameof(PollAction), + // UpdateType.PollAnswer => typeof(PollAction).FullName, + // UpdateType.MyChatMember => typeof(UnknownAction).FullName, + // UpdateType.ChatMember => typeof(UnknownAction).FullName, + UpdateType.Unknown => nameof(UnknownAction), + _ => default + }; } } \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/TelegramNavigatorProvider.cs b/src/Navigator.Providers.Telegram/TelegramNavigatorProvider.cs index 5a465eb..d3a7a72 100644 --- a/src/Navigator.Providers.Telegram/TelegramNavigatorProvider.cs +++ b/src/Navigator.Providers.Telegram/TelegramNavigatorProvider.cs @@ -2,25 +2,24 @@ using System.Threading.Tasks; using Telegram.Bot.Types; -namespace Navigator.Providers.Telegram +namespace Navigator.Providers.Telegram; + +public class TelegramNavigatorProvider : INavigatorProvider { - public class TelegramNavigatorProvider : INavigatorProvider - { - private readonly NavigatorTelegramClient _client; + private readonly NavigatorTelegramClient _client; - public TelegramNavigatorProvider(NavigatorTelegramClient client) - { - _client = client; - } + public TelegramNavigatorProvider(NavigatorTelegramClient client) + { + _client = client; + } - public INavigatorClient GetClient() - { - return _client; - } + public INavigatorClient GetClient() + { + return _client; + } - public Task HandleReply() - { - throw new NotImplementedException(); - } + public Task HandleReply() + { + throw new NotImplementedException(); } } \ No newline at end of file diff --git a/src/Navigator/Actions/ActionHandler.cs b/src/Navigator/Actions/ActionHandler.cs index 5609ec2..f67dfb5 100644 --- a/src/Navigator/Actions/ActionHandler.cs +++ b/src/Navigator/Actions/ActionHandler.cs @@ -5,27 +5,26 @@ using Navigator.Context; using Navigator.Replies; -namespace Navigator.Actions +namespace Navigator.Actions; + +public abstract class ActionHandler : IRequestHandler where TAction : IAction { - public abstract class ActionHandler : IRequestHandler where TAction : IAction - { - public INavigatorContext NavigatorContext; + public INavigatorContext NavigatorContext; - protected ActionHandler(INavigatorContextAccessor navigatorContextAccessor) - { - NavigatorContext = navigatorContextAccessor.NavigatorContext; - } + protected ActionHandler(INavigatorContextAccessor navigatorContextAccessor) + { + NavigatorContext = navigatorContextAccessor.NavigatorContext; + } - public abstract Task Handle(TAction action, CancellationToken cancellationToken); + public abstract Task Handle(TAction action, CancellationToken cancellationToken); - public static Status Success() - { - return new(true); - } + public static Status Success() + { + return new(true); + } - public static Status Error() - { - return new(false); - } + public static Status Error() + { + return new(false); } } \ No newline at end of file diff --git a/src/Navigator/Actions/ActionHandlerExtensions.cs b/src/Navigator/Actions/ActionHandlerExtensions.cs index 9a44a20..7e4403c 100644 --- a/src/Navigator/Actions/ActionHandlerExtensions.cs +++ b/src/Navigator/Actions/ActionHandlerExtensions.cs @@ -1,7 +1,6 @@ -namespace Navigator.Actions +namespace Navigator.Actions; + +public class ActionHandlerExtensions { - public class ActionHandlerExtensions - { - } } \ No newline at end of file diff --git a/src/Navigator/Actions/ActionLauncher.cs b/src/Navigator/Actions/ActionLauncher.cs index eab947a..3bed45a 100644 --- a/src/Navigator/Actions/ActionLauncher.cs +++ b/src/Navigator/Actions/ActionLauncher.cs @@ -9,74 +9,73 @@ using Navigator.Configuration; using Navigator.Context; -namespace Navigator.Actions +namespace Navigator.Actions; + +internal class ActionLauncher : IActionLauncher { - internal class ActionLauncher : IActionLauncher - { - private readonly ILogger _logger; - private readonly INavigatorContextAccessor _navigatorContextAccessor; - private readonly IServiceProvider _serviceProvider; - private readonly ISender _sender; - private readonly NavigatorOptions _navigatorOptions; - private readonly ImmutableDictionary _actions; - private readonly ImmutableDictionary _priorities; + private readonly ILogger _logger; + private readonly INavigatorContextAccessor _navigatorContextAccessor; + private readonly IServiceProvider _serviceProvider; + private readonly ISender _sender; + private readonly NavigatorOptions _navigatorOptions; + private readonly ImmutableDictionary _actions; + private readonly ImmutableDictionary _priorities; - public ActionLauncher(ILogger logger, NavigatorOptions navigatorOptions, INavigatorContextAccessor navigatorContextAccessor, IServiceProvider serviceProvider, ISender sender) - { - _logger = logger; - _navigatorContextAccessor = navigatorContextAccessor; - _serviceProvider = serviceProvider; - _sender = sender; - _navigatorOptions = navigatorOptions; - _actions = _navigatorOptions.RetrieveActions(); - _priorities = _navigatorOptions.RetrievePriorities(); - } + public ActionLauncher(ILogger logger, NavigatorOptions navigatorOptions, INavigatorContextAccessor navigatorContextAccessor, IServiceProvider serviceProvider, ISender sender) + { + _logger = logger; + _navigatorContextAccessor = navigatorContextAccessor; + _serviceProvider = serviceProvider; + _sender = sender; + _navigatorOptions = navigatorOptions; + _actions = _navigatorOptions.RetrieveActions(); + _priorities = _navigatorOptions.RetrievePriorities(); + } - public async Task Launch() - { - var actions = GetActions(); + public async Task Launch() + { + var actions = GetActions(); - foreach (var action in actions) + foreach (var action in actions) + { + try { - try - { - await _sender.Send(action); - } - catch (Exception e) - { - _logger.LogError(e, "Unhandled exception running {ActionName} ({@ActionData})", action.GetType().Name, action); - } + await _sender.Send(action); + } + catch (Exception e) + { + _logger.LogError(e, "Unhandled exception running {ActionName} ({@ActionData})", action.GetType().Name, action); } } + } - private IEnumerable GetActions() + private IEnumerable GetActions() + { + if (string.IsNullOrWhiteSpace(_navigatorContextAccessor.NavigatorContext.ActionType)) { - if (string.IsNullOrWhiteSpace(_navigatorContextAccessor.NavigatorContext.ActionType)) - { - return Array.Empty(); - } + return Array.Empty(); + } - var actions = _actions - .Where(a => a.Key == _navigatorContextAccessor.NavigatorContext.ActionType) - .ToImmutableList(); + var actions = _actions + .Where(a => a.Key == _navigatorContextAccessor.NavigatorContext.ActionType) + .ToImmutableList(); - if (_navigatorOptions.MultipleActionsUsageIsEnabled()) - { - return actions - .Select(pair => ((IAction) _serviceProvider.GetService(pair.Value)!, pair.Value.FullName)) - .Where(a => a.Item1.CanHandleCurrentContext()) - .OrderBy(a => _priorities.GetValueOrDefault(a.FullName ?? string.Empty, Priority.Default)) - .Select(a => a.Item1) - .AsEnumerable(); - } - - var action = actions + if (_navigatorOptions.MultipleActionsUsageIsEnabled()) + { + return actions .Select(pair => ((IAction) _serviceProvider.GetService(pair.Value)!, pair.Value.FullName)) + .Where(a => a.Item1.CanHandleCurrentContext()) .OrderBy(a => _priorities.GetValueOrDefault(a.FullName ?? string.Empty, Priority.Default)) .Select(a => a.Item1) - .FirstOrDefault(a => a.CanHandleCurrentContext()); - - return action is not null ? new[] {action} : Array.Empty(); + .AsEnumerable(); } + + var action = actions + .Select(pair => ((IAction) _serviceProvider.GetService(pair.Value)!, pair.Value.FullName)) + .OrderBy(a => _priorities.GetValueOrDefault(a.FullName ?? string.Empty, Priority.Default)) + .Select(a => a.Item1) + .FirstOrDefault(a => a.CanHandleCurrentContext()); + + return action is not null ? new[] {action} : Array.Empty(); } } \ No newline at end of file diff --git a/src/Navigator/Actions/BaseAction.cs b/src/Navigator/Actions/BaseAction.cs index daa2bba..b3fe12d 100644 --- a/src/Navigator/Actions/BaseAction.cs +++ b/src/Navigator/Actions/BaseAction.cs @@ -2,37 +2,36 @@ using Navigator.Actions.Attributes; using Navigator.Context; -namespace Navigator.Actions +namespace Navigator.Actions; + +/// +/// Base action to use for any action. +/// +[ActionPriority(Actions.Priority.Default)] +public abstract class BaseAction : IAction { /// - /// Base action to use for any action. + /// Used to access inside the action. /// - [ActionPriority(Actions.Priority.Default)] - public abstract class BaseAction : IAction - { - /// - /// Used to access inside the action. - /// - protected readonly INavigatorContextAccessor NavigatorContextAccessor; + protected readonly INavigatorContextAccessor NavigatorContextAccessor; - /// - public virtual ushort Priority { get; protected set; } = Actions.Priority.Default; + /// + public virtual ushort Priority { get; protected set; } = Actions.Priority.Default; - /// - /// Timestamp of the request on creation. - /// - public DateTime Timestamp { get; } - - /// - /// Default constructor for - /// - public BaseAction(INavigatorContextAccessor navigatorContextAccessor) - { - NavigatorContextAccessor = navigatorContextAccessor; - Timestamp = DateTime.UtcNow; - } + /// + /// Timestamp of the request on creation. + /// + public DateTime Timestamp { get; } - /// - public abstract bool CanHandleCurrentContext(); + /// + /// Default constructor for + /// + public BaseAction(INavigatorContextAccessor navigatorContextAccessor) + { + NavigatorContextAccessor = navigatorContextAccessor; + Timestamp = DateTime.UtcNow; } + + /// + public abstract bool CanHandleCurrentContext(); } \ No newline at end of file diff --git a/src/Navigator/Actions/IAction.cs b/src/Navigator/Actions/IAction.cs index 0b2fa50..b12d56f 100644 --- a/src/Navigator/Actions/IAction.cs +++ b/src/Navigator/Actions/IAction.cs @@ -1,17 +1,16 @@ using MediatR; using Navigator.Context; -namespace Navigator.Actions +namespace Navigator.Actions; + +/// +/// Base contract for an action. +/// +public interface IAction : IRequest { /// - /// Base contract for an action. + /// This function must return true when the incoming update can be handled by this action. /// - public interface IAction : IRequest - { - /// - /// This function must return true when the incoming update can be handled by this action. - /// - /// - bool CanHandleCurrentContext(); - } + /// + bool CanHandleCurrentContext(); } \ No newline at end of file diff --git a/src/Navigator/Actions/IActionLauncher.cs b/src/Navigator/Actions/IActionLauncher.cs index 0bd7543..a3235ff 100644 --- a/src/Navigator/Actions/IActionLauncher.cs +++ b/src/Navigator/Actions/IActionLauncher.cs @@ -1,9 +1,8 @@ using System.Threading.Tasks; -namespace Navigator.Actions +namespace Navigator.Actions; + +public interface IActionLauncher { - public interface IActionLauncher - { - Task Launch(); - } + Task Launch(); } \ No newline at end of file diff --git a/src/Navigator/Actions/IActionMiddleware.cs b/src/Navigator/Actions/IActionMiddleware.cs index 12d64d5..6730605 100644 --- a/src/Navigator/Actions/IActionMiddleware.cs +++ b/src/Navigator/Actions/IActionMiddleware.cs @@ -1,13 +1,12 @@ using MediatR; -namespace Navigator.Actions +namespace Navigator.Actions; + +/// +/// TODO +/// +/// +/// +public interface IActionMiddleware : IPipelineBehavior where TAction : IAction { - /// - /// TODO - /// - /// - /// - public interface IActionMiddleware : IPipelineBehavior where TAction : IAction - { - } } \ No newline at end of file diff --git a/src/Navigator/Actions/Priority.cs b/src/Navigator/Actions/Priority.cs index 8a0fa65..7ddfa02 100644 --- a/src/Navigator/Actions/Priority.cs +++ b/src/Navigator/Actions/Priority.cs @@ -1,9 +1,8 @@ -namespace Navigator.Actions +namespace Navigator.Actions; + +public static class Priority { - public static class Priority - { - public const ushort Low = 15000; - public const ushort Default = 10000; - public const ushort High = 5000; - } + public const ushort Low = 15000; + public const ushort Default = 10000; + public const ushort High = 5000; } \ No newline at end of file diff --git a/src/Navigator/Actions/Status.cs b/src/Navigator/Actions/Status.cs index 842b47b..1bcd3d5 100644 --- a/src/Navigator/Actions/Status.cs +++ b/src/Navigator/Actions/Status.cs @@ -1,15 +1,14 @@ -namespace Navigator.Actions +namespace Navigator.Actions; + +public struct Status { - public struct Status - { - private readonly bool _isSuccess; + private readonly bool _isSuccess; - public bool IsSuccess => _isSuccess; - public bool IsError => !_isSuccess; + public bool IsSuccess => _isSuccess; + public bool IsError => !_isSuccess; - public Status(bool isSuccess) - { - _isSuccess = isSuccess; - } + public Status(bool isSuccess) + { + _isSuccess = isSuccess; } } \ No newline at end of file diff --git a/src/Navigator/Configuration/EndpointRouteBuilderExtensions.cs b/src/Navigator/Configuration/EndpointRouteBuilderExtensions.cs index f3ff5a6..18b7a0f 100644 --- a/src/Navigator/Configuration/EndpointRouteBuilderExtensions.cs +++ b/src/Navigator/Configuration/EndpointRouteBuilderExtensions.cs @@ -1,17 +1,16 @@ using Microsoft.AspNetCore.Routing; -namespace Navigator.Configuration +namespace Navigator.Configuration; + +public static class EndpointRouteBuilderExtensions { - public static class EndpointRouteBuilderExtensions + /// + /// Configure navigator's provider's endpoints. + /// + /// + /// + public static NavigatorRouteConfiguration MapNavigator(this IEndpointRouteBuilder endpointRouteBuilder) { - /// - /// Configure navigator's provider's endpoints. - /// - /// - /// - public static NavigatorRouteConfiguration MapNavigator(this IEndpointRouteBuilder endpointRouteBuilder) - { - return new(endpointRouteBuilder); - } + return new(endpointRouteBuilder); } } \ No newline at end of file diff --git a/src/Navigator/Configuration/Extension/NavigatorExtensionConfiguration.cs b/src/Navigator/Configuration/Extension/NavigatorExtensionConfiguration.cs index 0921190..7e377b0 100644 --- a/src/Navigator/Configuration/Extension/NavigatorExtensionConfiguration.cs +++ b/src/Navigator/Configuration/Extension/NavigatorExtensionConfiguration.cs @@ -1,39 +1,38 @@ using System; using Microsoft.Extensions.DependencyInjection; -namespace Navigator.Configuration.Extension +namespace Navigator.Configuration.Extension; + +/// +/// Provides a entry point for configuring new extensions for Navigator. +/// +public class NavigatorExtensionConfiguration { + private readonly NavigatorConfiguration _navigatorConfiguration; + /// - /// Provides a entry point for configuring new extensions for Navigator. + /// Default constructor for . /// - public class NavigatorExtensionConfiguration + /// + public NavigatorExtensionConfiguration(NavigatorConfiguration navigatorConfiguration) { - private readonly NavigatorConfiguration _navigatorConfiguration; - - /// - /// Default constructor for . - /// - /// - public NavigatorExtensionConfiguration(NavigatorConfiguration navigatorConfiguration) - { - _navigatorConfiguration = navigatorConfiguration; - } + _navigatorConfiguration = navigatorConfiguration; + } - /// - /// Configure a new extension using this method. - /// - /// - /// - /// - public NavigatorConfiguration Extension(Action? optionsAction, Action? servicesAction) - { - optionsAction?.Invoke(_navigatorConfiguration.Options); + /// + /// Configure a new extension using this method. + /// + /// + /// + /// + public NavigatorConfiguration Extension(Action? optionsAction, Action? servicesAction) + { + optionsAction?.Invoke(_navigatorConfiguration.Options); - servicesAction?.Invoke(_navigatorConfiguration.Services); + servicesAction?.Invoke(_navigatorConfiguration.Services); - _navigatorConfiguration.RegisterOrReplaceOptions(); + _navigatorConfiguration.RegisterOrReplaceOptions(); - return _navigatorConfiguration; - } + return _navigatorConfiguration; } } \ No newline at end of file diff --git a/src/Navigator/Configuration/INavigatorOptions.cs b/src/Navigator/Configuration/INavigatorOptions.cs index b056a37..3251d1f 100644 --- a/src/Navigator/Configuration/INavigatorOptions.cs +++ b/src/Navigator/Configuration/INavigatorOptions.cs @@ -1,16 +1,15 @@ using System.Collections.Generic; -namespace Navigator.Configuration +namespace Navigator.Configuration; + +/// +/// Represents all the options you can use to configure Navigator. +/// +public interface INavigatorOptions { - /// - /// Represents all the options you can use to configure Navigator. - /// - public interface INavigatorOptions - { - bool TryRegisterOption(string key, object option); - void ForceRegisterOption(string key, object option); - TType? RetrieveOption(string key); - Dictionary RetrieveAllOptions(); - void Import(Dictionary options, bool overwrite = false); - } + bool TryRegisterOption(string key, object option); + void ForceRegisterOption(string key, object option); + TType? RetrieveOption(string key); + Dictionary RetrieveAllOptions(); + void Import(Dictionary options, bool overwrite = false); } \ No newline at end of file diff --git a/src/Navigator/Configuration/NavigatorConfiguration.cs b/src/Navigator/Configuration/NavigatorConfiguration.cs index b778d41..9b18ec0 100644 --- a/src/Navigator/Configuration/NavigatorConfiguration.cs +++ b/src/Navigator/Configuration/NavigatorConfiguration.cs @@ -4,55 +4,54 @@ using Navigator.Configuration.Extension; using Navigator.Configuration.Provider; -namespace Navigator.Configuration +namespace Navigator.Configuration; + +/// +/// Helper functions for configuring navigator services. +/// +public class NavigatorConfiguration { - /// - /// Helper functions for configuring navigator services. - /// - public class NavigatorConfiguration - { - public NavigatorProviderConfiguration WithProvider { get; internal set; } + public NavigatorProviderConfiguration WithProvider { get; internal set; } - public NavigatorExtensionConfiguration WithExtension { get; internal set; } + public NavigatorExtensionConfiguration WithExtension { get; internal set; } - /// - /// Gets the that are being used. - /// - /// - /// The - /// - public NavigatorOptions Options { get; internal set; } + /// + /// Gets the that are being used. + /// + /// + /// The + /// + public NavigatorOptions Options { get; internal set; } - /// - /// Gets the services are attached to. - /// - /// - /// The services are attached to. - /// - public IServiceCollection Services { get; internal set; } + /// + /// Gets the services are attached to. + /// + /// + /// The services are attached to. + /// + public IServiceCollection Services { get; internal set; } - /// - /// Creates a new instance of . - /// - /// The to use. - /// The to attach to. - public NavigatorConfiguration(Action options, IServiceCollection services) - { - Options = new NavigatorOptions(); - options.Invoke(Options); + /// + /// Creates a new instance of . + /// + /// The to use. + /// The to attach to. + public NavigatorConfiguration(Action options, IServiceCollection services) + { + Options = new NavigatorOptions(); + options.Invoke(Options); - Services = services; + Services = services; - services.AddSingleton(Options); + services.AddSingleton(Options); - WithProvider = new NavigatorProviderConfiguration(this); - WithExtension = new NavigatorExtensionConfiguration(this); - } + WithProvider = new NavigatorProviderConfiguration(this); + WithExtension = new NavigatorExtensionConfiguration(this); + } - public void RegisterOrReplaceOptions() - { - Services.Replace(ServiceDescriptor.Singleton(_ => Options)); - } + public void RegisterOrReplaceOptions() + { + Services.Replace(ServiceDescriptor.Singleton(_ => Options)); } } \ No newline at end of file diff --git a/src/Navigator/Configuration/NavigatorOptions.cs b/src/Navigator/Configuration/NavigatorOptions.cs index ff58728..f23dd4d 100644 --- a/src/Navigator/Configuration/NavigatorOptions.cs +++ b/src/Navigator/Configuration/NavigatorOptions.cs @@ -1,60 +1,59 @@ using System.Collections.Generic; -namespace Navigator.Configuration +namespace Navigator.Configuration; + +/// +public class NavigatorOptions : INavigatorOptions { - /// - public class NavigatorOptions : INavigatorOptions - { - private readonly Dictionary _options; + private readonly Dictionary _options; - public NavigatorOptions() - { - _options = new Dictionary(); - } + public NavigatorOptions() + { + _options = new Dictionary(); + } - public bool TryRegisterOption(string key, object option) - { - return _options.TryAdd(key, option); - } + public bool TryRegisterOption(string key, object option) + { + return _options.TryAdd(key, option); + } - public void ForceRegisterOption(string key, object option) - { - _options.Remove(key); + public void ForceRegisterOption(string key, object option) + { + _options.Remove(key); - TryRegisterOption(key, option); - } + TryRegisterOption(key, option); + } - public TType? RetrieveOption(string key) + public TType? RetrieveOption(string key) + { + if (_options.TryGetValue(key, out var option)) { - if (_options.TryGetValue(key, out var option)) - { - return (TType) option; - } - - return default; + return (TType) option; } - public Dictionary RetrieveAllOptions() - { - return _options; - } + return default; + } - public void Import(Dictionary options, bool overwrite = false) - { - if (overwrite) - { - foreach (var (key, option) in options) - { - ForceRegisterOption(key, option); - } - - return; - } + public Dictionary RetrieveAllOptions() + { + return _options; + } + public void Import(Dictionary options, bool overwrite = false) + { + if (overwrite) + { foreach (var (key, option) in options) { - TryRegisterOption(key, option); + ForceRegisterOption(key, option); } + + return; + } + + foreach (var (key, option) in options) + { + TryRegisterOption(key, option); } } } \ No newline at end of file diff --git a/src/Navigator/Configuration/NavigatorOptionsCollectionExtensions.cs b/src/Navigator/Configuration/NavigatorOptionsCollectionExtensions.cs index 3d6b38e..19b2ca6 100644 --- a/src/Navigator/Configuration/NavigatorOptionsCollectionExtensions.cs +++ b/src/Navigator/Configuration/NavigatorOptionsCollectionExtensions.cs @@ -1,72 +1,71 @@ using System.Collections.Generic; using System.Reflection; -namespace Navigator.Configuration +namespace Navigator.Configuration; + +/// +/// Navigator Configuration Options. +/// +public static class NavigatorOptionsCollectionExtensions { - /// - /// Navigator Configuration Options. - /// - public static class NavigatorOptionsCollectionExtensions - { - #region WebHookBaseUrl + #region WebHookBaseUrl - private const string WebHookBaseUrlKey = "_navigator.options.webhook_base_url"; + private const string WebHookBaseUrlKey = "_navigator.options.webhook_base_url"; - public static void SetWebHookBaseUrl(this NavigatorOptions navigatorOptions, string webHookBaseUrl) - { - navigatorOptions.TryRegisterOption(WebHookBaseUrlKey, webHookBaseUrl); + public static void SetWebHookBaseUrl(this NavigatorOptions navigatorOptions, string webHookBaseUrl) + { + navigatorOptions.TryRegisterOption(WebHookBaseUrlKey, webHookBaseUrl); - } + } - public static string? GetWebHookBaseUrl(this NavigatorOptions navigatorOptions) - { - return navigatorOptions.RetrieveOption(WebHookBaseUrlKey); - } + public static string? GetWebHookBaseUrl(this NavigatorOptions navigatorOptions) + { + return navigatorOptions.RetrieveOption(WebHookBaseUrlKey); + } - #endregion + #endregion - #region MultipleActions + #region MultipleActions - private const string MultipleActionsKey = "_navigator.options.multiple_actions"; + private const string MultipleActionsKey = "_navigator.options.multiple_actions"; - public static void EnableMultipleActionsUsage(this NavigatorOptions navigatorOptions) - { - navigatorOptions.TryRegisterOption(MultipleActionsKey, true); - } + public static void EnableMultipleActionsUsage(this NavigatorOptions navigatorOptions) + { + navigatorOptions.TryRegisterOption(MultipleActionsKey, true); + } - public static bool MultipleActionsUsageIsEnabled(this NavigatorOptions navigatorOptions) - { - return navigatorOptions.RetrieveOption(MultipleActionsKey); - } + public static bool MultipleActionsUsageIsEnabled(this NavigatorOptions navigatorOptions) + { + return navigatorOptions.RetrieveOption(MultipleActionsKey); + } - #endregion + #endregion - #region ActionsAssemblies + #region ActionsAssemblies - private const string ActionsAssembliesKey = "_navigator.options.actions_assemblies"; + private const string ActionsAssembliesKey = "_navigator.options.actions_assemblies"; - public static void RegisterActionsFromAssemblies(this NavigatorOptions navigatorOptions, params Assembly[] assemblies) - { - var registeredAssemblies = navigatorOptions.RetrieveOption(ActionsAssembliesKey); + public static void RegisterActionsFromAssemblies(this NavigatorOptions navigatorOptions, params Assembly[] assemblies) + { + var registeredAssemblies = navigatorOptions.RetrieveOption(ActionsAssembliesKey); - if (registeredAssemblies?.Length > 0) - { - var combinedAssemblies = new List(registeredAssemblies); - combinedAssemblies.AddRange(assemblies); + if (registeredAssemblies?.Length > 0) + { + var combinedAssemblies = new List(registeredAssemblies); + combinedAssemblies.AddRange(assemblies); - navigatorOptions.TryRegisterOption(ActionsAssembliesKey, combinedAssemblies); - } - else - { - navigatorOptions.TryRegisterOption(ActionsAssembliesKey, assemblies); - } + navigatorOptions.TryRegisterOption(ActionsAssembliesKey, combinedAssemblies); } - - public static Assembly[] GetActionsAssemblies(this NavigatorOptions navigatorOptions) + else { - return navigatorOptions.RetrieveOption(ActionsAssembliesKey) ?? new[] { Assembly.GetCallingAssembly()}; + navigatorOptions.TryRegisterOption(ActionsAssembliesKey, assemblies); } + } - #endregion + public static Assembly[] GetActionsAssemblies(this NavigatorOptions navigatorOptions) + { + return navigatorOptions.RetrieveOption(ActionsAssembliesKey) ?? new[] { Assembly.GetCallingAssembly()}; } + + #endregion } \ No newline at end of file diff --git a/src/Navigator/Configuration/NavigatorRouteConfiguration.cs b/src/Navigator/Configuration/NavigatorRouteConfiguration.cs index aa1f393..3b3d15c 100644 --- a/src/Navigator/Configuration/NavigatorRouteConfiguration.cs +++ b/src/Navigator/Configuration/NavigatorRouteConfiguration.cs @@ -1,19 +1,18 @@ using Microsoft.AspNetCore.Routing; using Navigator.Configuration.Provider; -namespace Navigator.Configuration +namespace Navigator.Configuration; + +public class NavigatorRouteConfiguration { - public class NavigatorRouteConfiguration - { - public IEndpointRouteBuilder EndpointRouteBuilder { get; internal set; } + public IEndpointRouteBuilder EndpointRouteBuilder { get; internal set; } - public NavigatorRouteProviderConfiguration ForProvider { get; internal set; } + public NavigatorRouteProviderConfiguration ForProvider { get; internal set; } - public NavigatorRouteConfiguration(IEndpointRouteBuilder endpointRouteBuilder) - { - EndpointRouteBuilder = endpointRouteBuilder; + public NavigatorRouteConfiguration(IEndpointRouteBuilder endpointRouteBuilder) + { + EndpointRouteBuilder = endpointRouteBuilder; - ForProvider = new NavigatorRouteProviderConfiguration(this); - } + ForProvider = new NavigatorRouteProviderConfiguration(this); } } \ No newline at end of file diff --git a/src/Navigator/Configuration/Provider/NavigatorProviderConfiguration.cs b/src/Navigator/Configuration/Provider/NavigatorProviderConfiguration.cs index 2da30ee..8efc4e1 100644 --- a/src/Navigator/Configuration/Provider/NavigatorProviderConfiguration.cs +++ b/src/Navigator/Configuration/Provider/NavigatorProviderConfiguration.cs @@ -1,39 +1,38 @@ using System; using Microsoft.Extensions.DependencyInjection; -namespace Navigator.Configuration.Provider +namespace Navigator.Configuration.Provider; + +/// +/// Provides a entry point for configuring new providers for Navigator. +/// +public class NavigatorProviderConfiguration { + private readonly NavigatorConfiguration _navigatorConfiguration; + /// - /// Provides a entry point for configuring new providers for Navigator. + /// Default constructor for . /// - public class NavigatorProviderConfiguration + /// + public NavigatorProviderConfiguration(NavigatorConfiguration navigatorConfiguration) { - private readonly NavigatorConfiguration _navigatorConfiguration; - - /// - /// Default constructor for . - /// - /// - public NavigatorProviderConfiguration(NavigatorConfiguration navigatorConfiguration) - { - _navigatorConfiguration = navigatorConfiguration; - } + _navigatorConfiguration = navigatorConfiguration; + } - /// - /// Configure a new provider using this method. - /// - /// - /// - /// - public NavigatorConfiguration Provider(Action? optionsAction, Action? servicesAction) - { - optionsAction?.Invoke(_navigatorConfiguration.Options); + /// + /// Configure a new provider using this method. + /// + /// + /// + /// + public NavigatorConfiguration Provider(Action? optionsAction, Action? servicesAction) + { + optionsAction?.Invoke(_navigatorConfiguration.Options); - servicesAction?.Invoke(_navigatorConfiguration.Services); + servicesAction?.Invoke(_navigatorConfiguration.Services); - _navigatorConfiguration.RegisterOrReplaceOptions(); + _navigatorConfiguration.RegisterOrReplaceOptions(); - return _navigatorConfiguration; - } + return _navigatorConfiguration; } } \ No newline at end of file diff --git a/src/Navigator/Configuration/Provider/NavigatorRouteProviderConfiguration.cs b/src/Navigator/Configuration/Provider/NavigatorRouteProviderConfiguration.cs index a355559..2806757 100644 --- a/src/Navigator/Configuration/Provider/NavigatorRouteProviderConfiguration.cs +++ b/src/Navigator/Configuration/Provider/NavigatorRouteProviderConfiguration.cs @@ -1,22 +1,21 @@ using System; using Microsoft.AspNetCore.Routing; -namespace Navigator.Configuration.Provider +namespace Navigator.Configuration.Provider; + +public class NavigatorRouteProviderConfiguration { - public class NavigatorRouteProviderConfiguration - { - private readonly NavigatorRouteConfiguration _navigatorRouteConfiguration; + private readonly NavigatorRouteConfiguration _navigatorRouteConfiguration; - public NavigatorRouteProviderConfiguration(NavigatorRouteConfiguration navigatorRouteConfiguration) - { - _navigatorRouteConfiguration = navigatorRouteConfiguration; - } + public NavigatorRouteProviderConfiguration(NavigatorRouteConfiguration navigatorRouteConfiguration) + { + _navigatorRouteConfiguration = navigatorRouteConfiguration; + } - public NavigatorRouteConfiguration Provider(Action routeActions) - { - routeActions.Invoke(_navigatorRouteConfiguration.EndpointRouteBuilder); + public NavigatorRouteConfiguration Provider(Action routeActions) + { + routeActions.Invoke(_navigatorRouteConfiguration.EndpointRouteBuilder); - return _navigatorRouteConfiguration; - } + return _navigatorRouteConfiguration; } } \ No newline at end of file diff --git a/src/Navigator/Context/Extensions/Bundled/OriginalEvent/NavigatorContextExtensions.cs b/src/Navigator/Context/Extensions/Bundled/OriginalEvent/NavigatorContextExtensions.cs index 4dab057..58c0142 100644 --- a/src/Navigator/Context/Extensions/Bundled/OriginalEvent/NavigatorContextExtensions.cs +++ b/src/Navigator/Context/Extensions/Bundled/OriginalEvent/NavigatorContextExtensions.cs @@ -1,30 +1,29 @@ using System.Collections.Generic; -namespace Navigator.Context.Extensions.Bundled.OriginalEvent +namespace Navigator.Context.Extensions.Bundled.OriginalEvent; + +public static class NavigatorContextExtensions { - public static class NavigatorContextExtensions - { - #region OriginalEvent + #region OriginalEvent - public static TEvent GetOriginalEvent(this INavigatorContext navigatorContext) where TEvent : class - { - var update = navigatorContext.GetOriginalEventOrDefault(); + public static TEvent GetOriginalEvent(this INavigatorContext navigatorContext) where TEvent : class + { + var update = navigatorContext.GetOriginalEventOrDefault(); - return update ?? throw new NavigatorException("Update was not found."); - } + return update ?? throw new NavigatorException("Update was not found."); + } - public static TEvent? GetOriginalEventOrDefault(this INavigatorContext navigatorContext) where TEvent : class - { - var @event = navigatorContext.Extensions.GetValueOrDefault(OriginalEventContextExtension.OriginalEventKey); - - if (@event is TEvent originalEvent) - { - return originalEvent; - } + public static TEvent? GetOriginalEventOrDefault(this INavigatorContext navigatorContext) where TEvent : class + { + var @event = navigatorContext.Extensions.GetValueOrDefault(OriginalEventContextExtension.OriginalEventKey); - return default; + if (@event is TEvent originalEvent) + { + return originalEvent; } - #endregion + return default; } + + #endregion } \ No newline at end of file diff --git a/src/Navigator/Context/Extensions/Bundled/OriginalEvent/OriginalEventContextExtension.cs b/src/Navigator/Context/Extensions/Bundled/OriginalEvent/OriginalEventContextExtension.cs index 895ec40..ccd6b53 100644 --- a/src/Navigator/Context/Extensions/Bundled/OriginalEvent/OriginalEventContextExtension.cs +++ b/src/Navigator/Context/Extensions/Bundled/OriginalEvent/OriginalEventContextExtension.cs @@ -1,16 +1,15 @@ using System.Threading.Tasks; -namespace Navigator.Context.Extensions.Bundled.OriginalEvent +namespace Navigator.Context.Extensions.Bundled.OriginalEvent; + +internal class OriginalEventContextExtension : INavigatorContextExtension { - internal class OriginalEventContextExtension : INavigatorContextExtension - { - public const string OriginalEventKey = "_navigator.extensions.original_event"; + public const string OriginalEventKey = "_navigator.extensions.original_event"; - public Task Extend(INavigatorContext navigatorContext, INavigatorContextBuilderOptions builderOptions) - { - navigatorContext.Extensions.TryAdd(OriginalEventKey, builderOptions.GetOriginalEventOrDefault()); + public Task Extend(INavigatorContext navigatorContext, INavigatorContextBuilderOptions builderOptions) + { + navigatorContext.Extensions.TryAdd(OriginalEventKey, builderOptions.GetOriginalEventOrDefault()); - return Task.FromResult(navigatorContext); - } + return Task.FromResult(navigatorContext); } } \ No newline at end of file diff --git a/src/Navigator/Context/Extensions/INavigatorContextExtension.cs b/src/Navigator/Context/Extensions/INavigatorContextExtension.cs index 57c5028..9022d9c 100644 --- a/src/Navigator/Context/Extensions/INavigatorContextExtension.cs +++ b/src/Navigator/Context/Extensions/INavigatorContextExtension.cs @@ -1,9 +1,8 @@ using System.Threading.Tasks; -namespace Navigator.Context.Extensions +namespace Navigator.Context.Extensions; + +public interface INavigatorContextExtension { - public interface INavigatorContextExtension - { - Task Extend(INavigatorContext navigatorContext, INavigatorContextBuilderOptions builderOptions); - } + Task Extend(INavigatorContext navigatorContext, INavigatorContextBuilderOptions builderOptions); } \ No newline at end of file diff --git a/src/Navigator/Context/INavigatorContext.cs b/src/Navigator/Context/INavigatorContext.cs index 2075380..c659530 100644 --- a/src/Navigator/Context/INavigatorContext.cs +++ b/src/Navigator/Context/INavigatorContext.cs @@ -1,35 +1,34 @@ using System.Collections.Generic; using Navigator.Entities; -namespace Navigator.Context +namespace Navigator.Context; + +public interface INavigatorContext { - public interface INavigatorContext - { - /// - /// - /// - INavigatorProvider Provider { get; } + /// + /// + /// + INavigatorProvider Provider { get; } - /// - /// - /// - Bot BotProfile { get; } + /// + /// + /// + Bot BotProfile { get; } - /// - /// - /// - Dictionary Extensions { get; } + /// + /// + /// + Dictionary Extensions { get; } - /// - /// - /// - Dictionary Items { get; } + /// + /// + /// + Dictionary Items { get; } - /// - /// - /// - public string ActionType { get; } + /// + /// + /// + public string ActionType { get; } - public Conversation Conversation { get; } - } + public Conversation Conversation { get; } } \ No newline at end of file diff --git a/src/Navigator/Context/INavigatorContextAccessor.cs b/src/Navigator/Context/INavigatorContextAccessor.cs index 6b1f332..4889463 100644 --- a/src/Navigator/Context/INavigatorContextAccessor.cs +++ b/src/Navigator/Context/INavigatorContextAccessor.cs @@ -1,7 +1,6 @@ -namespace Navigator.Context +namespace Navigator.Context; + +public interface INavigatorContextAccessor { - public interface INavigatorContextAccessor - { - INavigatorContext NavigatorContext { get; } - } + INavigatorContext NavigatorContext { get; } } \ No newline at end of file diff --git a/src/Navigator/Context/INavigatorContextBuilder.cs b/src/Navigator/Context/INavigatorContextBuilder.cs index 9096072..eda60a9 100644 --- a/src/Navigator/Context/INavigatorContextBuilder.cs +++ b/src/Navigator/Context/INavigatorContextBuilder.cs @@ -2,10 +2,9 @@ using System.Threading.Tasks; using Navigator.Entities; -namespace Navigator.Context +namespace Navigator.Context; + +public interface INavigatorContextBuilder { - public interface INavigatorContextBuilder - { - Task Build(Action configurationAction); - } + Task Build(Action configurationAction); } \ No newline at end of file diff --git a/src/Navigator/Context/INavigatorContextBuilderOptions.cs b/src/Navigator/Context/INavigatorContextBuilderOptions.cs index cc3b75c..a7c34c1 100644 --- a/src/Navigator/Context/INavigatorContextBuilderOptions.cs +++ b/src/Navigator/Context/INavigatorContextBuilderOptions.cs @@ -1,12 +1,11 @@ using System.Collections.Generic; -namespace Navigator.Context +namespace Navigator.Context; + +public interface INavigatorContextBuilderOptions { - public interface INavigatorContextBuilderOptions - { - bool TryRegisterOption(string key, object option); - void ForceRegisterOption(string key, object option); - TType? RetrieveOption(string key); - Dictionary RetrieveAllOptions(); - } + bool TryRegisterOption(string key, object option); + void ForceRegisterOption(string key, object option); + TType? RetrieveOption(string key); + Dictionary RetrieveAllOptions(); } \ No newline at end of file diff --git a/src/Navigator/Context/INavigatorContextFactory.cs b/src/Navigator/Context/INavigatorContextFactory.cs index 255cac8..d18a77c 100644 --- a/src/Navigator/Context/INavigatorContextFactory.cs +++ b/src/Navigator/Context/INavigatorContextFactory.cs @@ -1,12 +1,14 @@ using System; using System.Threading.Tasks; -namespace Navigator.Context +namespace Navigator.Context; + +/// +/// Factory for creating and retrieving implementations of +/// +public interface INavigatorContextFactory { - public interface INavigatorContextFactory - { - Task Supply(Action action); + Task Supply(Action action); - INavigatorContext Retrieve(); - } + INavigatorContext Retrieve(); } \ No newline at end of file diff --git a/src/Navigator/Context/NavigatorContext.cs b/src/Navigator/Context/NavigatorContext.cs index 6a685ad..fa53af0 100644 --- a/src/Navigator/Context/NavigatorContext.cs +++ b/src/Navigator/Context/NavigatorContext.cs @@ -1,43 +1,25 @@ using System.Collections.Generic; using Navigator.Entities; -namespace Navigator.Context -{ - /// - /// Navigator Context present in all actions. - /// - public class NavigatorContext : INavigatorContext - { - /// - /// - /// - public INavigatorProvider Provider { get; } - - /// - /// Profile of the bot running in this context. - /// - public Bot BotProfile { get; } - - public Dictionary Extensions { get; } +namespace Navigator.Context; - public Dictionary Items { get; } - - public string ActionType { get; } - - public Conversation Conversation { get; } +internal class NavigatorContext : INavigatorContext +{ + public INavigatorProvider Provider { get; } + public Bot BotProfile { get; } + public Dictionary Extensions { get; } + public Dictionary Items { get; } + public string ActionType { get; } + public Conversation Conversation { get; } - /// - /// Builds a new Navigator Context. - /// - public NavigatorContext(INavigatorProvider provider, Bot botProfile, string actionType, Conversation conversation) - { - Provider = provider; - BotProfile = botProfile; - ActionType = actionType; - Conversation = conversation; + public NavigatorContext(INavigatorProvider provider, Bot botProfile, string actionType, Conversation conversation) + { + Provider = provider; + BotProfile = botProfile; + ActionType = actionType; + Conversation = conversation; - Items = new Dictionary(); - Extensions = new Dictionary(); - } + Items = new Dictionary(); + Extensions = new Dictionary(); } } \ No newline at end of file diff --git a/src/Navigator/Context/NavigatorContextAccessor.cs b/src/Navigator/Context/NavigatorContextAccessor.cs index 94dd44f..68b7ff5 100644 --- a/src/Navigator/Context/NavigatorContextAccessor.cs +++ b/src/Navigator/Context/NavigatorContextAccessor.cs @@ -1,14 +1,13 @@ -namespace Navigator.Context -{ - public class NavigatorContextAccessor : INavigatorContextAccessor - { - private readonly INavigatorContextFactory _navigatorContextFactory; +namespace Navigator.Context; - public NavigatorContextAccessor(INavigatorContextFactory navigatorContextFactory) - { - _navigatorContextFactory = navigatorContextFactory; - } +internal class NavigatorContextAccessor : INavigatorContextAccessor +{ + private readonly INavigatorContextFactory _navigatorContextFactory; - public INavigatorContext NavigatorContext => _navigatorContextFactory.Retrieve(); + public NavigatorContextAccessor(INavigatorContextFactory navigatorContextFactory) + { + _navigatorContextFactory = navigatorContextFactory; } + + public INavigatorContext NavigatorContext => _navigatorContextFactory.Retrieve(); } \ No newline at end of file diff --git a/src/Navigator/Context/NavigatorContextBuilder.cs b/src/Navigator/Context/NavigatorContextBuilder.cs index f9a9379..15c5fe8 100644 --- a/src/Navigator/Context/NavigatorContextBuilder.cs +++ b/src/Navigator/Context/NavigatorContextBuilder.cs @@ -6,51 +6,50 @@ using Navigator.Context.Extensions; using Navigator.Entities; -namespace Navigator.Context +namespace Navigator.Context; + +internal class NavigatorContextBuilder : INavigatorContextBuilder { - public class NavigatorContextBuilder : INavigatorContextBuilder - { - private readonly ILogger _logger; - private readonly IEnumerable _navigatorProviders; - private readonly IEnumerable _navigatorContextExtensions; - private readonly INavigatorContextBuilderOptions _options; - private readonly INavigatorContextBuilderConversationSource _conversationSource; + private readonly ILogger _logger; + private readonly IEnumerable _navigatorProviders; + private readonly IEnumerable _navigatorContextExtensions; + private readonly INavigatorContextBuilderOptions _options; + private readonly INavigatorContextBuilderConversationSource _conversationSource; - public NavigatorContextBuilder(ILogger logger, IEnumerable navigatorClients, IEnumerable navigatorContextExtensions, INavigatorContextBuilderConversationSource conversationSource) - { - _logger = logger; - _navigatorProviders = navigatorClients; - _navigatorContextExtensions = navigatorContextExtensions; - _conversationSource = conversationSource; + public NavigatorContextBuilder(ILogger logger, IEnumerable navigatorClients, IEnumerable navigatorContextExtensions, INavigatorContextBuilderConversationSource conversationSource) + { + _logger = logger; + _navigatorProviders = navigatorClients; + _navigatorContextExtensions = navigatorContextExtensions; + _conversationSource = conversationSource; - _options = new NavigatorContextBuilderOptions(); - } + _options = new NavigatorContextBuilderOptions(); + } - public async Task Build(Action optionsAction) - { - optionsAction.Invoke(_options); + public async Task Build(Action optionsAction) + { + optionsAction.Invoke(_options); - var provider = _navigatorProviders.FirstOrDefault(p => p.GetType() == _options.GetProvider()); + var provider = _navigatorProviders.FirstOrDefault(p => p.GetType() == _options.GetProvider()); - if (provider is null) - { - _logger.LogError("No provider found for: {@Provider}", _options.GetProvider()); - //TODO: make NavigatorException - throw new Exception($"No provider found for: {_options.GetProvider()?.Name}"); - } + if (provider is null) + { + _logger.LogError("No provider found for: {@Provider}", _options.GetProvider()); + //TODO: make NavigatorException + throw new Exception($"No provider found for: {_options.GetProvider()?.Name}"); + } - var actionType = _options.GetAcitonType() ?? throw new InvalidOperationException(); + var actionType = _options.GetAcitonType() ?? throw new InvalidOperationException(); - var conversation = await _conversationSource.GetConversationAsync(_options.GetOriginalEventOrDefault()); + var conversation = await _conversationSource.GetConversationAsync(_options.GetOriginalEventOrDefault()); - INavigatorContext context = new NavigatorContext(provider, await provider.GetClient().GetProfile(), actionType, conversation); + INavigatorContext context = new NavigatorContext(provider, await provider.GetClient().GetProfile(), actionType, conversation); - foreach (var contextExtension in _navigatorContextExtensions) - { - context = await contextExtension.Extend(context, _options); - } - - return context; + foreach (var contextExtension in _navigatorContextExtensions) + { + context = await contextExtension.Extend(context, _options); } + + return context; } } \ No newline at end of file diff --git a/src/Navigator/Context/NavigatorContextBuilderOptions.cs b/src/Navigator/Context/NavigatorContextBuilderOptions.cs index a4ddcd3..86a78dc 100644 --- a/src/Navigator/Context/NavigatorContextBuilderOptions.cs +++ b/src/Navigator/Context/NavigatorContextBuilderOptions.cs @@ -1,42 +1,41 @@ using System.Collections.Generic; using Navigator.Entities; -namespace Navigator.Context +namespace Navigator.Context; + +public class NavigatorContextBuilderOptions : INavigatorContextBuilderOptions { - public class NavigatorContextBuilderOptions : INavigatorContextBuilderOptions - { - private readonly Dictionary _options; + private readonly Dictionary _options; - public NavigatorContextBuilderOptions() - { - _options = new Dictionary(); - } + public NavigatorContextBuilderOptions() + { + _options = new Dictionary(); + } - public bool TryRegisterOption(string key, object option) - { - return _options.TryAdd(key, option); - } + public bool TryRegisterOption(string key, object option) + { + return _options.TryAdd(key, option); + } - public void ForceRegisterOption(string key, object option) - { - _options.Remove(key); + public void ForceRegisterOption(string key, object option) + { + _options.Remove(key); - TryRegisterOption(key, option); - } + TryRegisterOption(key, option); + } - public TType? RetrieveOption(string key) + public TType? RetrieveOption(string key) + { + if (_options.TryGetValue(key, out var option)) { - if (_options.TryGetValue(key, out var option)) - { - return (TType) option; - } - - return default; + return (TType) option; } - public Dictionary RetrieveAllOptions() - { - return _options; - } + return default; + } + + public Dictionary RetrieveAllOptions() + { + return _options; } } \ No newline at end of file diff --git a/src/Navigator/Context/NavigatorContextBuilderOptionsExtensions.cs b/src/Navigator/Context/NavigatorContextBuilderOptionsExtensions.cs index 51b03c1..0d9bf07 100644 --- a/src/Navigator/Context/NavigatorContextBuilderOptionsExtensions.cs +++ b/src/Navigator/Context/NavigatorContextBuilderOptionsExtensions.cs @@ -1,59 +1,58 @@ using System; using Navigator.Entities; -namespace Navigator.Context +namespace Navigator.Context; + +public static class NavigatorContextBuilderOptionsExtensions { - public static class NavigatorContextBuilderOptionsExtensions - { - #region Provider + #region Provider - private const string ProviderKey = "_navigator.context.options.provider"; + private const string ProviderKey = "_navigator.context.options.provider"; - public static void SetProvider(this INavigatorContextBuilderOptions contextBuilderOptions) where TProvider : INavigatorProvider - { - contextBuilderOptions.TryRegisterOption(ProviderKey, typeof(TProvider)); + public static void SetProvider(this INavigatorContextBuilderOptions contextBuilderOptions) where TProvider : INavigatorProvider + { + contextBuilderOptions.TryRegisterOption(ProviderKey, typeof(TProvider)); - } + } - public static Type? GetProvider(this INavigatorContextBuilderOptions contextBuilderOptions) - { - return contextBuilderOptions.RetrieveOption(ProviderKey); - } + public static Type? GetProvider(this INavigatorContextBuilderOptions contextBuilderOptions) + { + return contextBuilderOptions.RetrieveOption(ProviderKey); + } - #endregion + #endregion - #region ActionType + #region ActionType - private const string ActionTypeKey = "_navigator.context.options.action_type"; + private const string ActionTypeKey = "_navigator.context.options.action_type"; - public static void SetActionType(this INavigatorContextBuilderOptions contextBuilderOptions, string actionType) - { - contextBuilderOptions.TryRegisterOption(ActionTypeKey, actionType); + public static void SetActionType(this INavigatorContextBuilderOptions contextBuilderOptions, string actionType) + { + contextBuilderOptions.TryRegisterOption(ActionTypeKey, actionType); - } + } - public static string? GetAcitonType(this INavigatorContextBuilderOptions contextBuilderOptions) - { - return contextBuilderOptions.RetrieveOption(ActionTypeKey); - } + public static string? GetAcitonType(this INavigatorContextBuilderOptions contextBuilderOptions) + { + return contextBuilderOptions.RetrieveOption(ActionTypeKey); + } - #endregion + #endregion - #region OriginalUpdate + #region OriginalUpdate - private const string OriginalEventKey = "_navigator.context.options.original_event"; + private const string OriginalEventKey = "_navigator.context.options.original_event"; - public static void SetOriginalEvent(this INavigatorContextBuilderOptions contextBuilderOptions, object originalUpdate) - { - contextBuilderOptions.TryRegisterOption(OriginalEventKey, originalUpdate); + public static void SetOriginalEvent(this INavigatorContextBuilderOptions contextBuilderOptions, object originalUpdate) + { + contextBuilderOptions.TryRegisterOption(OriginalEventKey, originalUpdate); - } + } - public static object? GetOriginalEventOrDefault(this INavigatorContextBuilderOptions contextBuilderOptions) - { - return contextBuilderOptions.RetrieveOption(OriginalEventKey); - } - - #endregion + public static object? GetOriginalEventOrDefault(this INavigatorContextBuilderOptions contextBuilderOptions) + { + return contextBuilderOptions.RetrieveOption(OriginalEventKey); } + + #endregion } \ No newline at end of file diff --git a/src/Navigator/Context/NavigatorContextFactory.cs b/src/Navigator/Context/NavigatorContextFactory.cs index 3e8d513..1baa1c8 100644 --- a/src/Navigator/Context/NavigatorContextFactory.cs +++ b/src/Navigator/Context/NavigatorContextFactory.cs @@ -2,38 +2,37 @@ using System.Threading.Tasks; using Microsoft.Extensions.Logging; -namespace Navigator.Context +namespace Navigator.Context; + +internal class NavigatorContextFactory : INavigatorContextFactory { - public class NavigatorContextFactory : INavigatorContextFactory - { - private readonly ILogger _logger; - private readonly INavigatorContextBuilder _navigatorContextBuilder; - private INavigatorContext NavigatorContext { get; set; } + private readonly ILogger _logger; + private readonly INavigatorContextBuilder _navigatorContextBuilder; + private INavigatorContext? NavigatorContext { get; set; } - public NavigatorContextFactory(ILogger logger, INavigatorContextBuilder navigatorContextBuilder) - { - _logger = logger; - _navigatorContextBuilder = navigatorContextBuilder; - } + public NavigatorContextFactory(ILogger logger, INavigatorContextBuilder navigatorContextBuilder) + { + _logger = logger; + _navigatorContextBuilder = navigatorContextBuilder; + } - public async Task Supply(Action action) + public async Task Supply(Action action) + { + try { - try - { - _logger.LogTrace("Building a new NavigatorContext"); + _logger.LogTrace("Building a new NavigatorContext"); - NavigatorContext = await _navigatorContextBuilder.Build(action); - } - catch (Exception e) - { - _logger.LogError(e, "Unhandled exception building NavigatorContext"); - throw; - } + NavigatorContext = await _navigatorContextBuilder.Build(action); } - - public INavigatorContext Retrieve() + catch (Exception e) { - return NavigatorContext ?? throw new NullReferenceException(); + _logger.LogError(e, "Unhandled exception building NavigatorContext"); + throw; } } + + public INavigatorContext Retrieve() + { + return NavigatorContext ?? throw new NullReferenceException(); + } } \ No newline at end of file diff --git a/src/Navigator/Entities/Bot.cs b/src/Navigator/Entities/Bot.cs index 3184ca2..a4e1789 100644 --- a/src/Navigator/Entities/Bot.cs +++ b/src/Navigator/Entities/Bot.cs @@ -7,17 +7,8 @@ namespace Navigator.Entities; public abstract class Bot : User { - protected Bot(string input) { Id = new Guid(SHA256.HashData(Encoding.UTF8.GetBytes(input)).Take(16).ToArray()); } - - /// - /// Id of the bot. - /// - /// Generally a deterministic Guid based on some kind of input. - /// - /// - public Guid Id { get; init; } } \ No newline at end of file diff --git a/src/Navigator/INavigatorClient.cs b/src/Navigator/INavigatorClient.cs index 6fb545f..f1e0fda 100644 --- a/src/Navigator/INavigatorClient.cs +++ b/src/Navigator/INavigatorClient.cs @@ -2,15 +2,14 @@ using System.Threading.Tasks; using Navigator.Entities; -namespace Navigator +namespace Navigator; + +public interface INavigatorClient { - public interface INavigatorClient - { - /// - /// Retrieves the bot user information. - /// - /// - /// - Task GetProfile(CancellationToken cancellationToken = default); - } + /// + /// Retrieves the bot user information. + /// + /// + /// + Task GetProfile(CancellationToken cancellationToken = default); } \ No newline at end of file diff --git a/src/Navigator/INavigatorProvider.cs b/src/Navigator/INavigatorProvider.cs index c3e3730..86ec8bc 100644 --- a/src/Navigator/INavigatorProvider.cs +++ b/src/Navigator/INavigatorProvider.cs @@ -1,16 +1,15 @@ using System.Threading.Tasks; -namespace Navigator +namespace Navigator; + +/// +/// Represents a provider for Navigator. +/// +public interface INavigatorProvider { /// - /// Represents a provider for Navigator. + /// Gets the specific client for this provider. /// - public interface INavigatorProvider - { - /// - /// Gets the specific client for this provider. - /// - /// An implementation of - INavigatorClient GetClient(); - } + /// An implementation of + INavigatorClient GetClient(); } \ No newline at end of file diff --git a/src/Navigator/NavigatorException.cs b/src/Navigator/NavigatorException.cs index db96b8c..a598fe0 100644 --- a/src/Navigator/NavigatorException.cs +++ b/src/Navigator/NavigatorException.cs @@ -1,31 +1,30 @@ using System; using System.Runtime.Serialization; -namespace Navigator +namespace Navigator; + +/// +/// TODO +/// +public class NavigatorException : Exception { - /// - /// TODO - /// - public class NavigatorException : Exception + /// + public NavigatorException() { - /// - public NavigatorException() - { - } + } - /// - protected NavigatorException(SerializationInfo info, StreamingContext context) : base(info, context) - { - } + /// + protected NavigatorException(SerializationInfo info, StreamingContext context) : base(info, context) + { + } - /// - public NavigatorException(string? message) : base(message) - { - } + /// + public NavigatorException(string? message) : base(message) + { + } - /// - public NavigatorException(string? message, Exception? innerException) : base(message, innerException) - { - } + /// + public NavigatorException(string? message, Exception? innerException) : base(message, innerException) + { } } \ No newline at end of file diff --git a/src/Navigator/Replies/ReplyBuilderOptions.cs b/src/Navigator/Replies/ReplyBuilderOptions.cs index 8f08365..79009b7 100644 --- a/src/Navigator/Replies/ReplyBuilderOptions.cs +++ b/src/Navigator/Replies/ReplyBuilderOptions.cs @@ -1,7 +1,6 @@ -namespace Navigator.Replies +namespace Navigator.Replies; + +public class ReplyBuilderOptions { - public class ReplyBuilderOptions - { - } } \ No newline at end of file diff --git a/src/Navigator/ServiceCollectionExtensions.cs b/src/Navigator/ServiceCollectionExtensions.cs index 9cfba06..0eae86a 100644 --- a/src/Navigator/ServiceCollectionExtensions.cs +++ b/src/Navigator/ServiceCollectionExtensions.cs @@ -10,48 +10,47 @@ using Navigator.Context.Extensions.Bundled.OriginalEvent; using Scrutor; -namespace Navigator +namespace Navigator; + +public static class ServiceCollectionExtensions { - public static class ServiceCollectionExtensions + public static NavigatorConfiguration AddNavigator(this IServiceCollection services, Action options) { - public static NavigatorConfiguration AddNavigator(this IServiceCollection services, Action options) + if (options == null) { - if (options == null) - { - throw new ArgumentNullException(nameof(options), "Navigator options are required for navigator framework to work."); - } + throw new ArgumentNullException(nameof(options), "Navigator options are required for navigator framework to work."); + } - var navigatorBuilder = new NavigatorConfiguration(options, services); + var navigatorBuilder = new NavigatorConfiguration(options, services); - services.AddNavigatorContextServices(); + services.AddNavigatorContextServices(); - services.AddScoped(); + services.AddScoped(); - services.AddScoped(); + services.AddScoped(); - services.AddMediatR(navigatorBuilder.Options.GetActionsAssemblies()); + services.AddMediatR(navigatorBuilder.Options.GetActionsAssemblies()); - services.Scan(scan => scan - .FromAssemblies(navigatorBuilder.Options.GetActionsAssemblies()) - .AddClasses(classes => classes.AssignableTo()) - .UsingRegistrationStrategy(RegistrationStrategy.Append) - .AsSelf() - .WithScopedLifetime()); + services.Scan(scan => scan + .FromAssemblies(navigatorBuilder.Options.GetActionsAssemblies()) + .AddClasses(classes => classes.AssignableTo()) + .UsingRegistrationStrategy(RegistrationStrategy.Append) + .AsSelf() + .WithScopedLifetime()); - navigatorBuilder.Options.RegisterActions(services - .Where(descriptor => descriptor.ImplementationType?.IsAssignableTo(typeof(IAction)) ?? false) - .Select(descriptor => descriptor.ImplementationType!)); + navigatorBuilder.Options.RegisterActions(services + .Where(descriptor => descriptor.ImplementationType?.IsAssignableTo(typeof(IAction)) ?? false) + .Select(descriptor => descriptor.ImplementationType!)); - navigatorBuilder.RegisterOrReplaceOptions(); + navigatorBuilder.RegisterOrReplaceOptions(); - return navigatorBuilder; - } + return navigatorBuilder; + } - internal static void AddNavigatorContextServices(this IServiceCollection services) - { - services.AddScoped(); - services.AddScoped(); - services.AddTransient(); - } + internal static void AddNavigatorContextServices(this IServiceCollection services) + { + services.AddScoped(); + services.AddScoped(); + services.AddTransient(); } } \ No newline at end of file From 367e9604bedc040ba490dcead2e3a7f692db0447 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 20 Dec 2021 17:52:09 +0100 Subject: [PATCH 221/304] feat: rename entities --- .../Entities/{Chat.cs => UniversalChat.cs} | 10 +++++----- .../{Conversation.cs => UniversalConversation.cs} | 6 +++--- .../Entities/{User.cs => UniversalUser.cs} | 10 +++++----- 3 files changed, 13 insertions(+), 13 deletions(-) rename src/Navigator.Extensions.Store/Entities/{Chat.cs => UniversalChat.cs} (68%) rename src/Navigator.Extensions.Store/Entities/{Conversation.cs => UniversalConversation.cs} (54%) rename src/Navigator.Extensions.Store/Entities/{User.cs => UniversalUser.cs} (68%) diff --git a/src/Navigator.Extensions.Store/Entities/Chat.cs b/src/Navigator.Extensions.Store/Entities/UniversalChat.cs similarity index 68% rename from src/Navigator.Extensions.Store/Entities/Chat.cs rename to src/Navigator.Extensions.Store/Entities/UniversalChat.cs index 85c1c69..cec380b 100644 --- a/src/Navigator.Extensions.Store/Entities/Chat.cs +++ b/src/Navigator.Extensions.Store/Entities/UniversalChat.cs @@ -1,11 +1,11 @@ using Navigator.Extensions.Store.Entities; -public class Chat : Navigator.Entities.Chat +public class UniversalChat : Navigator.Entities.Chat { - public Chat() + public UniversalChat() { ProviderEntities = new List(); - Users = new List(); + Users = new List(); } public Guid Id { get; set; } @@ -15,9 +15,9 @@ public Chat() /// /// Users related to the chat. /// - public ICollection Users { get; set; } + public ICollection Users { get; set; } - public ICollection Conversations { get; set; } + public ICollection Conversations { get; set; } /// /// Date of first interaction for this chat. diff --git a/src/Navigator.Extensions.Store/Entities/Conversation.cs b/src/Navigator.Extensions.Store/Entities/UniversalConversation.cs similarity index 54% rename from src/Navigator.Extensions.Store/Entities/Conversation.cs rename to src/Navigator.Extensions.Store/Entities/UniversalConversation.cs index d73e1d7..b3c44c9 100644 --- a/src/Navigator.Extensions.Store/Entities/Conversation.cs +++ b/src/Navigator.Extensions.Store/Entities/UniversalConversation.cs @@ -1,10 +1,10 @@ namespace Navigator.Extensions.Store.Entities; -public class Conversation : Navigator.Entities.Conversation +public class UniversalConversation : Navigator.Entities.Conversation { - public Chat Chat { get; set; } + public new UniversalChat Chat { get; set; } - public User User { get; set; } + public new UniversalUser User { get; set; } /// /// Date of first interaction for this chat. diff --git a/src/Navigator.Extensions.Store/Entities/User.cs b/src/Navigator.Extensions.Store/Entities/UniversalUser.cs similarity index 68% rename from src/Navigator.Extensions.Store/Entities/User.cs rename to src/Navigator.Extensions.Store/Entities/UniversalUser.cs index 9bef4a6..1406473 100644 --- a/src/Navigator.Extensions.Store/Entities/User.cs +++ b/src/Navigator.Extensions.Store/Entities/UniversalUser.cs @@ -1,11 +1,11 @@ namespace Navigator.Extensions.Store.Entities; -public class User : Navigator.Entities.User +public class UniversalUser : Navigator.Entities.User { - public User() + public UniversalUser() { ProviderEntities = new List(); - Chats = new List(); + Chats = new List(); } public Guid Id { get; set; } @@ -14,9 +14,9 @@ public User() /// /// Chats related to the user. /// - public IList Chats { get; set; } + public IList Chats { get; set; } - public ICollection Conversations { get; set; } + public ICollection Conversations { get; set; } /// /// Date of first interaction for this chat. From de9a6495e794596732cda279f5ea158723d0b881 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 20 Dec 2021 17:52:38 +0100 Subject: [PATCH 222/304] feat: correct entity type configurations --- .../Configuration/ChatEntityTypeConfiguration.cs | 6 +++--- .../Configuration/ConversationEntityTypeConfiguration.cs | 4 ++-- .../Configuration/UserEntityTypeConfiguration.cs | 6 +++--- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/Navigator.Extensions.Store/Configuration/ChatEntityTypeConfiguration.cs b/src/Navigator.Extensions.Store/Configuration/ChatEntityTypeConfiguration.cs index 7f08fd1..c34facb 100644 --- a/src/Navigator.Extensions.Store/Configuration/ChatEntityTypeConfiguration.cs +++ b/src/Navigator.Extensions.Store/Configuration/ChatEntityTypeConfiguration.cs @@ -4,9 +4,9 @@ namespace Navigator.Extensions.Store.Configuration; -public class ChatEntityTypeConfiguration : IEntityTypeConfiguration +public class ChatEntityTypeConfiguration : IEntityTypeConfiguration { - public void Configure(EntityTypeBuilder builder) + public void Configure(EntityTypeBuilder builder) { builder.HasKey(e => e.Id); @@ -15,7 +15,7 @@ public void Configure(EntityTypeBuilder builder) builder.HasMany(e => e.Users) .WithMany(e => e.Chats) - .UsingEntity( + .UsingEntity( e => e.HasOne(e => e.User) .WithMany(e => e.Conversations), e=> e.HasOne(e => e.Chat) diff --git a/src/Navigator.Extensions.Store/Configuration/ConversationEntityTypeConfiguration.cs b/src/Navigator.Extensions.Store/Configuration/ConversationEntityTypeConfiguration.cs index 245f1d1..155f2e5 100644 --- a/src/Navigator.Extensions.Store/Configuration/ConversationEntityTypeConfiguration.cs +++ b/src/Navigator.Extensions.Store/Configuration/ConversationEntityTypeConfiguration.cs @@ -4,9 +4,9 @@ namespace Navigator.Extensions.Store.Configuration; -public class ConversationEntityTypeConfiguration : IEntityTypeConfiguration +public class ConversationEntityTypeConfiguration : IEntityTypeConfiguration { - public void Configure(EntityTypeBuilder builder) + public void Configure(EntityTypeBuilder builder) { builder.Property(e => e.FirstInteractionAt) .IsRequired(); diff --git a/src/Navigator.Extensions.Store/Configuration/UserEntityTypeConfiguration.cs b/src/Navigator.Extensions.Store/Configuration/UserEntityTypeConfiguration.cs index 58b92b4..e32ac7c 100644 --- a/src/Navigator.Extensions.Store/Configuration/UserEntityTypeConfiguration.cs +++ b/src/Navigator.Extensions.Store/Configuration/UserEntityTypeConfiguration.cs @@ -4,9 +4,9 @@ namespace Navigator.Extensions.Store.Configuration; -public class UserEntityTypeConfiguration : IEntityTypeConfiguration +public class UserEntityTypeConfiguration : IEntityTypeConfiguration { - public void Configure(EntityTypeBuilder builder) + public void Configure(EntityTypeBuilder builder) { builder.HasKey(e => e.Id); @@ -15,7 +15,7 @@ public void Configure(EntityTypeBuilder builder) builder.HasMany(e => e.Chats) .WithMany(e => e.Users) - .UsingEntity( + .UsingEntity( e => e.HasOne(e => e.Chat) .WithMany(e => e.Conversations), e=> e.HasOne(e => e.User) From e1734d146a5612dc9ec9bbcb9b89b07404e66835 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 20 Dec 2021 17:52:48 +0100 Subject: [PATCH 223/304] feat: simplify NavigatorDbContext --- .../NavigatorDbContext.cs | 15 +++------------ 1 file changed, 3 insertions(+), 12 deletions(-) diff --git a/src/Navigator.Extensions.Store/NavigatorDbContext.cs b/src/Navigator.Extensions.Store/NavigatorDbContext.cs index 0ad9f88..b694ef2 100644 --- a/src/Navigator.Extensions.Store/NavigatorDbContext.cs +++ b/src/Navigator.Extensions.Store/NavigatorDbContext.cs @@ -4,19 +4,10 @@ namespace Navigator.Extensions.Store; -public class NavigatorDbContext : NavigatorDbContext +public class NavigatorDbContext : DbContext { - public NavigatorDbContext(DbContextOptions options) : base(options) - { - } -} - -public class NavigatorDbContext : DbContext - where TUser : User - where TChat : Chat -{ - public DbSet Users { get; set; } - public DbSet Chats { get; set; } + public DbSet Users { get; set; } + public DbSet Chats { get; set; } protected DbSet NavigatorProviderUserEntities { get; set; } protected DbSet NavigatorProviderChatEntities { get; set; } From 570d320f579bacb701c69e37b5caf0acb98e4ad7 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 20 Dec 2021 17:53:12 +0100 Subject: [PATCH 224/304] feat: implement Store as an INavigatorContextExtension --- .../Bundled/StoreContextExtension.cs | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 src/Navigator.Extensions.Store/Bundled/StoreContextExtension.cs diff --git a/src/Navigator.Extensions.Store/Bundled/StoreContextExtension.cs b/src/Navigator.Extensions.Store/Bundled/StoreContextExtension.cs new file mode 100644 index 0000000..9ea4479 --- /dev/null +++ b/src/Navigator.Extensions.Store/Bundled/StoreContextExtension.cs @@ -0,0 +1,24 @@ +using Navigator.Context; +using Navigator.Context.Extensions; +using Navigator.Extensions.Store.Entities; + +namespace Navigator.Extensions.Store.Bundled; + +public class StoreContextExtension: INavigatorContextExtension +{ + public const string StoreKey = "_navigator.extensions.navigator_store"; + + private readonly NavigatorDbContext _navigatorDbContext; + + public StoreContextExtension(NavigatorDbContext navigatorDbContext) + { + _navigatorDbContext = navigatorDbContext; + } + + public Task Extend(INavigatorContext navigatorContext, INavigatorContextBuilderOptions builderOptions) + { + navigatorContext.Extensions.Add(StoreKey, _navigatorDbContext); + + return Task.FromResult(navigatorContext); + } +} \ No newline at end of file From 5a4204081580587541ffd061a978c45bfd708f93 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 20 Dec 2021 17:53:39 +0100 Subject: [PATCH 225/304] feat: add common extensions to NavigatorContext --- .../NavigatorContextExtensions.cs | 87 +++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 src/Navigator.Extensions.Store/NavigatorContextExtensions.cs diff --git a/src/Navigator.Extensions.Store/NavigatorContextExtensions.cs b/src/Navigator.Extensions.Store/NavigatorContextExtensions.cs new file mode 100644 index 0000000..cb09fec --- /dev/null +++ b/src/Navigator.Extensions.Store/NavigatorContextExtensions.cs @@ -0,0 +1,87 @@ +using Microsoft.EntityFrameworkCore; +using Navigator.Context; +using Navigator.Extensions.Store.Bundled; +using Navigator.Extensions.Store.Entities; + +namespace Navigator.Extensions.Store; + +/// +/// Useful extensions for Navigator Context. +/// +public static class NavigatorContextExtensions +{ + #region Store + + public static NavigatorDbContext GetStore(this INavigatorContext context) + { + return GetStoreOrDefault(context) ?? throw new InvalidOperationException(); + } + + public static NavigatorDbContext? GetStoreOrDefault(this INavigatorContext context) + { + var value = context.Extensions.GetValueOrDefault(StoreContextExtension.StoreKey); + + if (value is NavigatorDbContext store) + { + return store; + } + + return default; + } + + #endregion + + #region User + + public static async Task GetUniversalChat(this INavigatorContext context) + { + return await GetUniversalChatOrDefault(context) ?? throw new InvalidOperationException(); + } + + public static async Task GetUniversalChatOrDefault(this INavigatorContext context) + { + return await context.GetStore().Chats + .AsNoTracking() + .FirstOrDefaultAsync(e => e.ProviderEntities + .Any(p => p.Id == context.Conversation.Chat.Id)); + } + + #endregion + + #region Conversation + + public static async Task GetUniversalConversation(this INavigatorContext context) + { + return await GetUniversalConversationOrDefault(context) ?? throw new InvalidOperationException(); + } + + public static async Task GetUniversalConversationOrDefault(this INavigatorContext context) + { + return await context.GetStore().Users + .AsNoTracking() + .Where(e => e.ProviderEntities + .Any(p => p.Id == context.Conversation.User.Id)) + .Select(e => e.Conversations.FirstOrDefault(c => c.Chat.ProviderEntities + .Any(p => p.Id == context.Conversation.Chat.Id))) + .FirstOrDefaultAsync(); + } + + #endregion + + #region User + + public static async Task GetUniversalUser(this INavigatorContext context) + { + return await GetUniversalUserOrDefault(context) ?? throw new InvalidOperationException(); + } + + public static async Task GetUniversalUserOrDefault(this INavigatorContext context) + { + return await context.GetStore().Users + .AsNoTracking() + .FirstOrDefaultAsync(e => e.ProviderEntities + .Any(p => p.Id == context.Conversation.User.Id)); + } + + #endregion +} \ No newline at end of file From 6dedc2273977c883b884e58ca1b736f4dacb4e21 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 20 Dec 2021 17:53:47 +0100 Subject: [PATCH 226/304] feat: rename solution folder --- src/Navigator.sln | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Navigator.sln b/src/Navigator.sln index 81a6e2c..fb0e2f5 100644 --- a/src/Navigator.sln +++ b/src/Navigator.sln @@ -3,7 +3,7 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Navigator", "Navigator\Navi EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Samples", "Samples", "{6D6A8E40-8C40-49AA-BEAD-B046D43F511A}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Navigator", "Navigator", "{E6F24E3B-A066-4572-94F0-14665E19EFC7}" +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Packages", "Packages", "{E6F24E3B-A066-4572-94F0-14665E19EFC7}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Providers", "Providers", "{DAA22477-BB29-475C-AD2C-905F81B4AD8E}" EndProject From caac196ef7fb39a299171b09b3f8bd85e79b604e Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 20 Dec 2021 18:07:33 +0100 Subject: [PATCH 227/304] chore: list necessary settings for sample to run --- src/Navigator.Samples.Echo/appsettings.Development.json | 7 +------ src/Navigator.Samples.Echo/appsettings.json | 9 ++------- 2 files changed, 3 insertions(+), 13 deletions(-) diff --git a/src/Navigator.Samples.Echo/appsettings.Development.json b/src/Navigator.Samples.Echo/appsettings.Development.json index 0c208ae..1797133 100644 --- a/src/Navigator.Samples.Echo/appsettings.Development.json +++ b/src/Navigator.Samples.Echo/appsettings.Development.json @@ -1,8 +1,3 @@ { - "Logging": { - "LogLevel": { - "Default": "Information", - "Microsoft.AspNetCore": "Warning" - } - } + } diff --git a/src/Navigator.Samples.Echo/appsettings.json b/src/Navigator.Samples.Echo/appsettings.json index 10f68b8..da75fb0 100644 --- a/src/Navigator.Samples.Echo/appsettings.json +++ b/src/Navigator.Samples.Echo/appsettings.json @@ -1,9 +1,4 @@ { - "Logging": { - "LogLevel": { - "Default": "Information", - "Microsoft.AspNetCore": "Warning" - } - }, - "AllowedHosts": "*" + "BASE_WEBHOOK_URL": "", + "BOT_TOKEN": "" } From 0201f47245e6746cf630b38a39818124372027cf Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 20 Dec 2021 18:11:47 +0100 Subject: [PATCH 228/304] feat: add store sample --- .../Actions/CooldownAction.cs | 18 ++++++++ .../Actions/CooldownActionHandler.cs | 23 ++++++++++ .../Actions/EchoAction.cs | 19 ++++++++ .../Actions/EchoActionHandler.cs | 23 ++++++++++ .../Navigator.Samples.Store.csproj | 21 +++++++++ src/Navigator.Samples.Store/Program.cs | 45 +++++++++++++++++++ .../appsettings.Development.json | 3 ++ src/Navigator.Samples.Store/appsettings.json | 7 +++ src/Navigator.sln | 7 +++ 9 files changed, 166 insertions(+) create mode 100644 src/Navigator.Samples.Store/Actions/CooldownAction.cs create mode 100644 src/Navigator.Samples.Store/Actions/CooldownActionHandler.cs create mode 100644 src/Navigator.Samples.Store/Actions/EchoAction.cs create mode 100644 src/Navigator.Samples.Store/Actions/EchoActionHandler.cs create mode 100644 src/Navigator.Samples.Store/Navigator.Samples.Store.csproj create mode 100644 src/Navigator.Samples.Store/Program.cs create mode 100644 src/Navigator.Samples.Store/appsettings.Development.json create mode 100644 src/Navigator.Samples.Store/appsettings.json diff --git a/src/Navigator.Samples.Store/Actions/CooldownAction.cs b/src/Navigator.Samples.Store/Actions/CooldownAction.cs new file mode 100644 index 0000000..776c81e --- /dev/null +++ b/src/Navigator.Samples.Store/Actions/CooldownAction.cs @@ -0,0 +1,18 @@ +using Navigator.Context; +using Navigator.Extensions.Cooldown; +using Navigator.Providers.Telegram.Actions.Messages; + +namespace Navigator.Samples.Echo.Actions; + +[Cooldown(Seconds = 10)] +public class CooldownAction : CommandAction +{ + public CooldownAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) + { + } + + public override bool CanHandleCurrentContext() + { + return Command.StartsWith("/cooldown", true, default); + } +} \ No newline at end of file diff --git a/src/Navigator.Samples.Store/Actions/CooldownActionHandler.cs b/src/Navigator.Samples.Store/Actions/CooldownActionHandler.cs new file mode 100644 index 0000000..573e08c --- /dev/null +++ b/src/Navigator.Samples.Store/Actions/CooldownActionHandler.cs @@ -0,0 +1,23 @@ +using System.Threading; +using System.Threading.Tasks; +using Navigator.Actions; +using Navigator.Context; +using Navigator.Providers.Telegram; +using Telegram.Bot; + +namespace Navigator.Samples.Echo.Actions; + +public class CooldownActionHandler : ActionHandler +{ + public CooldownActionHandler(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) + { + } + + public override async Task Handle(CooldownAction action, CancellationToken cancellationToken) + { + await this.GetTelegramClient().SendTextMessageAsync(this.GetTelegramChat().Id, + "not in cooldown", cancellationToken: cancellationToken); + + return Success(); + } +} \ No newline at end of file diff --git a/src/Navigator.Samples.Store/Actions/EchoAction.cs b/src/Navigator.Samples.Store/Actions/EchoAction.cs new file mode 100644 index 0000000..5546372 --- /dev/null +++ b/src/Navigator.Samples.Store/Actions/EchoAction.cs @@ -0,0 +1,19 @@ +using Navigator.Context; +using Navigator.Providers.Telegram.Actions.Messages; + +namespace Navigator.Samples.Echo.Actions; + +public class EchoAction : MessageAction +{ + public readonly string MessageToEcho; + + public EchoAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) + { + MessageToEcho = !string.IsNullOrWhiteSpace(Message.Text) ? Message.Text : string.Empty; + } + + public override bool CanHandleCurrentContext() + { + return !string.IsNullOrWhiteSpace(MessageToEcho); + } +} \ No newline at end of file diff --git a/src/Navigator.Samples.Store/Actions/EchoActionHandler.cs b/src/Navigator.Samples.Store/Actions/EchoActionHandler.cs new file mode 100644 index 0000000..120329d --- /dev/null +++ b/src/Navigator.Samples.Store/Actions/EchoActionHandler.cs @@ -0,0 +1,23 @@ +using System.Threading; +using System.Threading.Tasks; +using Navigator.Actions; +using Navigator.Context; +using Navigator.Providers.Telegram; +using Telegram.Bot; + +namespace Navigator.Samples.Echo.Actions; + +public class EchoActionHandler : ActionHandler +{ + public EchoActionHandler(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) + { + } + + public override async Task Handle(EchoAction action, CancellationToken cancellationToken) + { + await this.GetTelegramClient().SendTextMessageAsync(this.GetTelegramChat().Id, + action.MessageToEcho, cancellationToken: cancellationToken); + + return Success(); + } +} \ No newline at end of file diff --git a/src/Navigator.Samples.Store/Navigator.Samples.Store.csproj b/src/Navigator.Samples.Store/Navigator.Samples.Store.csproj new file mode 100644 index 0000000..fc6d327 --- /dev/null +++ b/src/Navigator.Samples.Store/Navigator.Samples.Store.csproj @@ -0,0 +1,21 @@ + + + + net6.0 + enable + enable + + + + + + + + + + + + + + + diff --git a/src/Navigator.Samples.Store/Program.cs b/src/Navigator.Samples.Store/Program.cs new file mode 100644 index 0000000..36dde46 --- /dev/null +++ b/src/Navigator.Samples.Store/Program.cs @@ -0,0 +1,45 @@ +using Microsoft.AspNetCore.Builder; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Navigator; +using Navigator.Configuration; +using Navigator.Extensions.Cooldown; +using Navigator.Extensions.Store; +using Navigator.Providers.Telegram; +using Navigator.Samples.Echo.Actions; + +var builder = WebApplication.CreateBuilder(args); + +// Add services to the container. + +// For Extensions.Cooldown +builder.Services.AddDistributedMemoryCache(); + +builder.Services + .AddNavigator(options => + { + options.SetWebHookBaseUrl(builder.Configuration["BASE_WEBHOOK_URL"]); + options.RegisterActionsFromAssemblies(typeof(EchoAction).Assembly); + }) + .WithProvider.Telegram(options => { options.SetTelegramToken(builder.Configuration["BOT_TOKEN"]); }) + .WithExtension.Cooldown() + .WithExtension.Store(dbBuilder => + { + dbBuilder.UseSqlite(builder.Configuration.GetConnectionString("DefaultConnection"), + b => b.MigrationsAssembly("Navigator.Samples.Echo")); + }); + +var app = builder.Build(); + +// Configure the HTTP request pipeline. +if (app.Environment.IsDevelopment()) +{ +} + +app.UseHttpsRedirection(); + +app.MapNavigator() + .ForProvider.Telegram(); + +app.Run(); \ No newline at end of file diff --git a/src/Navigator.Samples.Store/appsettings.Development.json b/src/Navigator.Samples.Store/appsettings.Development.json new file mode 100644 index 0000000..077404a --- /dev/null +++ b/src/Navigator.Samples.Store/appsettings.Development.json @@ -0,0 +1,3 @@ +{ + +} \ No newline at end of file diff --git a/src/Navigator.Samples.Store/appsettings.json b/src/Navigator.Samples.Store/appsettings.json new file mode 100644 index 0000000..3fca8c5 --- /dev/null +++ b/src/Navigator.Samples.Store/appsettings.json @@ -0,0 +1,7 @@ +{ + "ConnectionStrings": { + "DefaultConnection": "DataSource=app.db" + }, + "BASE_WEBHOOK_URL": "", + "BOT_TOKEN": "" +} diff --git a/src/Navigator.sln b/src/Navigator.sln index fb0e2f5..1a45399 100644 --- a/src/Navigator.sln +++ b/src/Navigator.sln @@ -17,6 +17,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Extensions", "Extensions", EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Navigator.Extensions.Store", "Navigator.Extensions.Store\Navigator.Extensions.Store.csproj", "{E7D6F33B-C30E-4ED2-878C-B2F899CF1805}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Navigator.Samples.Store", "Navigator.Samples.Store\Navigator.Samples.Store.csproj", "{50766B99-2587-4298-B43C-58DE387F5860}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -43,6 +45,10 @@ Global {E7D6F33B-C30E-4ED2-878C-B2F899CF1805}.Debug|Any CPU.Build.0 = Debug|Any CPU {E7D6F33B-C30E-4ED2-878C-B2F899CF1805}.Release|Any CPU.ActiveCfg = Release|Any CPU {E7D6F33B-C30E-4ED2-878C-B2F899CF1805}.Release|Any CPU.Build.0 = Release|Any CPU + {50766B99-2587-4298-B43C-58DE387F5860}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {50766B99-2587-4298-B43C-58DE387F5860}.Debug|Any CPU.Build.0 = Debug|Any CPU + {50766B99-2587-4298-B43C-58DE387F5860}.Release|Any CPU.ActiveCfg = Release|Any CPU + {50766B99-2587-4298-B43C-58DE387F5860}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(NestedProjects) = preSolution {6DBAD041-6623-4903-9939-254FDC4EBD60} = {E6F24E3B-A066-4572-94F0-14665E19EFC7} @@ -52,5 +58,6 @@ Global {DAA22477-BB29-475C-AD2C-905F81B4AD8E} = {E6F24E3B-A066-4572-94F0-14665E19EFC7} {A6DF6F5F-F784-4EF1-97D1-C3DDD2E66B5E} = {E6F24E3B-A066-4572-94F0-14665E19EFC7} {E7D6F33B-C30E-4ED2-878C-B2F899CF1805} = {A6DF6F5F-F784-4EF1-97D1-C3DDD2E66B5E} + {50766B99-2587-4298-B43C-58DE387F5860} = {6D6A8E40-8C40-49AA-BEAD-B046D43F511A} EndGlobalSection EndGlobal From 1f1e41d6808bc96d407879255fe5e5f31479887b Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Wed, 22 Dec 2021 13:11:54 +0100 Subject: [PATCH 229/304] feat: refactor from ProviderEntities to Profiles --- .../ChatEntityTypeConfiguration.cs | 4 +-- .../ConversationEntityTypeConfiguration.cs | 3 +++ .../NavigatorProviderChatEntity.cs | 12 --------- .../NavigatorProviderUserEntity.cs | 13 ---------- .../ProfileEntityTypeConfiguration.cs | 25 +++++++++++++++++++ .../UserEntityTypeConfiguration.cs | 4 +-- .../Entities/UniversalChat.cs | 8 +----- .../Entities/UniversalConversation.cs | 4 +++ .../Entities/UniversalProfile.cs | 25 +++++++++++++++++++ .../Entities/UniversalUser.cs | 8 +----- .../NavigatorContextExtensions.cs | 16 ++++++------ .../NavigatorDbContext.cs | 10 +++++--- ...vigatorExtensionConfigurationExtensions.cs | 23 +++++++++++++++++ 13 files changed, 101 insertions(+), 54 deletions(-) delete mode 100644 src/Navigator.Extensions.Store/Configuration/NavigatorProviderChatEntity.cs delete mode 100644 src/Navigator.Extensions.Store/Configuration/NavigatorProviderUserEntity.cs create mode 100644 src/Navigator.Extensions.Store/Configuration/ProfileEntityTypeConfiguration.cs create mode 100644 src/Navigator.Extensions.Store/Entities/UniversalProfile.cs create mode 100644 src/Navigator.Extensions.Store/NavigatorExtensionConfigurationExtensions.cs diff --git a/src/Navigator.Extensions.Store/Configuration/ChatEntityTypeConfiguration.cs b/src/Navigator.Extensions.Store/Configuration/ChatEntityTypeConfiguration.cs index c34facb..d8b96f1 100644 --- a/src/Navigator.Extensions.Store/Configuration/ChatEntityTypeConfiguration.cs +++ b/src/Navigator.Extensions.Store/Configuration/ChatEntityTypeConfiguration.cs @@ -10,9 +10,9 @@ public void Configure(EntityTypeBuilder builder) { builder.HasKey(e => e.Id); - builder.HasMany(e => e.ProviderEntities) + builder.HasMany(e => e.Profiles) .WithOne(); - + builder.HasMany(e => e.Users) .WithMany(e => e.Chats) .UsingEntity( diff --git a/src/Navigator.Extensions.Store/Configuration/ConversationEntityTypeConfiguration.cs b/src/Navigator.Extensions.Store/Configuration/ConversationEntityTypeConfiguration.cs index 155f2e5..16aba29 100644 --- a/src/Navigator.Extensions.Store/Configuration/ConversationEntityTypeConfiguration.cs +++ b/src/Navigator.Extensions.Store/Configuration/ConversationEntityTypeConfiguration.cs @@ -10,5 +10,8 @@ public void Configure(EntityTypeBuilder builder) { builder.Property(e => e.FirstInteractionAt) .IsRequired(); + + builder.HasMany(e => e.Profiles) + .WithOne(); } } \ No newline at end of file diff --git a/src/Navigator.Extensions.Store/Configuration/NavigatorProviderChatEntity.cs b/src/Navigator.Extensions.Store/Configuration/NavigatorProviderChatEntity.cs deleted file mode 100644 index 6c301b3..0000000 --- a/src/Navigator.Extensions.Store/Configuration/NavigatorProviderChatEntity.cs +++ /dev/null @@ -1,12 +0,0 @@ -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Metadata.Builders; - -namespace Navigator.Extensions.Store.Configuration; - -public class NavigatorProviderChatEntity : IEntityTypeConfiguration -{ - public void Configure(EntityTypeBuilder builder) - { - builder.HasKey(e => e.Id); - } -} \ No newline at end of file diff --git a/src/Navigator.Extensions.Store/Configuration/NavigatorProviderUserEntity.cs b/src/Navigator.Extensions.Store/Configuration/NavigatorProviderUserEntity.cs deleted file mode 100644 index 33a2368..0000000 --- a/src/Navigator.Extensions.Store/Configuration/NavigatorProviderUserEntity.cs +++ /dev/null @@ -1,13 +0,0 @@ -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Metadata.Builders; -using Navigator.Extensions.Store.Entities; - -namespace Navigator.Extensions.Store.Configuration; - -public class NavigatorProviderUserEntity : IEntityTypeConfiguration -{ - public void Configure(EntityTypeBuilder builder) - { - builder.HasKey(e => e.Id); - } -} \ No newline at end of file diff --git a/src/Navigator.Extensions.Store/Configuration/ProfileEntityTypeConfiguration.cs b/src/Navigator.Extensions.Store/Configuration/ProfileEntityTypeConfiguration.cs new file mode 100644 index 0000000..6f9f613 --- /dev/null +++ b/src/Navigator.Extensions.Store/Configuration/ProfileEntityTypeConfiguration.cs @@ -0,0 +1,25 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; +using Navigator.Extensions.Store.Entities; + +namespace Navigator.Extensions.Store.Configuration; + +public class ProfileEntityTypeConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder builder) + { + builder.HasKey(e => e.Id); + + builder.Property(e => e.Provider) + .IsRequired(); + + builder.Property(e => e.Identification) + .IsRequired(); + + builder.Property(e => e.CreatedAt) + .IsRequired(); + + builder.Property(e => e.LastUpdatedAt) + .IsRequired(); + } +} \ No newline at end of file diff --git a/src/Navigator.Extensions.Store/Configuration/UserEntityTypeConfiguration.cs b/src/Navigator.Extensions.Store/Configuration/UserEntityTypeConfiguration.cs index e32ac7c..c6a2168 100644 --- a/src/Navigator.Extensions.Store/Configuration/UserEntityTypeConfiguration.cs +++ b/src/Navigator.Extensions.Store/Configuration/UserEntityTypeConfiguration.cs @@ -10,9 +10,9 @@ public void Configure(EntityTypeBuilder builder) { builder.HasKey(e => e.Id); - builder.HasMany(e => e.ProviderEntities) + builder.HasMany(e => e.Profiles) .WithOne(); - + builder.HasMany(e => e.Chats) .WithMany(e => e.Users) .UsingEntity( diff --git a/src/Navigator.Extensions.Store/Entities/UniversalChat.cs b/src/Navigator.Extensions.Store/Entities/UniversalChat.cs index cec380b..310b4c1 100644 --- a/src/Navigator.Extensions.Store/Entities/UniversalChat.cs +++ b/src/Navigator.Extensions.Store/Entities/UniversalChat.cs @@ -4,13 +4,12 @@ public class UniversalChat : Navigator.Entities.Chat { public UniversalChat() { - ProviderEntities = new List(); Users = new List(); } public Guid Id { get; set; } - public IList ProviderEntities { get; set; } + public IList Profiles { get; set; } /// /// Users related to the chat. @@ -23,9 +22,4 @@ public UniversalChat() /// Date of first interaction for this chat. /// public DateTime FirstInteractionAt { get; set; } -} - -public interface INavigatorProviderChatEntity -{ - public Guid Id { get; set; } } \ No newline at end of file diff --git a/src/Navigator.Extensions.Store/Entities/UniversalConversation.cs b/src/Navigator.Extensions.Store/Entities/UniversalConversation.cs index b3c44c9..07d7e8e 100644 --- a/src/Navigator.Extensions.Store/Entities/UniversalConversation.cs +++ b/src/Navigator.Extensions.Store/Entities/UniversalConversation.cs @@ -1,3 +1,5 @@ +using Navigator.Entities; + namespace Navigator.Extensions.Store.Entities; public class UniversalConversation : Navigator.Entities.Conversation @@ -6,6 +8,8 @@ public class UniversalConversation : Navigator.Entities.Conversation public new UniversalUser User { get; set; } + public IList Profiles { get; set; } + /// /// Date of first interaction for this chat. /// diff --git a/src/Navigator.Extensions.Store/Entities/UniversalProfile.cs b/src/Navigator.Extensions.Store/Entities/UniversalProfile.cs new file mode 100644 index 0000000..762627b --- /dev/null +++ b/src/Navigator.Extensions.Store/Entities/UniversalProfile.cs @@ -0,0 +1,25 @@ +namespace Navigator.Extensions.Store.Entities; + +public class UniversalProfile +{ + public Guid Id { get; set; } + public string Provider { get; set; } + public Guid Identification { get; set; } + public DateTime CreatedAt { get; set; } + public DateTime LastUpdatedAt { get; set; } +} + +public class UserProfile : UniversalProfile +{ + +} + +public class ChatProfile : UniversalProfile +{ + +} + +public class ConversationProfile : UniversalProfile +{ + +} \ No newline at end of file diff --git a/src/Navigator.Extensions.Store/Entities/UniversalUser.cs b/src/Navigator.Extensions.Store/Entities/UniversalUser.cs index 1406473..88ff132 100644 --- a/src/Navigator.Extensions.Store/Entities/UniversalUser.cs +++ b/src/Navigator.Extensions.Store/Entities/UniversalUser.cs @@ -4,12 +4,11 @@ public class UniversalUser : Navigator.Entities.User { public UniversalUser() { - ProviderEntities = new List(); Chats = new List(); } public Guid Id { get; set; } - public IList ProviderEntities { get; set; } + public IList Profiles { get; set; } /// /// Chats related to the user. @@ -22,9 +21,4 @@ public UniversalUser() /// Date of first interaction for this chat. /// public DateTime FirstInteractionAt { get; set; } -} - -public interface INavigatorProviderUserEntity -{ - public Guid Id { get; set; } } \ No newline at end of file diff --git a/src/Navigator.Extensions.Store/NavigatorContextExtensions.cs b/src/Navigator.Extensions.Store/NavigatorContextExtensions.cs index cb09fec..6c99711 100644 --- a/src/Navigator.Extensions.Store/NavigatorContextExtensions.cs +++ b/src/Navigator.Extensions.Store/NavigatorContextExtensions.cs @@ -42,8 +42,8 @@ public static async Task GetUniversalChat(this INavigatorContext { return await context.GetStore().Chats .AsNoTracking() - .FirstOrDefaultAsync(e => e.ProviderEntities - .Any(p => p.Id == context.Conversation.Chat.Id)); + .FirstOrDefaultAsync(e => e.Profiles + .Any(p => p.Identification == context.Conversation.Chat.Id)); } #endregion @@ -59,10 +59,10 @@ public static async Task GetUniversalConversation(this IN { return await context.GetStore().Users .AsNoTracking() - .Where(e => e.ProviderEntities - .Any(p => p.Id == context.Conversation.User.Id)) - .Select(e => e.Conversations.FirstOrDefault(c => c.Chat.ProviderEntities - .Any(p => p.Id == context.Conversation.Chat.Id))) + .Where(e => e.Profiles + .Any(p => p.Identification == context.Conversation.User.Id)) + .Select(e => e.Conversations.FirstOrDefault(c => c.Chat.Profiles + .Any(p => p.Identification == context.Conversation.Chat.Id))) .FirstOrDefaultAsync(); } @@ -79,8 +79,8 @@ public static async Task GetUniversalUser(this INavigatorContext { return await context.GetStore().Users .AsNoTracking() - .FirstOrDefaultAsync(e => e.ProviderEntities - .Any(p => p.Id == context.Conversation.User.Id)); + .FirstOrDefaultAsync(e => e.Profiles + .Any(p => p.Identification == context.Conversation.User.Id)); } #endregion diff --git a/src/Navigator.Extensions.Store/NavigatorDbContext.cs b/src/Navigator.Extensions.Store/NavigatorDbContext.cs index b694ef2..a34a17f 100644 --- a/src/Navigator.Extensions.Store/NavigatorDbContext.cs +++ b/src/Navigator.Extensions.Store/NavigatorDbContext.cs @@ -8,9 +8,8 @@ public class NavigatorDbContext : DbContext { public DbSet Users { get; set; } public DbSet Chats { get; set; } - - protected DbSet NavigatorProviderUserEntities { get; set; } - protected DbSet NavigatorProviderChatEntities { get; set; } + public DbSet Conversations { get; set; } + public DbSet Profiles { get; set; } protected NavigatorDbContext() { @@ -27,5 +26,10 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) modelBuilder.ApplyConfiguration(new ChatEntityTypeConfiguration()); modelBuilder.ApplyConfiguration(new UserEntityTypeConfiguration()); modelBuilder.ApplyConfiguration(new ConversationEntityTypeConfiguration()); + modelBuilder.ApplyConfiguration(new ProfileEntityTypeConfiguration()); + + modelBuilder.Entity(b => b.HasBaseType()); + modelBuilder.Entity(b => b.HasBaseType()); + modelBuilder.Entity(b => b.HasBaseType()); } } \ No newline at end of file diff --git a/src/Navigator.Extensions.Store/NavigatorExtensionConfigurationExtensions.cs b/src/Navigator.Extensions.Store/NavigatorExtensionConfigurationExtensions.cs new file mode 100644 index 0000000..995cef7 --- /dev/null +++ b/src/Navigator.Extensions.Store/NavigatorExtensionConfigurationExtensions.cs @@ -0,0 +1,23 @@ +using MediatR; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Navigator.Configuration; +using Navigator.Configuration.Extension; +using Navigator.Context.Extensions; +using Navigator.Extensions.Store.Bundled; + +namespace Navigator.Extensions.Store; + +public static class NavigatorExtensionConfigurationExtensions +{ + public static NavigatorConfiguration Store(this NavigatorExtensionConfiguration providerConfiguration, Action? dbContextOptions = default) + { + return providerConfiguration.Extension( + _ => {}, + services => + { + services.AddDbContext(dbContextOptions); + services.AddScoped(); + }); + } +} \ No newline at end of file From bfedcdc119dc2d49072f32cbc87e560177902815 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Wed, 22 Dec 2021 13:29:16 +0100 Subject: [PATCH 230/304] feat: add NavigatorStoreException --- .../NavigatorStoreException.cs | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 src/Navigator.Extensions.Store/NavigatorStoreException.cs diff --git a/src/Navigator.Extensions.Store/NavigatorStoreException.cs b/src/Navigator.Extensions.Store/NavigatorStoreException.cs new file mode 100644 index 0000000..f180adc --- /dev/null +++ b/src/Navigator.Extensions.Store/NavigatorStoreException.cs @@ -0,0 +1,22 @@ +using System.Runtime.Serialization; + +namespace Navigator.Extensions.Store; + +public class NavigatorStoreException : NavigatorException +{ + public NavigatorStoreException() + { + } + + protected NavigatorStoreException(SerializationInfo info, StreamingContext context) : base(info, context) + { + } + + public NavigatorStoreException(string? message) : base(message) + { + } + + public NavigatorStoreException(string? message, Exception? innerException) : base(message, innerException) + { + } +} \ No newline at end of file From def4ef1278e4cf30ea36fa9ab7d76428ba3aee4f Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Wed, 22 Dec 2021 13:29:35 +0100 Subject: [PATCH 231/304] feat: add constructor with default DateTime values to UniversalProfile --- src/Navigator.Extensions.Store/Entities/UniversalProfile.cs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/Navigator.Extensions.Store/Entities/UniversalProfile.cs b/src/Navigator.Extensions.Store/Entities/UniversalProfile.cs index 762627b..d1151e4 100644 --- a/src/Navigator.Extensions.Store/Entities/UniversalProfile.cs +++ b/src/Navigator.Extensions.Store/Entities/UniversalProfile.cs @@ -2,6 +2,12 @@ namespace Navigator.Extensions.Store.Entities; public class UniversalProfile { + protected UniversalProfile() + { + CreatedAt = DateTime.UtcNow; + LastUpdatedAt = DateTime.UtcNow; + } + public Guid Id { get; set; } public string Provider { get; set; } public Guid Identification { get; set; } From 10c3b031fa86ce6793768d71acfa95c9a900191a Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Wed, 22 Dec 2021 13:29:51 +0100 Subject: [PATCH 232/304] feat: implement first iteration of IUniversalStore --- .../IUniversalStore.cs | 13 +++ .../UniversalStore.cs | 110 ++++++++++++++++++ 2 files changed, 123 insertions(+) create mode 100644 src/Navigator.Extensions.Store/IUniversalStore.cs create mode 100644 src/Navigator.Extensions.Store/UniversalStore.cs diff --git a/src/Navigator.Extensions.Store/IUniversalStore.cs b/src/Navigator.Extensions.Store/IUniversalStore.cs new file mode 100644 index 0000000..53a97ee --- /dev/null +++ b/src/Navigator.Extensions.Store/IUniversalStore.cs @@ -0,0 +1,13 @@ +namespace Navigator.Extensions.Store; + +public interface IUniversalStore +{ + Task AddUserProfile(string provider, Guid identification, CancellationToken cancellationToken = default); + Task TryAddUserProfile(string provider, Guid identification, CancellationToken cancellationToken = default); + + Task AddChatProfile(string provider, Guid identification, CancellationToken cancellationToken = default); + Task TryAddChatProfile(string provider, Guid identification, CancellationToken cancellationToken = default); + + Task AddConversationProfile(string provider, Guid identification, CancellationToken cancellationToken = default); + Task TryAddConversationProfile(string provider, Guid identification, CancellationToken cancellationToken = default); +} \ No newline at end of file diff --git a/src/Navigator.Extensions.Store/UniversalStore.cs b/src/Navigator.Extensions.Store/UniversalStore.cs new file mode 100644 index 0000000..4324e01 --- /dev/null +++ b/src/Navigator.Extensions.Store/UniversalStore.cs @@ -0,0 +1,110 @@ +using Microsoft.EntityFrameworkCore; +using Navigator.Extensions.Store.Entities; + +namespace Navigator.Extensions.Store; + +public class UniversalStore : IUniversalStore +{ + private readonly NavigatorDbContext _dbContext; + + public UniversalStore(NavigatorDbContext dbContext) + { + _dbContext = dbContext; + } + + public async Task AddUserProfile(string provider, Guid identification, CancellationToken cancellationToken = default) + { + var any = await _dbContext.Profiles.AnyAsync(e => e.Provider == provider && e.Identification == identification, cancellationToken); + + if (any) + { + throw new NavigatorStoreException("Profile already exists for this combination of provider and identification"); + } + + var profile = new UserProfile + { + Id = Guid.NewGuid(), + Provider = provider, + Identification = identification, + }; + + await _dbContext.Profiles.AddAsync(profile, cancellationToken); + await _dbContext.SaveChangesAsync(cancellationToken); + } + + public async Task TryAddUserProfile(string provider, Guid identification, CancellationToken cancellationToken = default) + { + try + { + await AddUserProfile(provider, identification, cancellationToken); + } + catch (Exception e) + { + //TODO: log warning + } + } + + public async Task AddChatProfile(string provider, Guid identification, CancellationToken cancellationToken = default) + { + var any = await _dbContext.Profiles.AnyAsync(e => e.Provider == provider && e.Identification == identification, cancellationToken); + + if (any) + { + throw new NavigatorStoreException("Profile already exists for this combination of provider and identification"); + } + + var profile = new ChatProfile + { + Id = Guid.NewGuid(), + Provider = provider, + Identification = identification, + }; + + await _dbContext.Profiles.AddAsync(profile, cancellationToken); + await _dbContext.SaveChangesAsync(cancellationToken); + } + + public async Task TryAddChatProfile(string provider, Guid identification, CancellationToken cancellationToken = default) + { + try + { + await AddChatProfile(provider, identification, cancellationToken); + } + catch (Exception e) + { + //TODO: log warning + } + } + + public async Task AddConversationProfile(string provider, Guid identification, CancellationToken cancellationToken = default) + { + var any = await _dbContext.Profiles.AnyAsync(e => e.Provider == provider && e.Identification == identification, cancellationToken); + + if (any) + { + throw new NavigatorStoreException("Profile already exists for this combination of provider and identification"); + } + + var profile = new ConversationProfile + { + Id = Guid.NewGuid(), + Provider = provider, + Identification = identification, + }; + + await _dbContext.Profiles.AddAsync(profile, cancellationToken); + await _dbContext.SaveChangesAsync(cancellationToken); + } + + public async Task TryAddConversationProfile(string provider, Guid identification, CancellationToken cancellationToken = default) + { + try + { + await AddConversationProfile(provider, identification, cancellationToken); + } + catch (Exception e) + { + //TODO: log warning + } + } +} \ No newline at end of file From 83b7727ee4ce31293178437f6a393383861a903c Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Wed, 22 Dec 2021 14:44:03 +0100 Subject: [PATCH 233/304] feat: refactor namespaces --- .../Configuration/ChatEntityTypeConfiguration.cs | 0 .../Configuration/ConversationEntityTypeConfiguration.cs | 0 .../Configuration/ProfileEntityTypeConfiguration.cs | 0 .../Configuration/UserEntityTypeConfiguration.cs | 0 .../{ => Context}/NavigatorDbContext.cs | 0 .../NavigatorExtensionConfigurationExtensions.cs | 1 + src/Navigator.Samples.Store/Actions/CooldownAction.cs | 2 +- .../Actions/CooldownActionHandler.cs | 2 +- src/Navigator.Samples.Store/Actions/EchoAction.cs | 2 +- src/Navigator.Samples.Store/Actions/EchoActionHandler.cs | 5 ++++- .../Navigator.Samples.Store.csproj | 3 +-- src/Navigator.Samples.Store/Program.cs | 9 +++++++-- 12 files changed, 16 insertions(+), 8 deletions(-) rename src/Navigator.Extensions.Store/{ => Context}/Configuration/ChatEntityTypeConfiguration.cs (100%) rename src/Navigator.Extensions.Store/{ => Context}/Configuration/ConversationEntityTypeConfiguration.cs (100%) rename src/Navigator.Extensions.Store/{ => Context}/Configuration/ProfileEntityTypeConfiguration.cs (100%) rename src/Navigator.Extensions.Store/{ => Context}/Configuration/UserEntityTypeConfiguration.cs (100%) rename src/Navigator.Extensions.Store/{ => Context}/NavigatorDbContext.cs (100%) diff --git a/src/Navigator.Extensions.Store/Configuration/ChatEntityTypeConfiguration.cs b/src/Navigator.Extensions.Store/Context/Configuration/ChatEntityTypeConfiguration.cs similarity index 100% rename from src/Navigator.Extensions.Store/Configuration/ChatEntityTypeConfiguration.cs rename to src/Navigator.Extensions.Store/Context/Configuration/ChatEntityTypeConfiguration.cs diff --git a/src/Navigator.Extensions.Store/Configuration/ConversationEntityTypeConfiguration.cs b/src/Navigator.Extensions.Store/Context/Configuration/ConversationEntityTypeConfiguration.cs similarity index 100% rename from src/Navigator.Extensions.Store/Configuration/ConversationEntityTypeConfiguration.cs rename to src/Navigator.Extensions.Store/Context/Configuration/ConversationEntityTypeConfiguration.cs diff --git a/src/Navigator.Extensions.Store/Configuration/ProfileEntityTypeConfiguration.cs b/src/Navigator.Extensions.Store/Context/Configuration/ProfileEntityTypeConfiguration.cs similarity index 100% rename from src/Navigator.Extensions.Store/Configuration/ProfileEntityTypeConfiguration.cs rename to src/Navigator.Extensions.Store/Context/Configuration/ProfileEntityTypeConfiguration.cs diff --git a/src/Navigator.Extensions.Store/Configuration/UserEntityTypeConfiguration.cs b/src/Navigator.Extensions.Store/Context/Configuration/UserEntityTypeConfiguration.cs similarity index 100% rename from src/Navigator.Extensions.Store/Configuration/UserEntityTypeConfiguration.cs rename to src/Navigator.Extensions.Store/Context/Configuration/UserEntityTypeConfiguration.cs diff --git a/src/Navigator.Extensions.Store/NavigatorDbContext.cs b/src/Navigator.Extensions.Store/Context/NavigatorDbContext.cs similarity index 100% rename from src/Navigator.Extensions.Store/NavigatorDbContext.cs rename to src/Navigator.Extensions.Store/Context/NavigatorDbContext.cs diff --git a/src/Navigator.Extensions.Store/NavigatorExtensionConfigurationExtensions.cs b/src/Navigator.Extensions.Store/NavigatorExtensionConfigurationExtensions.cs index 995cef7..b88ebe5 100644 --- a/src/Navigator.Extensions.Store/NavigatorExtensionConfigurationExtensions.cs +++ b/src/Navigator.Extensions.Store/NavigatorExtensionConfigurationExtensions.cs @@ -18,6 +18,7 @@ public static NavigatorConfiguration Store(this NavigatorExtensionConfiguration { services.AddDbContext(dbContextOptions); services.AddScoped(); + services.AddTransient(); }); } } \ No newline at end of file diff --git a/src/Navigator.Samples.Store/Actions/CooldownAction.cs b/src/Navigator.Samples.Store/Actions/CooldownAction.cs index 776c81e..f436cbf 100644 --- a/src/Navigator.Samples.Store/Actions/CooldownAction.cs +++ b/src/Navigator.Samples.Store/Actions/CooldownAction.cs @@ -2,7 +2,7 @@ using Navigator.Extensions.Cooldown; using Navigator.Providers.Telegram.Actions.Messages; -namespace Navigator.Samples.Echo.Actions; +namespace Navigator.Samples.Store.Actions; [Cooldown(Seconds = 10)] public class CooldownAction : CommandAction diff --git a/src/Navigator.Samples.Store/Actions/CooldownActionHandler.cs b/src/Navigator.Samples.Store/Actions/CooldownActionHandler.cs index 573e08c..cb1940c 100644 --- a/src/Navigator.Samples.Store/Actions/CooldownActionHandler.cs +++ b/src/Navigator.Samples.Store/Actions/CooldownActionHandler.cs @@ -5,7 +5,7 @@ using Navigator.Providers.Telegram; using Telegram.Bot; -namespace Navigator.Samples.Echo.Actions; +namespace Navigator.Samples.Store.Actions; public class CooldownActionHandler : ActionHandler { diff --git a/src/Navigator.Samples.Store/Actions/EchoAction.cs b/src/Navigator.Samples.Store/Actions/EchoAction.cs index 5546372..ef47eeb 100644 --- a/src/Navigator.Samples.Store/Actions/EchoAction.cs +++ b/src/Navigator.Samples.Store/Actions/EchoAction.cs @@ -1,7 +1,7 @@ using Navigator.Context; using Navigator.Providers.Telegram.Actions.Messages; -namespace Navigator.Samples.Echo.Actions; +namespace Navigator.Samples.Store.Actions; public class EchoAction : MessageAction { diff --git a/src/Navigator.Samples.Store/Actions/EchoActionHandler.cs b/src/Navigator.Samples.Store/Actions/EchoActionHandler.cs index 120329d..1780f49 100644 --- a/src/Navigator.Samples.Store/Actions/EchoActionHandler.cs +++ b/src/Navigator.Samples.Store/Actions/EchoActionHandler.cs @@ -2,10 +2,11 @@ using System.Threading.Tasks; using Navigator.Actions; using Navigator.Context; +using Navigator.Extensions.Store; using Navigator.Providers.Telegram; using Telegram.Bot; -namespace Navigator.Samples.Echo.Actions; +namespace Navigator.Samples.Store.Actions; public class EchoActionHandler : ActionHandler { @@ -15,6 +16,8 @@ public EchoActionHandler(INavigatorContextAccessor navigatorContextAccessor) : b public override async Task Handle(EchoAction action, CancellationToken cancellationToken) { + var store = NavigatorContext.GetStoreOrDefault(); + await this.GetTelegramClient().SendTextMessageAsync(this.GetTelegramChat().Id, action.MessageToEcho, cancellationToken: cancellationToken); diff --git a/src/Navigator.Samples.Store/Navigator.Samples.Store.csproj b/src/Navigator.Samples.Store/Navigator.Samples.Store.csproj index fc6d327..6f8a893 100644 --- a/src/Navigator.Samples.Store/Navigator.Samples.Store.csproj +++ b/src/Navigator.Samples.Store/Navigator.Samples.Store.csproj @@ -3,12 +3,11 @@ net6.0 enable - enable - + diff --git a/src/Navigator.Samples.Store/Program.cs b/src/Navigator.Samples.Store/Program.cs index 36dde46..b69bc81 100644 --- a/src/Navigator.Samples.Store/Program.cs +++ b/src/Navigator.Samples.Store/Program.cs @@ -1,5 +1,6 @@ using Microsoft.AspNetCore.Builder; using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Navigator; @@ -7,7 +8,7 @@ using Navigator.Extensions.Cooldown; using Navigator.Extensions.Store; using Navigator.Providers.Telegram; -using Navigator.Samples.Echo.Actions; +using Navigator.Samples.Store.Actions; var builder = WebApplication.CreateBuilder(args); @@ -27,7 +28,7 @@ .WithExtension.Store(dbBuilder => { dbBuilder.UseSqlite(builder.Configuration.GetConnectionString("DefaultConnection"), - b => b.MigrationsAssembly("Navigator.Samples.Echo")); + b => b.MigrationsAssembly("Navigator.Samples.Store")); }); var app = builder.Build(); @@ -37,6 +38,10 @@ { } + +using var serviceScope = app.Services.GetService()?.CreateScope(); +serviceScope?.ServiceProvider.GetRequiredService().Database.Migrate(); + app.UseHttpsRedirection(); app.MapNavigator() From 99ee892993e711f00f237cf5525c17d6bf7c1f7d Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Wed, 22 Dec 2021 14:44:13 +0100 Subject: [PATCH 234/304] feat: add migration for sample --- ...0211222133231_InitialMigration.Designer.cs | 198 ++++++++++++++++++ .../20211222133231_InitialMigration.cs | 132 ++++++++++++ .../NavigatorDbContextModelSnapshot.cs | 196 +++++++++++++++++ 3 files changed, 526 insertions(+) create mode 100644 src/Navigator.Samples.Store/Migrations/20211222133231_InitialMigration.Designer.cs create mode 100644 src/Navigator.Samples.Store/Migrations/20211222133231_InitialMigration.cs create mode 100644 src/Navigator.Samples.Store/Migrations/NavigatorDbContextModelSnapshot.cs diff --git a/src/Navigator.Samples.Store/Migrations/20211222133231_InitialMigration.Designer.cs b/src/Navigator.Samples.Store/Migrations/20211222133231_InitialMigration.Designer.cs new file mode 100644 index 0000000..5d9b1ca --- /dev/null +++ b/src/Navigator.Samples.Store/Migrations/20211222133231_InitialMigration.Designer.cs @@ -0,0 +1,198 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Navigator.Extensions.Store; + +#nullable disable + +namespace Navigator.Samples.Store.Migrations +{ + [DbContext(typeof(NavigatorDbContext))] + [Migration("20211222133231_InitialMigration")] + partial class InitialMigration + { + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "6.0.1"); + + modelBuilder.Entity("Navigator.Extensions.Store.Entities.UniversalConversation", b => + { + b.Property("ChatId") + .HasColumnType("TEXT"); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("FirstInteractionAt") + .HasColumnType("TEXT"); + + b.HasKey("ChatId", "UserId"); + + b.HasIndex("UserId"); + + b.ToTable("Conversations"); + }); + + modelBuilder.Entity("Navigator.Extensions.Store.Entities.UniversalProfile", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("Discriminator") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Identification") + .HasColumnType("TEXT"); + + b.Property("LastUpdatedAt") + .HasColumnType("TEXT"); + + b.Property("Provider") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("Profiles"); + + b.HasDiscriminator("Discriminator").HasValue("UniversalProfile"); + }); + + modelBuilder.Entity("Navigator.Extensions.Store.Entities.UniversalUser", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("FirstInteractionAt") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("Users"); + }); + + modelBuilder.Entity("UniversalChat", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("FirstInteractionAt") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("Chats"); + }); + + modelBuilder.Entity("Navigator.Extensions.Store.Entities.ChatProfile", b => + { + b.HasBaseType("Navigator.Extensions.Store.Entities.UniversalProfile"); + + b.Property("UniversalChatId") + .HasColumnType("TEXT"); + + b.HasIndex("UniversalChatId"); + + b.HasDiscriminator().HasValue("ChatProfile"); + }); + + modelBuilder.Entity("Navigator.Extensions.Store.Entities.ConversationProfile", b => + { + b.HasBaseType("Navigator.Extensions.Store.Entities.UniversalProfile"); + + b.Property("UniversalConversationChatId") + .HasColumnType("TEXT"); + + b.Property("UniversalConversationUserId") + .HasColumnType("TEXT"); + + b.HasIndex("UniversalConversationChatId", "UniversalConversationUserId"); + + b.HasDiscriminator().HasValue("ConversationProfile"); + }); + + modelBuilder.Entity("Navigator.Extensions.Store.Entities.UserProfile", b => + { + b.HasBaseType("Navigator.Extensions.Store.Entities.UniversalProfile"); + + b.Property("UniversalUserId") + .HasColumnType("TEXT"); + + b.HasIndex("UniversalUserId"); + + b.HasDiscriminator().HasValue("UserProfile"); + }); + + modelBuilder.Entity("Navigator.Extensions.Store.Entities.UniversalConversation", b => + { + b.HasOne("UniversalChat", "Chat") + .WithMany("Conversations") + .HasForeignKey("ChatId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Navigator.Extensions.Store.Entities.UniversalUser", "User") + .WithMany("Conversations") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Chat"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Navigator.Extensions.Store.Entities.ChatProfile", b => + { + b.HasOne("UniversalChat", null) + .WithMany("Profiles") + .HasForeignKey("UniversalChatId"); + }); + + modelBuilder.Entity("Navigator.Extensions.Store.Entities.ConversationProfile", b => + { + b.HasOne("Navigator.Extensions.Store.Entities.UniversalConversation", null) + .WithMany("Profiles") + .HasForeignKey("UniversalConversationChatId", "UniversalConversationUserId"); + }); + + modelBuilder.Entity("Navigator.Extensions.Store.Entities.UserProfile", b => + { + b.HasOne("Navigator.Extensions.Store.Entities.UniversalUser", null) + .WithMany("Profiles") + .HasForeignKey("UniversalUserId"); + }); + + modelBuilder.Entity("Navigator.Extensions.Store.Entities.UniversalConversation", b => + { + b.Navigation("Profiles"); + }); + + modelBuilder.Entity("Navigator.Extensions.Store.Entities.UniversalUser", b => + { + b.Navigation("Conversations"); + + b.Navigation("Profiles"); + }); + + modelBuilder.Entity("UniversalChat", b => + { + b.Navigation("Conversations"); + + b.Navigation("Profiles"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Navigator.Samples.Store/Migrations/20211222133231_InitialMigration.cs b/src/Navigator.Samples.Store/Migrations/20211222133231_InitialMigration.cs new file mode 100644 index 0000000..6eadceb --- /dev/null +++ b/src/Navigator.Samples.Store/Migrations/20211222133231_InitialMigration.cs @@ -0,0 +1,132 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Navigator.Samples.Store.Migrations +{ + public partial class InitialMigration : Migration + { + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "Chats", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + FirstInteractionAt = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Chats", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "Users", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + FirstInteractionAt = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Users", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "Conversations", + columns: table => new + { + ChatId = table.Column(type: "TEXT", nullable: false), + UserId = table.Column(type: "TEXT", nullable: false), + FirstInteractionAt = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Conversations", x => new { x.ChatId, x.UserId }); + table.ForeignKey( + name: "FK_Conversations_Chats_ChatId", + column: x => x.ChatId, + principalTable: "Chats", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_Conversations_Users_UserId", + column: x => x.UserId, + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "Profiles", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + Provider = table.Column(type: "TEXT", nullable: false), + Identification = table.Column(type: "TEXT", nullable: false), + CreatedAt = table.Column(type: "TEXT", nullable: false), + LastUpdatedAt = table.Column(type: "TEXT", nullable: false), + Discriminator = table.Column(type: "TEXT", nullable: false), + UniversalChatId = table.Column(type: "TEXT", nullable: true), + UniversalConversationChatId = table.Column(type: "TEXT", nullable: true), + UniversalConversationUserId = table.Column(type: "TEXT", nullable: true), + UniversalUserId = table.Column(type: "TEXT", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_Profiles", x => x.Id); + table.ForeignKey( + name: "FK_Profiles_Chats_UniversalChatId", + column: x => x.UniversalChatId, + principalTable: "Chats", + principalColumn: "Id"); + table.ForeignKey( + name: "FK_Profiles_Conversations_UniversalConversationChatId_UniversalConversationUserId", + columns: x => new { x.UniversalConversationChatId, x.UniversalConversationUserId }, + principalTable: "Conversations", + principalColumns: new[] { "ChatId", "UserId" }); + table.ForeignKey( + name: "FK_Profiles_Users_UniversalUserId", + column: x => x.UniversalUserId, + principalTable: "Users", + principalColumn: "Id"); + }); + + migrationBuilder.CreateIndex( + name: "IX_Conversations_UserId", + table: "Conversations", + column: "UserId"); + + migrationBuilder.CreateIndex( + name: "IX_Profiles_UniversalChatId", + table: "Profiles", + column: "UniversalChatId"); + + migrationBuilder.CreateIndex( + name: "IX_Profiles_UniversalConversationChatId_UniversalConversationUserId", + table: "Profiles", + columns: new[] { "UniversalConversationChatId", "UniversalConversationUserId" }); + + migrationBuilder.CreateIndex( + name: "IX_Profiles_UniversalUserId", + table: "Profiles", + column: "UniversalUserId"); + } + + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "Profiles"); + + migrationBuilder.DropTable( + name: "Conversations"); + + migrationBuilder.DropTable( + name: "Chats"); + + migrationBuilder.DropTable( + name: "Users"); + } + } +} diff --git a/src/Navigator.Samples.Store/Migrations/NavigatorDbContextModelSnapshot.cs b/src/Navigator.Samples.Store/Migrations/NavigatorDbContextModelSnapshot.cs new file mode 100644 index 0000000..6d1f837 --- /dev/null +++ b/src/Navigator.Samples.Store/Migrations/NavigatorDbContextModelSnapshot.cs @@ -0,0 +1,196 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Navigator.Extensions.Store; + +#nullable disable + +namespace Navigator.Samples.Store.Migrations +{ + [DbContext(typeof(NavigatorDbContext))] + partial class NavigatorDbContextModelSnapshot : ModelSnapshot + { + protected override void BuildModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "6.0.1"); + + modelBuilder.Entity("Navigator.Extensions.Store.Entities.UniversalConversation", b => + { + b.Property("ChatId") + .HasColumnType("TEXT"); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("FirstInteractionAt") + .HasColumnType("TEXT"); + + b.HasKey("ChatId", "UserId"); + + b.HasIndex("UserId"); + + b.ToTable("Conversations"); + }); + + modelBuilder.Entity("Navigator.Extensions.Store.Entities.UniversalProfile", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("Discriminator") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Identification") + .HasColumnType("TEXT"); + + b.Property("LastUpdatedAt") + .HasColumnType("TEXT"); + + b.Property("Provider") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("Profiles"); + + b.HasDiscriminator("Discriminator").HasValue("UniversalProfile"); + }); + + modelBuilder.Entity("Navigator.Extensions.Store.Entities.UniversalUser", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("FirstInteractionAt") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("Users"); + }); + + modelBuilder.Entity("UniversalChat", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("FirstInteractionAt") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("Chats"); + }); + + modelBuilder.Entity("Navigator.Extensions.Store.Entities.ChatProfile", b => + { + b.HasBaseType("Navigator.Extensions.Store.Entities.UniversalProfile"); + + b.Property("UniversalChatId") + .HasColumnType("TEXT"); + + b.HasIndex("UniversalChatId"); + + b.HasDiscriminator().HasValue("ChatProfile"); + }); + + modelBuilder.Entity("Navigator.Extensions.Store.Entities.ConversationProfile", b => + { + b.HasBaseType("Navigator.Extensions.Store.Entities.UniversalProfile"); + + b.Property("UniversalConversationChatId") + .HasColumnType("TEXT"); + + b.Property("UniversalConversationUserId") + .HasColumnType("TEXT"); + + b.HasIndex("UniversalConversationChatId", "UniversalConversationUserId"); + + b.HasDiscriminator().HasValue("ConversationProfile"); + }); + + modelBuilder.Entity("Navigator.Extensions.Store.Entities.UserProfile", b => + { + b.HasBaseType("Navigator.Extensions.Store.Entities.UniversalProfile"); + + b.Property("UniversalUserId") + .HasColumnType("TEXT"); + + b.HasIndex("UniversalUserId"); + + b.HasDiscriminator().HasValue("UserProfile"); + }); + + modelBuilder.Entity("Navigator.Extensions.Store.Entities.UniversalConversation", b => + { + b.HasOne("UniversalChat", "Chat") + .WithMany("Conversations") + .HasForeignKey("ChatId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Navigator.Extensions.Store.Entities.UniversalUser", "User") + .WithMany("Conversations") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Chat"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Navigator.Extensions.Store.Entities.ChatProfile", b => + { + b.HasOne("UniversalChat", null) + .WithMany("Profiles") + .HasForeignKey("UniversalChatId"); + }); + + modelBuilder.Entity("Navigator.Extensions.Store.Entities.ConversationProfile", b => + { + b.HasOne("Navigator.Extensions.Store.Entities.UniversalConversation", null) + .WithMany("Profiles") + .HasForeignKey("UniversalConversationChatId", "UniversalConversationUserId"); + }); + + modelBuilder.Entity("Navigator.Extensions.Store.Entities.UserProfile", b => + { + b.HasOne("Navigator.Extensions.Store.Entities.UniversalUser", null) + .WithMany("Profiles") + .HasForeignKey("UniversalUserId"); + }); + + modelBuilder.Entity("Navigator.Extensions.Store.Entities.UniversalConversation", b => + { + b.Navigation("Profiles"); + }); + + modelBuilder.Entity("Navigator.Extensions.Store.Entities.UniversalUser", b => + { + b.Navigation("Conversations"); + + b.Navigation("Profiles"); + }); + + modelBuilder.Entity("UniversalChat", b => + { + b.Navigation("Conversations"); + + b.Navigation("Profiles"); + }); +#pragma warning restore 612, 618 + } + } +} From e375b5dc69044886cb16bafd1a25b149640f1102 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Thu, 23 Dec 2021 11:29:54 +0100 Subject: [PATCH 235/304] feat: update INavigatorProvider --- src/Navigator/INavigatorProvider.cs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/Navigator/INavigatorProvider.cs b/src/Navigator/INavigatorProvider.cs index 86ec8bc..cb944fc 100644 --- a/src/Navigator/INavigatorProvider.cs +++ b/src/Navigator/INavigatorProvider.cs @@ -1,3 +1,4 @@ +using System; using System.Threading.Tasks; namespace Navigator; @@ -7,9 +8,14 @@ namespace Navigator; /// public interface INavigatorProvider { + string Name { get; } + /// /// Gets the specific client for this provider. /// /// An implementation of INavigatorClient GetClient(); + + + Type GetConversationType(); } \ No newline at end of file From 38f614de38693e48d494b9dc918997bdfca4f86b Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Thu, 23 Dec 2021 11:30:26 +0100 Subject: [PATCH 236/304] feat: implement interface changes on TelegramNavigatorProvider --- .../TelegramNavigatorProvider.cs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/Navigator.Providers.Telegram/TelegramNavigatorProvider.cs b/src/Navigator.Providers.Telegram/TelegramNavigatorProvider.cs index d3a7a72..b3e2553 100644 --- a/src/Navigator.Providers.Telegram/TelegramNavigatorProvider.cs +++ b/src/Navigator.Providers.Telegram/TelegramNavigatorProvider.cs @@ -1,13 +1,16 @@ using System; using System.Threading.Tasks; +using Navigator.Providers.Telegram.Entities; using Telegram.Bot.Types; namespace Navigator.Providers.Telegram; -public class TelegramNavigatorProvider : INavigatorProvider +internal class TelegramNavigatorProvider : INavigatorProvider { private readonly NavigatorTelegramClient _client; + public string Name => "navigator.provider.telegram"; + public TelegramNavigatorProvider(NavigatorTelegramClient client) { _client = client; @@ -18,8 +21,8 @@ public INavigatorClient GetClient() return _client; } - public Task HandleReply() + public Type GetConversationType() { - throw new NotImplementedException(); + return typeof(TelegramConversation); } } \ No newline at end of file From 77a190dfd9002f1cdd33892058b23278eec32ea2 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Thu, 23 Dec 2021 11:30:46 +0100 Subject: [PATCH 237/304] feat: add new methods to IUniversalStore --- .../IUniversalStore.cs | 28 +++++++++++++++---- 1 file changed, 22 insertions(+), 6 deletions(-) diff --git a/src/Navigator.Extensions.Store/IUniversalStore.cs b/src/Navigator.Extensions.Store/IUniversalStore.cs index 53a97ee..706029d 100644 --- a/src/Navigator.Extensions.Store/IUniversalStore.cs +++ b/src/Navigator.Extensions.Store/IUniversalStore.cs @@ -1,13 +1,29 @@ +using Navigator.Entities; +using Navigator.Extensions.Store.Entities; + namespace Navigator.Extensions.Store; public interface IUniversalStore { - Task AddUserProfile(string provider, Guid identification, CancellationToken cancellationToken = default); - Task TryAddUserProfile(string provider, Guid identification, CancellationToken cancellationToken = default); + #region Conversation + + Task FindOrCreateConversation(Conversation conversation, string provider, + CancellationToken cancellationToken = default); + Task FindConversation(Conversation conversation, string provider, + CancellationToken cancellationToken = default); + + #endregion - Task AddChatProfile(string provider, Guid identification, CancellationToken cancellationToken = default); - Task TryAddChatProfile(string provider, Guid identification, CancellationToken cancellationToken = default); + #region Profile + + Task AddUserProfile(UniversalUser user, string provider, Guid identification, CancellationToken cancellationToken = default, bool? saveChanges = true); + Task TryAddUserProfile(UniversalUser user, string provider, Guid identification, CancellationToken cancellationToken = default, bool? saveChanges = true); + + Task AddChatProfile(UniversalChat chat, string provider, Guid identification, CancellationToken cancellationToken = default, bool? saveChanges = true); + Task TryAddChatProfile(UniversalChat chat, string provider, Guid identification, CancellationToken cancellationToken = default, bool? saveChanges = true); + + Task AddConversationProfile(UniversalConversation conversation, string provider, Guid identification, CancellationToken cancellationToken = default, bool? saveChanges = true); + Task TryAddConversationProfile(UniversalConversation conversation, string provider, Guid identification, CancellationToken cancellationToken = default, bool? saveChanges = true); - Task AddConversationProfile(string provider, Guid identification, CancellationToken cancellationToken = default); - Task TryAddConversationProfile(string provider, Guid identification, CancellationToken cancellationToken = default); + #endregion } \ No newline at end of file From 8349df65cb60f864aec685d07a8611c9ee8d2c15 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Thu, 23 Dec 2021 11:31:02 +0100 Subject: [PATCH 238/304] feat: implement new interface methods on UniversalStore --- .../UniversalStore.cs | 105 +++++++++++++++--- 1 file changed, 91 insertions(+), 14 deletions(-) diff --git a/src/Navigator.Extensions.Store/UniversalStore.cs b/src/Navigator.Extensions.Store/UniversalStore.cs index 4324e01..0ea55f4 100644 --- a/src/Navigator.Extensions.Store/UniversalStore.cs +++ b/src/Navigator.Extensions.Store/UniversalStore.cs @@ -1,4 +1,5 @@ using Microsoft.EntityFrameworkCore; +using Navigator.Entities; using Navigator.Extensions.Store.Entities; namespace Navigator.Extensions.Store; @@ -11,8 +12,79 @@ public UniversalStore(NavigatorDbContext dbContext) { _dbContext = dbContext; } + + #region Conversation - public async Task AddUserProfile(string provider, Guid identification, CancellationToken cancellationToken = default) + public async Task FindOrCreateConversation(Conversation conversation, string provider, CancellationToken cancellationToken = default) + { + var universalConversation = await FindConversation(conversation, provider, cancellationToken); + + if (universalConversation is null) + { + var user = new UniversalUser + { + Id = Guid.NewGuid() + }; + + user.Profiles.Add(new UserProfile + { + Id = Guid.NewGuid(), + Provider = provider, + Identification = conversation.User.Id + }); + + var chat = new UniversalChat + { + Id = Guid.NewGuid() + }; + + chat.Profiles.Add(new ChatProfile + { + Id = Guid.NewGuid(), + Provider = provider, + Identification = conversation.Chat.Id, + }); + + await _dbContext.Users.AddAsync(user, cancellationToken); + await _dbContext.Chats.AddAsync(chat, cancellationToken); + + universalConversation = new UniversalConversation + { + User = user, + Chat = chat, + }; + + universalConversation.Profiles.Add(new ConversationProfile + { + Id = Guid.NewGuid(), + Provider = provider, + Identification = Guid.NewGuid() + }); + + await _dbContext.Conversations.AddAsync(universalConversation, cancellationToken); + + await _dbContext.SaveChangesAsync(cancellationToken); + } + + return universalConversation; + } + + public async Task FindConversation(Conversation conversation, string provider, CancellationToken cancellationToken = default) + { + return await _dbContext.Conversations + .Include(e => e.User) + .Include(e => e.Chat) + .Where(e => e.Profiles.Any(p => p.Provider == provider)) + .Where(e => e.Chat.Profiles.Any(p => p.Provider == provider && p.Identification == conversation.Chat.Id)) + .Where(e => e.User.Profiles.Any(p => p.Provider == provider && p.Identification == conversation.User.Id)) + .FirstOrDefaultAsync(cancellationToken); + } + + #endregion + + #region Profile + + public async Task AddUserProfile(UniversalUser user, string provider, Guid identification, CancellationToken cancellationToken = default, bool? saveChanges = true) { var any = await _dbContext.Profiles.AnyAsync(e => e.Provider == provider && e.Identification == identification, cancellationToken); @@ -25,18 +97,19 @@ public async Task AddUserProfile(string provider, Guid identification, Cancellat { Id = Guid.NewGuid(), Provider = provider, - Identification = identification, + Identification = identification }; - - await _dbContext.Profiles.AddAsync(profile, cancellationToken); + + user.Profiles.Add(profile); + await _dbContext.SaveChangesAsync(cancellationToken); } - public async Task TryAddUserProfile(string provider, Guid identification, CancellationToken cancellationToken = default) + public async Task TryAddUserProfile(UniversalUser user, string provider, Guid identification, CancellationToken cancellationToken = default, bool? saveChanges = true) { try { - await AddUserProfile(provider, identification, cancellationToken); + await AddUserProfile(user, provider, identification, cancellationToken, saveChanges); } catch (Exception e) { @@ -44,7 +117,7 @@ public async Task TryAddUserProfile(string provider, Guid identification, Cancel } } - public async Task AddChatProfile(string provider, Guid identification, CancellationToken cancellationToken = default) + public async Task AddChatProfile(UniversalChat chat, string provider, Guid identification, CancellationToken cancellationToken = default, bool? saveChanges = true) { var any = await _dbContext.Profiles.AnyAsync(e => e.Provider == provider && e.Identification == identification, cancellationToken); @@ -60,15 +133,16 @@ public async Task AddChatProfile(string provider, Guid identification, Cancellat Identification = identification, }; - await _dbContext.Profiles.AddAsync(profile, cancellationToken); + chat.Profiles.Add(profile); + await _dbContext.SaveChangesAsync(cancellationToken); } - public async Task TryAddChatProfile(string provider, Guid identification, CancellationToken cancellationToken = default) + public async Task TryAddChatProfile(UniversalChat chat, string provider, Guid identification, CancellationToken cancellationToken = default, bool? saveChanges = true) { try { - await AddChatProfile(provider, identification, cancellationToken); + await AddChatProfile(chat, provider, identification, cancellationToken, saveChanges); } catch (Exception e) { @@ -76,7 +150,7 @@ public async Task TryAddChatProfile(string provider, Guid identification, Cancel } } - public async Task AddConversationProfile(string provider, Guid identification, CancellationToken cancellationToken = default) + public async Task AddConversationProfile(UniversalConversation conversation, string provider, Guid identification, CancellationToken cancellationToken = default, bool? saveChanges = true) { var any = await _dbContext.Profiles.AnyAsync(e => e.Provider == provider && e.Identification == identification, cancellationToken); @@ -92,19 +166,22 @@ public async Task AddConversationProfile(string provider, Guid identification, C Identification = identification, }; - await _dbContext.Profiles.AddAsync(profile, cancellationToken); + conversation.Profiles.Add(profile); + await _dbContext.SaveChangesAsync(cancellationToken); } - public async Task TryAddConversationProfile(string provider, Guid identification, CancellationToken cancellationToken = default) + public async Task TryAddConversationProfile(UniversalConversation conversation, string provider, Guid identification, CancellationToken cancellationToken = default, bool? saveChanges = true) { try { - await AddConversationProfile(provider, identification, cancellationToken); + await AddConversationProfile(conversation, provider, identification, cancellationToken, saveChanges); } catch (Exception e) { //TODO: log warning } } + + #endregion } \ No newline at end of file From 95c79874b4eeb7e4a8c9fde2ff337a012aec1244 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Thu, 23 Dec 2021 11:31:23 +0100 Subject: [PATCH 239/304] feat: update default constructors of Store entities --- .../Entities/UniversalChat.cs | 3 +++ .../Entities/UniversalConversation.cs | 11 +++++++++++ .../Entities/UniversalUser.cs | 8 +++++++- 3 files changed, 21 insertions(+), 1 deletion(-) diff --git a/src/Navigator.Extensions.Store/Entities/UniversalChat.cs b/src/Navigator.Extensions.Store/Entities/UniversalChat.cs index 310b4c1..4733327 100644 --- a/src/Navigator.Extensions.Store/Entities/UniversalChat.cs +++ b/src/Navigator.Extensions.Store/Entities/UniversalChat.cs @@ -4,7 +4,10 @@ public class UniversalChat : Navigator.Entities.Chat { public UniversalChat() { + Profiles = new List(); Users = new List(); + Conversations = new List(); + FirstInteractionAt = DateTime.UtcNow; } public Guid Id { get; set; } diff --git a/src/Navigator.Extensions.Store/Entities/UniversalConversation.cs b/src/Navigator.Extensions.Store/Entities/UniversalConversation.cs index 07d7e8e..8abbb9e 100644 --- a/src/Navigator.Extensions.Store/Entities/UniversalConversation.cs +++ b/src/Navigator.Extensions.Store/Entities/UniversalConversation.cs @@ -4,6 +4,17 @@ namespace Navigator.Extensions.Store.Entities; public class UniversalConversation : Navigator.Entities.Conversation { + public UniversalConversation() + { + Profiles = new List(); + FirstInteractionAt = DateTime.UtcNow; + } + public UniversalConversation(User user, Chat chat) : base(user, chat) + { + Profiles = new List(); + FirstInteractionAt = DateTime.UtcNow; + } + public new UniversalChat Chat { get; set; } public new UniversalUser User { get; set; } diff --git a/src/Navigator.Extensions.Store/Entities/UniversalUser.cs b/src/Navigator.Extensions.Store/Entities/UniversalUser.cs index 88ff132..381ff0a 100644 --- a/src/Navigator.Extensions.Store/Entities/UniversalUser.cs +++ b/src/Navigator.Extensions.Store/Entities/UniversalUser.cs @@ -1,12 +1,18 @@ +using Navigator.Entities; + namespace Navigator.Extensions.Store.Entities; public class UniversalUser : Navigator.Entities.User { public UniversalUser() { + Profiles = new List(); Chats = new List(); + Conversations = new List(); + FirstInteractionAt = DateTime.UtcNow; } - public Guid Id { get; set; } + + public new Guid Id { get; set; } public IList Profiles { get; set; } From 83deab29c3bdac8b95299f6d435c22fdbb7cc382 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Thu, 23 Dec 2021 11:32:04 +0100 Subject: [PATCH 240/304] feat: implement UniversalConversationContextExtension --- .../UniversalConversationContextExtension.cs | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 src/Navigator.Extensions.Store/Bundled/UniversalConversationContextExtension.cs diff --git a/src/Navigator.Extensions.Store/Bundled/UniversalConversationContextExtension.cs b/src/Navigator.Extensions.Store/Bundled/UniversalConversationContextExtension.cs new file mode 100644 index 0000000..4f13da0 --- /dev/null +++ b/src/Navigator.Extensions.Store/Bundled/UniversalConversationContextExtension.cs @@ -0,0 +1,30 @@ +using System.Text; +using System.Text.Json; +using Navigator.Context; +using Navigator.Context.Extensions; + +namespace Navigator.Extensions.Store.Bundled; + +internal class UniversalConversationContextExtension : INavigatorContextExtension +{ + public const string UniversalConversation = "_navigator.extensions.store.universal_conversation"; + + private readonly IUniversalStore _universalStore; + + public UniversalConversationContextExtension(IUniversalStore universalStore) + { + _universalStore = universalStore; + } + + public async Task Extend(INavigatorContext navigatorContext, INavigatorContextBuilderOptions builderOptions) + { + var conversation = navigatorContext.Conversation; + + var universalConversation = await _universalStore.FindOrCreateConversation(conversation, navigatorContext.Provider.Name); + + + + + return await Task.FromResult(navigatorContext); + } +} \ No newline at end of file From d677fba796741dac17f49ef9187b5de57042a49d Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Thu, 23 Dec 2021 11:49:40 +0100 Subject: [PATCH 241/304] feat: add more methods to UniversalStore --- .../IUniversalStore.cs | 12 ++++++++++ .../UniversalStore.cs | 24 +++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/src/Navigator.Extensions.Store/IUniversalStore.cs b/src/Navigator.Extensions.Store/IUniversalStore.cs index 706029d..4c48435 100644 --- a/src/Navigator.Extensions.Store/IUniversalStore.cs +++ b/src/Navigator.Extensions.Store/IUniversalStore.cs @@ -5,6 +5,12 @@ namespace Navigator.Extensions.Store; public interface IUniversalStore { + #region Chat + + Task FindChat(Chat chat, string provider, CancellationToken cancellationToken = default); + + #endregion + #region Conversation Task FindOrCreateConversation(Conversation conversation, string provider, @@ -13,6 +19,12 @@ Task FindOrCreateConversation(Conversation conversation, CancellationToken cancellationToken = default); #endregion + + #region User + + Task FindUser(User user, string provider, CancellationToken cancellationToken = default); + + #endregion #region Profile diff --git a/src/Navigator.Extensions.Store/UniversalStore.cs b/src/Navigator.Extensions.Store/UniversalStore.cs index 0ea55f4..8e41e16 100644 --- a/src/Navigator.Extensions.Store/UniversalStore.cs +++ b/src/Navigator.Extensions.Store/UniversalStore.cs @@ -13,6 +13,18 @@ public UniversalStore(NavigatorDbContext dbContext) _dbContext = dbContext; } + #region Chat + + public async Task FindChat(Chat chat, string provider, CancellationToken cancellationToken = default) + { + return await _dbContext.Chats + .Where(e => e.Profiles.Any(p => p.Provider == provider)) + .Where(e => e.Profiles.Any(p => p.Identification == chat.Id)) + .FirstOrDefaultAsync(cancellationToken); + } + + #endregion + #region Conversation public async Task FindOrCreateConversation(Conversation conversation, string provider, CancellationToken cancellationToken = default) @@ -80,6 +92,18 @@ public async Task FindOrCreateConversation(Conversation c .FirstOrDefaultAsync(cancellationToken); } + #endregion + + #region User + + public async Task FindUser(User user, string provider, CancellationToken cancellationToken = default) + { + return await _dbContext.Users + .Where(e => e.Profiles.Any(p => p.Provider == provider)) + .Where(e => e.Profiles.Any(p => p.Identification == user.Id)) + .FirstOrDefaultAsync(cancellationToken); + } + #endregion #region Profile From b7a1c51b81ae67386d1de14e7df3beea1f850550 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Thu, 23 Dec 2021 11:51:53 +0100 Subject: [PATCH 242/304] feat: update StoreContextExtension provide UniversalStore instead of DbContext --- .../Bundled/StoreContextExtension.cs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/Navigator.Extensions.Store/Bundled/StoreContextExtension.cs b/src/Navigator.Extensions.Store/Bundled/StoreContextExtension.cs index 9ea4479..0f02788 100644 --- a/src/Navigator.Extensions.Store/Bundled/StoreContextExtension.cs +++ b/src/Navigator.Extensions.Store/Bundled/StoreContextExtension.cs @@ -6,18 +6,18 @@ namespace Navigator.Extensions.Store.Bundled; public class StoreContextExtension: INavigatorContextExtension { - public const string StoreKey = "_navigator.extensions.navigator_store"; + public const string StoreKey = "_navigator.extensions.store.navigator_db_context"; - private readonly NavigatorDbContext _navigatorDbContext; + private readonly IUniversalStore _universalStore; - public StoreContextExtension(NavigatorDbContext navigatorDbContext) + public StoreContextExtension(IUniversalStore universalStore) { - _navigatorDbContext = navigatorDbContext; + _universalStore = universalStore; } public Task Extend(INavigatorContext navigatorContext, INavigatorContextBuilderOptions builderOptions) { - navigatorContext.Extensions.Add(StoreKey, _navigatorDbContext); + navigatorContext.Extensions.Add(StoreKey, _universalStore); return Task.FromResult(navigatorContext); } From 57fc3094faf64355f55cb73ae513cdee8d9749be Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Thu, 23 Dec 2021 11:52:12 +0100 Subject: [PATCH 243/304] feat: update store extensions to NavigatorContext --- .../NavigatorContextExtensions.cs | 42 +++++++------------ 1 file changed, 15 insertions(+), 27 deletions(-) diff --git a/src/Navigator.Extensions.Store/NavigatorContextExtensions.cs b/src/Navigator.Extensions.Store/NavigatorContextExtensions.cs index 6c99711..fd4e83a 100644 --- a/src/Navigator.Extensions.Store/NavigatorContextExtensions.cs +++ b/src/Navigator.Extensions.Store/NavigatorContextExtensions.cs @@ -12,16 +12,16 @@ public static class NavigatorContextExtensions { #region Store - public static NavigatorDbContext GetStore(this INavigatorContext context) + public static IUniversalStore GetStore(this INavigatorContext context) { return GetStoreOrDefault(context) ?? throw new InvalidOperationException(); } - public static NavigatorDbContext? GetStoreOrDefault(this INavigatorContext context) + public static IUniversalStore? GetStoreOrDefault(this INavigatorContext context) { var value = context.Extensions.GetValueOrDefault(StoreContextExtension.StoreKey); - if (value is NavigatorDbContext store) + if (value is IUniversalStore store) { return store; } @@ -31,56 +31,44 @@ public static NavigatorDbContext GetStore(this INavigatorContext context) #endregion - #region User + #region Chat - public static async Task GetUniversalChat(this INavigatorContext context) + public static async Task GetUniversalChat(this INavigatorContext context, CancellationToken cancellationToken = default) { return await GetUniversalChatOrDefault(context) ?? throw new InvalidOperationException(); } - public static async Task GetUniversalChatOrDefault(this INavigatorContext context) + public static async Task GetUniversalChatOrDefault(this INavigatorContext context, CancellationToken cancellationToken = default) { - return await context.GetStore().Chats - .AsNoTracking() - .FirstOrDefaultAsync(e => e.Profiles - .Any(p => p.Identification == context.Conversation.Chat.Id)); + return await context.GetStore().FindChat(context.Conversation.Chat, context.Provider.Name, cancellationToken); } #endregion #region Conversation - public static async Task GetUniversalConversation(this INavigatorContext context) + public static async Task GetUniversalConversation(this INavigatorContext context, CancellationToken cancellationToken = default) { - return await GetUniversalConversationOrDefault(context) ?? throw new InvalidOperationException(); + return await GetUniversalConversationOrDefault(context, cancellationToken) ?? throw new InvalidOperationException(); } - public static async Task GetUniversalConversationOrDefault(this INavigatorContext context) + public static async Task GetUniversalConversationOrDefault(this INavigatorContext context, CancellationToken cancellationToken = default) { - return await context.GetStore().Users - .AsNoTracking() - .Where(e => e.Profiles - .Any(p => p.Identification == context.Conversation.User.Id)) - .Select(e => e.Conversations.FirstOrDefault(c => c.Chat.Profiles - .Any(p => p.Identification == context.Conversation.Chat.Id))) - .FirstOrDefaultAsync(); + return await context.GetStore().FindConversation(context.Conversation, context.Provider.Name, cancellationToken); } #endregion #region User - public static async Task GetUniversalUser(this INavigatorContext context) + public static async Task GetUniversalUser(this INavigatorContext context, CancellationToken cancellationToken = default) { - return await GetUniversalUserOrDefault(context) ?? throw new InvalidOperationException(); + return await GetUniversalUserOrDefault(context, cancellationToken) ?? throw new InvalidOperationException(); } - public static async Task GetUniversalUserOrDefault(this INavigatorContext context) + public static async Task GetUniversalUserOrDefault(this INavigatorContext context, CancellationToken cancellationToken = default) { - return await context.GetStore().Users - .AsNoTracking() - .FirstOrDefaultAsync(e => e.Profiles - .Any(p => p.Identification == context.Conversation.User.Id)); + return await context.GetStore().FindUser(context.Conversation.User, context.Provider.Name, cancellationToken); } #endregion From 6da87f162865d9372d283913acda864d81329a71 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Thu, 23 Dec 2021 11:52:22 +0100 Subject: [PATCH 244/304] feat: update Store DI --- .../NavigatorExtensionConfigurationExtensions.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Navigator.Extensions.Store/NavigatorExtensionConfigurationExtensions.cs b/src/Navigator.Extensions.Store/NavigatorExtensionConfigurationExtensions.cs index b88ebe5..1908ce1 100644 --- a/src/Navigator.Extensions.Store/NavigatorExtensionConfigurationExtensions.cs +++ b/src/Navigator.Extensions.Store/NavigatorExtensionConfigurationExtensions.cs @@ -18,6 +18,7 @@ public static NavigatorConfiguration Store(this NavigatorExtensionConfiguration { services.AddDbContext(dbContextOptions); services.AddScoped(); + services.AddScoped(); services.AddTransient(); }); } From 6b7c720aaea313687acc4224591787dd40ef10e4 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Thu, 23 Dec 2021 11:52:50 +0100 Subject: [PATCH 245/304] feat: add interaction with UniversalStore to EchoAction --- .../Actions/EchoActionHandler.cs | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/src/Navigator.Samples.Store/Actions/EchoActionHandler.cs b/src/Navigator.Samples.Store/Actions/EchoActionHandler.cs index 1780f49..c108cab 100644 --- a/src/Navigator.Samples.Store/Actions/EchoActionHandler.cs +++ b/src/Navigator.Samples.Store/Actions/EchoActionHandler.cs @@ -1,5 +1,8 @@ -using System.Threading; +using System.Globalization; +using System.Linq; +using System.Threading; using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; using Navigator.Actions; using Navigator.Context; using Navigator.Extensions.Store; @@ -10,13 +13,18 @@ namespace Navigator.Samples.Store.Actions; public class EchoActionHandler : ActionHandler { - public EchoActionHandler(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) + private readonly NavigatorDbContext _dbContext; + public EchoActionHandler(INavigatorContextAccessor navigatorContextAccessor, NavigatorDbContext dbContext) : base(navigatorContextAccessor) { + _dbContext = dbContext; } public override async Task Handle(EchoAction action, CancellationToken cancellationToken) { - var store = NavigatorContext.GetStoreOrDefault(); + var uc = await NavigatorContext.GetStoreOrDefault()?.FindConversation(NavigatorContext.Conversation, NavigatorContext.Provider.Name, cancellationToken); + + await this.GetTelegramClient().SendTextMessageAsync(this.GetTelegramChat().Id, + uc.FirstInteractionAt.ToLongDateString(), cancellationToken: cancellationToken); await this.GetTelegramClient().SendTextMessageAsync(this.GetTelegramChat().Id, action.MessageToEcho, cancellationToken: cancellationToken); From 0804242bac484e537c36f0092560b51e40dcea03 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Thu, 23 Dec 2021 11:59:22 +0100 Subject: [PATCH 246/304] chore: refactor and correct namespaces --- .../Context/Configuration/ChatEntityTypeConfiguration.cs | 2 +- .../Configuration/ConversationEntityTypeConfiguration.cs | 2 +- .../Context/Configuration/ProfileEntityTypeConfiguration.cs | 2 +- .../Context/Configuration/UserEntityTypeConfiguration.cs | 2 +- src/Navigator.Extensions.Store/Context/NavigatorDbContext.cs | 4 ++-- src/Navigator.Extensions.Store/Entities/UniversalChat.cs | 2 +- .../NavigatorExtensionConfigurationExtensions.cs | 1 + src/Navigator.Extensions.Store/UniversalStore.cs | 1 + src/Navigator.Samples.Store/Actions/EchoActionHandler.cs | 1 + .../Migrations/20211222133231_InitialMigration.Designer.cs | 1 + .../Migrations/NavigatorDbContextModelSnapshot.cs | 1 + src/Navigator.Samples.Store/Program.cs | 1 + 12 files changed, 13 insertions(+), 7 deletions(-) diff --git a/src/Navigator.Extensions.Store/Context/Configuration/ChatEntityTypeConfiguration.cs b/src/Navigator.Extensions.Store/Context/Configuration/ChatEntityTypeConfiguration.cs index d8b96f1..2f1f740 100644 --- a/src/Navigator.Extensions.Store/Context/Configuration/ChatEntityTypeConfiguration.cs +++ b/src/Navigator.Extensions.Store/Context/Configuration/ChatEntityTypeConfiguration.cs @@ -2,7 +2,7 @@ using Microsoft.EntityFrameworkCore.Metadata.Builders; using Navigator.Extensions.Store.Entities; -namespace Navigator.Extensions.Store.Configuration; +namespace Navigator.Extensions.Store.Context.Configuration; public class ChatEntityTypeConfiguration : IEntityTypeConfiguration { diff --git a/src/Navigator.Extensions.Store/Context/Configuration/ConversationEntityTypeConfiguration.cs b/src/Navigator.Extensions.Store/Context/Configuration/ConversationEntityTypeConfiguration.cs index 16aba29..bdeb1c6 100644 --- a/src/Navigator.Extensions.Store/Context/Configuration/ConversationEntityTypeConfiguration.cs +++ b/src/Navigator.Extensions.Store/Context/Configuration/ConversationEntityTypeConfiguration.cs @@ -2,7 +2,7 @@ using Microsoft.EntityFrameworkCore.Metadata.Builders; using Navigator.Extensions.Store.Entities; -namespace Navigator.Extensions.Store.Configuration; +namespace Navigator.Extensions.Store.Context.Configuration; public class ConversationEntityTypeConfiguration : IEntityTypeConfiguration { diff --git a/src/Navigator.Extensions.Store/Context/Configuration/ProfileEntityTypeConfiguration.cs b/src/Navigator.Extensions.Store/Context/Configuration/ProfileEntityTypeConfiguration.cs index 6f9f613..b9bd6c6 100644 --- a/src/Navigator.Extensions.Store/Context/Configuration/ProfileEntityTypeConfiguration.cs +++ b/src/Navigator.Extensions.Store/Context/Configuration/ProfileEntityTypeConfiguration.cs @@ -2,7 +2,7 @@ using Microsoft.EntityFrameworkCore.Metadata.Builders; using Navigator.Extensions.Store.Entities; -namespace Navigator.Extensions.Store.Configuration; +namespace Navigator.Extensions.Store.Context.Configuration; public class ProfileEntityTypeConfiguration : IEntityTypeConfiguration { diff --git a/src/Navigator.Extensions.Store/Context/Configuration/UserEntityTypeConfiguration.cs b/src/Navigator.Extensions.Store/Context/Configuration/UserEntityTypeConfiguration.cs index c6a2168..b2eebcb 100644 --- a/src/Navigator.Extensions.Store/Context/Configuration/UserEntityTypeConfiguration.cs +++ b/src/Navigator.Extensions.Store/Context/Configuration/UserEntityTypeConfiguration.cs @@ -2,7 +2,7 @@ using Microsoft.EntityFrameworkCore.Metadata.Builders; using Navigator.Extensions.Store.Entities; -namespace Navigator.Extensions.Store.Configuration; +namespace Navigator.Extensions.Store.Context.Configuration; public class UserEntityTypeConfiguration : IEntityTypeConfiguration { diff --git a/src/Navigator.Extensions.Store/Context/NavigatorDbContext.cs b/src/Navigator.Extensions.Store/Context/NavigatorDbContext.cs index a34a17f..47694ca 100644 --- a/src/Navigator.Extensions.Store/Context/NavigatorDbContext.cs +++ b/src/Navigator.Extensions.Store/Context/NavigatorDbContext.cs @@ -1,8 +1,8 @@ using Microsoft.EntityFrameworkCore; -using Navigator.Extensions.Store.Configuration; +using Navigator.Extensions.Store.Context.Configuration; using Navigator.Extensions.Store.Entities; -namespace Navigator.Extensions.Store; +namespace Navigator.Extensions.Store.Context; public class NavigatorDbContext : DbContext { diff --git a/src/Navigator.Extensions.Store/Entities/UniversalChat.cs b/src/Navigator.Extensions.Store/Entities/UniversalChat.cs index 4733327..ccaddfc 100644 --- a/src/Navigator.Extensions.Store/Entities/UniversalChat.cs +++ b/src/Navigator.Extensions.Store/Entities/UniversalChat.cs @@ -1,4 +1,4 @@ -using Navigator.Extensions.Store.Entities; +namespace Navigator.Extensions.Store.Entities; public class UniversalChat : Navigator.Entities.Chat { diff --git a/src/Navigator.Extensions.Store/NavigatorExtensionConfigurationExtensions.cs b/src/Navigator.Extensions.Store/NavigatorExtensionConfigurationExtensions.cs index 1908ce1..afa64eb 100644 --- a/src/Navigator.Extensions.Store/NavigatorExtensionConfigurationExtensions.cs +++ b/src/Navigator.Extensions.Store/NavigatorExtensionConfigurationExtensions.cs @@ -5,6 +5,7 @@ using Navigator.Configuration.Extension; using Navigator.Context.Extensions; using Navigator.Extensions.Store.Bundled; +using Navigator.Extensions.Store.Context; namespace Navigator.Extensions.Store; diff --git a/src/Navigator.Extensions.Store/UniversalStore.cs b/src/Navigator.Extensions.Store/UniversalStore.cs index 8e41e16..5bf4cc3 100644 --- a/src/Navigator.Extensions.Store/UniversalStore.cs +++ b/src/Navigator.Extensions.Store/UniversalStore.cs @@ -1,5 +1,6 @@ using Microsoft.EntityFrameworkCore; using Navigator.Entities; +using Navigator.Extensions.Store.Context; using Navigator.Extensions.Store.Entities; namespace Navigator.Extensions.Store; diff --git a/src/Navigator.Samples.Store/Actions/EchoActionHandler.cs b/src/Navigator.Samples.Store/Actions/EchoActionHandler.cs index c108cab..de9a663 100644 --- a/src/Navigator.Samples.Store/Actions/EchoActionHandler.cs +++ b/src/Navigator.Samples.Store/Actions/EchoActionHandler.cs @@ -6,6 +6,7 @@ using Navigator.Actions; using Navigator.Context; using Navigator.Extensions.Store; +using Navigator.Extensions.Store.Context; using Navigator.Providers.Telegram; using Telegram.Bot; diff --git a/src/Navigator.Samples.Store/Migrations/20211222133231_InitialMigration.Designer.cs b/src/Navigator.Samples.Store/Migrations/20211222133231_InitialMigration.Designer.cs index 5d9b1ca..06b0b77 100644 --- a/src/Navigator.Samples.Store/Migrations/20211222133231_InitialMigration.Designer.cs +++ b/src/Navigator.Samples.Store/Migrations/20211222133231_InitialMigration.Designer.cs @@ -5,6 +5,7 @@ using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using Navigator.Extensions.Store; +using Navigator.Extensions.Store.Context; #nullable disable diff --git a/src/Navigator.Samples.Store/Migrations/NavigatorDbContextModelSnapshot.cs b/src/Navigator.Samples.Store/Migrations/NavigatorDbContextModelSnapshot.cs index 6d1f837..80ecab4 100644 --- a/src/Navigator.Samples.Store/Migrations/NavigatorDbContextModelSnapshot.cs +++ b/src/Navigator.Samples.Store/Migrations/NavigatorDbContextModelSnapshot.cs @@ -4,6 +4,7 @@ using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using Navigator.Extensions.Store; +using Navigator.Extensions.Store.Context; #nullable disable diff --git a/src/Navigator.Samples.Store/Program.cs b/src/Navigator.Samples.Store/Program.cs index b69bc81..6debd6b 100644 --- a/src/Navigator.Samples.Store/Program.cs +++ b/src/Navigator.Samples.Store/Program.cs @@ -7,6 +7,7 @@ using Navigator.Configuration; using Navigator.Extensions.Cooldown; using Navigator.Extensions.Store; +using Navigator.Extensions.Store.Context; using Navigator.Providers.Telegram; using Navigator.Samples.Store.Actions; From 5927db4e224875f1e0ccf1b872a2aa4dd11409a6 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Thu, 23 Dec 2021 15:08:47 +0100 Subject: [PATCH 247/304] feat: add Id to Conversation --- src/Navigator/Entities/Conversation.cs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/Navigator/Entities/Conversation.cs b/src/Navigator/Entities/Conversation.cs index fc41df2..52aa511 100644 --- a/src/Navigator/Entities/Conversation.cs +++ b/src/Navigator/Entities/Conversation.cs @@ -1,3 +1,8 @@ +using System; +using System.Linq; +using System.Security.Cryptography; +using System.Text; + namespace Navigator.Entities; /// @@ -11,10 +16,14 @@ protected Conversation() protected Conversation(User user, Chat chat) { + Id = new Guid(SHA256.HashData(Encoding.UTF8.GetBytes($"{user.Id}+{chat.Id}")).Take(16).ToArray()); + User = user; Chat = chat; } + public Guid Id { get; init; } + /// /// User /// From 60830a4861d31299a5c2f8ae8d918caa8d8f9aac Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Thu, 23 Dec 2021 15:09:21 +0100 Subject: [PATCH 248/304] feat: update universal entities --- .../Entities/UniversalChat.cs | 2 +- .../Entities/UniversalConversation.cs | 2 ++ .../Entities/UniversalProfile.cs | 11 ++++++++--- 3 files changed, 11 insertions(+), 4 deletions(-) diff --git a/src/Navigator.Extensions.Store/Entities/UniversalChat.cs b/src/Navigator.Extensions.Store/Entities/UniversalChat.cs index ccaddfc..305b238 100644 --- a/src/Navigator.Extensions.Store/Entities/UniversalChat.cs +++ b/src/Navigator.Extensions.Store/Entities/UniversalChat.cs @@ -10,7 +10,7 @@ public UniversalChat() FirstInteractionAt = DateTime.UtcNow; } - public Guid Id { get; set; } + public new Guid Id { get; set; } public IList Profiles { get; set; } diff --git a/src/Navigator.Extensions.Store/Entities/UniversalConversation.cs b/src/Navigator.Extensions.Store/Entities/UniversalConversation.cs index 8abbb9e..ce20104 100644 --- a/src/Navigator.Extensions.Store/Entities/UniversalConversation.cs +++ b/src/Navigator.Extensions.Store/Entities/UniversalConversation.cs @@ -15,6 +15,8 @@ public UniversalConversation(User user, Chat chat) : base(user, chat) FirstInteractionAt = DateTime.UtcNow; } + public new Guid Id { get; set; } + public new UniversalChat Chat { get; set; } public new UniversalUser User { get; set; } diff --git a/src/Navigator.Extensions.Store/Entities/UniversalProfile.cs b/src/Navigator.Extensions.Store/Entities/UniversalProfile.cs index d1151e4..1c2b5f7 100644 --- a/src/Navigator.Extensions.Store/Entities/UniversalProfile.cs +++ b/src/Navigator.Extensions.Store/Entities/UniversalProfile.cs @@ -1,3 +1,5 @@ +using Navigator.Entities; + namespace Navigator.Extensions.Store.Entities; public class UniversalProfile @@ -17,15 +19,18 @@ protected UniversalProfile() public class UserProfile : UniversalProfile { - + public User Data { get; set; } + public Guid DataId { get; set; } } public class ChatProfile : UniversalProfile { - + public Chat Data { get; set; } + public Guid DataId { get; set; } } public class ConversationProfile : UniversalProfile { - + public Conversation Data { get; set; } + public Guid DataId { get; set; } } \ No newline at end of file From 11112c88e738c4646edfc17d25f5cab65f588293 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Thu, 23 Dec 2021 15:09:57 +0100 Subject: [PATCH 249/304] feat: add default constructor to TelegramConversation --- .../Entities/TelegramConversation.cs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/Navigator.Providers.Telegram/Entities/TelegramConversation.cs b/src/Navigator.Providers.Telegram/Entities/TelegramConversation.cs index c50bc13..bc65622 100644 --- a/src/Navigator.Providers.Telegram/Entities/TelegramConversation.cs +++ b/src/Navigator.Providers.Telegram/Entities/TelegramConversation.cs @@ -4,6 +4,11 @@ namespace Navigator.Providers.Telegram.Entities; public class TelegramConversation : Conversation { + public TelegramConversation() + { + + } + public TelegramConversation(TelegramUser user, TelegramChat chat) : base(user, chat) { User = user; From 57748b4569e06f145e4bf7b2cdd7476db86a8c95 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Thu, 23 Dec 2021 15:10:34 +0100 Subject: [PATCH 250/304] feat: implement extension of entities for DbContext --- .../UniversalConversationContextExtension.cs | 8 +-- .../ChatEntityTypeConfiguration.cs | 2 +- .../UserEntityTypeConfiguration.cs | 2 +- .../DbContextOptionsBuilderExtensions.cs | 13 +++++ .../Extension/NavigatorStoreModelExtension.cs | 21 ++++++++ .../NavigatorStoreModelExtensionInfo.cs | 30 +++++++++++ .../Context/NavigatorDbContext.cs | 54 +++++++++++++++++-- 7 files changed, 121 insertions(+), 9 deletions(-) create mode 100644 src/Navigator.Extensions.Store/Context/Extension/DbContextOptionsBuilderExtensions.cs create mode 100644 src/Navigator.Extensions.Store/Context/Extension/NavigatorStoreModelExtension.cs create mode 100644 src/Navigator.Extensions.Store/Context/Extension/NavigatorStoreModelExtensionInfo.cs diff --git a/src/Navigator.Extensions.Store/Bundled/UniversalConversationContextExtension.cs b/src/Navigator.Extensions.Store/Bundled/UniversalConversationContextExtension.cs index 4f13da0..ab1520f 100644 --- a/src/Navigator.Extensions.Store/Bundled/UniversalConversationContextExtension.cs +++ b/src/Navigator.Extensions.Store/Bundled/UniversalConversationContextExtension.cs @@ -2,6 +2,7 @@ using System.Text.Json; using Navigator.Context; using Navigator.Context.Extensions; +using Navigator.Extensions.Store.Context; namespace Navigator.Extensions.Store.Bundled; @@ -10,10 +11,12 @@ internal class UniversalConversationContextExtension : INavigatorContextExtensio public const string UniversalConversation = "_navigator.extensions.store.universal_conversation"; private readonly IUniversalStore _universalStore; + private readonly NavigatorDbContext _dbContext; - public UniversalConversationContextExtension(IUniversalStore universalStore) + public UniversalConversationContextExtension(IUniversalStore universalStore, NavigatorDbContext dbContext) { _universalStore = universalStore; + _dbContext = dbContext; } public async Task Extend(INavigatorContext navigatorContext, INavigatorContextBuilderOptions builderOptions) @@ -22,9 +25,6 @@ public async Task Extend(INavigatorContext navigatorContext, var universalConversation = await _universalStore.FindOrCreateConversation(conversation, navigatorContext.Provider.Name); - - - return await Task.FromResult(navigatorContext); } } \ No newline at end of file diff --git a/src/Navigator.Extensions.Store/Context/Configuration/ChatEntityTypeConfiguration.cs b/src/Navigator.Extensions.Store/Context/Configuration/ChatEntityTypeConfiguration.cs index 2f1f740..0f8f4c4 100644 --- a/src/Navigator.Extensions.Store/Context/Configuration/ChatEntityTypeConfiguration.cs +++ b/src/Navigator.Extensions.Store/Context/Configuration/ChatEntityTypeConfiguration.cs @@ -8,7 +8,7 @@ public class ChatEntityTypeConfiguration : IEntityTypeConfiguration builder) { - builder.HasKey(e => e.Id); + // builder.HasKey(e => e.Id); builder.HasMany(e => e.Profiles) .WithOne(); diff --git a/src/Navigator.Extensions.Store/Context/Configuration/UserEntityTypeConfiguration.cs b/src/Navigator.Extensions.Store/Context/Configuration/UserEntityTypeConfiguration.cs index b2eebcb..99634cc 100644 --- a/src/Navigator.Extensions.Store/Context/Configuration/UserEntityTypeConfiguration.cs +++ b/src/Navigator.Extensions.Store/Context/Configuration/UserEntityTypeConfiguration.cs @@ -8,7 +8,7 @@ public class UserEntityTypeConfiguration : IEntityTypeConfiguration builder) { - builder.HasKey(e => e.Id); + // builder.HasKey(e => e.Id); builder.HasMany(e => e.Profiles) .WithOne(); diff --git a/src/Navigator.Extensions.Store/Context/Extension/DbContextOptionsBuilderExtensions.cs b/src/Navigator.Extensions.Store/Context/Extension/DbContextOptionsBuilderExtensions.cs new file mode 100644 index 0000000..0bccdb5 --- /dev/null +++ b/src/Navigator.Extensions.Store/Context/Extension/DbContextOptionsBuilderExtensions.cs @@ -0,0 +1,13 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; + +namespace Navigator.Extensions.Store.Context.Extension; + +public static class DbContextOptionsBuilderExtensions +{ + public static void UsingStoreExtension(this DbContextOptionsBuilder builder) + where TExtension : class, IDbContextOptionsExtension, new() + { + ((IDbContextOptionsBuilderInfrastructure)builder).AddOrUpdateExtension(new TExtension()); + } +} \ No newline at end of file diff --git a/src/Navigator.Extensions.Store/Context/Extension/NavigatorStoreModelExtension.cs b/src/Navigator.Extensions.Store/Context/Extension/NavigatorStoreModelExtension.cs new file mode 100644 index 0000000..82d5be4 --- /dev/null +++ b/src/Navigator.Extensions.Store/Context/Extension/NavigatorStoreModelExtension.cs @@ -0,0 +1,21 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.Extensions.DependencyInjection; + +namespace Navigator.Extensions.Store.Context.Extension; + +public abstract class NavigatorStoreModelExtension : IDbContextOptionsExtension +{ + public Action Extension { get; } + public void ApplyServices(IServiceCollection services) + { + + } + + public void Validate(IDbContextOptions options) + { + + } + + public abstract DbContextOptionsExtensionInfo Info { get; } +} \ No newline at end of file diff --git a/src/Navigator.Extensions.Store/Context/Extension/NavigatorStoreModelExtensionInfo.cs b/src/Navigator.Extensions.Store/Context/Extension/NavigatorStoreModelExtensionInfo.cs new file mode 100644 index 0000000..860a17e --- /dev/null +++ b/src/Navigator.Extensions.Store/Context/Extension/NavigatorStoreModelExtensionInfo.cs @@ -0,0 +1,30 @@ +using Microsoft.EntityFrameworkCore.Infrastructure; + +namespace Navigator.Extensions.Store.Context.Extension; + +public abstract class NavigatorStoreModelExtensionInfo : DbContextOptionsExtensionInfo +{ + public NavigatorStoreModelExtensionInfo(IDbContextOptionsExtension extension) : base(extension) + { + } + + public override int GetServiceProviderHashCode() + { + + var hashCode = new HashCode(); + + return hashCode.ToHashCode(); + } + + public override bool ShouldUseSameServiceProvider(DbContextOptionsExtensionInfo other) + { + return other is NavigatorStoreModelExtensionInfo; + } + + public override void PopulateDebugInfo(IDictionary debugInfo) + { + } + + public override bool IsDatabaseProvider { get; } + public override string LogFragment { get; } +} \ No newline at end of file diff --git a/src/Navigator.Extensions.Store/Context/NavigatorDbContext.cs b/src/Navigator.Extensions.Store/Context/NavigatorDbContext.cs index 47694ca..5ad14e4 100644 --- a/src/Navigator.Extensions.Store/Context/NavigatorDbContext.cs +++ b/src/Navigator.Extensions.Store/Context/NavigatorDbContext.cs @@ -1,5 +1,10 @@ +using System.Diagnostics; using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; +using Microsoft.Extensions.DependencyInjection; +using Navigator.Entities; using Navigator.Extensions.Store.Context.Configuration; +using Navigator.Extensions.Store.Context.Extension; using Navigator.Extensions.Store.Entities; namespace Navigator.Extensions.Store.Context; @@ -15,8 +20,16 @@ protected NavigatorDbContext() { } + private readonly IList> _entityTypeConfigurations = new List>(); + public NavigatorDbContext(DbContextOptions options) : base(options) { + foreach (var extension in options.Extensions + .OfType() + .Select(e => e.Extension)) + { + _entityTypeConfigurations.Add(extension); + } } protected override void OnModelCreating(ModelBuilder modelBuilder) @@ -28,8 +41,43 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) modelBuilder.ApplyConfiguration(new ConversationEntityTypeConfiguration()); modelBuilder.ApplyConfiguration(new ProfileEntityTypeConfiguration()); - modelBuilder.Entity(b => b.HasBaseType()); - modelBuilder.Entity(b => b.HasBaseType()); - modelBuilder.Entity(b => b.HasBaseType()); + modelBuilder.Entity(b => + { + b.HasKey(e => e.Id); + }); + modelBuilder.Entity(b => + { + b.HasKey(e => e.Id); + }); + modelBuilder.Entity(b => + { + b.HasKey(e => e.Id); + }); + + modelBuilder.Entity(b => + { + b.HasBaseType(); + // b.OwnsOne(e => e.Data); + }); + + modelBuilder.Entity(b => + { + b.HasBaseType(); + // b.OwnsOne(e => e.Data); + }); + + modelBuilder.Entity(b => + { + b.HasBaseType(); + b.HasOne(e => e.Data) + .WithOne(); + }); + + foreach (var entityTypeConfiguration in _entityTypeConfigurations) + { + entityTypeConfiguration.Invoke(modelBuilder); + + Console.WriteLine("##### EXECUTING EXTENSION #####"); + } } } \ No newline at end of file From bcaf501f626357f4148f589f8c7ea05ee6818eb2 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Thu, 23 Dec 2021 15:10:50 +0100 Subject: [PATCH 251/304] feat: implement Store extension for Telegram --- ...Navigator.Extensions.Store.Telegram.csproj | 14 ++++++++ .../NavigatorStoreTelegramExtension.cs | 32 +++++++++++++++++++ .../NavigatorStoreTelegramExtensionInfo.cs | 21 ++++++++++++ .../TelegramChatProfile.cs | 9 ++++++ .../TelegramConversationProfile.cs | 9 ++++++ .../TelegramUserProfile.cs | 9 ++++++ src/Navigator.sln | 7 ++++ 7 files changed, 101 insertions(+) create mode 100644 src/Navigator.Extensions.Store.Telegram/Navigator.Extensions.Store.Telegram.csproj create mode 100644 src/Navigator.Extensions.Store.Telegram/NavigatorStoreTelegramExtension.cs create mode 100644 src/Navigator.Extensions.Store.Telegram/NavigatorStoreTelegramExtensionInfo.cs create mode 100644 src/Navigator.Extensions.Store.Telegram/TelegramChatProfile.cs create mode 100644 src/Navigator.Extensions.Store.Telegram/TelegramConversationProfile.cs create mode 100644 src/Navigator.Extensions.Store.Telegram/TelegramUserProfile.cs diff --git a/src/Navigator.Extensions.Store.Telegram/Navigator.Extensions.Store.Telegram.csproj b/src/Navigator.Extensions.Store.Telegram/Navigator.Extensions.Store.Telegram.csproj new file mode 100644 index 0000000..55c98b6 --- /dev/null +++ b/src/Navigator.Extensions.Store.Telegram/Navigator.Extensions.Store.Telegram.csproj @@ -0,0 +1,14 @@ + + + + net6.0 + enable + enable + + + + + + + + diff --git a/src/Navigator.Extensions.Store.Telegram/NavigatorStoreTelegramExtension.cs b/src/Navigator.Extensions.Store.Telegram/NavigatorStoreTelegramExtension.cs new file mode 100644 index 0000000..5daadb3 --- /dev/null +++ b/src/Navigator.Extensions.Store.Telegram/NavigatorStoreTelegramExtension.cs @@ -0,0 +1,32 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Navigator.Entities; +using Navigator.Extensions.Store.Context.Extension; +using Navigator.Extensions.Store.Entities; +using Navigator.Providers.Telegram.Entities; + +namespace Navigator.Extensions.Store.Telegram; + + +public class NavigatorStoreTelegramExtension : NavigatorStoreModelExtension +{ + public NavigatorStoreTelegramExtension() + { + Extension = modelBuilder => + { + modelBuilder.Entity(typeBuilder => typeBuilder.HasBaseType()); + modelBuilder.Entity(typeBuilder => typeBuilder.HasBaseType()); + + modelBuilder.Entity(typeBuilder => typeBuilder.HasBaseType()); + modelBuilder.Entity(typeBuilder => typeBuilder.HasBaseType()); + + modelBuilder.Entity(typeBuilder => typeBuilder.HasBaseType()); + modelBuilder.Entity(typeBuilder => typeBuilder.HasBaseType()); + }; + Info = new NavigatorStoreTelegramExtensionInfo(this); + } + + public Action Extension { get; } + + public override DbContextOptionsExtensionInfo Info { get; } +} \ No newline at end of file diff --git a/src/Navigator.Extensions.Store.Telegram/NavigatorStoreTelegramExtensionInfo.cs b/src/Navigator.Extensions.Store.Telegram/NavigatorStoreTelegramExtensionInfo.cs new file mode 100644 index 0000000..e0b214f --- /dev/null +++ b/src/Navigator.Extensions.Store.Telegram/NavigatorStoreTelegramExtensionInfo.cs @@ -0,0 +1,21 @@ +using Microsoft.EntityFrameworkCore.Infrastructure; +using Navigator.Extensions.Store.Context.Extension; + +namespace Navigator.Extensions.Store.Telegram; + +public class NavigatorStoreTelegramExtensionInfo : NavigatorStoreModelExtensionInfo +{ + public NavigatorStoreTelegramExtensionInfo(IDbContextOptionsExtension extension) : base(extension) + { + } + + public override int GetServiceProviderHashCode() + { + var hashCode = new HashCode(); + + hashCode.Add(base.GetServiceProviderHashCode()); + hashCode.Add(Extension); + + return hashCode.ToHashCode(); + } +} \ No newline at end of file diff --git a/src/Navigator.Extensions.Store.Telegram/TelegramChatProfile.cs b/src/Navigator.Extensions.Store.Telegram/TelegramChatProfile.cs new file mode 100644 index 0000000..7a23400 --- /dev/null +++ b/src/Navigator.Extensions.Store.Telegram/TelegramChatProfile.cs @@ -0,0 +1,9 @@ +using Navigator.Extensions.Store.Entities; +using Navigator.Providers.Telegram.Entities; + +namespace Navigator.Extensions.Store.Telegram; + +public class TelegramChatProfile : ChatProfile +{ + public new TelegramChat Data { get; set; } +} \ No newline at end of file diff --git a/src/Navigator.Extensions.Store.Telegram/TelegramConversationProfile.cs b/src/Navigator.Extensions.Store.Telegram/TelegramConversationProfile.cs new file mode 100644 index 0000000..104e725 --- /dev/null +++ b/src/Navigator.Extensions.Store.Telegram/TelegramConversationProfile.cs @@ -0,0 +1,9 @@ +using Navigator.Extensions.Store.Entities; +using Navigator.Providers.Telegram.Entities; + +namespace Navigator.Extensions.Store.Telegram; + +public class TelegramConversationProfile : ConversationProfile +{ + public new TelegramConversation Data { get; set; } +} \ No newline at end of file diff --git a/src/Navigator.Extensions.Store.Telegram/TelegramUserProfile.cs b/src/Navigator.Extensions.Store.Telegram/TelegramUserProfile.cs new file mode 100644 index 0000000..e38561f --- /dev/null +++ b/src/Navigator.Extensions.Store.Telegram/TelegramUserProfile.cs @@ -0,0 +1,9 @@ +using Navigator.Extensions.Store.Entities; +using Navigator.Providers.Telegram.Entities; + +namespace Navigator.Extensions.Store.Telegram; + +public class TelegramUserProfile : UserProfile +{ + public new TelegramUser Data { get; set; } +} \ No newline at end of file diff --git a/src/Navigator.sln b/src/Navigator.sln index 1a45399..b0ddcdd 100644 --- a/src/Navigator.sln +++ b/src/Navigator.sln @@ -19,6 +19,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Navigator.Extensions.Store" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Navigator.Samples.Store", "Navigator.Samples.Store\Navigator.Samples.Store.csproj", "{50766B99-2587-4298-B43C-58DE387F5860}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Navigator.Extensions.Store.Telegram", "Navigator.Extensions.Store.Telegram\Navigator.Extensions.Store.Telegram.csproj", "{342AEA62-E0C8-4B02-A048-5FACD34E9B29}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -49,6 +51,10 @@ Global {50766B99-2587-4298-B43C-58DE387F5860}.Debug|Any CPU.Build.0 = Debug|Any CPU {50766B99-2587-4298-B43C-58DE387F5860}.Release|Any CPU.ActiveCfg = Release|Any CPU {50766B99-2587-4298-B43C-58DE387F5860}.Release|Any CPU.Build.0 = Release|Any CPU + {342AEA62-E0C8-4B02-A048-5FACD34E9B29}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {342AEA62-E0C8-4B02-A048-5FACD34E9B29}.Debug|Any CPU.Build.0 = Debug|Any CPU + {342AEA62-E0C8-4B02-A048-5FACD34E9B29}.Release|Any CPU.ActiveCfg = Release|Any CPU + {342AEA62-E0C8-4B02-A048-5FACD34E9B29}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(NestedProjects) = preSolution {6DBAD041-6623-4903-9939-254FDC4EBD60} = {E6F24E3B-A066-4572-94F0-14665E19EFC7} @@ -59,5 +65,6 @@ Global {A6DF6F5F-F784-4EF1-97D1-C3DDD2E66B5E} = {E6F24E3B-A066-4572-94F0-14665E19EFC7} {E7D6F33B-C30E-4ED2-878C-B2F899CF1805} = {A6DF6F5F-F784-4EF1-97D1-C3DDD2E66B5E} {50766B99-2587-4298-B43C-58DE387F5860} = {6D6A8E40-8C40-49AA-BEAD-B046D43F511A} + {342AEA62-E0C8-4B02-A048-5FACD34E9B29} = {A6DF6F5F-F784-4EF1-97D1-C3DDD2E66B5E} EndGlobalSection EndGlobal From afc04cef685b6b898595ade46f75bed9692770ed Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Thu, 23 Dec 2021 15:11:01 +0100 Subject: [PATCH 252/304] feat: update demo project --- ...0211222133231_InitialMigration.Designer.cs | 199 ------------------ .../20211222133231_InitialMigration.cs | 132 ------------ .../NavigatorDbContextModelSnapshot.cs | 197 ----------------- .../Navigator.Samples.Store.csproj | 1 + src/Navigator.Samples.Store/Program.cs | 5 + 5 files changed, 6 insertions(+), 528 deletions(-) delete mode 100644 src/Navigator.Samples.Store/Migrations/20211222133231_InitialMigration.Designer.cs delete mode 100644 src/Navigator.Samples.Store/Migrations/20211222133231_InitialMigration.cs delete mode 100644 src/Navigator.Samples.Store/Migrations/NavigatorDbContextModelSnapshot.cs diff --git a/src/Navigator.Samples.Store/Migrations/20211222133231_InitialMigration.Designer.cs b/src/Navigator.Samples.Store/Migrations/20211222133231_InitialMigration.Designer.cs deleted file mode 100644 index 06b0b77..0000000 --- a/src/Navigator.Samples.Store/Migrations/20211222133231_InitialMigration.Designer.cs +++ /dev/null @@ -1,199 +0,0 @@ -// -using System; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Infrastructure; -using Microsoft.EntityFrameworkCore.Migrations; -using Microsoft.EntityFrameworkCore.Storage.ValueConversion; -using Navigator.Extensions.Store; -using Navigator.Extensions.Store.Context; - -#nullable disable - -namespace Navigator.Samples.Store.Migrations -{ - [DbContext(typeof(NavigatorDbContext))] - [Migration("20211222133231_InitialMigration")] - partial class InitialMigration - { - protected override void BuildTargetModel(ModelBuilder modelBuilder) - { -#pragma warning disable 612, 618 - modelBuilder.HasAnnotation("ProductVersion", "6.0.1"); - - modelBuilder.Entity("Navigator.Extensions.Store.Entities.UniversalConversation", b => - { - b.Property("ChatId") - .HasColumnType("TEXT"); - - b.Property("UserId") - .HasColumnType("TEXT"); - - b.Property("FirstInteractionAt") - .HasColumnType("TEXT"); - - b.HasKey("ChatId", "UserId"); - - b.HasIndex("UserId"); - - b.ToTable("Conversations"); - }); - - modelBuilder.Entity("Navigator.Extensions.Store.Entities.UniversalProfile", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("CreatedAt") - .HasColumnType("TEXT"); - - b.Property("Discriminator") - .IsRequired() - .HasColumnType("TEXT"); - - b.Property("Identification") - .HasColumnType("TEXT"); - - b.Property("LastUpdatedAt") - .HasColumnType("TEXT"); - - b.Property("Provider") - .IsRequired() - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("Profiles"); - - b.HasDiscriminator("Discriminator").HasValue("UniversalProfile"); - }); - - modelBuilder.Entity("Navigator.Extensions.Store.Entities.UniversalUser", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("FirstInteractionAt") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("Users"); - }); - - modelBuilder.Entity("UniversalChat", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("FirstInteractionAt") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("Chats"); - }); - - modelBuilder.Entity("Navigator.Extensions.Store.Entities.ChatProfile", b => - { - b.HasBaseType("Navigator.Extensions.Store.Entities.UniversalProfile"); - - b.Property("UniversalChatId") - .HasColumnType("TEXT"); - - b.HasIndex("UniversalChatId"); - - b.HasDiscriminator().HasValue("ChatProfile"); - }); - - modelBuilder.Entity("Navigator.Extensions.Store.Entities.ConversationProfile", b => - { - b.HasBaseType("Navigator.Extensions.Store.Entities.UniversalProfile"); - - b.Property("UniversalConversationChatId") - .HasColumnType("TEXT"); - - b.Property("UniversalConversationUserId") - .HasColumnType("TEXT"); - - b.HasIndex("UniversalConversationChatId", "UniversalConversationUserId"); - - b.HasDiscriminator().HasValue("ConversationProfile"); - }); - - modelBuilder.Entity("Navigator.Extensions.Store.Entities.UserProfile", b => - { - b.HasBaseType("Navigator.Extensions.Store.Entities.UniversalProfile"); - - b.Property("UniversalUserId") - .HasColumnType("TEXT"); - - b.HasIndex("UniversalUserId"); - - b.HasDiscriminator().HasValue("UserProfile"); - }); - - modelBuilder.Entity("Navigator.Extensions.Store.Entities.UniversalConversation", b => - { - b.HasOne("UniversalChat", "Chat") - .WithMany("Conversations") - .HasForeignKey("ChatId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.HasOne("Navigator.Extensions.Store.Entities.UniversalUser", "User") - .WithMany("Conversations") - .HasForeignKey("UserId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("Chat"); - - b.Navigation("User"); - }); - - modelBuilder.Entity("Navigator.Extensions.Store.Entities.ChatProfile", b => - { - b.HasOne("UniversalChat", null) - .WithMany("Profiles") - .HasForeignKey("UniversalChatId"); - }); - - modelBuilder.Entity("Navigator.Extensions.Store.Entities.ConversationProfile", b => - { - b.HasOne("Navigator.Extensions.Store.Entities.UniversalConversation", null) - .WithMany("Profiles") - .HasForeignKey("UniversalConversationChatId", "UniversalConversationUserId"); - }); - - modelBuilder.Entity("Navigator.Extensions.Store.Entities.UserProfile", b => - { - b.HasOne("Navigator.Extensions.Store.Entities.UniversalUser", null) - .WithMany("Profiles") - .HasForeignKey("UniversalUserId"); - }); - - modelBuilder.Entity("Navigator.Extensions.Store.Entities.UniversalConversation", b => - { - b.Navigation("Profiles"); - }); - - modelBuilder.Entity("Navigator.Extensions.Store.Entities.UniversalUser", b => - { - b.Navigation("Conversations"); - - b.Navigation("Profiles"); - }); - - modelBuilder.Entity("UniversalChat", b => - { - b.Navigation("Conversations"); - - b.Navigation("Profiles"); - }); -#pragma warning restore 612, 618 - } - } -} diff --git a/src/Navigator.Samples.Store/Migrations/20211222133231_InitialMigration.cs b/src/Navigator.Samples.Store/Migrations/20211222133231_InitialMigration.cs deleted file mode 100644 index 6eadceb..0000000 --- a/src/Navigator.Samples.Store/Migrations/20211222133231_InitialMigration.cs +++ /dev/null @@ -1,132 +0,0 @@ -using System; -using Microsoft.EntityFrameworkCore.Migrations; - -#nullable disable - -namespace Navigator.Samples.Store.Migrations -{ - public partial class InitialMigration : Migration - { - protected override void Up(MigrationBuilder migrationBuilder) - { - migrationBuilder.CreateTable( - name: "Chats", - columns: table => new - { - Id = table.Column(type: "TEXT", nullable: false), - FirstInteractionAt = table.Column(type: "TEXT", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_Chats", x => x.Id); - }); - - migrationBuilder.CreateTable( - name: "Users", - columns: table => new - { - Id = table.Column(type: "TEXT", nullable: false), - FirstInteractionAt = table.Column(type: "TEXT", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_Users", x => x.Id); - }); - - migrationBuilder.CreateTable( - name: "Conversations", - columns: table => new - { - ChatId = table.Column(type: "TEXT", nullable: false), - UserId = table.Column(type: "TEXT", nullable: false), - FirstInteractionAt = table.Column(type: "TEXT", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_Conversations", x => new { x.ChatId, x.UserId }); - table.ForeignKey( - name: "FK_Conversations_Chats_ChatId", - column: x => x.ChatId, - principalTable: "Chats", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - table.ForeignKey( - name: "FK_Conversations_Users_UserId", - column: x => x.UserId, - principalTable: "Users", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); - - migrationBuilder.CreateTable( - name: "Profiles", - columns: table => new - { - Id = table.Column(type: "TEXT", nullable: false), - Provider = table.Column(type: "TEXT", nullable: false), - Identification = table.Column(type: "TEXT", nullable: false), - CreatedAt = table.Column(type: "TEXT", nullable: false), - LastUpdatedAt = table.Column(type: "TEXT", nullable: false), - Discriminator = table.Column(type: "TEXT", nullable: false), - UniversalChatId = table.Column(type: "TEXT", nullable: true), - UniversalConversationChatId = table.Column(type: "TEXT", nullable: true), - UniversalConversationUserId = table.Column(type: "TEXT", nullable: true), - UniversalUserId = table.Column(type: "TEXT", nullable: true) - }, - constraints: table => - { - table.PrimaryKey("PK_Profiles", x => x.Id); - table.ForeignKey( - name: "FK_Profiles_Chats_UniversalChatId", - column: x => x.UniversalChatId, - principalTable: "Chats", - principalColumn: "Id"); - table.ForeignKey( - name: "FK_Profiles_Conversations_UniversalConversationChatId_UniversalConversationUserId", - columns: x => new { x.UniversalConversationChatId, x.UniversalConversationUserId }, - principalTable: "Conversations", - principalColumns: new[] { "ChatId", "UserId" }); - table.ForeignKey( - name: "FK_Profiles_Users_UniversalUserId", - column: x => x.UniversalUserId, - principalTable: "Users", - principalColumn: "Id"); - }); - - migrationBuilder.CreateIndex( - name: "IX_Conversations_UserId", - table: "Conversations", - column: "UserId"); - - migrationBuilder.CreateIndex( - name: "IX_Profiles_UniversalChatId", - table: "Profiles", - column: "UniversalChatId"); - - migrationBuilder.CreateIndex( - name: "IX_Profiles_UniversalConversationChatId_UniversalConversationUserId", - table: "Profiles", - columns: new[] { "UniversalConversationChatId", "UniversalConversationUserId" }); - - migrationBuilder.CreateIndex( - name: "IX_Profiles_UniversalUserId", - table: "Profiles", - column: "UniversalUserId"); - } - - protected override void Down(MigrationBuilder migrationBuilder) - { - migrationBuilder.DropTable( - name: "Profiles"); - - migrationBuilder.DropTable( - name: "Conversations"); - - migrationBuilder.DropTable( - name: "Chats"); - - migrationBuilder.DropTable( - name: "Users"); - } - } -} diff --git a/src/Navigator.Samples.Store/Migrations/NavigatorDbContextModelSnapshot.cs b/src/Navigator.Samples.Store/Migrations/NavigatorDbContextModelSnapshot.cs deleted file mode 100644 index 80ecab4..0000000 --- a/src/Navigator.Samples.Store/Migrations/NavigatorDbContextModelSnapshot.cs +++ /dev/null @@ -1,197 +0,0 @@ -// -using System; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Infrastructure; -using Microsoft.EntityFrameworkCore.Storage.ValueConversion; -using Navigator.Extensions.Store; -using Navigator.Extensions.Store.Context; - -#nullable disable - -namespace Navigator.Samples.Store.Migrations -{ - [DbContext(typeof(NavigatorDbContext))] - partial class NavigatorDbContextModelSnapshot : ModelSnapshot - { - protected override void BuildModel(ModelBuilder modelBuilder) - { -#pragma warning disable 612, 618 - modelBuilder.HasAnnotation("ProductVersion", "6.0.1"); - - modelBuilder.Entity("Navigator.Extensions.Store.Entities.UniversalConversation", b => - { - b.Property("ChatId") - .HasColumnType("TEXT"); - - b.Property("UserId") - .HasColumnType("TEXT"); - - b.Property("FirstInteractionAt") - .HasColumnType("TEXT"); - - b.HasKey("ChatId", "UserId"); - - b.HasIndex("UserId"); - - b.ToTable("Conversations"); - }); - - modelBuilder.Entity("Navigator.Extensions.Store.Entities.UniversalProfile", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("CreatedAt") - .HasColumnType("TEXT"); - - b.Property("Discriminator") - .IsRequired() - .HasColumnType("TEXT"); - - b.Property("Identification") - .HasColumnType("TEXT"); - - b.Property("LastUpdatedAt") - .HasColumnType("TEXT"); - - b.Property("Provider") - .IsRequired() - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("Profiles"); - - b.HasDiscriminator("Discriminator").HasValue("UniversalProfile"); - }); - - modelBuilder.Entity("Navigator.Extensions.Store.Entities.UniversalUser", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("FirstInteractionAt") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("Users"); - }); - - modelBuilder.Entity("UniversalChat", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("FirstInteractionAt") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("Chats"); - }); - - modelBuilder.Entity("Navigator.Extensions.Store.Entities.ChatProfile", b => - { - b.HasBaseType("Navigator.Extensions.Store.Entities.UniversalProfile"); - - b.Property("UniversalChatId") - .HasColumnType("TEXT"); - - b.HasIndex("UniversalChatId"); - - b.HasDiscriminator().HasValue("ChatProfile"); - }); - - modelBuilder.Entity("Navigator.Extensions.Store.Entities.ConversationProfile", b => - { - b.HasBaseType("Navigator.Extensions.Store.Entities.UniversalProfile"); - - b.Property("UniversalConversationChatId") - .HasColumnType("TEXT"); - - b.Property("UniversalConversationUserId") - .HasColumnType("TEXT"); - - b.HasIndex("UniversalConversationChatId", "UniversalConversationUserId"); - - b.HasDiscriminator().HasValue("ConversationProfile"); - }); - - modelBuilder.Entity("Navigator.Extensions.Store.Entities.UserProfile", b => - { - b.HasBaseType("Navigator.Extensions.Store.Entities.UniversalProfile"); - - b.Property("UniversalUserId") - .HasColumnType("TEXT"); - - b.HasIndex("UniversalUserId"); - - b.HasDiscriminator().HasValue("UserProfile"); - }); - - modelBuilder.Entity("Navigator.Extensions.Store.Entities.UniversalConversation", b => - { - b.HasOne("UniversalChat", "Chat") - .WithMany("Conversations") - .HasForeignKey("ChatId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.HasOne("Navigator.Extensions.Store.Entities.UniversalUser", "User") - .WithMany("Conversations") - .HasForeignKey("UserId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("Chat"); - - b.Navigation("User"); - }); - - modelBuilder.Entity("Navigator.Extensions.Store.Entities.ChatProfile", b => - { - b.HasOne("UniversalChat", null) - .WithMany("Profiles") - .HasForeignKey("UniversalChatId"); - }); - - modelBuilder.Entity("Navigator.Extensions.Store.Entities.ConversationProfile", b => - { - b.HasOne("Navigator.Extensions.Store.Entities.UniversalConversation", null) - .WithMany("Profiles") - .HasForeignKey("UniversalConversationChatId", "UniversalConversationUserId"); - }); - - modelBuilder.Entity("Navigator.Extensions.Store.Entities.UserProfile", b => - { - b.HasOne("Navigator.Extensions.Store.Entities.UniversalUser", null) - .WithMany("Profiles") - .HasForeignKey("UniversalUserId"); - }); - - modelBuilder.Entity("Navigator.Extensions.Store.Entities.UniversalConversation", b => - { - b.Navigation("Profiles"); - }); - - modelBuilder.Entity("Navigator.Extensions.Store.Entities.UniversalUser", b => - { - b.Navigation("Conversations"); - - b.Navigation("Profiles"); - }); - - modelBuilder.Entity("UniversalChat", b => - { - b.Navigation("Conversations"); - - b.Navigation("Profiles"); - }); -#pragma warning restore 612, 618 - } - } -} diff --git a/src/Navigator.Samples.Store/Navigator.Samples.Store.csproj b/src/Navigator.Samples.Store/Navigator.Samples.Store.csproj index 6f8a893..6d254a6 100644 --- a/src/Navigator.Samples.Store/Navigator.Samples.Store.csproj +++ b/src/Navigator.Samples.Store/Navigator.Samples.Store.csproj @@ -12,6 +12,7 @@ + diff --git a/src/Navigator.Samples.Store/Program.cs b/src/Navigator.Samples.Store/Program.cs index 6debd6b..4f8fbb2 100644 --- a/src/Navigator.Samples.Store/Program.cs +++ b/src/Navigator.Samples.Store/Program.cs @@ -1,5 +1,6 @@ using Microsoft.AspNetCore.Builder; using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; @@ -8,6 +9,8 @@ using Navigator.Extensions.Cooldown; using Navigator.Extensions.Store; using Navigator.Extensions.Store.Context; +using Navigator.Extensions.Store.Context.Extension; +using Navigator.Extensions.Store.Telegram; using Navigator.Providers.Telegram; using Navigator.Samples.Store.Actions; @@ -30,6 +33,8 @@ { dbBuilder.UseSqlite(builder.Configuration.GetConnectionString("DefaultConnection"), b => b.MigrationsAssembly("Navigator.Samples.Store")); + + dbBuilder.UsingStoreExtension(); }); var app = builder.Build(); From 85b823af666b95c01670f6ae0af00b2e53124877 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Thu, 23 Dec 2021 15:34:19 +0100 Subject: [PATCH 253/304] feat: made StoreModelExtension able to specify services for DI --- .../NavigatorStoreTelegramExtension.cs | 2 - .../Extension/NavigatorStoreModelExtension.cs | 4 +- .../IUniversalStore.cs | 24 ++-- ...vigatorExtensionConfigurationExtensions.cs | 13 ++- .../UniversalStore.cs | 103 ------------------ 5 files changed, 27 insertions(+), 119 deletions(-) diff --git a/src/Navigator.Extensions.Store.Telegram/NavigatorStoreTelegramExtension.cs b/src/Navigator.Extensions.Store.Telegram/NavigatorStoreTelegramExtension.cs index 5daadb3..fcfb289 100644 --- a/src/Navigator.Extensions.Store.Telegram/NavigatorStoreTelegramExtension.cs +++ b/src/Navigator.Extensions.Store.Telegram/NavigatorStoreTelegramExtension.cs @@ -26,7 +26,5 @@ public NavigatorStoreTelegramExtension() Info = new NavigatorStoreTelegramExtensionInfo(this); } - public Action Extension { get; } - public override DbContextOptionsExtensionInfo Info { get; } } \ No newline at end of file diff --git a/src/Navigator.Extensions.Store/Context/Extension/NavigatorStoreModelExtension.cs b/src/Navigator.Extensions.Store/Context/Extension/NavigatorStoreModelExtension.cs index 82d5be4..b739743 100644 --- a/src/Navigator.Extensions.Store/Context/Extension/NavigatorStoreModelExtension.cs +++ b/src/Navigator.Extensions.Store/Context/Extension/NavigatorStoreModelExtension.cs @@ -6,7 +6,9 @@ namespace Navigator.Extensions.Store.Context.Extension; public abstract class NavigatorStoreModelExtension : IDbContextOptionsExtension { - public Action Extension { get; } + public Action? Extension { get; protected set; } + public Action? ExtensionServices { get; protected set; } + public void ApplyServices(IServiceCollection services) { diff --git a/src/Navigator.Extensions.Store/IUniversalStore.cs b/src/Navigator.Extensions.Store/IUniversalStore.cs index 4c48435..9c13109 100644 --- a/src/Navigator.Extensions.Store/IUniversalStore.cs +++ b/src/Navigator.Extensions.Store/IUniversalStore.cs @@ -26,16 +26,16 @@ Task FindOrCreateConversation(Conversation conversation, #endregion - #region Profile - - Task AddUserProfile(UniversalUser user, string provider, Guid identification, CancellationToken cancellationToken = default, bool? saveChanges = true); - Task TryAddUserProfile(UniversalUser user, string provider, Guid identification, CancellationToken cancellationToken = default, bool? saveChanges = true); - - Task AddChatProfile(UniversalChat chat, string provider, Guid identification, CancellationToken cancellationToken = default, bool? saveChanges = true); - Task TryAddChatProfile(UniversalChat chat, string provider, Guid identification, CancellationToken cancellationToken = default, bool? saveChanges = true); - - Task AddConversationProfile(UniversalConversation conversation, string provider, Guid identification, CancellationToken cancellationToken = default, bool? saveChanges = true); - Task TryAddConversationProfile(UniversalConversation conversation, string provider, Guid identification, CancellationToken cancellationToken = default, bool? saveChanges = true); - - #endregion + // #region Profile + // + // Task AddUserProfile(UniversalUser user, string provider, Guid identification, CancellationToken cancellationToken = default, bool? saveChanges = true); + // Task TryAddUserProfile(UniversalUser user, string provider, Guid identification, CancellationToken cancellationToken = default, bool? saveChanges = true); + // + // Task AddChatProfile(UniversalChat chat, string provider, Guid identification, CancellationToken cancellationToken = default, bool? saveChanges = true); + // Task TryAddChatProfile(UniversalChat chat, string provider, Guid identification, CancellationToken cancellationToken = default, bool? saveChanges = true); + // + // Task AddConversationProfile(UniversalConversation conversation, string provider, Guid identification, CancellationToken cancellationToken = default, bool? saveChanges = true); + // Task TryAddConversationProfile(UniversalConversation conversation, string provider, Guid identification, CancellationToken cancellationToken = default, bool? saveChanges = true); + // + // #endregion } \ No newline at end of file diff --git a/src/Navigator.Extensions.Store/NavigatorExtensionConfigurationExtensions.cs b/src/Navigator.Extensions.Store/NavigatorExtensionConfigurationExtensions.cs index afa64eb..d7a56c8 100644 --- a/src/Navigator.Extensions.Store/NavigatorExtensionConfigurationExtensions.cs +++ b/src/Navigator.Extensions.Store/NavigatorExtensionConfigurationExtensions.cs @@ -6,6 +6,7 @@ using Navigator.Context.Extensions; using Navigator.Extensions.Store.Bundled; using Navigator.Extensions.Store.Context; +using Navigator.Extensions.Store.Context.Extension; namespace Navigator.Extensions.Store; @@ -13,14 +14,24 @@ public static class NavigatorExtensionConfigurationExtensions { public static NavigatorConfiguration Store(this NavigatorExtensionConfiguration providerConfiguration, Action? dbContextOptions = default) { + var temporal = new DbContextOptionsBuilder(); + + dbContextOptions?.Invoke(temporal); + return providerConfiguration.Extension( _ => {}, services => { services.AddDbContext(dbContextOptions); + services.AddTransient(); + services.AddScoped(); services.AddScoped(); - services.AddTransient(); + + foreach (var extension in temporal.Options.Extensions.OfType()) + { + extension.ExtensionServices?.Invoke(services); + } }); } } \ No newline at end of file diff --git a/src/Navigator.Extensions.Store/UniversalStore.cs b/src/Navigator.Extensions.Store/UniversalStore.cs index 5bf4cc3..19aecf4 100644 --- a/src/Navigator.Extensions.Store/UniversalStore.cs +++ b/src/Navigator.Extensions.Store/UniversalStore.cs @@ -106,107 +106,4 @@ public async Task FindOrCreateConversation(Conversation c } #endregion - - #region Profile - - public async Task AddUserProfile(UniversalUser user, string provider, Guid identification, CancellationToken cancellationToken = default, bool? saveChanges = true) - { - var any = await _dbContext.Profiles.AnyAsync(e => e.Provider == provider && e.Identification == identification, cancellationToken); - - if (any) - { - throw new NavigatorStoreException("Profile already exists for this combination of provider and identification"); - } - - var profile = new UserProfile - { - Id = Guid.NewGuid(), - Provider = provider, - Identification = identification - }; - - user.Profiles.Add(profile); - - await _dbContext.SaveChangesAsync(cancellationToken); - } - - public async Task TryAddUserProfile(UniversalUser user, string provider, Guid identification, CancellationToken cancellationToken = default, bool? saveChanges = true) - { - try - { - await AddUserProfile(user, provider, identification, cancellationToken, saveChanges); - } - catch (Exception e) - { - //TODO: log warning - } - } - - public async Task AddChatProfile(UniversalChat chat, string provider, Guid identification, CancellationToken cancellationToken = default, bool? saveChanges = true) - { - var any = await _dbContext.Profiles.AnyAsync(e => e.Provider == provider && e.Identification == identification, cancellationToken); - - if (any) - { - throw new NavigatorStoreException("Profile already exists for this combination of provider and identification"); - } - - var profile = new ChatProfile - { - Id = Guid.NewGuid(), - Provider = provider, - Identification = identification, - }; - - chat.Profiles.Add(profile); - - await _dbContext.SaveChangesAsync(cancellationToken); - } - - public async Task TryAddChatProfile(UniversalChat chat, string provider, Guid identification, CancellationToken cancellationToken = default, bool? saveChanges = true) - { - try - { - await AddChatProfile(chat, provider, identification, cancellationToken, saveChanges); - } - catch (Exception e) - { - //TODO: log warning - } - } - - public async Task AddConversationProfile(UniversalConversation conversation, string provider, Guid identification, CancellationToken cancellationToken = default, bool? saveChanges = true) - { - var any = await _dbContext.Profiles.AnyAsync(e => e.Provider == provider && e.Identification == identification, cancellationToken); - - if (any) - { - throw new NavigatorStoreException("Profile already exists for this combination of provider and identification"); - } - - var profile = new ConversationProfile - { - Id = Guid.NewGuid(), - Provider = provider, - Identification = identification, - }; - - conversation.Profiles.Add(profile); - - await _dbContext.SaveChangesAsync(cancellationToken); - } - - public async Task TryAddConversationProfile(UniversalConversation conversation, string provider, Guid identification, CancellationToken cancellationToken = default, bool? saveChanges = true) - { - try - { - await AddConversationProfile(conversation, provider, identification, cancellationToken, saveChanges); - } - catch (Exception e) - { - //TODO: log warning - } - } - - #endregion } \ No newline at end of file From 4624c09ed6342a83381a0a859d5990f8c7cacc81 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Thu, 23 Dec 2021 16:23:29 +0100 Subject: [PATCH 254/304] feat: simplify universal entities --- .../Entities/UniversalChat.cs | 2 +- .../Entities/UniversalConversation.cs | 2 +- .../Entities/UniversalProfile.cs | 12 ++++++------ .../Entities/UniversalUser.cs | 2 +- 4 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/Navigator.Extensions.Store/Entities/UniversalChat.cs b/src/Navigator.Extensions.Store/Entities/UniversalChat.cs index 305b238..c302a02 100644 --- a/src/Navigator.Extensions.Store/Entities/UniversalChat.cs +++ b/src/Navigator.Extensions.Store/Entities/UniversalChat.cs @@ -10,7 +10,7 @@ public UniversalChat() FirstInteractionAt = DateTime.UtcNow; } - public new Guid Id { get; set; } + // public new Guid Id { get; set; } public IList Profiles { get; set; } diff --git a/src/Navigator.Extensions.Store/Entities/UniversalConversation.cs b/src/Navigator.Extensions.Store/Entities/UniversalConversation.cs index ce20104..265617e 100644 --- a/src/Navigator.Extensions.Store/Entities/UniversalConversation.cs +++ b/src/Navigator.Extensions.Store/Entities/UniversalConversation.cs @@ -15,7 +15,7 @@ public UniversalConversation(User user, Chat chat) : base(user, chat) FirstInteractionAt = DateTime.UtcNow; } - public new Guid Id { get; set; } + // public new Guid Id { get; set; } public new UniversalChat Chat { get; set; } diff --git a/src/Navigator.Extensions.Store/Entities/UniversalProfile.cs b/src/Navigator.Extensions.Store/Entities/UniversalProfile.cs index 1c2b5f7..bd3e83d 100644 --- a/src/Navigator.Extensions.Store/Entities/UniversalProfile.cs +++ b/src/Navigator.Extensions.Store/Entities/UniversalProfile.cs @@ -19,18 +19,18 @@ protected UniversalProfile() public class UserProfile : UniversalProfile { - public User Data { get; set; } - public Guid DataId { get; set; } + public User? Data { get; set; } + public Guid? DataId { get; set; } } public class ChatProfile : UniversalProfile { - public Chat Data { get; set; } - public Guid DataId { get; set; } + public Chat? Data { get; set; } + public Guid? DataId { get; set; } } public class ConversationProfile : UniversalProfile { - public Conversation Data { get; set; } - public Guid DataId { get; set; } + public Conversation? Data { get; set; } + public Guid? DataId { get; set; } } \ No newline at end of file diff --git a/src/Navigator.Extensions.Store/Entities/UniversalUser.cs b/src/Navigator.Extensions.Store/Entities/UniversalUser.cs index 381ff0a..1e51acc 100644 --- a/src/Navigator.Extensions.Store/Entities/UniversalUser.cs +++ b/src/Navigator.Extensions.Store/Entities/UniversalUser.cs @@ -12,7 +12,7 @@ public UniversalUser() FirstInteractionAt = DateTime.UtcNow; } - public new Guid Id { get; set; } + // public new Guid Id { get; set; } public IList Profiles { get; set; } From 5f58c255de674c45dbfa59a4b942456a27831057 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Thu, 23 Dec 2021 16:23:47 +0100 Subject: [PATCH 255/304] feat: update navigator entity --- src/Navigator/Entities/Conversation.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Navigator/Entities/Conversation.cs b/src/Navigator/Entities/Conversation.cs index 52aa511..fc4d36f 100644 --- a/src/Navigator/Entities/Conversation.cs +++ b/src/Navigator/Entities/Conversation.cs @@ -22,15 +22,15 @@ protected Conversation(User user, Chat chat) Chat = chat; } - public Guid Id { get; init; } + public Guid Id { get; set; } /// /// User /// - public User User { get; init; } + public User User { get; set; } /// /// Chat /// - public Chat Chat { get; init; } + public Chat Chat { get; set; } } \ No newline at end of file From 1133de2d5e1bcdf849525f5c98eba629a4ed7a15 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Thu, 23 Dec 2021 16:24:12 +0100 Subject: [PATCH 256/304] feat: update entity defitinions for DbContext --- .../Context/NavigatorDbContext.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/Navigator.Extensions.Store/Context/NavigatorDbContext.cs b/src/Navigator.Extensions.Store/Context/NavigatorDbContext.cs index 5ad14e4..628ca14 100644 --- a/src/Navigator.Extensions.Store/Context/NavigatorDbContext.cs +++ b/src/Navigator.Extensions.Store/Context/NavigatorDbContext.cs @@ -57,13 +57,15 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) modelBuilder.Entity(b => { b.HasBaseType(); - // b.OwnsOne(e => e.Data); + b.HasOne(e => e.Data) + .WithOne(); }); modelBuilder.Entity(b => { b.HasBaseType(); - // b.OwnsOne(e => e.Data); + b.HasOne(e => e.Data) + .WithOne(); }); modelBuilder.Entity(b => @@ -76,8 +78,6 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) foreach (var entityTypeConfiguration in _entityTypeConfigurations) { entityTypeConfiguration.Invoke(modelBuilder); - - Console.WriteLine("##### EXECUTING EXTENSION #####"); } } } \ No newline at end of file From a44762e9199b992533c8b47327ab58f128a72716 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Thu, 23 Dec 2021 16:24:49 +0100 Subject: [PATCH 257/304] chore: correct namespaces --- .../NavigatorStoreTelegramExtension.cs | 1 + .../{ => Profiles}/TelegramChatProfile.cs | 2 +- .../{ => Profiles}/TelegramConversationProfile.cs | 2 +- .../{ => Profiles}/TelegramUserProfile.cs | 2 +- 4 files changed, 4 insertions(+), 3 deletions(-) rename src/Navigator.Extensions.Store.Telegram/{ => Profiles}/TelegramChatProfile.cs (76%) rename src/Navigator.Extensions.Store.Telegram/{ => Profiles}/TelegramConversationProfile.cs (79%) rename src/Navigator.Extensions.Store.Telegram/{ => Profiles}/TelegramUserProfile.cs (76%) diff --git a/src/Navigator.Extensions.Store.Telegram/NavigatorStoreTelegramExtension.cs b/src/Navigator.Extensions.Store.Telegram/NavigatorStoreTelegramExtension.cs index fcfb289..4f5788a 100644 --- a/src/Navigator.Extensions.Store.Telegram/NavigatorStoreTelegramExtension.cs +++ b/src/Navigator.Extensions.Store.Telegram/NavigatorStoreTelegramExtension.cs @@ -3,6 +3,7 @@ using Navigator.Entities; using Navigator.Extensions.Store.Context.Extension; using Navigator.Extensions.Store.Entities; +using Navigator.Extensions.Store.Telegram.Profiles; using Navigator.Providers.Telegram.Entities; namespace Navigator.Extensions.Store.Telegram; diff --git a/src/Navigator.Extensions.Store.Telegram/TelegramChatProfile.cs b/src/Navigator.Extensions.Store.Telegram/Profiles/TelegramChatProfile.cs similarity index 76% rename from src/Navigator.Extensions.Store.Telegram/TelegramChatProfile.cs rename to src/Navigator.Extensions.Store.Telegram/Profiles/TelegramChatProfile.cs index 7a23400..116a004 100644 --- a/src/Navigator.Extensions.Store.Telegram/TelegramChatProfile.cs +++ b/src/Navigator.Extensions.Store.Telegram/Profiles/TelegramChatProfile.cs @@ -1,7 +1,7 @@ using Navigator.Extensions.Store.Entities; using Navigator.Providers.Telegram.Entities; -namespace Navigator.Extensions.Store.Telegram; +namespace Navigator.Extensions.Store.Telegram.Profiles; public class TelegramChatProfile : ChatProfile { diff --git a/src/Navigator.Extensions.Store.Telegram/TelegramConversationProfile.cs b/src/Navigator.Extensions.Store.Telegram/Profiles/TelegramConversationProfile.cs similarity index 79% rename from src/Navigator.Extensions.Store.Telegram/TelegramConversationProfile.cs rename to src/Navigator.Extensions.Store.Telegram/Profiles/TelegramConversationProfile.cs index 104e725..fa17dde 100644 --- a/src/Navigator.Extensions.Store.Telegram/TelegramConversationProfile.cs +++ b/src/Navigator.Extensions.Store.Telegram/Profiles/TelegramConversationProfile.cs @@ -1,7 +1,7 @@ using Navigator.Extensions.Store.Entities; using Navigator.Providers.Telegram.Entities; -namespace Navigator.Extensions.Store.Telegram; +namespace Navigator.Extensions.Store.Telegram.Profiles; public class TelegramConversationProfile : ConversationProfile { diff --git a/src/Navigator.Extensions.Store.Telegram/TelegramUserProfile.cs b/src/Navigator.Extensions.Store.Telegram/Profiles/TelegramUserProfile.cs similarity index 76% rename from src/Navigator.Extensions.Store.Telegram/TelegramUserProfile.cs rename to src/Navigator.Extensions.Store.Telegram/Profiles/TelegramUserProfile.cs index e38561f..a305e95 100644 --- a/src/Navigator.Extensions.Store.Telegram/TelegramUserProfile.cs +++ b/src/Navigator.Extensions.Store.Telegram/Profiles/TelegramUserProfile.cs @@ -1,7 +1,7 @@ using Navigator.Extensions.Store.Entities; using Navigator.Providers.Telegram.Entities; -namespace Navigator.Extensions.Store.Telegram; +namespace Navigator.Extensions.Store.Telegram.Profiles; public class TelegramUserProfile : UserProfile { From 6f964135daac0f799b36c7d45a0eeb443ec93642 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Thu, 23 Dec 2021 16:25:02 +0100 Subject: [PATCH 258/304] fix: correct UniversalStore Conversation creation --- src/Navigator.Extensions.Store/UniversalStore.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Navigator.Extensions.Store/UniversalStore.cs b/src/Navigator.Extensions.Store/UniversalStore.cs index 19aecf4..d4a3fd9 100644 --- a/src/Navigator.Extensions.Store/UniversalStore.cs +++ b/src/Navigator.Extensions.Store/UniversalStore.cs @@ -63,13 +63,14 @@ public async Task FindOrCreateConversation(Conversation c universalConversation = new UniversalConversation { + Id = Guid.NewGuid(), User = user, Chat = chat, }; universalConversation.Profiles.Add(new ConversationProfile { - Id = Guid.NewGuid(), + Id = conversation.Id, Provider = provider, Identification = Guid.NewGuid() }); From b29be1ee4f4d984ee3eb6aea73116c070a128dce Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Thu, 23 Dec 2021 16:25:22 +0100 Subject: [PATCH 259/304] feat: add IProviderProfileMapper to use on profile creation --- .../Mappers/IProviderProfileMapper.cs | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 src/Navigator.Extensions.Store/Mappers/IProviderProfileMapper.cs diff --git a/src/Navigator.Extensions.Store/Mappers/IProviderProfileMapper.cs b/src/Navigator.Extensions.Store/Mappers/IProviderProfileMapper.cs new file mode 100644 index 0000000..6b29b19 --- /dev/null +++ b/src/Navigator.Extensions.Store/Mappers/IProviderProfileMapper.cs @@ -0,0 +1,11 @@ +using Navigator.Entities; +using Navigator.Extensions.Store.Entities; + +namespace Navigator.Extensions.Store.Mappers; + +public interface IProviderProfileMapper +{ + TProfile? From(Conversation conversation); + + UniversalProfile? To(TProfile profile); +} \ No newline at end of file From ece4fcd3c0a3c423a34226453c7e792cc9ba0e60 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Thu, 23 Dec 2021 16:25:32 +0100 Subject: [PATCH 260/304] feat: update migrations of sample --- .../Actions/EchoActionHandler.cs | 2 +- ...0211223144637_InitialMigration.Designer.cs | 373 ++++++++++++++++++ .../20211223144637_InitialMigration.cs | 207 ++++++++++ .../NavigatorDbContextModelSnapshot.cs | 371 +++++++++++++++++ 4 files changed, 952 insertions(+), 1 deletion(-) create mode 100644 src/Navigator.Samples.Store/Migrations/20211223144637_InitialMigration.Designer.cs create mode 100644 src/Navigator.Samples.Store/Migrations/20211223144637_InitialMigration.cs create mode 100644 src/Navigator.Samples.Store/Migrations/NavigatorDbContextModelSnapshot.cs diff --git a/src/Navigator.Samples.Store/Actions/EchoActionHandler.cs b/src/Navigator.Samples.Store/Actions/EchoActionHandler.cs index de9a663..46d1280 100644 --- a/src/Navigator.Samples.Store/Actions/EchoActionHandler.cs +++ b/src/Navigator.Samples.Store/Actions/EchoActionHandler.cs @@ -25,7 +25,7 @@ public override async Task Handle(EchoAction action, CancellationToken c var uc = await NavigatorContext.GetStoreOrDefault()?.FindConversation(NavigatorContext.Conversation, NavigatorContext.Provider.Name, cancellationToken); await this.GetTelegramClient().SendTextMessageAsync(this.GetTelegramChat().Id, - uc.FirstInteractionAt.ToLongDateString(), cancellationToken: cancellationToken); + uc.Id.ToString(), cancellationToken: cancellationToken); await this.GetTelegramClient().SendTextMessageAsync(this.GetTelegramChat().Id, action.MessageToEcho, cancellationToken: cancellationToken); diff --git a/src/Navigator.Samples.Store/Migrations/20211223144637_InitialMigration.Designer.cs b/src/Navigator.Samples.Store/Migrations/20211223144637_InitialMigration.Designer.cs new file mode 100644 index 0000000..fc73c84 --- /dev/null +++ b/src/Navigator.Samples.Store/Migrations/20211223144637_InitialMigration.Designer.cs @@ -0,0 +1,373 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Navigator.Extensions.Store.Context; + +#nullable disable + +namespace Navigator.Samples.Store.Migrations +{ + [DbContext(typeof(NavigatorDbContext))] + [Migration("20211223144637_InitialMigration")] + partial class InitialMigration + { + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "6.0.1"); + + modelBuilder.Entity("Navigator.Entities.Chat", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Discriminator") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("Chat"); + + b.HasDiscriminator("Discriminator").HasValue("Chat"); + }); + + modelBuilder.Entity("Navigator.Entities.Conversation", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Discriminator") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("Conversation"); + + b.HasDiscriminator("Discriminator").HasValue("Conversation"); + }); + + modelBuilder.Entity("Navigator.Entities.User", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Discriminator") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("User"); + + b.HasDiscriminator("Discriminator").HasValue("User"); + }); + + modelBuilder.Entity("Navigator.Extensions.Store.Entities.UniversalProfile", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("Discriminator") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Identification") + .HasColumnType("TEXT"); + + b.Property("LastUpdatedAt") + .HasColumnType("TEXT"); + + b.Property("Provider") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("Profiles"); + + b.HasDiscriminator("Discriminator").HasValue("UniversalProfile"); + }); + + modelBuilder.Entity("Navigator.Extensions.Store.Entities.ChatProfile", b => + { + b.HasBaseType("Navigator.Extensions.Store.Entities.UniversalProfile"); + + b.Property("DataId") + .HasColumnType("TEXT") + .HasColumnName("ChatProfile_DataId"); + + b.Property("UniversalChatId") + .HasColumnType("TEXT"); + + b.HasIndex("DataId") + .IsUnique(); + + b.HasIndex("UniversalChatId"); + + b.HasDiscriminator().HasValue("ChatProfile"); + }); + + modelBuilder.Entity("Navigator.Extensions.Store.Entities.ConversationProfile", b => + { + b.HasBaseType("Navigator.Extensions.Store.Entities.UniversalProfile"); + + b.Property("DataId") + .HasColumnType("TEXT"); + + b.Property("UniversalConversationId") + .HasColumnType("TEXT"); + + b.HasIndex("DataId") + .IsUnique(); + + b.HasIndex("UniversalConversationId"); + + b.HasDiscriminator().HasValue("ConversationProfile"); + }); + + modelBuilder.Entity("Navigator.Extensions.Store.Entities.UniversalChat", b => + { + b.HasBaseType("Navigator.Entities.Chat"); + + b.Property("FirstInteractionAt") + .HasColumnType("TEXT"); + + b.HasDiscriminator().HasValue("UniversalChat"); + }); + + modelBuilder.Entity("Navigator.Extensions.Store.Entities.UniversalConversation", b => + { + b.HasBaseType("Navigator.Entities.Conversation"); + + b.Property("ChatId") + .HasColumnType("TEXT"); + + b.Property("FirstInteractionAt") + .HasColumnType("TEXT"); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasIndex("ChatId"); + + b.HasIndex("UserId"); + + b.HasDiscriminator().HasValue("UniversalConversation"); + }); + + modelBuilder.Entity("Navigator.Extensions.Store.Entities.UniversalUser", b => + { + b.HasBaseType("Navigator.Entities.User"); + + b.Property("FirstInteractionAt") + .HasColumnType("TEXT"); + + b.HasDiscriminator().HasValue("UniversalUser"); + }); + + modelBuilder.Entity("Navigator.Extensions.Store.Entities.UserProfile", b => + { + b.HasBaseType("Navigator.Extensions.Store.Entities.UniversalProfile"); + + b.Property("DataId") + .HasColumnType("TEXT") + .HasColumnName("UserProfile_DataId"); + + b.Property("UniversalUserId") + .HasColumnType("TEXT"); + + b.HasIndex("DataId") + .IsUnique(); + + b.HasIndex("UniversalUserId"); + + b.HasDiscriminator().HasValue("UserProfile"); + }); + + modelBuilder.Entity("Navigator.Providers.Telegram.Entities.TelegramChat", b => + { + b.HasBaseType("Navigator.Entities.Chat"); + + b.Property("ExternalIdentifier") + .HasColumnType("INTEGER"); + + b.Property("Title") + .HasColumnType("TEXT"); + + b.HasDiscriminator().HasValue("TelegramChat"); + }); + + modelBuilder.Entity("Navigator.Providers.Telegram.Entities.TelegramConversation", b => + { + b.HasBaseType("Navigator.Entities.Conversation"); + + b.Property("ChatId") + .HasColumnType("TEXT") + .HasColumnName("TelegramConversation_ChatId"); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnName("TelegramConversation_UserId"); + + b.HasIndex("ChatId"); + + b.HasIndex("UserId"); + + b.HasDiscriminator().HasValue("TelegramConversation"); + }); + + modelBuilder.Entity("Navigator.Providers.Telegram.Entities.TelegramUser", b => + { + b.HasBaseType("Navigator.Entities.User"); + + b.Property("ExternalIdentifier") + .HasColumnType("INTEGER"); + + b.Property("FirstName") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("LanguageCode") + .HasColumnType("TEXT"); + + b.Property("LastName") + .HasColumnType("TEXT"); + + b.Property("Username") + .HasColumnType("TEXT"); + + b.HasDiscriminator().HasValue("TelegramUser"); + }); + + modelBuilder.Entity("Navigator.Extensions.Store.Telegram.TelegramChatProfile", b => + { + b.HasBaseType("Navigator.Extensions.Store.Entities.ChatProfile"); + + b.HasDiscriminator().HasValue("TelegramChatProfile"); + }); + + modelBuilder.Entity("Navigator.Extensions.Store.Telegram.TelegramConversationProfile", b => + { + b.HasBaseType("Navigator.Extensions.Store.Entities.ConversationProfile"); + + b.HasDiscriminator().HasValue("TelegramConversationProfile"); + }); + + modelBuilder.Entity("Navigator.Extensions.Store.Telegram.TelegramUserProfile", b => + { + b.HasBaseType("Navigator.Extensions.Store.Entities.UserProfile"); + + b.HasDiscriminator().HasValue("TelegramUserProfile"); + }); + + modelBuilder.Entity("Navigator.Extensions.Store.Entities.ChatProfile", b => + { + b.HasOne("Navigator.Entities.Chat", "Data") + .WithOne() + .HasForeignKey("Navigator.Extensions.Store.Entities.ChatProfile", "DataId"); + + b.HasOne("Navigator.Extensions.Store.Entities.UniversalChat", null) + .WithMany("Profiles") + .HasForeignKey("UniversalChatId"); + + b.Navigation("Data"); + }); + + modelBuilder.Entity("Navigator.Extensions.Store.Entities.ConversationProfile", b => + { + b.HasOne("Navigator.Entities.Conversation", "Data") + .WithOne() + .HasForeignKey("Navigator.Extensions.Store.Entities.ConversationProfile", "DataId"); + + b.HasOne("Navigator.Extensions.Store.Entities.UniversalConversation", null) + .WithMany("Profiles") + .HasForeignKey("UniversalConversationId"); + + b.Navigation("Data"); + }); + + modelBuilder.Entity("Navigator.Extensions.Store.Entities.UniversalConversation", b => + { + b.HasOne("Navigator.Extensions.Store.Entities.UniversalChat", "Chat") + .WithMany("Conversations") + .HasForeignKey("ChatId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Navigator.Extensions.Store.Entities.UniversalUser", "User") + .WithMany("Conversations") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Chat"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Navigator.Extensions.Store.Entities.UserProfile", b => + { + b.HasOne("Navigator.Entities.User", "Data") + .WithOne() + .HasForeignKey("Navigator.Extensions.Store.Entities.UserProfile", "DataId"); + + b.HasOne("Navigator.Extensions.Store.Entities.UniversalUser", null) + .WithMany("Profiles") + .HasForeignKey("UniversalUserId"); + + b.Navigation("Data"); + }); + + modelBuilder.Entity("Navigator.Providers.Telegram.Entities.TelegramConversation", b => + { + b.HasOne("Navigator.Providers.Telegram.Entities.TelegramChat", "Chat") + .WithMany() + .HasForeignKey("ChatId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Navigator.Providers.Telegram.Entities.TelegramUser", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Chat"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Navigator.Extensions.Store.Entities.UniversalChat", b => + { + b.Navigation("Conversations"); + + b.Navigation("Profiles"); + }); + + modelBuilder.Entity("Navigator.Extensions.Store.Entities.UniversalConversation", b => + { + b.Navigation("Profiles"); + }); + + modelBuilder.Entity("Navigator.Extensions.Store.Entities.UniversalUser", b => + { + b.Navigation("Conversations"); + + b.Navigation("Profiles"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Navigator.Samples.Store/Migrations/20211223144637_InitialMigration.cs b/src/Navigator.Samples.Store/Migrations/20211223144637_InitialMigration.cs new file mode 100644 index 0000000..c4f897f --- /dev/null +++ b/src/Navigator.Samples.Store/Migrations/20211223144637_InitialMigration.cs @@ -0,0 +1,207 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Navigator.Samples.Store.Migrations +{ + public partial class InitialMigration : Migration + { + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "Chat", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + Discriminator = table.Column(type: "TEXT", nullable: false), + FirstInteractionAt = table.Column(type: "TEXT", nullable: true), + ExternalIdentifier = table.Column(type: "INTEGER", nullable: true), + Title = table.Column(type: "TEXT", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_Chat", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "User", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + Discriminator = table.Column(type: "TEXT", nullable: false), + FirstInteractionAt = table.Column(type: "TEXT", nullable: true), + ExternalIdentifier = table.Column(type: "INTEGER", nullable: true), + Username = table.Column(type: "TEXT", nullable: true), + FirstName = table.Column(type: "TEXT", nullable: true), + LastName = table.Column(type: "TEXT", nullable: true), + LanguageCode = table.Column(type: "TEXT", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_User", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "Conversation", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + Discriminator = table.Column(type: "TEXT", nullable: false), + ChatId = table.Column(type: "TEXT", nullable: true), + UserId = table.Column(type: "TEXT", nullable: true), + FirstInteractionAt = table.Column(type: "TEXT", nullable: true), + TelegramConversation_UserId = table.Column(type: "TEXT", nullable: true), + TelegramConversation_ChatId = table.Column(type: "TEXT", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_Conversation", x => x.Id); + table.ForeignKey( + name: "FK_Conversation_Chat_ChatId", + column: x => x.ChatId, + principalTable: "Chat", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_Conversation_Chat_TelegramConversation_ChatId", + column: x => x.TelegramConversation_ChatId, + principalTable: "Chat", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_Conversation_User_TelegramConversation_UserId", + column: x => x.TelegramConversation_UserId, + principalTable: "User", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_Conversation_User_UserId", + column: x => x.UserId, + principalTable: "User", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "Profiles", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + Provider = table.Column(type: "TEXT", nullable: false), + Identification = table.Column(type: "TEXT", nullable: false), + CreatedAt = table.Column(type: "TEXT", nullable: false), + LastUpdatedAt = table.Column(type: "TEXT", nullable: false), + Discriminator = table.Column(type: "TEXT", nullable: false), + ChatProfile_DataId = table.Column(type: "TEXT", nullable: true), + UniversalChatId = table.Column(type: "TEXT", nullable: true), + DataId = table.Column(type: "TEXT", nullable: true), + UniversalConversationId = table.Column(type: "TEXT", nullable: true), + UserProfile_DataId = table.Column(type: "TEXT", nullable: true), + UniversalUserId = table.Column(type: "TEXT", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_Profiles", x => x.Id); + table.ForeignKey( + name: "FK_Profiles_Chat_ChatProfile_DataId", + column: x => x.ChatProfile_DataId, + principalTable: "Chat", + principalColumn: "Id"); + table.ForeignKey( + name: "FK_Profiles_Chat_UniversalChatId", + column: x => x.UniversalChatId, + principalTable: "Chat", + principalColumn: "Id"); + table.ForeignKey( + name: "FK_Profiles_Conversation_DataId", + column: x => x.DataId, + principalTable: "Conversation", + principalColumn: "Id"); + table.ForeignKey( + name: "FK_Profiles_Conversation_UniversalConversationId", + column: x => x.UniversalConversationId, + principalTable: "Conversation", + principalColumn: "Id"); + table.ForeignKey( + name: "FK_Profiles_User_UniversalUserId", + column: x => x.UniversalUserId, + principalTable: "User", + principalColumn: "Id"); + table.ForeignKey( + name: "FK_Profiles_User_UserProfile_DataId", + column: x => x.UserProfile_DataId, + principalTable: "User", + principalColumn: "Id"); + }); + + migrationBuilder.CreateIndex( + name: "IX_Conversation_ChatId", + table: "Conversation", + column: "ChatId"); + + migrationBuilder.CreateIndex( + name: "IX_Conversation_TelegramConversation_ChatId", + table: "Conversation", + column: "TelegramConversation_ChatId"); + + migrationBuilder.CreateIndex( + name: "IX_Conversation_TelegramConversation_UserId", + table: "Conversation", + column: "TelegramConversation_UserId"); + + migrationBuilder.CreateIndex( + name: "IX_Conversation_UserId", + table: "Conversation", + column: "UserId"); + + migrationBuilder.CreateIndex( + name: "IX_Profiles_ChatProfile_DataId", + table: "Profiles", + column: "ChatProfile_DataId", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_Profiles_DataId", + table: "Profiles", + column: "DataId", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_Profiles_UniversalChatId", + table: "Profiles", + column: "UniversalChatId"); + + migrationBuilder.CreateIndex( + name: "IX_Profiles_UniversalConversationId", + table: "Profiles", + column: "UniversalConversationId"); + + migrationBuilder.CreateIndex( + name: "IX_Profiles_UniversalUserId", + table: "Profiles", + column: "UniversalUserId"); + + migrationBuilder.CreateIndex( + name: "IX_Profiles_UserProfile_DataId", + table: "Profiles", + column: "UserProfile_DataId", + unique: true); + } + + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "Profiles"); + + migrationBuilder.DropTable( + name: "Conversation"); + + migrationBuilder.DropTable( + name: "Chat"); + + migrationBuilder.DropTable( + name: "User"); + } + } +} diff --git a/src/Navigator.Samples.Store/Migrations/NavigatorDbContextModelSnapshot.cs b/src/Navigator.Samples.Store/Migrations/NavigatorDbContextModelSnapshot.cs new file mode 100644 index 0000000..58ce572 --- /dev/null +++ b/src/Navigator.Samples.Store/Migrations/NavigatorDbContextModelSnapshot.cs @@ -0,0 +1,371 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Navigator.Extensions.Store.Context; + +#nullable disable + +namespace Navigator.Samples.Store.Migrations +{ + [DbContext(typeof(NavigatorDbContext))] + partial class NavigatorDbContextModelSnapshot : ModelSnapshot + { + protected override void BuildModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "6.0.1"); + + modelBuilder.Entity("Navigator.Entities.Chat", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Discriminator") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("Chat"); + + b.HasDiscriminator("Discriminator").HasValue("Chat"); + }); + + modelBuilder.Entity("Navigator.Entities.Conversation", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Discriminator") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("Conversation"); + + b.HasDiscriminator("Discriminator").HasValue("Conversation"); + }); + + modelBuilder.Entity("Navigator.Entities.User", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Discriminator") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("User"); + + b.HasDiscriminator("Discriminator").HasValue("User"); + }); + + modelBuilder.Entity("Navigator.Extensions.Store.Entities.UniversalProfile", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("Discriminator") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Identification") + .HasColumnType("TEXT"); + + b.Property("LastUpdatedAt") + .HasColumnType("TEXT"); + + b.Property("Provider") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("Profiles"); + + b.HasDiscriminator("Discriminator").HasValue("UniversalProfile"); + }); + + modelBuilder.Entity("Navigator.Extensions.Store.Entities.ChatProfile", b => + { + b.HasBaseType("Navigator.Extensions.Store.Entities.UniversalProfile"); + + b.Property("DataId") + .HasColumnType("TEXT") + .HasColumnName("ChatProfile_DataId"); + + b.Property("UniversalChatId") + .HasColumnType("TEXT"); + + b.HasIndex("DataId") + .IsUnique(); + + b.HasIndex("UniversalChatId"); + + b.HasDiscriminator().HasValue("ChatProfile"); + }); + + modelBuilder.Entity("Navigator.Extensions.Store.Entities.ConversationProfile", b => + { + b.HasBaseType("Navigator.Extensions.Store.Entities.UniversalProfile"); + + b.Property("DataId") + .HasColumnType("TEXT"); + + b.Property("UniversalConversationId") + .HasColumnType("TEXT"); + + b.HasIndex("DataId") + .IsUnique(); + + b.HasIndex("UniversalConversationId"); + + b.HasDiscriminator().HasValue("ConversationProfile"); + }); + + modelBuilder.Entity("Navigator.Extensions.Store.Entities.UniversalChat", b => + { + b.HasBaseType("Navigator.Entities.Chat"); + + b.Property("FirstInteractionAt") + .HasColumnType("TEXT"); + + b.HasDiscriminator().HasValue("UniversalChat"); + }); + + modelBuilder.Entity("Navigator.Extensions.Store.Entities.UniversalConversation", b => + { + b.HasBaseType("Navigator.Entities.Conversation"); + + b.Property("ChatId") + .HasColumnType("TEXT"); + + b.Property("FirstInteractionAt") + .HasColumnType("TEXT"); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasIndex("ChatId"); + + b.HasIndex("UserId"); + + b.HasDiscriminator().HasValue("UniversalConversation"); + }); + + modelBuilder.Entity("Navigator.Extensions.Store.Entities.UniversalUser", b => + { + b.HasBaseType("Navigator.Entities.User"); + + b.Property("FirstInteractionAt") + .HasColumnType("TEXT"); + + b.HasDiscriminator().HasValue("UniversalUser"); + }); + + modelBuilder.Entity("Navigator.Extensions.Store.Entities.UserProfile", b => + { + b.HasBaseType("Navigator.Extensions.Store.Entities.UniversalProfile"); + + b.Property("DataId") + .HasColumnType("TEXT") + .HasColumnName("UserProfile_DataId"); + + b.Property("UniversalUserId") + .HasColumnType("TEXT"); + + b.HasIndex("DataId") + .IsUnique(); + + b.HasIndex("UniversalUserId"); + + b.HasDiscriminator().HasValue("UserProfile"); + }); + + modelBuilder.Entity("Navigator.Providers.Telegram.Entities.TelegramChat", b => + { + b.HasBaseType("Navigator.Entities.Chat"); + + b.Property("ExternalIdentifier") + .HasColumnType("INTEGER"); + + b.Property("Title") + .HasColumnType("TEXT"); + + b.HasDiscriminator().HasValue("TelegramChat"); + }); + + modelBuilder.Entity("Navigator.Providers.Telegram.Entities.TelegramConversation", b => + { + b.HasBaseType("Navigator.Entities.Conversation"); + + b.Property("ChatId") + .HasColumnType("TEXT") + .HasColumnName("TelegramConversation_ChatId"); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnName("TelegramConversation_UserId"); + + b.HasIndex("ChatId"); + + b.HasIndex("UserId"); + + b.HasDiscriminator().HasValue("TelegramConversation"); + }); + + modelBuilder.Entity("Navigator.Providers.Telegram.Entities.TelegramUser", b => + { + b.HasBaseType("Navigator.Entities.User"); + + b.Property("ExternalIdentifier") + .HasColumnType("INTEGER"); + + b.Property("FirstName") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("LanguageCode") + .HasColumnType("TEXT"); + + b.Property("LastName") + .HasColumnType("TEXT"); + + b.Property("Username") + .HasColumnType("TEXT"); + + b.HasDiscriminator().HasValue("TelegramUser"); + }); + + modelBuilder.Entity("Navigator.Extensions.Store.Telegram.TelegramChatProfile", b => + { + b.HasBaseType("Navigator.Extensions.Store.Entities.ChatProfile"); + + b.HasDiscriminator().HasValue("TelegramChatProfile"); + }); + + modelBuilder.Entity("Navigator.Extensions.Store.Telegram.TelegramConversationProfile", b => + { + b.HasBaseType("Navigator.Extensions.Store.Entities.ConversationProfile"); + + b.HasDiscriminator().HasValue("TelegramConversationProfile"); + }); + + modelBuilder.Entity("Navigator.Extensions.Store.Telegram.TelegramUserProfile", b => + { + b.HasBaseType("Navigator.Extensions.Store.Entities.UserProfile"); + + b.HasDiscriminator().HasValue("TelegramUserProfile"); + }); + + modelBuilder.Entity("Navigator.Extensions.Store.Entities.ChatProfile", b => + { + b.HasOne("Navigator.Entities.Chat", "Data") + .WithOne() + .HasForeignKey("Navigator.Extensions.Store.Entities.ChatProfile", "DataId"); + + b.HasOne("Navigator.Extensions.Store.Entities.UniversalChat", null) + .WithMany("Profiles") + .HasForeignKey("UniversalChatId"); + + b.Navigation("Data"); + }); + + modelBuilder.Entity("Navigator.Extensions.Store.Entities.ConversationProfile", b => + { + b.HasOne("Navigator.Entities.Conversation", "Data") + .WithOne() + .HasForeignKey("Navigator.Extensions.Store.Entities.ConversationProfile", "DataId"); + + b.HasOne("Navigator.Extensions.Store.Entities.UniversalConversation", null) + .WithMany("Profiles") + .HasForeignKey("UniversalConversationId"); + + b.Navigation("Data"); + }); + + modelBuilder.Entity("Navigator.Extensions.Store.Entities.UniversalConversation", b => + { + b.HasOne("Navigator.Extensions.Store.Entities.UniversalChat", "Chat") + .WithMany("Conversations") + .HasForeignKey("ChatId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Navigator.Extensions.Store.Entities.UniversalUser", "User") + .WithMany("Conversations") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Chat"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Navigator.Extensions.Store.Entities.UserProfile", b => + { + b.HasOne("Navigator.Entities.User", "Data") + .WithOne() + .HasForeignKey("Navigator.Extensions.Store.Entities.UserProfile", "DataId"); + + b.HasOne("Navigator.Extensions.Store.Entities.UniversalUser", null) + .WithMany("Profiles") + .HasForeignKey("UniversalUserId"); + + b.Navigation("Data"); + }); + + modelBuilder.Entity("Navigator.Providers.Telegram.Entities.TelegramConversation", b => + { + b.HasOne("Navigator.Providers.Telegram.Entities.TelegramChat", "Chat") + .WithMany() + .HasForeignKey("ChatId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Navigator.Providers.Telegram.Entities.TelegramUser", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Chat"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Navigator.Extensions.Store.Entities.UniversalChat", b => + { + b.Navigation("Conversations"); + + b.Navigation("Profiles"); + }); + + modelBuilder.Entity("Navigator.Extensions.Store.Entities.UniversalConversation", b => + { + b.Navigation("Profiles"); + }); + + modelBuilder.Entity("Navigator.Extensions.Store.Entities.UniversalUser", b => + { + b.Navigation("Conversations"); + + b.Navigation("Profiles"); + }); +#pragma warning restore 612, 618 + } + } +} From b29bf568dcf8c6ead077c4ebff69132fb71136d4 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sun, 3 Apr 2022 22:26:41 +0200 Subject: [PATCH 261/304] feat: add things I do not remember --- .../NavigatorStoreTelegramExtension.cs | 11 ++ .../TelegramProviderChatProfileMapper.cs | 35 ++++++ ...legramProviderConversationProfileMapper.cs | 35 ++++++ .../TelegramProviderUserProfileMapper.cs | 35 ++++++ .../UniversalConversationContextExtension.cs | 6 +- .../ChatEntityTypeConfiguration.cs | 7 +- .../ConversationEntityTypeConfiguration.cs | 3 - .../ProfileEntityTypeConfiguration.cs | 25 ---- .../UserEntityTypeConfiguration.cs | 5 +- .../Context/NavigatorDbContext.cs | 28 +---- .../Entities/UniversalChat.cs | 5 - .../Entities/UniversalConversation.cs | 4 - .../Entities/UniversalProfile.cs | 36 ------ .../Entities/UniversalUser.cs | 5 - .../Mappers/IProviderProfileMapper.cs | 11 -- .../UniversalStore.cs | 110 +++++++++--------- .../Actions/EchoActionHandler.cs | 5 +- src/Navigator/Entities/Bot.cs | 10 +- 18 files changed, 189 insertions(+), 187 deletions(-) create mode 100644 src/Navigator.Extensions.Store.Telegram/Profiles/Mappers/TelegramProviderChatProfileMapper.cs create mode 100644 src/Navigator.Extensions.Store.Telegram/Profiles/Mappers/TelegramProviderConversationProfileMapper.cs create mode 100644 src/Navigator.Extensions.Store.Telegram/Profiles/Mappers/TelegramProviderUserProfileMapper.cs delete mode 100644 src/Navigator.Extensions.Store/Context/Configuration/ProfileEntityTypeConfiguration.cs delete mode 100644 src/Navigator.Extensions.Store/Entities/UniversalProfile.cs delete mode 100644 src/Navigator.Extensions.Store/Mappers/IProviderProfileMapper.cs diff --git a/src/Navigator.Extensions.Store.Telegram/NavigatorStoreTelegramExtension.cs b/src/Navigator.Extensions.Store.Telegram/NavigatorStoreTelegramExtension.cs index 4f5788a..edcd445 100644 --- a/src/Navigator.Extensions.Store.Telegram/NavigatorStoreTelegramExtension.cs +++ b/src/Navigator.Extensions.Store.Telegram/NavigatorStoreTelegramExtension.cs @@ -1,9 +1,12 @@ using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.Extensions.DependencyInjection; using Navigator.Entities; using Navigator.Extensions.Store.Context.Extension; using Navigator.Extensions.Store.Entities; +using Navigator.Extensions.Store.Mappers; using Navigator.Extensions.Store.Telegram.Profiles; +using Navigator.Extensions.Store.Telegram.Profiles.Mappers; using Navigator.Providers.Telegram.Entities; namespace Navigator.Extensions.Store.Telegram; @@ -24,6 +27,14 @@ public NavigatorStoreTelegramExtension() modelBuilder.Entity(typeBuilder => typeBuilder.HasBaseType()); modelBuilder.Entity(typeBuilder => typeBuilder.HasBaseType()); }; + + ExtensionServices = services => + { + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + }; + Info = new NavigatorStoreTelegramExtensionInfo(this); } diff --git a/src/Navigator.Extensions.Store.Telegram/Profiles/Mappers/TelegramProviderChatProfileMapper.cs b/src/Navigator.Extensions.Store.Telegram/Profiles/Mappers/TelegramProviderChatProfileMapper.cs new file mode 100644 index 0000000..4b86947 --- /dev/null +++ b/src/Navigator.Extensions.Store.Telegram/Profiles/Mappers/TelegramProviderChatProfileMapper.cs @@ -0,0 +1,35 @@ +using Navigator.Entities; +using Navigator.Extensions.Store.Entities; +using Navigator.Extensions.Store.Mappers; +using Navigator.Providers.Telegram.Entities; + +namespace Navigator.Extensions.Store.Telegram.Profiles.Mappers; + +public class TelegramProviderChatProfileMapper : IProviderChatProfileMapper +{ + public ChatProfile? From(Conversation sourceConversation) + { + if (sourceConversation.Chat is TelegramChat chat) + { + return new TelegramChatProfile + { + Id = Guid.NewGuid(), + Identification = sourceConversation.Chat.Id, + Data = chat, + DataId = sourceConversation.Chat.Id + }; + } + + return default; + } + + UniversalProfile? IProviderProfileMapper.From(Conversation sourceConversation) + { + return From(sourceConversation); + } + + public bool Maps(Type type) + { + return type == typeof(TelegramChat); + } +} \ No newline at end of file diff --git a/src/Navigator.Extensions.Store.Telegram/Profiles/Mappers/TelegramProviderConversationProfileMapper.cs b/src/Navigator.Extensions.Store.Telegram/Profiles/Mappers/TelegramProviderConversationProfileMapper.cs new file mode 100644 index 0000000..a21cc59 --- /dev/null +++ b/src/Navigator.Extensions.Store.Telegram/Profiles/Mappers/TelegramProviderConversationProfileMapper.cs @@ -0,0 +1,35 @@ +using Navigator.Entities; +using Navigator.Extensions.Store.Entities; +using Navigator.Extensions.Store.Mappers; +using Navigator.Providers.Telegram.Entities; + +namespace Navigator.Extensions.Store.Telegram.Profiles.Mappers; + +public class TelegramProviderConversationProfileMapper : IProviderConversationProfileMapper +{ + public ConversationProfile? From(Conversation sourceConversation) + { + if (sourceConversation is TelegramConversation conversation) + { + return new TelegramConversationProfile + { + Id = Guid.NewGuid(), + Identification = sourceConversation.Id, + Data = conversation, + DataId = sourceConversation.Id + }; + } + + return default; + } + + UniversalProfile? IProviderProfileMapper.From(Conversation sourceConversation) + { + return From(sourceConversation); + } + + public bool Maps(Type type) + { + return type == typeof(TelegramConversation); + } +} \ No newline at end of file diff --git a/src/Navigator.Extensions.Store.Telegram/Profiles/Mappers/TelegramProviderUserProfileMapper.cs b/src/Navigator.Extensions.Store.Telegram/Profiles/Mappers/TelegramProviderUserProfileMapper.cs new file mode 100644 index 0000000..e79ab58 --- /dev/null +++ b/src/Navigator.Extensions.Store.Telegram/Profiles/Mappers/TelegramProviderUserProfileMapper.cs @@ -0,0 +1,35 @@ +using Navigator.Entities; +using Navigator.Extensions.Store.Entities; +using Navigator.Extensions.Store.Mappers; +using Navigator.Providers.Telegram.Entities; + +namespace Navigator.Extensions.Store.Telegram.Profiles.Mappers; + +public class TelegramProviderUserProfileMapper : IProviderUserProfileMapper +{ + public UserProfile? From(Conversation sourceConversation) + { + if (sourceConversation.User is TelegramUser user) + { + return new TelegramUserProfile + { + Id = Guid.NewGuid(), + Identification = sourceConversation.User.Id, + Data = user, + DataId = sourceConversation.User.Id + }; + } + + return default; + } + + UniversalProfile? IProviderProfileMapper.From(Conversation sourceConversation) + { + return From(sourceConversation); + } + + public bool Maps(Type type) + { + return type == typeof(TelegramUser) || type == typeof(TelegramBot); + } +} \ No newline at end of file diff --git a/src/Navigator.Extensions.Store/Bundled/UniversalConversationContextExtension.cs b/src/Navigator.Extensions.Store/Bundled/UniversalConversationContextExtension.cs index ab1520f..c408114 100644 --- a/src/Navigator.Extensions.Store/Bundled/UniversalConversationContextExtension.cs +++ b/src/Navigator.Extensions.Store/Bundled/UniversalConversationContextExtension.cs @@ -10,12 +10,10 @@ internal class UniversalConversationContextExtension : INavigatorContextExtensio { public const string UniversalConversation = "_navigator.extensions.store.universal_conversation"; - private readonly IUniversalStore _universalStore; private readonly NavigatorDbContext _dbContext; - public UniversalConversationContextExtension(IUniversalStore universalStore, NavigatorDbContext dbContext) + public UniversalConversationContextExtension(NavigatorDbContext dbContext) { - _universalStore = universalStore; _dbContext = dbContext; } @@ -27,4 +25,6 @@ public async Task Extend(INavigatorContext navigatorContext, return await Task.FromResult(navigatorContext); } + + } \ No newline at end of file diff --git a/src/Navigator.Extensions.Store/Context/Configuration/ChatEntityTypeConfiguration.cs b/src/Navigator.Extensions.Store/Context/Configuration/ChatEntityTypeConfiguration.cs index 0f8f4c4..17556d0 100644 --- a/src/Navigator.Extensions.Store/Context/Configuration/ChatEntityTypeConfiguration.cs +++ b/src/Navigator.Extensions.Store/Context/Configuration/ChatEntityTypeConfiguration.cs @@ -7,12 +7,9 @@ namespace Navigator.Extensions.Store.Context.Configuration; public class ChatEntityTypeConfiguration : IEntityTypeConfiguration { public void Configure(EntityTypeBuilder builder) - { - // builder.HasKey(e => e.Id); + { + builder.HasKey(e => e.Id); - builder.HasMany(e => e.Profiles) - .WithOne(); - builder.HasMany(e => e.Users) .WithMany(e => e.Chats) .UsingEntity( diff --git a/src/Navigator.Extensions.Store/Context/Configuration/ConversationEntityTypeConfiguration.cs b/src/Navigator.Extensions.Store/Context/Configuration/ConversationEntityTypeConfiguration.cs index bdeb1c6..065a173 100644 --- a/src/Navigator.Extensions.Store/Context/Configuration/ConversationEntityTypeConfiguration.cs +++ b/src/Navigator.Extensions.Store/Context/Configuration/ConversationEntityTypeConfiguration.cs @@ -10,8 +10,5 @@ public void Configure(EntityTypeBuilder builder) { builder.Property(e => e.FirstInteractionAt) .IsRequired(); - - builder.HasMany(e => e.Profiles) - .WithOne(); } } \ No newline at end of file diff --git a/src/Navigator.Extensions.Store/Context/Configuration/ProfileEntityTypeConfiguration.cs b/src/Navigator.Extensions.Store/Context/Configuration/ProfileEntityTypeConfiguration.cs deleted file mode 100644 index b9bd6c6..0000000 --- a/src/Navigator.Extensions.Store/Context/Configuration/ProfileEntityTypeConfiguration.cs +++ /dev/null @@ -1,25 +0,0 @@ -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Metadata.Builders; -using Navigator.Extensions.Store.Entities; - -namespace Navigator.Extensions.Store.Context.Configuration; - -public class ProfileEntityTypeConfiguration : IEntityTypeConfiguration -{ - public void Configure(EntityTypeBuilder builder) - { - builder.HasKey(e => e.Id); - - builder.Property(e => e.Provider) - .IsRequired(); - - builder.Property(e => e.Identification) - .IsRequired(); - - builder.Property(e => e.CreatedAt) - .IsRequired(); - - builder.Property(e => e.LastUpdatedAt) - .IsRequired(); - } -} \ No newline at end of file diff --git a/src/Navigator.Extensions.Store/Context/Configuration/UserEntityTypeConfiguration.cs b/src/Navigator.Extensions.Store/Context/Configuration/UserEntityTypeConfiguration.cs index 99634cc..11f49d9 100644 --- a/src/Navigator.Extensions.Store/Context/Configuration/UserEntityTypeConfiguration.cs +++ b/src/Navigator.Extensions.Store/Context/Configuration/UserEntityTypeConfiguration.cs @@ -8,11 +8,8 @@ public class UserEntityTypeConfiguration : IEntityTypeConfiguration builder) { - // builder.HasKey(e => e.Id); + builder.HasKey(e => e.Id); - builder.HasMany(e => e.Profiles) - .WithOne(); - builder.HasMany(e => e.Chats) .WithMany(e => e.Users) .UsingEntity( diff --git a/src/Navigator.Extensions.Store/Context/NavigatorDbContext.cs b/src/Navigator.Extensions.Store/Context/NavigatorDbContext.cs index 628ca14..d22e3ff 100644 --- a/src/Navigator.Extensions.Store/Context/NavigatorDbContext.cs +++ b/src/Navigator.Extensions.Store/Context/NavigatorDbContext.cs @@ -1,7 +1,4 @@ -using System.Diagnostics; using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Metadata.Builders; -using Microsoft.Extensions.DependencyInjection; using Navigator.Entities; using Navigator.Extensions.Store.Context.Configuration; using Navigator.Extensions.Store.Context.Extension; @@ -14,7 +11,6 @@ public class NavigatorDbContext : DbContext public DbSet Users { get; set; } public DbSet Chats { get; set; } public DbSet Conversations { get; set; } - public DbSet Profiles { get; set; } protected NavigatorDbContext() { @@ -28,7 +24,7 @@ public NavigatorDbContext(DbContextOptions options) : base(options) .OfType() .Select(e => e.Extension)) { - _entityTypeConfigurations.Add(extension); + if (extension is not null) _entityTypeConfigurations.Add(extension); } } @@ -39,7 +35,6 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) modelBuilder.ApplyConfiguration(new ChatEntityTypeConfiguration()); modelBuilder.ApplyConfiguration(new UserEntityTypeConfiguration()); modelBuilder.ApplyConfiguration(new ConversationEntityTypeConfiguration()); - modelBuilder.ApplyConfiguration(new ProfileEntityTypeConfiguration()); modelBuilder.Entity(b => { @@ -53,27 +48,6 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) { b.HasKey(e => e.Id); }); - - modelBuilder.Entity(b => - { - b.HasBaseType(); - b.HasOne(e => e.Data) - .WithOne(); - }); - - modelBuilder.Entity(b => - { - b.HasBaseType(); - b.HasOne(e => e.Data) - .WithOne(); - }); - - modelBuilder.Entity(b => - { - b.HasBaseType(); - b.HasOne(e => e.Data) - .WithOne(); - }); foreach (var entityTypeConfiguration in _entityTypeConfigurations) { diff --git a/src/Navigator.Extensions.Store/Entities/UniversalChat.cs b/src/Navigator.Extensions.Store/Entities/UniversalChat.cs index c302a02..351b5a0 100644 --- a/src/Navigator.Extensions.Store/Entities/UniversalChat.cs +++ b/src/Navigator.Extensions.Store/Entities/UniversalChat.cs @@ -4,16 +4,11 @@ public class UniversalChat : Navigator.Entities.Chat { public UniversalChat() { - Profiles = new List(); Users = new List(); Conversations = new List(); FirstInteractionAt = DateTime.UtcNow; } - // public new Guid Id { get; set; } - - public IList Profiles { get; set; } - /// /// Users related to the chat. /// diff --git a/src/Navigator.Extensions.Store/Entities/UniversalConversation.cs b/src/Navigator.Extensions.Store/Entities/UniversalConversation.cs index 265617e..4739aef 100644 --- a/src/Navigator.Extensions.Store/Entities/UniversalConversation.cs +++ b/src/Navigator.Extensions.Store/Entities/UniversalConversation.cs @@ -6,12 +6,10 @@ public class UniversalConversation : Navigator.Entities.Conversation { public UniversalConversation() { - Profiles = new List(); FirstInteractionAt = DateTime.UtcNow; } public UniversalConversation(User user, Chat chat) : base(user, chat) { - Profiles = new List(); FirstInteractionAt = DateTime.UtcNow; } @@ -20,8 +18,6 @@ public UniversalConversation(User user, Chat chat) : base(user, chat) public new UniversalChat Chat { get; set; } public new UniversalUser User { get; set; } - - public IList Profiles { get; set; } /// /// Date of first interaction for this chat. diff --git a/src/Navigator.Extensions.Store/Entities/UniversalProfile.cs b/src/Navigator.Extensions.Store/Entities/UniversalProfile.cs deleted file mode 100644 index bd3e83d..0000000 --- a/src/Navigator.Extensions.Store/Entities/UniversalProfile.cs +++ /dev/null @@ -1,36 +0,0 @@ -using Navigator.Entities; - -namespace Navigator.Extensions.Store.Entities; - -public class UniversalProfile -{ - protected UniversalProfile() - { - CreatedAt = DateTime.UtcNow; - LastUpdatedAt = DateTime.UtcNow; - } - - public Guid Id { get; set; } - public string Provider { get; set; } - public Guid Identification { get; set; } - public DateTime CreatedAt { get; set; } - public DateTime LastUpdatedAt { get; set; } -} - -public class UserProfile : UniversalProfile -{ - public User? Data { get; set; } - public Guid? DataId { get; set; } -} - -public class ChatProfile : UniversalProfile -{ - public Chat? Data { get; set; } - public Guid? DataId { get; set; } -} - -public class ConversationProfile : UniversalProfile -{ - public Conversation? Data { get; set; } - public Guid? DataId { get; set; } -} \ No newline at end of file diff --git a/src/Navigator.Extensions.Store/Entities/UniversalUser.cs b/src/Navigator.Extensions.Store/Entities/UniversalUser.cs index 1e51acc..d65f34c 100644 --- a/src/Navigator.Extensions.Store/Entities/UniversalUser.cs +++ b/src/Navigator.Extensions.Store/Entities/UniversalUser.cs @@ -6,15 +6,10 @@ public class UniversalUser : Navigator.Entities.User { public UniversalUser() { - Profiles = new List(); Chats = new List(); Conversations = new List(); FirstInteractionAt = DateTime.UtcNow; } - - // public new Guid Id { get; set; } - - public IList Profiles { get; set; } /// /// Chats related to the user. diff --git a/src/Navigator.Extensions.Store/Mappers/IProviderProfileMapper.cs b/src/Navigator.Extensions.Store/Mappers/IProviderProfileMapper.cs deleted file mode 100644 index 6b29b19..0000000 --- a/src/Navigator.Extensions.Store/Mappers/IProviderProfileMapper.cs +++ /dev/null @@ -1,11 +0,0 @@ -using Navigator.Entities; -using Navigator.Extensions.Store.Entities; - -namespace Navigator.Extensions.Store.Mappers; - -public interface IProviderProfileMapper -{ - TProfile? From(Conversation conversation); - - UniversalProfile? To(TProfile profile); -} \ No newline at end of file diff --git a/src/Navigator.Extensions.Store/UniversalStore.cs b/src/Navigator.Extensions.Store/UniversalStore.cs index d4a3fd9..e3d9ad7 100644 --- a/src/Navigator.Extensions.Store/UniversalStore.cs +++ b/src/Navigator.Extensions.Store/UniversalStore.cs @@ -1,17 +1,21 @@ +using Microsoft.AspNetCore.Components; using Microsoft.EntityFrameworkCore; using Navigator.Entities; using Navigator.Extensions.Store.Context; using Navigator.Extensions.Store.Entities; +using Navigator.Extensions.Store.Mappers; namespace Navigator.Extensions.Store; public class UniversalStore : IUniversalStore { private readonly NavigatorDbContext _dbContext; + private readonly IEnumerable _profileMappers; - public UniversalStore(NavigatorDbContext dbContext) + public UniversalStore(NavigatorDbContext dbContext, IEnumerable profileMappers) { _dbContext = dbContext; + _profileMappers = profileMappers; } #region Chat @@ -30,57 +34,8 @@ public UniversalStore(NavigatorDbContext dbContext) public async Task FindOrCreateConversation(Conversation conversation, string provider, CancellationToken cancellationToken = default) { - var universalConversation = await FindConversation(conversation, provider, cancellationToken); - - if (universalConversation is null) - { - var user = new UniversalUser - { - Id = Guid.NewGuid() - }; - - user.Profiles.Add(new UserProfile - { - Id = Guid.NewGuid(), - Provider = provider, - Identification = conversation.User.Id - }); - - var chat = new UniversalChat - { - Id = Guid.NewGuid() - }; - - chat.Profiles.Add(new ChatProfile - { - Id = Guid.NewGuid(), - Provider = provider, - Identification = conversation.Chat.Id, - }); - - await _dbContext.Users.AddAsync(user, cancellationToken); - await _dbContext.Chats.AddAsync(chat, cancellationToken); - - universalConversation = new UniversalConversation - { - Id = Guid.NewGuid(), - User = user, - Chat = chat, - }; - - universalConversation.Profiles.Add(new ConversationProfile - { - Id = conversation.Id, - Provider = provider, - Identification = Guid.NewGuid() - }); - - await _dbContext.Conversations.AddAsync(universalConversation, cancellationToken); - - await _dbContext.SaveChangesAsync(cancellationToken); - } - - return universalConversation; + return await FindConversation(conversation, provider, cancellationToken) + ?? await SaveConversation(conversation, provider, cancellationToken); } public async Task FindConversation(Conversation conversation, string provider, CancellationToken cancellationToken = default) @@ -88,7 +43,6 @@ public async Task FindOrCreateConversation(Conversation c return await _dbContext.Conversations .Include(e => e.User) .Include(e => e.Chat) - .Where(e => e.Profiles.Any(p => p.Provider == provider)) .Where(e => e.Chat.Profiles.Any(p => p.Provider == provider && p.Identification == conversation.Chat.Id)) .Where(e => e.User.Profiles.Any(p => p.Provider == provider && p.Identification == conversation.User.Id)) .FirstOrDefaultAsync(cancellationToken); @@ -105,6 +59,54 @@ public async Task FindOrCreateConversation(Conversation c .Where(e => e.Profiles.Any(p => p.Identification == user.Id)) .FirstOrDefaultAsync(cancellationToken); } - + #endregion + + protected async Task SaveConversation(Conversation conversation, string provider, CancellationToken cancellationToken = default) + { + var userProfileMapper = _profileMappers + .OfType() + .FirstOrDefault(mapper => mapper.Maps(conversation.User.GetType())); + + var user = new UniversalUser + { + Id = Guid.NewGuid() + }; + + user.Profiles.Add(userProfileMapper?.From(conversation) ?? throw new NavigationException("TODO")); + + + var chatProfileMapper = _profileMappers + .OfType() + .FirstOrDefault(mapper => mapper.Maps(conversation.Chat.GetType())); + + var chat = new UniversalChat + { + Id = Guid.NewGuid() + }; + + chat.Profiles.Add(chatProfileMapper?.From(conversation) ?? throw new NavigationException("TODO")); + + await _dbContext.Users.AddAsync(user, cancellationToken); + await _dbContext.Chats.AddAsync(chat, cancellationToken); + + var universalConversation = new UniversalConversation + { + Id = Guid.NewGuid(), + User = user, + Chat = chat, + }; + + var conversationProfileMapper = _profileMappers + .OfType() + .FirstOrDefault(mapper => mapper.Maps(conversation.Chat.GetType())); + + universalConversation.Profiles.Add(conversationProfileMapper?.From(conversation) ?? throw new NavigationException("TODO")); + + await _dbContext.Conversations.AddAsync(universalConversation, cancellationToken); + + await _dbContext.SaveChangesAsync(cancellationToken); + + return universalConversation; + } } \ No newline at end of file diff --git a/src/Navigator.Samples.Store/Actions/EchoActionHandler.cs b/src/Navigator.Samples.Store/Actions/EchoActionHandler.cs index 46d1280..9347649 100644 --- a/src/Navigator.Samples.Store/Actions/EchoActionHandler.cs +++ b/src/Navigator.Samples.Store/Actions/EchoActionHandler.cs @@ -6,7 +6,6 @@ using Navigator.Actions; using Navigator.Context; using Navigator.Extensions.Store; -using Navigator.Extensions.Store.Context; using Navigator.Providers.Telegram; using Telegram.Bot; @@ -14,10 +13,8 @@ namespace Navigator.Samples.Store.Actions; public class EchoActionHandler : ActionHandler { - private readonly NavigatorDbContext _dbContext; - public EchoActionHandler(INavigatorContextAccessor navigatorContextAccessor, NavigatorDbContext dbContext) : base(navigatorContextAccessor) + public EchoActionHandler(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) { - _dbContext = dbContext; } public override async Task Handle(EchoAction action, CancellationToken cancellationToken) diff --git a/src/Navigator/Entities/Bot.cs b/src/Navigator/Entities/Bot.cs index a4e1789..7fe0234 100644 --- a/src/Navigator/Entities/Bot.cs +++ b/src/Navigator/Entities/Bot.cs @@ -5,10 +5,18 @@ namespace Navigator.Entities; -public abstract class Bot : User +public abstract class Bot { protected Bot(string input) { Id = new Guid(SHA256.HashData(Encoding.UTF8.GetBytes(input)).Take(16).ToArray()); } + + /// + /// Id of the bot. + /// + /// Generally a deterministic Guid based on some kind of input. + /// + /// + public Guid Id { get; init; } } \ No newline at end of file From f28b5e0c3a3c8757c241ec82fe1a60d3140d416c Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sun, 3 Apr 2022 22:40:00 +0200 Subject: [PATCH 262/304] refactor: rename store entities --- .../NavigatorStoreTelegramExtension.cs | 3 + .../TelegramProviderChatProfileMapper.cs | 1 + ...legramProviderConversationProfileMapper.cs | 1 + .../TelegramProviderUserProfileMapper.cs | 1 + ...s => StoreConversationContextExtension.cs} | 18 +- .../ChatEntityTypeConfiguration.cs | 6 +- .../ConversationEntityTypeConfiguration.cs | 4 +- .../UserEntityTypeConfiguration.cs | 6 +- .../Context/NavigatorDbContext.cs | 22 +- .../Entities/{UniversalChat.cs => Chat.cs} | 12 +- ...iversalConversation.cs => Conversation.cs} | 10 +- .../Entities/{UniversalUser.cs => User.cs} | 12 +- .../IUniversalStore.cs | 23 +- .../NavigatorContextExtensions.cs | 12 +- ...vigatorExtensionConfigurationExtensions.cs | 5 +- .../UniversalStore.cs | 227 +++++++++--------- ...0211223144637_InitialMigration.Designer.cs | 30 +-- .../NavigatorDbContextModelSnapshot.cs | 30 +-- 18 files changed, 216 insertions(+), 207 deletions(-) rename src/Navigator.Extensions.Store/Bundled/{UniversalConversationContextExtension.cs => StoreConversationContextExtension.cs} (59%) rename src/Navigator.Extensions.Store/Entities/{UniversalChat.cs => Chat.cs} (51%) rename src/Navigator.Extensions.Store/Entities/{UniversalConversation.cs => Conversation.cs} (58%) rename src/Navigator.Extensions.Store/Entities/{UniversalUser.cs => User.cs} (53%) diff --git a/src/Navigator.Extensions.Store.Telegram/NavigatorStoreTelegramExtension.cs b/src/Navigator.Extensions.Store.Telegram/NavigatorStoreTelegramExtension.cs index edcd445..86111d2 100644 --- a/src/Navigator.Extensions.Store.Telegram/NavigatorStoreTelegramExtension.cs +++ b/src/Navigator.Extensions.Store.Telegram/NavigatorStoreTelegramExtension.cs @@ -8,6 +8,9 @@ using Navigator.Extensions.Store.Telegram.Profiles; using Navigator.Extensions.Store.Telegram.Profiles.Mappers; using Navigator.Providers.Telegram.Entities; +using Chat = Navigator.Entities.Chat; +using Conversation = Navigator.Entities.Conversation; +using User = Navigator.Entities.User; namespace Navigator.Extensions.Store.Telegram; diff --git a/src/Navigator.Extensions.Store.Telegram/Profiles/Mappers/TelegramProviderChatProfileMapper.cs b/src/Navigator.Extensions.Store.Telegram/Profiles/Mappers/TelegramProviderChatProfileMapper.cs index 4b86947..0a182f0 100644 --- a/src/Navigator.Extensions.Store.Telegram/Profiles/Mappers/TelegramProviderChatProfileMapper.cs +++ b/src/Navigator.Extensions.Store.Telegram/Profiles/Mappers/TelegramProviderChatProfileMapper.cs @@ -2,6 +2,7 @@ using Navigator.Extensions.Store.Entities; using Navigator.Extensions.Store.Mappers; using Navigator.Providers.Telegram.Entities; +using Conversation = Navigator.Entities.Conversation; namespace Navigator.Extensions.Store.Telegram.Profiles.Mappers; diff --git a/src/Navigator.Extensions.Store.Telegram/Profiles/Mappers/TelegramProviderConversationProfileMapper.cs b/src/Navigator.Extensions.Store.Telegram/Profiles/Mappers/TelegramProviderConversationProfileMapper.cs index a21cc59..0e80aff 100644 --- a/src/Navigator.Extensions.Store.Telegram/Profiles/Mappers/TelegramProviderConversationProfileMapper.cs +++ b/src/Navigator.Extensions.Store.Telegram/Profiles/Mappers/TelegramProviderConversationProfileMapper.cs @@ -2,6 +2,7 @@ using Navigator.Extensions.Store.Entities; using Navigator.Extensions.Store.Mappers; using Navigator.Providers.Telegram.Entities; +using Conversation = Navigator.Entities.Conversation; namespace Navigator.Extensions.Store.Telegram.Profiles.Mappers; diff --git a/src/Navigator.Extensions.Store.Telegram/Profiles/Mappers/TelegramProviderUserProfileMapper.cs b/src/Navigator.Extensions.Store.Telegram/Profiles/Mappers/TelegramProviderUserProfileMapper.cs index e79ab58..70b5ba3 100644 --- a/src/Navigator.Extensions.Store.Telegram/Profiles/Mappers/TelegramProviderUserProfileMapper.cs +++ b/src/Navigator.Extensions.Store.Telegram/Profiles/Mappers/TelegramProviderUserProfileMapper.cs @@ -2,6 +2,7 @@ using Navigator.Extensions.Store.Entities; using Navigator.Extensions.Store.Mappers; using Navigator.Providers.Telegram.Entities; +using Conversation = Navigator.Entities.Conversation; namespace Navigator.Extensions.Store.Telegram.Profiles.Mappers; diff --git a/src/Navigator.Extensions.Store/Bundled/UniversalConversationContextExtension.cs b/src/Navigator.Extensions.Store/Bundled/StoreConversationContextExtension.cs similarity index 59% rename from src/Navigator.Extensions.Store/Bundled/UniversalConversationContextExtension.cs rename to src/Navigator.Extensions.Store/Bundled/StoreConversationContextExtension.cs index c408114..2004dad 100644 --- a/src/Navigator.Extensions.Store/Bundled/UniversalConversationContextExtension.cs +++ b/src/Navigator.Extensions.Store/Bundled/StoreConversationContextExtension.cs @@ -1,18 +1,19 @@ using System.Text; using System.Text.Json; +using Microsoft.EntityFrameworkCore; using Navigator.Context; using Navigator.Context.Extensions; using Navigator.Extensions.Store.Context; namespace Navigator.Extensions.Store.Bundled; -internal class UniversalConversationContextExtension : INavigatorContextExtension +internal class StoreConversationContextExtension : INavigatorContextExtension { - public const string UniversalConversation = "_navigator.extensions.store.universal_conversation"; + public const string UniversalConversation = "_navigator.extensions.store.conversation"; private readonly NavigatorDbContext _dbContext; - public UniversalConversationContextExtension(NavigatorDbContext dbContext) + public StoreConversationContextExtension(NavigatorDbContext dbContext) { _dbContext = dbContext; } @@ -21,8 +22,15 @@ public async Task Extend(INavigatorContext navigatorContext, { var conversation = navigatorContext.Conversation; - var universalConversation = await _universalStore.FindOrCreateConversation(conversation, navigatorContext.Provider.Name); - + if (await _dbContext.Conversations.AnyAsync(e => e.Id == navigatorContext.Conversation.Id)) + { + return navigatorContext; + } + else + { + + } + return await Task.FromResult(navigatorContext); } diff --git a/src/Navigator.Extensions.Store/Context/Configuration/ChatEntityTypeConfiguration.cs b/src/Navigator.Extensions.Store/Context/Configuration/ChatEntityTypeConfiguration.cs index 17556d0..a9c571f 100644 --- a/src/Navigator.Extensions.Store/Context/Configuration/ChatEntityTypeConfiguration.cs +++ b/src/Navigator.Extensions.Store/Context/Configuration/ChatEntityTypeConfiguration.cs @@ -4,15 +4,15 @@ namespace Navigator.Extensions.Store.Context.Configuration; -public class ChatEntityTypeConfiguration : IEntityTypeConfiguration +public class ChatEntityTypeConfiguration : IEntityTypeConfiguration { - public void Configure(EntityTypeBuilder builder) + public void Configure(EntityTypeBuilder builder) { builder.HasKey(e => e.Id); builder.HasMany(e => e.Users) .WithMany(e => e.Chats) - .UsingEntity( + .UsingEntity( e => e.HasOne(e => e.User) .WithMany(e => e.Conversations), e=> e.HasOne(e => e.Chat) diff --git a/src/Navigator.Extensions.Store/Context/Configuration/ConversationEntityTypeConfiguration.cs b/src/Navigator.Extensions.Store/Context/Configuration/ConversationEntityTypeConfiguration.cs index 065a173..522ce5a 100644 --- a/src/Navigator.Extensions.Store/Context/Configuration/ConversationEntityTypeConfiguration.cs +++ b/src/Navigator.Extensions.Store/Context/Configuration/ConversationEntityTypeConfiguration.cs @@ -4,9 +4,9 @@ namespace Navigator.Extensions.Store.Context.Configuration; -public class ConversationEntityTypeConfiguration : IEntityTypeConfiguration +public class ConversationEntityTypeConfiguration : IEntityTypeConfiguration { - public void Configure(EntityTypeBuilder builder) + public void Configure(EntityTypeBuilder builder) { builder.Property(e => e.FirstInteractionAt) .IsRequired(); diff --git a/src/Navigator.Extensions.Store/Context/Configuration/UserEntityTypeConfiguration.cs b/src/Navigator.Extensions.Store/Context/Configuration/UserEntityTypeConfiguration.cs index 11f49d9..801563d 100644 --- a/src/Navigator.Extensions.Store/Context/Configuration/UserEntityTypeConfiguration.cs +++ b/src/Navigator.Extensions.Store/Context/Configuration/UserEntityTypeConfiguration.cs @@ -4,15 +4,15 @@ namespace Navigator.Extensions.Store.Context.Configuration; -public class UserEntityTypeConfiguration : IEntityTypeConfiguration +public class UserEntityTypeConfiguration : IEntityTypeConfiguration { - public void Configure(EntityTypeBuilder builder) + public void Configure(EntityTypeBuilder builder) { builder.HasKey(e => e.Id); builder.HasMany(e => e.Chats) .WithMany(e => e.Users) - .UsingEntity( + .UsingEntity( e => e.HasOne(e => e.Chat) .WithMany(e => e.Conversations), e=> e.HasOne(e => e.User) diff --git a/src/Navigator.Extensions.Store/Context/NavigatorDbContext.cs b/src/Navigator.Extensions.Store/Context/NavigatorDbContext.cs index d22e3ff..af79ab3 100644 --- a/src/Navigator.Extensions.Store/Context/NavigatorDbContext.cs +++ b/src/Navigator.Extensions.Store/Context/NavigatorDbContext.cs @@ -3,14 +3,17 @@ using Navigator.Extensions.Store.Context.Configuration; using Navigator.Extensions.Store.Context.Extension; using Navigator.Extensions.Store.Entities; +using Chat = Navigator.Extensions.Store.Entities.Chat; +using Conversation = Navigator.Extensions.Store.Entities.Conversation; +using User = Navigator.Extensions.Store.Entities.User; namespace Navigator.Extensions.Store.Context; public class NavigatorDbContext : DbContext { - public DbSet Users { get; set; } - public DbSet Chats { get; set; } - public DbSet Conversations { get; set; } + public DbSet Users { get; set; } + public DbSet Chats { get; set; } + public DbSet Conversations { get; set; } protected NavigatorDbContext() { @@ -36,19 +39,6 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) modelBuilder.ApplyConfiguration(new UserEntityTypeConfiguration()); modelBuilder.ApplyConfiguration(new ConversationEntityTypeConfiguration()); - modelBuilder.Entity(b => - { - b.HasKey(e => e.Id); - }); - modelBuilder.Entity(b => - { - b.HasKey(e => e.Id); - }); - modelBuilder.Entity(b => - { - b.HasKey(e => e.Id); - }); - foreach (var entityTypeConfiguration in _entityTypeConfigurations) { entityTypeConfiguration.Invoke(modelBuilder); diff --git a/src/Navigator.Extensions.Store/Entities/UniversalChat.cs b/src/Navigator.Extensions.Store/Entities/Chat.cs similarity index 51% rename from src/Navigator.Extensions.Store/Entities/UniversalChat.cs rename to src/Navigator.Extensions.Store/Entities/Chat.cs index 351b5a0..f22e72e 100644 --- a/src/Navigator.Extensions.Store/Entities/UniversalChat.cs +++ b/src/Navigator.Extensions.Store/Entities/Chat.cs @@ -1,20 +1,20 @@ namespace Navigator.Extensions.Store.Entities; -public class UniversalChat : Navigator.Entities.Chat +public class Chat : Navigator.Entities.Chat { - public UniversalChat() + public Chat() { - Users = new List(); - Conversations = new List(); + Users = new List(); + Conversations = new List(); FirstInteractionAt = DateTime.UtcNow; } /// /// Users related to the chat. /// - public ICollection Users { get; set; } + public ICollection Users { get; set; } - public ICollection Conversations { get; set; } + public ICollection Conversations { get; set; } /// /// Date of first interaction for this chat. diff --git a/src/Navigator.Extensions.Store/Entities/UniversalConversation.cs b/src/Navigator.Extensions.Store/Entities/Conversation.cs similarity index 58% rename from src/Navigator.Extensions.Store/Entities/UniversalConversation.cs rename to src/Navigator.Extensions.Store/Entities/Conversation.cs index 4739aef..7c79308 100644 --- a/src/Navigator.Extensions.Store/Entities/UniversalConversation.cs +++ b/src/Navigator.Extensions.Store/Entities/Conversation.cs @@ -2,22 +2,22 @@ namespace Navigator.Extensions.Store.Entities; -public class UniversalConversation : Navigator.Entities.Conversation +public class Conversation : Navigator.Entities.Conversation { - public UniversalConversation() + public Conversation() { FirstInteractionAt = DateTime.UtcNow; } - public UniversalConversation(User user, Chat chat) : base(user, chat) + public Conversation(Navigator.Entities.User user, Chat chat) : base(user, chat) { FirstInteractionAt = DateTime.UtcNow; } // public new Guid Id { get; set; } - public new UniversalChat Chat { get; set; } + public new Chat Chat { get; set; } - public new UniversalUser User { get; set; } + public new User User { get; set; } /// /// Date of first interaction for this chat. diff --git a/src/Navigator.Extensions.Store/Entities/UniversalUser.cs b/src/Navigator.Extensions.Store/Entities/User.cs similarity index 53% rename from src/Navigator.Extensions.Store/Entities/UniversalUser.cs rename to src/Navigator.Extensions.Store/Entities/User.cs index d65f34c..a8cb122 100644 --- a/src/Navigator.Extensions.Store/Entities/UniversalUser.cs +++ b/src/Navigator.Extensions.Store/Entities/User.cs @@ -2,21 +2,21 @@ namespace Navigator.Extensions.Store.Entities; -public class UniversalUser : Navigator.Entities.User +public class User : Navigator.Entities.User { - public UniversalUser() + public User() { - Chats = new List(); - Conversations = new List(); + Chats = new List(); + Conversations = new List(); FirstInteractionAt = DateTime.UtcNow; } /// /// Chats related to the user. /// - public IList Chats { get; set; } + public IList Chats { get; set; } - public ICollection Conversations { get; set; } + public ICollection Conversations { get; set; } /// /// Date of first interaction for this chat. diff --git a/src/Navigator.Extensions.Store/IUniversalStore.cs b/src/Navigator.Extensions.Store/IUniversalStore.cs index 9c13109..d1b97c0 100644 --- a/src/Navigator.Extensions.Store/IUniversalStore.cs +++ b/src/Navigator.Extensions.Store/IUniversalStore.cs @@ -1,5 +1,8 @@ using Navigator.Entities; using Navigator.Extensions.Store.Entities; +using Chat = Navigator.Extensions.Store.Entities.Chat; +using Conversation = Navigator.Extensions.Store.Entities.Conversation; +using User = Navigator.Extensions.Store.Entities.User; namespace Navigator.Extensions.Store; @@ -7,35 +10,35 @@ public interface IUniversalStore { #region Chat - Task FindChat(Chat chat, string provider, CancellationToken cancellationToken = default); + Task FindChat(Navigator.Entities.Chat chat, string provider, CancellationToken cancellationToken = default); #endregion #region Conversation - Task FindOrCreateConversation(Conversation conversation, string provider, + Task FindOrCreateConversation(Navigator.Entities.Conversation conversation, string provider, CancellationToken cancellationToken = default); - Task FindConversation(Conversation conversation, string provider, + Task FindConversation(Navigator.Entities.Conversation conversation, string provider, CancellationToken cancellationToken = default); #endregion #region User - Task FindUser(User user, string provider, CancellationToken cancellationToken = default); + Task FindUser(Navigator.Entities.User user, string provider, CancellationToken cancellationToken = default); #endregion // #region Profile // - // Task AddUserProfile(UniversalUser user, string provider, Guid identification, CancellationToken cancellationToken = default, bool? saveChanges = true); - // Task TryAddUserProfile(UniversalUser user, string provider, Guid identification, CancellationToken cancellationToken = default, bool? saveChanges = true); + // Task AddUserProfile(User user, string provider, Guid identification, CancellationToken cancellationToken = default, bool? saveChanges = true); + // Task TryAddUserProfile(User user, string provider, Guid identification, CancellationToken cancellationToken = default, bool? saveChanges = true); // - // Task AddChatProfile(UniversalChat chat, string provider, Guid identification, CancellationToken cancellationToken = default, bool? saveChanges = true); - // Task TryAddChatProfile(UniversalChat chat, string provider, Guid identification, CancellationToken cancellationToken = default, bool? saveChanges = true); + // Task AddChatProfile(Chat chat, string provider, Guid identification, CancellationToken cancellationToken = default, bool? saveChanges = true); + // Task TryAddChatProfile(Chat chat, string provider, Guid identification, CancellationToken cancellationToken = default, bool? saveChanges = true); // - // Task AddConversationProfile(UniversalConversation conversation, string provider, Guid identification, CancellationToken cancellationToken = default, bool? saveChanges = true); - // Task TryAddConversationProfile(UniversalConversation conversation, string provider, Guid identification, CancellationToken cancellationToken = default, bool? saveChanges = true); + // Task AddConversationProfile(Conversation conversation, string provider, Guid identification, CancellationToken cancellationToken = default, bool? saveChanges = true); + // Task TryAddConversationProfile(Conversation conversation, string provider, Guid identification, CancellationToken cancellationToken = default, bool? saveChanges = true); // // #endregion } \ No newline at end of file diff --git a/src/Navigator.Extensions.Store/NavigatorContextExtensions.cs b/src/Navigator.Extensions.Store/NavigatorContextExtensions.cs index fd4e83a..45290b2 100644 --- a/src/Navigator.Extensions.Store/NavigatorContextExtensions.cs +++ b/src/Navigator.Extensions.Store/NavigatorContextExtensions.cs @@ -33,12 +33,12 @@ public static IUniversalStore GetStore(this INavigatorContext context) #region Chat - public static async Task GetUniversalChat(this INavigatorContext context, CancellationToken cancellationToken = default) + public static async Task GetUniversalChat(this INavigatorContext context, CancellationToken cancellationToken = default) { return await GetUniversalChatOrDefault(context) ?? throw new InvalidOperationException(); } - public static async Task GetUniversalChatOrDefault(this INavigatorContext context, CancellationToken cancellationToken = default) + public static async Task GetUniversalChatOrDefault(this INavigatorContext context, CancellationToken cancellationToken = default) { return await context.GetStore().FindChat(context.Conversation.Chat, context.Provider.Name, cancellationToken); } @@ -47,12 +47,12 @@ public static async Task GetUniversalChat(this INavigatorContext #region Conversation - public static async Task GetUniversalConversation(this INavigatorContext context, CancellationToken cancellationToken = default) + public static async Task GetUniversalConversation(this INavigatorContext context, CancellationToken cancellationToken = default) { return await GetUniversalConversationOrDefault(context, cancellationToken) ?? throw new InvalidOperationException(); } - public static async Task GetUniversalConversationOrDefault(this INavigatorContext context, CancellationToken cancellationToken = default) + public static async Task GetUniversalConversationOrDefault(this INavigatorContext context, CancellationToken cancellationToken = default) { return await context.GetStore().FindConversation(context.Conversation, context.Provider.Name, cancellationToken); } @@ -61,12 +61,12 @@ public static async Task GetUniversalConversation(this IN #region User - public static async Task GetUniversalUser(this INavigatorContext context, CancellationToken cancellationToken = default) + public static async Task GetUniversalUser(this INavigatorContext context, CancellationToken cancellationToken = default) { return await GetUniversalUserOrDefault(context, cancellationToken) ?? throw new InvalidOperationException(); } - public static async Task GetUniversalUserOrDefault(this INavigatorContext context, CancellationToken cancellationToken = default) + public static async Task GetUniversalUserOrDefault(this INavigatorContext context, CancellationToken cancellationToken = default) { return await context.GetStore().FindUser(context.Conversation.User, context.Provider.Name, cancellationToken); } diff --git a/src/Navigator.Extensions.Store/NavigatorExtensionConfigurationExtensions.cs b/src/Navigator.Extensions.Store/NavigatorExtensionConfigurationExtensions.cs index d7a56c8..1f97509 100644 --- a/src/Navigator.Extensions.Store/NavigatorExtensionConfigurationExtensions.cs +++ b/src/Navigator.Extensions.Store/NavigatorExtensionConfigurationExtensions.cs @@ -23,10 +23,9 @@ public static NavigatorConfiguration Store(this NavigatorExtensionConfiguration services => { services.AddDbContext(dbContextOptions); - services.AddTransient(); - + services.AddScoped(); - services.AddScoped(); + services.AddScoped(); foreach (var extension in temporal.Options.Extensions.OfType()) { diff --git a/src/Navigator.Extensions.Store/UniversalStore.cs b/src/Navigator.Extensions.Store/UniversalStore.cs index e3d9ad7..80f6d43 100644 --- a/src/Navigator.Extensions.Store/UniversalStore.cs +++ b/src/Navigator.Extensions.Store/UniversalStore.cs @@ -1,112 +1,115 @@ -using Microsoft.AspNetCore.Components; -using Microsoft.EntityFrameworkCore; -using Navigator.Entities; -using Navigator.Extensions.Store.Context; -using Navigator.Extensions.Store.Entities; -using Navigator.Extensions.Store.Mappers; - -namespace Navigator.Extensions.Store; - -public class UniversalStore : IUniversalStore -{ - private readonly NavigatorDbContext _dbContext; - private readonly IEnumerable _profileMappers; - - public UniversalStore(NavigatorDbContext dbContext, IEnumerable profileMappers) - { - _dbContext = dbContext; - _profileMappers = profileMappers; - } - - #region Chat - - public async Task FindChat(Chat chat, string provider, CancellationToken cancellationToken = default) - { - return await _dbContext.Chats - .Where(e => e.Profiles.Any(p => p.Provider == provider)) - .Where(e => e.Profiles.Any(p => p.Identification == chat.Id)) - .FirstOrDefaultAsync(cancellationToken); - } - - #endregion - - #region Conversation - - public async Task FindOrCreateConversation(Conversation conversation, string provider, CancellationToken cancellationToken = default) - { - return await FindConversation(conversation, provider, cancellationToken) - ?? await SaveConversation(conversation, provider, cancellationToken); - } - - public async Task FindConversation(Conversation conversation, string provider, CancellationToken cancellationToken = default) - { - return await _dbContext.Conversations - .Include(e => e.User) - .Include(e => e.Chat) - .Where(e => e.Chat.Profiles.Any(p => p.Provider == provider && p.Identification == conversation.Chat.Id)) - .Where(e => e.User.Profiles.Any(p => p.Provider == provider && p.Identification == conversation.User.Id)) - .FirstOrDefaultAsync(cancellationToken); - } - - #endregion - - #region User - - public async Task FindUser(User user, string provider, CancellationToken cancellationToken = default) - { - return await _dbContext.Users - .Where(e => e.Profiles.Any(p => p.Provider == provider)) - .Where(e => e.Profiles.Any(p => p.Identification == user.Id)) - .FirstOrDefaultAsync(cancellationToken); - } - - #endregion - - protected async Task SaveConversation(Conversation conversation, string provider, CancellationToken cancellationToken = default) - { - var userProfileMapper = _profileMappers - .OfType() - .FirstOrDefault(mapper => mapper.Maps(conversation.User.GetType())); - - var user = new UniversalUser - { - Id = Guid.NewGuid() - }; - - user.Profiles.Add(userProfileMapper?.From(conversation) ?? throw new NavigationException("TODO")); - - - var chatProfileMapper = _profileMappers - .OfType() - .FirstOrDefault(mapper => mapper.Maps(conversation.Chat.GetType())); - - var chat = new UniversalChat - { - Id = Guid.NewGuid() - }; - - chat.Profiles.Add(chatProfileMapper?.From(conversation) ?? throw new NavigationException("TODO")); - - await _dbContext.Users.AddAsync(user, cancellationToken); - await _dbContext.Chats.AddAsync(chat, cancellationToken); - - var universalConversation = new UniversalConversation - { - Id = Guid.NewGuid(), - User = user, - Chat = chat, - }; - - var conversationProfileMapper = _profileMappers - .OfType() - .FirstOrDefault(mapper => mapper.Maps(conversation.Chat.GetType())); - - universalConversation.Profiles.Add(conversationProfileMapper?.From(conversation) ?? throw new NavigationException("TODO")); - - await _dbContext.Conversations.AddAsync(universalConversation, cancellationToken); - - await _dbContext.SaveChangesAsync(cancellationToken); - - return universalConversation; - } -} \ No newline at end of file +// using Microsoft.AspNetCore.Components; +// using Microsoft.EntityFrameworkCore; +// using Navigator.Entities; +// using Navigator.Extensions.Store.Context; +// using Navigator.Extensions.Store.Entities; +// using Navigator.Extensions.Store.Mappers; +// using Chat = Navigator.Extensions.Store.Entities.Chat; +// using Conversation = Navigator.Extensions.Store.Entities.Conversation; +// using User = Navigator.Extensions.Store.Entities.User; +// +// namespace Navigator.Extensions.Store; +// +// public class UniversalStore : IUniversalStore +// { +// private readonly NavigatorDbContext _dbContext; +// private readonly IEnumerable _profileMappers; +// +// public UniversalStore(NavigatorDbContext dbContext, IEnumerable profileMappers) +// { +// _dbContext = dbContext; +// _profileMappers = profileMappers; +// } +// +// #region Chat +// +// public async Task FindChat(Navigator.Entities.Chat chat, string provider, CancellationToken cancellationToken = default) +// { +// return await _dbContext.Chats +// .Where(e => e.Profiles.Any(p => p.Provider == provider)) +// .Where(e => e.Profiles.Any(p => p.Identification == chat.Id)) +// .FirstOrDefaultAsync(cancellationToken); +// } +// +// #endregion +// +// #region Conversation +// +// public async Task FindOrCreateConversation(Navigator.Entities.Conversation conversation, string provider, CancellationToken cancellationToken = default) +// { +// return await FindConversation(conversation, provider, cancellationToken) +// ?? await SaveConversation(conversation, provider, cancellationToken); +// } +// +// public async Task FindConversation(Navigator.Entities.Conversation conversation, string provider, CancellationToken cancellationToken = default) +// { +// return await _dbContext.Conversations +// .Include(e => e.User) +// .Include(e => e.Chat) +// .Where(e => e.Chat.Profiles.Any(p => p.Provider == provider && p.Identification == conversation.Chat.Id)) +// .Where(e => e.User.Profiles.Any(p => p.Provider == provider && p.Identification == conversation.User.Id)) +// .FirstOrDefaultAsync(cancellationToken); +// } +// +// #endregion +// +// #region User +// +// public async Task FindUser(Navigator.Entities.User user, string provider, CancellationToken cancellationToken = default) +// { +// return await _dbContext.Users +// .Where(e => e.Profiles.Any(p => p.Provider == provider)) +// .Where(e => e.Profiles.Any(p => p.Identification == user.Id)) +// .FirstOrDefaultAsync(cancellationToken); +// } +// +// #endregion +// +// protected async Task SaveConversation(Navigator.Entities.Conversation conversation, string provider, CancellationToken cancellationToken = default) +// { +// var userProfileMapper = _profileMappers +// .OfType() +// .FirstOrDefault(mapper => mapper.Maps(conversation.User.GetType())); +// +// var user = new User +// { +// Id = Guid.NewGuid() +// }; +// +// user.Profiles.Add(userProfileMapper?.From(conversation) ?? throw new NavigationException("TODO")); +// +// +// var chatProfileMapper = _profileMappers +// .OfType() +// .FirstOrDefault(mapper => mapper.Maps(conversation.Chat.GetType())); +// +// var chat = new Chat +// { +// Id = Guid.NewGuid() +// }; +// +// chat.Profiles.Add(chatProfileMapper?.From(conversation) ?? throw new NavigationException("TODO")); +// +// await _dbContext.Users.AddAsync(user, cancellationToken); +// await _dbContext.Chats.AddAsync(chat, cancellationToken); +// +// var universalConversation = new Conversation +// { +// Id = Guid.NewGuid(), +// User = user, +// Chat = chat, +// }; +// +// var conversationProfileMapper = _profileMappers +// .OfType() +// .FirstOrDefault(mapper => mapper.Maps(conversation.Chat.GetType())); +// +// universalConversation.Profiles.Add(conversationProfileMapper?.From(conversation) ?? throw new NavigationException("TODO")); +// +// await _dbContext.Conversations.AddAsync(universalConversation, cancellationToken); +// +// await _dbContext.SaveChangesAsync(cancellationToken); +// +// return universalConversation; +// } +// } \ No newline at end of file diff --git a/src/Navigator.Samples.Store/Migrations/20211223144637_InitialMigration.Designer.cs b/src/Navigator.Samples.Store/Migrations/20211223144637_InitialMigration.Designer.cs index fc73c84..433ee4e 100644 --- a/src/Navigator.Samples.Store/Migrations/20211223144637_InitialMigration.Designer.cs +++ b/src/Navigator.Samples.Store/Migrations/20211223144637_InitialMigration.Designer.cs @@ -137,17 +137,17 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) b.HasDiscriminator().HasValue("ConversationProfile"); }); - modelBuilder.Entity("Navigator.Extensions.Store.Entities.UniversalChat", b => + modelBuilder.Entity("Navigator.Extensions.Store.Entities.Chat", b => { b.HasBaseType("Navigator.Entities.Chat"); b.Property("FirstInteractionAt") .HasColumnType("TEXT"); - b.HasDiscriminator().HasValue("UniversalChat"); + b.HasDiscriminator().HasValue("Chat"); }); - modelBuilder.Entity("Navigator.Extensions.Store.Entities.UniversalConversation", b => + modelBuilder.Entity("Navigator.Extensions.Store.Entities.Conversation", b => { b.HasBaseType("Navigator.Entities.Conversation"); @@ -164,17 +164,17 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) b.HasIndex("UserId"); - b.HasDiscriminator().HasValue("UniversalConversation"); + b.HasDiscriminator().HasValue("Conversation"); }); - modelBuilder.Entity("Navigator.Extensions.Store.Entities.UniversalUser", b => + modelBuilder.Entity("Navigator.Extensions.Store.Entities.User", b => { b.HasBaseType("Navigator.Entities.User"); b.Property("FirstInteractionAt") .HasColumnType("TEXT"); - b.HasDiscriminator().HasValue("UniversalUser"); + b.HasDiscriminator().HasValue("User"); }); modelBuilder.Entity("Navigator.Extensions.Store.Entities.UserProfile", b => @@ -278,7 +278,7 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) .WithOne() .HasForeignKey("Navigator.Extensions.Store.Entities.ChatProfile", "DataId"); - b.HasOne("Navigator.Extensions.Store.Entities.UniversalChat", null) + b.HasOne("Navigator.Extensions.Store.Entities.Chat", null) .WithMany("Profiles") .HasForeignKey("UniversalChatId"); @@ -291,22 +291,22 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) .WithOne() .HasForeignKey("Navigator.Extensions.Store.Entities.ConversationProfile", "DataId"); - b.HasOne("Navigator.Extensions.Store.Entities.UniversalConversation", null) + b.HasOne("Navigator.Extensions.Store.Entities.Conversation", null) .WithMany("Profiles") .HasForeignKey("UniversalConversationId"); b.Navigation("Data"); }); - modelBuilder.Entity("Navigator.Extensions.Store.Entities.UniversalConversation", b => + modelBuilder.Entity("Navigator.Extensions.Store.Entities.Conversation", b => { - b.HasOne("Navigator.Extensions.Store.Entities.UniversalChat", "Chat") + b.HasOne("Navigator.Extensions.Store.Entities.Chat", "Chat") .WithMany("Conversations") .HasForeignKey("ChatId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); - b.HasOne("Navigator.Extensions.Store.Entities.UniversalUser", "User") + b.HasOne("Navigator.Extensions.Store.Entities.User", "User") .WithMany("Conversations") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) @@ -323,7 +323,7 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) .WithOne() .HasForeignKey("Navigator.Extensions.Store.Entities.UserProfile", "DataId"); - b.HasOne("Navigator.Extensions.Store.Entities.UniversalUser", null) + b.HasOne("Navigator.Extensions.Store.Entities.User", null) .WithMany("Profiles") .HasForeignKey("UniversalUserId"); @@ -349,19 +349,19 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) b.Navigation("User"); }); - modelBuilder.Entity("Navigator.Extensions.Store.Entities.UniversalChat", b => + modelBuilder.Entity("Navigator.Extensions.Store.Entities.Chat", b => { b.Navigation("Conversations"); b.Navigation("Profiles"); }); - modelBuilder.Entity("Navigator.Extensions.Store.Entities.UniversalConversation", b => + modelBuilder.Entity("Navigator.Extensions.Store.Entities.Conversation", b => { b.Navigation("Profiles"); }); - modelBuilder.Entity("Navigator.Extensions.Store.Entities.UniversalUser", b => + modelBuilder.Entity("Navigator.Extensions.Store.Entities.User", b => { b.Navigation("Conversations"); diff --git a/src/Navigator.Samples.Store/Migrations/NavigatorDbContextModelSnapshot.cs b/src/Navigator.Samples.Store/Migrations/NavigatorDbContextModelSnapshot.cs index 58ce572..3903e92 100644 --- a/src/Navigator.Samples.Store/Migrations/NavigatorDbContextModelSnapshot.cs +++ b/src/Navigator.Samples.Store/Migrations/NavigatorDbContextModelSnapshot.cs @@ -135,17 +135,17 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.HasDiscriminator().HasValue("ConversationProfile"); }); - modelBuilder.Entity("Navigator.Extensions.Store.Entities.UniversalChat", b => + modelBuilder.Entity("Navigator.Extensions.Store.Entities.Chat", b => { b.HasBaseType("Navigator.Entities.Chat"); b.Property("FirstInteractionAt") .HasColumnType("TEXT"); - b.HasDiscriminator().HasValue("UniversalChat"); + b.HasDiscriminator().HasValue("Chat"); }); - modelBuilder.Entity("Navigator.Extensions.Store.Entities.UniversalConversation", b => + modelBuilder.Entity("Navigator.Extensions.Store.Entities.Conversation", b => { b.HasBaseType("Navigator.Entities.Conversation"); @@ -162,17 +162,17 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.HasIndex("UserId"); - b.HasDiscriminator().HasValue("UniversalConversation"); + b.HasDiscriminator().HasValue("Conversation"); }); - modelBuilder.Entity("Navigator.Extensions.Store.Entities.UniversalUser", b => + modelBuilder.Entity("Navigator.Extensions.Store.Entities.User", b => { b.HasBaseType("Navigator.Entities.User"); b.Property("FirstInteractionAt") .HasColumnType("TEXT"); - b.HasDiscriminator().HasValue("UniversalUser"); + b.HasDiscriminator().HasValue("User"); }); modelBuilder.Entity("Navigator.Extensions.Store.Entities.UserProfile", b => @@ -276,7 +276,7 @@ protected override void BuildModel(ModelBuilder modelBuilder) .WithOne() .HasForeignKey("Navigator.Extensions.Store.Entities.ChatProfile", "DataId"); - b.HasOne("Navigator.Extensions.Store.Entities.UniversalChat", null) + b.HasOne("Navigator.Extensions.Store.Entities.Chat", null) .WithMany("Profiles") .HasForeignKey("UniversalChatId"); @@ -289,22 +289,22 @@ protected override void BuildModel(ModelBuilder modelBuilder) .WithOne() .HasForeignKey("Navigator.Extensions.Store.Entities.ConversationProfile", "DataId"); - b.HasOne("Navigator.Extensions.Store.Entities.UniversalConversation", null) + b.HasOne("Navigator.Extensions.Store.Entities.Conversation", null) .WithMany("Profiles") .HasForeignKey("UniversalConversationId"); b.Navigation("Data"); }); - modelBuilder.Entity("Navigator.Extensions.Store.Entities.UniversalConversation", b => + modelBuilder.Entity("Navigator.Extensions.Store.Entities.Conversation", b => { - b.HasOne("Navigator.Extensions.Store.Entities.UniversalChat", "Chat") + b.HasOne("Navigator.Extensions.Store.Entities.Chat", "Chat") .WithMany("Conversations") .HasForeignKey("ChatId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); - b.HasOne("Navigator.Extensions.Store.Entities.UniversalUser", "User") + b.HasOne("Navigator.Extensions.Store.Entities.User", "User") .WithMany("Conversations") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) @@ -321,7 +321,7 @@ protected override void BuildModel(ModelBuilder modelBuilder) .WithOne() .HasForeignKey("Navigator.Extensions.Store.Entities.UserProfile", "DataId"); - b.HasOne("Navigator.Extensions.Store.Entities.UniversalUser", null) + b.HasOne("Navigator.Extensions.Store.Entities.User", null) .WithMany("Profiles") .HasForeignKey("UniversalUserId"); @@ -347,19 +347,19 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.Navigation("User"); }); - modelBuilder.Entity("Navigator.Extensions.Store.Entities.UniversalChat", b => + modelBuilder.Entity("Navigator.Extensions.Store.Entities.Chat", b => { b.Navigation("Conversations"); b.Navigation("Profiles"); }); - modelBuilder.Entity("Navigator.Extensions.Store.Entities.UniversalConversation", b => + modelBuilder.Entity("Navigator.Extensions.Store.Entities.Conversation", b => { b.Navigation("Profiles"); }); - modelBuilder.Entity("Navigator.Extensions.Store.Entities.UniversalUser", b => + modelBuilder.Entity("Navigator.Extensions.Store.Entities.User", b => { b.Navigation("Conversations"); From 8d16bd7ee97fde3ba179b06bb297b28932a906c3 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sun, 3 Apr 2022 22:53:37 +0200 Subject: [PATCH 263/304] fix: correct comment on TelegramChat.ExternalIdentifier --- src/Navigator.Providers.Telegram/Entities/TelegramChat.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Navigator.Providers.Telegram/Entities/TelegramChat.cs b/src/Navigator.Providers.Telegram/Entities/TelegramChat.cs index 210d7dd..18948d6 100644 --- a/src/Navigator.Providers.Telegram/Entities/TelegramChat.cs +++ b/src/Navigator.Providers.Telegram/Entities/TelegramChat.cs @@ -11,7 +11,7 @@ public TelegramChat(long externalIdentifier) : base($"{nameof(TelegramChat)}.{ex } /// - /// Telegram identifier for the user. + /// Telegram identifier for the chat. /// public long ExternalIdentifier { get; init; } From 60cd0ad63b56e3d5886948088d6cb8aa2f06814f Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sun, 3 Apr 2022 23:13:54 +0200 Subject: [PATCH 264/304] feat: add data property to store entities --- src/Navigator.Extensions.Store/Entities/Chat.cs | 3 +++ src/Navigator.Extensions.Store/Entities/Conversation.cs | 6 +++++- src/Navigator.Extensions.Store/Entities/User.cs | 3 +++ 3 files changed, 11 insertions(+), 1 deletion(-) diff --git a/src/Navigator.Extensions.Store/Entities/Chat.cs b/src/Navigator.Extensions.Store/Entities/Chat.cs index f22e72e..7c1fd57 100644 --- a/src/Navigator.Extensions.Store/Entities/Chat.cs +++ b/src/Navigator.Extensions.Store/Entities/Chat.cs @@ -6,6 +6,7 @@ public Chat() { Users = new List(); Conversations = new List(); + Data = new Dictionary(); FirstInteractionAt = DateTime.UtcNow; } @@ -16,6 +17,8 @@ public Chat() public ICollection Conversations { get; set; } + public IDictionary Data { get; set; } + /// /// Date of first interaction for this chat. /// diff --git a/src/Navigator.Extensions.Store/Entities/Conversation.cs b/src/Navigator.Extensions.Store/Entities/Conversation.cs index 7c79308..0f5dd4f 100644 --- a/src/Navigator.Extensions.Store/Entities/Conversation.cs +++ b/src/Navigator.Extensions.Store/Entities/Conversation.cs @@ -6,10 +6,12 @@ public class Conversation : Navigator.Entities.Conversation { public Conversation() { + Data = new Dictionary(); FirstInteractionAt = DateTime.UtcNow; } - public Conversation(Navigator.Entities.User user, Chat chat) : base(user, chat) + public Conversation(User user, Chat chat) : base(user, chat) { + Data = new Dictionary(); FirstInteractionAt = DateTime.UtcNow; } @@ -18,6 +20,8 @@ public Conversation(Navigator.Entities.User user, Chat chat) : base(user, chat) public new Chat Chat { get; set; } public new User User { get; set; } + + public IDictionary Data { get; set; } /// /// Date of first interaction for this chat. diff --git a/src/Navigator.Extensions.Store/Entities/User.cs b/src/Navigator.Extensions.Store/Entities/User.cs index a8cb122..c10a3a4 100644 --- a/src/Navigator.Extensions.Store/Entities/User.cs +++ b/src/Navigator.Extensions.Store/Entities/User.cs @@ -8,6 +8,7 @@ public User() { Chats = new List(); Conversations = new List(); + Data = new Dictionary(); FirstInteractionAt = DateTime.UtcNow; } @@ -17,6 +18,8 @@ public User() public IList Chats { get; set; } public ICollection Conversations { get; set; } + + public IDictionary Data { get; set; } /// /// Date of first interaction for this chat. From 5192a906346c9487a01d08ebb08aa38b3463fbe8 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sun, 3 Apr 2022 23:14:07 +0200 Subject: [PATCH 265/304] feat: create data extractor interface --- .../Extractors/IDataExtractor.cs | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 src/Navigator.Extensions.Store/Extractors/IDataExtractor.cs diff --git a/src/Navigator.Extensions.Store/Extractors/IDataExtractor.cs b/src/Navigator.Extensions.Store/Extractors/IDataExtractor.cs new file mode 100644 index 0000000..3b6d346 --- /dev/null +++ b/src/Navigator.Extensions.Store/Extractors/IDataExtractor.cs @@ -0,0 +1,9 @@ +using Navigator.Entities; + +namespace Navigator.Extensions.Store.Extractors; + +public interface IDataExtractor +{ + Dictionary From(Conversation source); + public bool Maps(Type type); +} \ No newline at end of file From 9f1893b1bc81b93ddfbed0c0ee725c06aa5575f9 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sun, 3 Apr 2022 23:21:03 +0200 Subject: [PATCH 266/304] refactor: recreate profile mappers as data extractors --- .../Extractors/TelegramChatDataExtractor.cs | 30 +++++++++++++ .../TelegramConversationDataExtractor.cs | 20 +++++++++ .../Extractors/TelegramUserDataExtractor.cs | 42 +++++++++++++++++++ .../NavigatorStoreTelegramExtension.cs | 30 +++---------- .../TelegramProviderChatProfileMapper.cs | 36 ---------------- ...legramProviderConversationProfileMapper.cs | 36 ---------------- .../TelegramProviderUserProfileMapper.cs | 36 ---------------- .../Profiles/TelegramChatProfile.cs | 9 ---- .../Profiles/TelegramConversationProfile.cs | 9 ---- .../Profiles/TelegramUserProfile.cs | 9 ---- 10 files changed, 97 insertions(+), 160 deletions(-) create mode 100644 src/Navigator.Extensions.Store.Telegram/Extractors/TelegramChatDataExtractor.cs create mode 100644 src/Navigator.Extensions.Store.Telegram/Extractors/TelegramConversationDataExtractor.cs create mode 100644 src/Navigator.Extensions.Store.Telegram/Extractors/TelegramUserDataExtractor.cs delete mode 100644 src/Navigator.Extensions.Store.Telegram/Profiles/Mappers/TelegramProviderChatProfileMapper.cs delete mode 100644 src/Navigator.Extensions.Store.Telegram/Profiles/Mappers/TelegramProviderConversationProfileMapper.cs delete mode 100644 src/Navigator.Extensions.Store.Telegram/Profiles/Mappers/TelegramProviderUserProfileMapper.cs delete mode 100644 src/Navigator.Extensions.Store.Telegram/Profiles/TelegramChatProfile.cs delete mode 100644 src/Navigator.Extensions.Store.Telegram/Profiles/TelegramConversationProfile.cs delete mode 100644 src/Navigator.Extensions.Store.Telegram/Profiles/TelegramUserProfile.cs diff --git a/src/Navigator.Extensions.Store.Telegram/Extractors/TelegramChatDataExtractor.cs b/src/Navigator.Extensions.Store.Telegram/Extractors/TelegramChatDataExtractor.cs new file mode 100644 index 0000000..da60ac3 --- /dev/null +++ b/src/Navigator.Extensions.Store.Telegram/Extractors/TelegramChatDataExtractor.cs @@ -0,0 +1,30 @@ +using Navigator.Entities; +using Navigator.Extensions.Store.Extractors; +using Navigator.Providers.Telegram.Entities; + +namespace Navigator.Extensions.Store.Telegram.Extractors; + +public class TelegramChatDataExtractor : IDataExtractor +{ + public Dictionary From(Conversation source) + { + var dict = new Dictionary(); + + if (source.Chat is TelegramChat chat) + { + dict.Add($"navigator.telegram.{nameof(TelegramChat.ExternalIdentifier)}", chat.ExternalIdentifier.ToString()); + + if (chat.Title is not null) + { + dict.Add($"navigator.telegram.{nameof(TelegramChat.Title)}", chat.Title); + } + } + + return dict; + } + + public bool Maps(Type type) + { + return type == typeof(TelegramChat); + } +} \ No newline at end of file diff --git a/src/Navigator.Extensions.Store.Telegram/Extractors/TelegramConversationDataExtractor.cs b/src/Navigator.Extensions.Store.Telegram/Extractors/TelegramConversationDataExtractor.cs new file mode 100644 index 0000000..cc301c1 --- /dev/null +++ b/src/Navigator.Extensions.Store.Telegram/Extractors/TelegramConversationDataExtractor.cs @@ -0,0 +1,20 @@ +using Navigator.Entities; +using Navigator.Extensions.Store.Extractors; +using Navigator.Providers.Telegram.Entities; + +namespace Navigator.Extensions.Store.Telegram.Extractors; + +public class TelegramConversationDataExtractor : IDataExtractor +{ + public Dictionary From(Conversation source) + { + var dict = new Dictionary(); + + return dict; + } + + public bool Maps(Type type) + { + return type == typeof(TelegramConversation); + } +} \ No newline at end of file diff --git a/src/Navigator.Extensions.Store.Telegram/Extractors/TelegramUserDataExtractor.cs b/src/Navigator.Extensions.Store.Telegram/Extractors/TelegramUserDataExtractor.cs new file mode 100644 index 0000000..b1ad08b --- /dev/null +++ b/src/Navigator.Extensions.Store.Telegram/Extractors/TelegramUserDataExtractor.cs @@ -0,0 +1,42 @@ +using Navigator.Entities; +using Navigator.Extensions.Store.Extractors; +using Navigator.Providers.Telegram.Entities; + +namespace Navigator.Extensions.Store.Telegram.Extractors; + +public class TelegramUserDataExtractor : IDataExtractor +{ + public Dictionary From(Conversation source) + { + var dict = new Dictionary(); + + if (source.User is TelegramUser user) + { + dict.Add($"navigator.telegram.{nameof(TelegramUser.ExternalIdentifier)}", user.ExternalIdentifier.ToString()); + + if (user.Username is not null) + { + dict.Add($"navigator.telegram.{nameof(TelegramUser.Username)}", user.Username); + } + + dict.Add($"navigator.telegram.{nameof(TelegramUser.FirstName)}", user.FirstName); + + if (user.LastName is not null) + { + dict.Add($"navigator.telegram.{nameof(TelegramUser.LastName)}", user.LastName); + } + + if (user.LanguageCode is not null) + { + dict.Add($"navigator.telegram.{nameof(TelegramUser.LanguageCode)}", user.LanguageCode); + } + } + + return dict; + } + + public bool Maps(Type type) + { + return type == typeof(TelegramUser); + } +} \ No newline at end of file diff --git a/src/Navigator.Extensions.Store.Telegram/NavigatorStoreTelegramExtension.cs b/src/Navigator.Extensions.Store.Telegram/NavigatorStoreTelegramExtension.cs index 86111d2..b9ec9a5 100644 --- a/src/Navigator.Extensions.Store.Telegram/NavigatorStoreTelegramExtension.cs +++ b/src/Navigator.Extensions.Store.Telegram/NavigatorStoreTelegramExtension.cs @@ -1,16 +1,8 @@ -using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.Extensions.DependencyInjection; -using Navigator.Entities; using Navigator.Extensions.Store.Context.Extension; -using Navigator.Extensions.Store.Entities; -using Navigator.Extensions.Store.Mappers; -using Navigator.Extensions.Store.Telegram.Profiles; -using Navigator.Extensions.Store.Telegram.Profiles.Mappers; -using Navigator.Providers.Telegram.Entities; -using Chat = Navigator.Entities.Chat; -using Conversation = Navigator.Entities.Conversation; -using User = Navigator.Entities.User; +using Navigator.Extensions.Store.Extractors; +using Navigator.Extensions.Store.Telegram.Extractors; namespace Navigator.Extensions.Store.Telegram; @@ -19,23 +11,11 @@ public class NavigatorStoreTelegramExtension : NavigatorStoreModelExtension { public NavigatorStoreTelegramExtension() { - Extension = modelBuilder => - { - modelBuilder.Entity(typeBuilder => typeBuilder.HasBaseType()); - modelBuilder.Entity(typeBuilder => typeBuilder.HasBaseType()); - - modelBuilder.Entity(typeBuilder => typeBuilder.HasBaseType()); - modelBuilder.Entity(typeBuilder => typeBuilder.HasBaseType()); - - modelBuilder.Entity(typeBuilder => typeBuilder.HasBaseType()); - modelBuilder.Entity(typeBuilder => typeBuilder.HasBaseType()); - }; - ExtensionServices = services => { - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); }; Info = new NavigatorStoreTelegramExtensionInfo(this); diff --git a/src/Navigator.Extensions.Store.Telegram/Profiles/Mappers/TelegramProviderChatProfileMapper.cs b/src/Navigator.Extensions.Store.Telegram/Profiles/Mappers/TelegramProviderChatProfileMapper.cs deleted file mode 100644 index 0a182f0..0000000 --- a/src/Navigator.Extensions.Store.Telegram/Profiles/Mappers/TelegramProviderChatProfileMapper.cs +++ /dev/null @@ -1,36 +0,0 @@ -using Navigator.Entities; -using Navigator.Extensions.Store.Entities; -using Navigator.Extensions.Store.Mappers; -using Navigator.Providers.Telegram.Entities; -using Conversation = Navigator.Entities.Conversation; - -namespace Navigator.Extensions.Store.Telegram.Profiles.Mappers; - -public class TelegramProviderChatProfileMapper : IProviderChatProfileMapper -{ - public ChatProfile? From(Conversation sourceConversation) - { - if (sourceConversation.Chat is TelegramChat chat) - { - return new TelegramChatProfile - { - Id = Guid.NewGuid(), - Identification = sourceConversation.Chat.Id, - Data = chat, - DataId = sourceConversation.Chat.Id - }; - } - - return default; - } - - UniversalProfile? IProviderProfileMapper.From(Conversation sourceConversation) - { - return From(sourceConversation); - } - - public bool Maps(Type type) - { - return type == typeof(TelegramChat); - } -} \ No newline at end of file diff --git a/src/Navigator.Extensions.Store.Telegram/Profiles/Mappers/TelegramProviderConversationProfileMapper.cs b/src/Navigator.Extensions.Store.Telegram/Profiles/Mappers/TelegramProviderConversationProfileMapper.cs deleted file mode 100644 index 0e80aff..0000000 --- a/src/Navigator.Extensions.Store.Telegram/Profiles/Mappers/TelegramProviderConversationProfileMapper.cs +++ /dev/null @@ -1,36 +0,0 @@ -using Navigator.Entities; -using Navigator.Extensions.Store.Entities; -using Navigator.Extensions.Store.Mappers; -using Navigator.Providers.Telegram.Entities; -using Conversation = Navigator.Entities.Conversation; - -namespace Navigator.Extensions.Store.Telegram.Profiles.Mappers; - -public class TelegramProviderConversationProfileMapper : IProviderConversationProfileMapper -{ - public ConversationProfile? From(Conversation sourceConversation) - { - if (sourceConversation is TelegramConversation conversation) - { - return new TelegramConversationProfile - { - Id = Guid.NewGuid(), - Identification = sourceConversation.Id, - Data = conversation, - DataId = sourceConversation.Id - }; - } - - return default; - } - - UniversalProfile? IProviderProfileMapper.From(Conversation sourceConversation) - { - return From(sourceConversation); - } - - public bool Maps(Type type) - { - return type == typeof(TelegramConversation); - } -} \ No newline at end of file diff --git a/src/Navigator.Extensions.Store.Telegram/Profiles/Mappers/TelegramProviderUserProfileMapper.cs b/src/Navigator.Extensions.Store.Telegram/Profiles/Mappers/TelegramProviderUserProfileMapper.cs deleted file mode 100644 index 70b5ba3..0000000 --- a/src/Navigator.Extensions.Store.Telegram/Profiles/Mappers/TelegramProviderUserProfileMapper.cs +++ /dev/null @@ -1,36 +0,0 @@ -using Navigator.Entities; -using Navigator.Extensions.Store.Entities; -using Navigator.Extensions.Store.Mappers; -using Navigator.Providers.Telegram.Entities; -using Conversation = Navigator.Entities.Conversation; - -namespace Navigator.Extensions.Store.Telegram.Profiles.Mappers; - -public class TelegramProviderUserProfileMapper : IProviderUserProfileMapper -{ - public UserProfile? From(Conversation sourceConversation) - { - if (sourceConversation.User is TelegramUser user) - { - return new TelegramUserProfile - { - Id = Guid.NewGuid(), - Identification = sourceConversation.User.Id, - Data = user, - DataId = sourceConversation.User.Id - }; - } - - return default; - } - - UniversalProfile? IProviderProfileMapper.From(Conversation sourceConversation) - { - return From(sourceConversation); - } - - public bool Maps(Type type) - { - return type == typeof(TelegramUser) || type == typeof(TelegramBot); - } -} \ No newline at end of file diff --git a/src/Navigator.Extensions.Store.Telegram/Profiles/TelegramChatProfile.cs b/src/Navigator.Extensions.Store.Telegram/Profiles/TelegramChatProfile.cs deleted file mode 100644 index 116a004..0000000 --- a/src/Navigator.Extensions.Store.Telegram/Profiles/TelegramChatProfile.cs +++ /dev/null @@ -1,9 +0,0 @@ -using Navigator.Extensions.Store.Entities; -using Navigator.Providers.Telegram.Entities; - -namespace Navigator.Extensions.Store.Telegram.Profiles; - -public class TelegramChatProfile : ChatProfile -{ - public new TelegramChat Data { get; set; } -} \ No newline at end of file diff --git a/src/Navigator.Extensions.Store.Telegram/Profiles/TelegramConversationProfile.cs b/src/Navigator.Extensions.Store.Telegram/Profiles/TelegramConversationProfile.cs deleted file mode 100644 index fa17dde..0000000 --- a/src/Navigator.Extensions.Store.Telegram/Profiles/TelegramConversationProfile.cs +++ /dev/null @@ -1,9 +0,0 @@ -using Navigator.Extensions.Store.Entities; -using Navigator.Providers.Telegram.Entities; - -namespace Navigator.Extensions.Store.Telegram.Profiles; - -public class TelegramConversationProfile : ConversationProfile -{ - public new TelegramConversation Data { get; set; } -} \ No newline at end of file diff --git a/src/Navigator.Extensions.Store.Telegram/Profiles/TelegramUserProfile.cs b/src/Navigator.Extensions.Store.Telegram/Profiles/TelegramUserProfile.cs deleted file mode 100644 index a305e95..0000000 --- a/src/Navigator.Extensions.Store.Telegram/Profiles/TelegramUserProfile.cs +++ /dev/null @@ -1,9 +0,0 @@ -using Navigator.Extensions.Store.Entities; -using Navigator.Providers.Telegram.Entities; - -namespace Navigator.Extensions.Store.Telegram.Profiles; - -public class TelegramUserProfile : UserProfile -{ - public new TelegramUser Data { get; set; } -} \ No newline at end of file From 72975d9467e0fba8e00729c3e106b78395d9d4e4 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sun, 3 Apr 2022 23:37:15 +0200 Subject: [PATCH 267/304] feat: implement store of new conversations --- .../StoreConversationContextExtension.cs | 92 +++++++++++++++++-- 1 file changed, 83 insertions(+), 9 deletions(-) diff --git a/src/Navigator.Extensions.Store/Bundled/StoreConversationContextExtension.cs b/src/Navigator.Extensions.Store/Bundled/StoreConversationContextExtension.cs index 2004dad..6c51be7 100644 --- a/src/Navigator.Extensions.Store/Bundled/StoreConversationContextExtension.cs +++ b/src/Navigator.Extensions.Store/Bundled/StoreConversationContextExtension.cs @@ -4,35 +4,109 @@ using Navigator.Context; using Navigator.Context.Extensions; using Navigator.Extensions.Store.Context; +using Navigator.Extensions.Store.Entities; +using Navigator.Extensions.Store.Extractors; namespace Navigator.Extensions.Store.Bundled; internal class StoreConversationContextExtension : INavigatorContextExtension { - public const string UniversalConversation = "_navigator.extensions.store.conversation"; + public const string UniversalConversation = "_navigator.extensions.store.source"; private readonly NavigatorDbContext _dbContext; + private readonly IEnumerable _dataExtractors; - public StoreConversationContextExtension(NavigatorDbContext dbContext) + public StoreConversationContextExtension(NavigatorDbContext dbContext, IEnumerable dataExtractors) { _dbContext = dbContext; + _dataExtractors = dataExtractors; } public async Task Extend(INavigatorContext navigatorContext, INavigatorContextBuilderOptions builderOptions) { - var conversation = navigatorContext.Conversation; - if (await _dbContext.Conversations.AnyAsync(e => e.Id == navigatorContext.Conversation.Id)) { return navigatorContext; } - else + + var user = await StoreUserAsync(navigatorContext.Conversation); + var chat = await StoreChatAsync(navigatorContext.Conversation); + await StoreConversationAsync(navigatorContext.Conversation, user, chat); + + await _dbContext.SaveChangesAsync(); + + return navigatorContext; + } + + private async Task StoreUserAsync(Navigator.Entities.Conversation source) + { + var user = new User + { + Id = source.User.Id + }; + + var data = _dataExtractors + .FirstOrDefault(extractor => extractor.Maps(source.User.GetType()))? + .From(source); + + if (data is not null) { - + foreach (var pair in data) + { + user.Data.Add(pair); + } } - - return await Task.FromResult(navigatorContext); + + await _dbContext.Users.AddAsync(user); + + return user; } - + private async Task StoreChatAsync(Navigator.Entities.Conversation source) + { + var chat = new Chat + { + Id = source.Chat.Id + }; + + var data = _dataExtractors + .FirstOrDefault(extractor => extractor.Maps(source.Chat.GetType()))? + .From(source); + + if (data is not null) + { + foreach (var pair in data) + { + chat.Data.Add(pair); + } + } + + await _dbContext.Chats.AddAsync(chat); + + return chat; + } + + private async Task StoreConversationAsync(Navigator.Entities.Conversation source, User user, Chat chat) + { + var conversation = new Conversation(user, chat) + { + Id = source.Id, + User = user, + Chat = chat + }; + + var data = _dataExtractors + .FirstOrDefault(extractor => extractor.Maps(source.GetType()))? + .From(source); + + if (data is not null) + { + foreach (var pair in data) + { + chat.Data.Add(pair); + } + } + + await _dbContext.Conversations.AddAsync(conversation); + } } \ No newline at end of file From af33745650d1240d025bfadd442598e78bd8dd3b Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sun, 3 Apr 2022 23:42:04 +0200 Subject: [PATCH 268/304] feat: delete old store --- .../Bundled/StoreContextExtension.cs | 24 ---- .../IUniversalStore.cs | 44 ------- .../NavigatorContextExtensions.cs | 75 ------------ ...vigatorExtensionConfigurationExtensions.cs | 1 - .../UniversalStore.cs | 115 ------------------ .../Actions/EchoActionHandler.cs | 5 - 6 files changed, 264 deletions(-) delete mode 100644 src/Navigator.Extensions.Store/Bundled/StoreContextExtension.cs delete mode 100644 src/Navigator.Extensions.Store/IUniversalStore.cs delete mode 100644 src/Navigator.Extensions.Store/NavigatorContextExtensions.cs delete mode 100644 src/Navigator.Extensions.Store/UniversalStore.cs diff --git a/src/Navigator.Extensions.Store/Bundled/StoreContextExtension.cs b/src/Navigator.Extensions.Store/Bundled/StoreContextExtension.cs deleted file mode 100644 index 0f02788..0000000 --- a/src/Navigator.Extensions.Store/Bundled/StoreContextExtension.cs +++ /dev/null @@ -1,24 +0,0 @@ -using Navigator.Context; -using Navigator.Context.Extensions; -using Navigator.Extensions.Store.Entities; - -namespace Navigator.Extensions.Store.Bundled; - -public class StoreContextExtension: INavigatorContextExtension -{ - public const string StoreKey = "_navigator.extensions.store.navigator_db_context"; - - private readonly IUniversalStore _universalStore; - - public StoreContextExtension(IUniversalStore universalStore) - { - _universalStore = universalStore; - } - - public Task Extend(INavigatorContext navigatorContext, INavigatorContextBuilderOptions builderOptions) - { - navigatorContext.Extensions.Add(StoreKey, _universalStore); - - return Task.FromResult(navigatorContext); - } -} \ No newline at end of file diff --git a/src/Navigator.Extensions.Store/IUniversalStore.cs b/src/Navigator.Extensions.Store/IUniversalStore.cs deleted file mode 100644 index d1b97c0..0000000 --- a/src/Navigator.Extensions.Store/IUniversalStore.cs +++ /dev/null @@ -1,44 +0,0 @@ -using Navigator.Entities; -using Navigator.Extensions.Store.Entities; -using Chat = Navigator.Extensions.Store.Entities.Chat; -using Conversation = Navigator.Extensions.Store.Entities.Conversation; -using User = Navigator.Extensions.Store.Entities.User; - -namespace Navigator.Extensions.Store; - -public interface IUniversalStore -{ - #region Chat - - Task FindChat(Navigator.Entities.Chat chat, string provider, CancellationToken cancellationToken = default); - - #endregion - - #region Conversation - - Task FindOrCreateConversation(Navigator.Entities.Conversation conversation, string provider, - CancellationToken cancellationToken = default); - Task FindConversation(Navigator.Entities.Conversation conversation, string provider, - CancellationToken cancellationToken = default); - - #endregion - - #region User - - Task FindUser(Navigator.Entities.User user, string provider, CancellationToken cancellationToken = default); - - #endregion - - // #region Profile - // - // Task AddUserProfile(User user, string provider, Guid identification, CancellationToken cancellationToken = default, bool? saveChanges = true); - // Task TryAddUserProfile(User user, string provider, Guid identification, CancellationToken cancellationToken = default, bool? saveChanges = true); - // - // Task AddChatProfile(Chat chat, string provider, Guid identification, CancellationToken cancellationToken = default, bool? saveChanges = true); - // Task TryAddChatProfile(Chat chat, string provider, Guid identification, CancellationToken cancellationToken = default, bool? saveChanges = true); - // - // Task AddConversationProfile(Conversation conversation, string provider, Guid identification, CancellationToken cancellationToken = default, bool? saveChanges = true); - // Task TryAddConversationProfile(Conversation conversation, string provider, Guid identification, CancellationToken cancellationToken = default, bool? saveChanges = true); - // - // #endregion -} \ No newline at end of file diff --git a/src/Navigator.Extensions.Store/NavigatorContextExtensions.cs b/src/Navigator.Extensions.Store/NavigatorContextExtensions.cs deleted file mode 100644 index 45290b2..0000000 --- a/src/Navigator.Extensions.Store/NavigatorContextExtensions.cs +++ /dev/null @@ -1,75 +0,0 @@ -using Microsoft.EntityFrameworkCore; -using Navigator.Context; -using Navigator.Extensions.Store.Bundled; -using Navigator.Extensions.Store.Entities; - -namespace Navigator.Extensions.Store; - -/// -/// Useful extensions for Navigator Context. -/// -public static class NavigatorContextExtensions -{ - #region Store - - public static IUniversalStore GetStore(this INavigatorContext context) - { - return GetStoreOrDefault(context) ?? throw new InvalidOperationException(); - } - - public static IUniversalStore? GetStoreOrDefault(this INavigatorContext context) - { - var value = context.Extensions.GetValueOrDefault(StoreContextExtension.StoreKey); - - if (value is IUniversalStore store) - { - return store; - } - - return default; - } - - #endregion - - #region Chat - - public static async Task GetUniversalChat(this INavigatorContext context, CancellationToken cancellationToken = default) - { - return await GetUniversalChatOrDefault(context) ?? throw new InvalidOperationException(); - } - - public static async Task GetUniversalChatOrDefault(this INavigatorContext context, CancellationToken cancellationToken = default) - { - return await context.GetStore().FindChat(context.Conversation.Chat, context.Provider.Name, cancellationToken); - } - - #endregion - - #region Conversation - - public static async Task GetUniversalConversation(this INavigatorContext context, CancellationToken cancellationToken = default) - { - return await GetUniversalConversationOrDefault(context, cancellationToken) ?? throw new InvalidOperationException(); - } - - public static async Task GetUniversalConversationOrDefault(this INavigatorContext context, CancellationToken cancellationToken = default) - { - return await context.GetStore().FindConversation(context.Conversation, context.Provider.Name, cancellationToken); - } - - #endregion - - #region User - - public static async Task GetUniversalUser(this INavigatorContext context, CancellationToken cancellationToken = default) - { - return await GetUniversalUserOrDefault(context, cancellationToken) ?? throw new InvalidOperationException(); - } - - public static async Task GetUniversalUserOrDefault(this INavigatorContext context, CancellationToken cancellationToken = default) - { - return await context.GetStore().FindUser(context.Conversation.User, context.Provider.Name, cancellationToken); - } - - #endregion -} \ No newline at end of file diff --git a/src/Navigator.Extensions.Store/NavigatorExtensionConfigurationExtensions.cs b/src/Navigator.Extensions.Store/NavigatorExtensionConfigurationExtensions.cs index 1f97509..ec09692 100644 --- a/src/Navigator.Extensions.Store/NavigatorExtensionConfigurationExtensions.cs +++ b/src/Navigator.Extensions.Store/NavigatorExtensionConfigurationExtensions.cs @@ -24,7 +24,6 @@ public static NavigatorConfiguration Store(this NavigatorExtensionConfiguration { services.AddDbContext(dbContextOptions); - services.AddScoped(); services.AddScoped(); foreach (var extension in temporal.Options.Extensions.OfType()) diff --git a/src/Navigator.Extensions.Store/UniversalStore.cs b/src/Navigator.Extensions.Store/UniversalStore.cs deleted file mode 100644 index 80f6d43..0000000 --- a/src/Navigator.Extensions.Store/UniversalStore.cs +++ /dev/null @@ -1,115 +0,0 @@ -// using Microsoft.AspNetCore.Components; -// using Microsoft.EntityFrameworkCore; -// using Navigator.Entities; -// using Navigator.Extensions.Store.Context; -// using Navigator.Extensions.Store.Entities; -// using Navigator.Extensions.Store.Mappers; -// using Chat = Navigator.Extensions.Store.Entities.Chat; -// using Conversation = Navigator.Extensions.Store.Entities.Conversation; -// using User = Navigator.Extensions.Store.Entities.User; -// -// namespace Navigator.Extensions.Store; -// -// public class UniversalStore : IUniversalStore -// { -// private readonly NavigatorDbContext _dbContext; -// private readonly IEnumerable _profileMappers; -// -// public UniversalStore(NavigatorDbContext dbContext, IEnumerable profileMappers) -// { -// _dbContext = dbContext; -// _profileMappers = profileMappers; -// } -// -// #region Chat -// -// public async Task FindChat(Navigator.Entities.Chat chat, string provider, CancellationToken cancellationToken = default) -// { -// return await _dbContext.Chats -// .Where(e => e.Profiles.Any(p => p.Provider == provider)) -// .Where(e => e.Profiles.Any(p => p.Identification == chat.Id)) -// .FirstOrDefaultAsync(cancellationToken); -// } -// -// #endregion -// -// #region Conversation -// -// public async Task FindOrCreateConversation(Navigator.Entities.Conversation conversation, string provider, CancellationToken cancellationToken = default) -// { -// return await FindConversation(conversation, provider, cancellationToken) -// ?? await SaveConversation(conversation, provider, cancellationToken); -// } -// -// public async Task FindConversation(Navigator.Entities.Conversation conversation, string provider, CancellationToken cancellationToken = default) -// { -// return await _dbContext.Conversations -// .Include(e => e.User) -// .Include(e => e.Chat) -// .Where(e => e.Chat.Profiles.Any(p => p.Provider == provider && p.Identification == conversation.Chat.Id)) -// .Where(e => e.User.Profiles.Any(p => p.Provider == provider && p.Identification == conversation.User.Id)) -// .FirstOrDefaultAsync(cancellationToken); -// } -// -// #endregion -// -// #region User -// -// public async Task FindUser(Navigator.Entities.User user, string provider, CancellationToken cancellationToken = default) -// { -// return await _dbContext.Users -// .Where(e => e.Profiles.Any(p => p.Provider == provider)) -// .Where(e => e.Profiles.Any(p => p.Identification == user.Id)) -// .FirstOrDefaultAsync(cancellationToken); -// } -// -// #endregion -// -// protected async Task SaveConversation(Navigator.Entities.Conversation conversation, string provider, CancellationToken cancellationToken = default) -// { -// var userProfileMapper = _profileMappers -// .OfType() -// .FirstOrDefault(mapper => mapper.Maps(conversation.User.GetType())); -// -// var user = new User -// { -// Id = Guid.NewGuid() -// }; -// -// user.Profiles.Add(userProfileMapper?.From(conversation) ?? throw new NavigationException("TODO")); -// -// -// var chatProfileMapper = _profileMappers -// .OfType() -// .FirstOrDefault(mapper => mapper.Maps(conversation.Chat.GetType())); -// -// var chat = new Chat -// { -// Id = Guid.NewGuid() -// }; -// -// chat.Profiles.Add(chatProfileMapper?.From(conversation) ?? throw new NavigationException("TODO")); -// -// await _dbContext.Users.AddAsync(user, cancellationToken); -// await _dbContext.Chats.AddAsync(chat, cancellationToken); -// -// var universalConversation = new Conversation -// { -// Id = Guid.NewGuid(), -// User = user, -// Chat = chat, -// }; -// -// var conversationProfileMapper = _profileMappers -// .OfType() -// .FirstOrDefault(mapper => mapper.Maps(conversation.Chat.GetType())); -// -// universalConversation.Profiles.Add(conversationProfileMapper?.From(conversation) ?? throw new NavigationException("TODO")); -// -// await _dbContext.Conversations.AddAsync(universalConversation, cancellationToken); -// -// await _dbContext.SaveChangesAsync(cancellationToken); -// -// return universalConversation; -// } -// } \ No newline at end of file diff --git a/src/Navigator.Samples.Store/Actions/EchoActionHandler.cs b/src/Navigator.Samples.Store/Actions/EchoActionHandler.cs index 9347649..d594bae 100644 --- a/src/Navigator.Samples.Store/Actions/EchoActionHandler.cs +++ b/src/Navigator.Samples.Store/Actions/EchoActionHandler.cs @@ -19,11 +19,6 @@ public EchoActionHandler(INavigatorContextAccessor navigatorContextAccessor) : b public override async Task Handle(EchoAction action, CancellationToken cancellationToken) { - var uc = await NavigatorContext.GetStoreOrDefault()?.FindConversation(NavigatorContext.Conversation, NavigatorContext.Provider.Name, cancellationToken); - - await this.GetTelegramClient().SendTextMessageAsync(this.GetTelegramChat().Id, - uc.Id.ToString(), cancellationToken: cancellationToken); - await this.GetTelegramClient().SendTextMessageAsync(this.GetTelegramChat().Id, action.MessageToEcho, cancellationToken: cancellationToken); From 059f2e1c6fa5826f7a6d0bc026043eac4eba4971 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 4 Apr 2022 13:20:32 +0200 Subject: [PATCH 269/304] feat: lots of changes --- .../CooldownActionMiddleware.cs | 2 +- .../StoreConversationContextExtension.cs | 21 +- .../ChatEntityTypeConfiguration.cs | 10 + .../ConversationEntityTypeConfiguration.cs | 9 + .../UserEntityTypeConfiguration.cs | 9 + .../Entities/TelegramChat.cs | 14 + .../Entities/TelegramConversation.cs | 4 +- .../Extensions/TelegramUpdateExtensions.cs | 65 +-- .../Actions/InlineAction.cs | 16 + .../Actions/InlineActionHandler.cs | 27 ++ ...0211223144637_InitialMigration.Designer.cs | 373 ------------------ .../20211223144637_InitialMigration.cs | 207 ---------- ...0220404102457_InitialMigration.Designer.cs | 117 ++++++ .../20220404102457_InitialMigration.cs | 88 +++++ .../NavigatorDbContextModelSnapshot.cs | 288 +------------- src/Navigator/Entities/Conversation.cs | 6 +- 16 files changed, 362 insertions(+), 894 deletions(-) create mode 100644 src/Navigator.Samples.Store/Actions/InlineAction.cs create mode 100644 src/Navigator.Samples.Store/Actions/InlineActionHandler.cs delete mode 100644 src/Navigator.Samples.Store/Migrations/20211223144637_InitialMigration.Designer.cs delete mode 100644 src/Navigator.Samples.Store/Migrations/20211223144637_InitialMigration.cs create mode 100644 src/Navigator.Samples.Store/Migrations/20220404102457_InitialMigration.Designer.cs create mode 100644 src/Navigator.Samples.Store/Migrations/20220404102457_InitialMigration.cs diff --git a/src/Navigator.Extensions.Cooldown/CooldownActionMiddleware.cs b/src/Navigator.Extensions.Cooldown/CooldownActionMiddleware.cs index a13a3d7..ec4fc1c 100644 --- a/src/Navigator.Extensions.Cooldown/CooldownActionMiddleware.cs +++ b/src/Navigator.Extensions.Cooldown/CooldownActionMiddleware.cs @@ -40,6 +40,6 @@ public async Task Handle(TAction action, CancellationToken cancellationT private string GenerateKey(TAction action) { - return $"{action.GetType().FullName}:{_navigatorContext.Conversation.Chat.Id}"; + return $"{action.GetType().FullName}:{_navigatorContext.Conversation.Chat?.Id.ToString() ?? "no_chat"}"; } } \ No newline at end of file diff --git a/src/Navigator.Extensions.Store/Bundled/StoreConversationContextExtension.cs b/src/Navigator.Extensions.Store/Bundled/StoreConversationContextExtension.cs index 6c51be7..2ed047b 100644 --- a/src/Navigator.Extensions.Store/Bundled/StoreConversationContextExtension.cs +++ b/src/Navigator.Extensions.Store/Bundled/StoreConversationContextExtension.cs @@ -29,17 +29,19 @@ public async Task Extend(INavigatorContext navigatorContext, return navigatorContext; } - var user = await StoreUserAsync(navigatorContext.Conversation); - var chat = await StoreChatAsync(navigatorContext.Conversation); - await StoreConversationAsync(navigatorContext.Conversation, user, chat); + var user = await TryStoreUserAsync(navigatorContext.Conversation); + var chat = await TryStoreChatAsync(navigatorContext.Conversation); + await TryStoreConversationAsync(navigatorContext.Conversation, user, chat); await _dbContext.SaveChangesAsync(); return navigatorContext; } - private async Task StoreUserAsync(Navigator.Entities.Conversation source) + private async Task TryStoreUserAsync(Navigator.Entities.Conversation source) { + if (await _dbContext.Users.AnyAsync(user => user.Id == source.User.Id)) return default; + var user = new User { Id = source.User.Id @@ -62,8 +64,10 @@ private async Task StoreUserAsync(Navigator.Entities.Conversation source) return user; } - private async Task StoreChatAsync(Navigator.Entities.Conversation source) + private async Task TryStoreChatAsync(Navigator.Entities.Conversation source) { + if (source.Chat is null) return default; + var chat = new Chat { Id = source.Chat.Id @@ -84,17 +88,20 @@ private async Task StoreChatAsync(Navigator.Entities.Conversation source) await _dbContext.Chats.AddAsync(chat); return chat; + } - private async Task StoreConversationAsync(Navigator.Entities.Conversation source, User user, Chat chat) + private async Task TryStoreConversationAsync(Navigator.Entities.Conversation source, User? user, Chat? chat) { + if (user is null || chat is null) return; + var conversation = new Conversation(user, chat) { Id = source.Id, User = user, Chat = chat }; - + var data = _dataExtractors .FirstOrDefault(extractor => extractor.Maps(source.GetType()))? .From(source); diff --git a/src/Navigator.Extensions.Store/Context/Configuration/ChatEntityTypeConfiguration.cs b/src/Navigator.Extensions.Store/Context/Configuration/ChatEntityTypeConfiguration.cs index a9c571f..9aee2e8 100644 --- a/src/Navigator.Extensions.Store/Context/Configuration/ChatEntityTypeConfiguration.cs +++ b/src/Navigator.Extensions.Store/Context/Configuration/ChatEntityTypeConfiguration.cs @@ -1,4 +1,7 @@ +using System.Text.Json; +using System.Text.Json.Serialization; using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.ChangeTracking; using Microsoft.EntityFrameworkCore.Metadata.Builders; using Navigator.Extensions.Store.Entities; @@ -18,6 +21,13 @@ public void Configure(EntityTypeBuilder builder) e=> e.HasOne(e => e.Chat) .WithMany(e => e.Conversations)); + builder.Property(e => e.Data) + .HasConversion( + dictionary => JsonSerializer.Serialize(dictionary, default(JsonSerializerOptions)), + json => JsonSerializer.Deserialize>(json, default(JsonSerializerOptions)) + ?? new Dictionary(), + ValueComparer.CreateDefault(typeof(IDictionary), false)); + builder.Property(e => e.FirstInteractionAt) .IsRequired(); } diff --git a/src/Navigator.Extensions.Store/Context/Configuration/ConversationEntityTypeConfiguration.cs b/src/Navigator.Extensions.Store/Context/Configuration/ConversationEntityTypeConfiguration.cs index 522ce5a..2193bf9 100644 --- a/src/Navigator.Extensions.Store/Context/Configuration/ConversationEntityTypeConfiguration.cs +++ b/src/Navigator.Extensions.Store/Context/Configuration/ConversationEntityTypeConfiguration.cs @@ -1,4 +1,6 @@ +using System.Text.Json; using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.ChangeTracking; using Microsoft.EntityFrameworkCore.Metadata.Builders; using Navigator.Extensions.Store.Entities; @@ -8,6 +10,13 @@ public class ConversationEntityTypeConfiguration : IEntityTypeConfiguration builder) { + builder.Property(e => e.Data) + .HasConversion( + dictionary => JsonSerializer.Serialize(dictionary, default(JsonSerializerOptions)), + json => JsonSerializer.Deserialize>(json, default(JsonSerializerOptions)) + ?? new Dictionary(), + ValueComparer.CreateDefault(typeof(IDictionary), false)); + builder.Property(e => e.FirstInteractionAt) .IsRequired(); } diff --git a/src/Navigator.Extensions.Store/Context/Configuration/UserEntityTypeConfiguration.cs b/src/Navigator.Extensions.Store/Context/Configuration/UserEntityTypeConfiguration.cs index 801563d..ddb07c8 100644 --- a/src/Navigator.Extensions.Store/Context/Configuration/UserEntityTypeConfiguration.cs +++ b/src/Navigator.Extensions.Store/Context/Configuration/UserEntityTypeConfiguration.cs @@ -1,4 +1,6 @@ +using System.Text.Json; using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.ChangeTracking; using Microsoft.EntityFrameworkCore.Metadata.Builders; using Navigator.Extensions.Store.Entities; @@ -18,6 +20,13 @@ public void Configure(EntityTypeBuilder builder) e=> e.HasOne(e => e.User) .WithMany(e => e.Conversations)); + builder.Property(e => e.Data) + .HasConversion( + dictionary => JsonSerializer.Serialize(dictionary, default(JsonSerializerOptions)), + json => JsonSerializer.Deserialize>(json, default(JsonSerializerOptions)) + ?? new Dictionary(), + ValueComparer.CreateDefault(typeof(IDictionary), false)); + builder.Property(e => e.FirstInteractionAt) .IsRequired(); } diff --git a/src/Navigator.Providers.Telegram/Entities/TelegramChat.cs b/src/Navigator.Providers.Telegram/Entities/TelegramChat.cs index 18948d6..273de0c 100644 --- a/src/Navigator.Providers.Telegram/Entities/TelegramChat.cs +++ b/src/Navigator.Providers.Telegram/Entities/TelegramChat.cs @@ -19,4 +19,18 @@ public TelegramChat(long externalIdentifier) : base($"{nameof(TelegramChat)}.{ex /// Title of the chat, if any. /// public string? Title { get; init; } + + /// + /// Type of the chat, can be any of . + /// + public TelegramChatType Type { get; init; } +} + +public enum TelegramChatType +{ + Private, + Group, + Channel, + Supergroup, + Sender } \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/Entities/TelegramConversation.cs b/src/Navigator.Providers.Telegram/Entities/TelegramConversation.cs index bc65622..f37924c 100644 --- a/src/Navigator.Providers.Telegram/Entities/TelegramConversation.cs +++ b/src/Navigator.Providers.Telegram/Entities/TelegramConversation.cs @@ -9,7 +9,7 @@ public TelegramConversation() } - public TelegramConversation(TelegramUser user, TelegramChat chat) : base(user, chat) + public TelegramConversation(TelegramUser user, TelegramChat? chat) : base(user, chat) { User = user; Chat = chat; @@ -23,5 +23,5 @@ public TelegramConversation(TelegramUser user, TelegramChat chat) : base(user, c /// /// Telegram chat. /// - public new TelegramChat Chat { get; init; } + public new TelegramChat? Chat { get; init; } } \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/Extensions/TelegramUpdateExtensions.cs b/src/Navigator.Providers.Telegram/Extensions/TelegramUpdateExtensions.cs index 3795653..6e49fc1 100644 --- a/src/Navigator.Providers.Telegram/Extensions/TelegramUpdateExtensions.cs +++ b/src/Navigator.Providers.Telegram/Extensions/TelegramUpdateExtensions.cs @@ -36,15 +36,15 @@ internal static class TelegramUpdateExtensions { return update.Type switch { - UpdateType.Message => update.Message.From, - UpdateType.InlineQuery => update.InlineQuery.From, - UpdateType.ChosenInlineResult => update.ChosenInlineResult.From, - UpdateType.CallbackQuery => update.CallbackQuery.From, - UpdateType.EditedMessage => update.EditedMessage.From, - UpdateType.ChannelPost => update.ChannelPost.From, - UpdateType.EditedChannelPost => update.EditedChannelPost.From, - UpdateType.ShippingQuery => update.ShippingQuery.From, - UpdateType.PreCheckoutQuery => update.PreCheckoutQuery.From, + UpdateType.Message => update.Message?.From, + UpdateType.InlineQuery => update.InlineQuery?.From, + UpdateType.ChosenInlineResult => update.ChosenInlineResult?.From, + UpdateType.CallbackQuery => update.CallbackQuery?.From, + UpdateType.EditedMessage => update.EditedMessage?.From, + UpdateType.ChannelPost => update.ChannelPost?.From, + UpdateType.EditedChannelPost => update.EditedChannelPost?.From, + UpdateType.ShippingQuery => update.ShippingQuery?.From, + UpdateType.PreCheckoutQuery => update.PreCheckoutQuery?.From, _ => default }; } @@ -53,36 +53,43 @@ internal static class TelegramUpdateExtensions { return update.Type switch { - UpdateType.CallbackQuery => update.CallbackQuery.Message.Chat, - UpdateType.Message => update.Message.Chat, - UpdateType.EditedMessage => update.EditedMessage.Chat, - UpdateType.ChannelPost => update.ChannelPost.Chat, - UpdateType.EditedChannelPost => update.EditedChannelPost.Chat, + UpdateType.CallbackQuery => update.CallbackQuery?.Message?.Chat, + UpdateType.Message => update.Message?.Chat, + UpdateType.EditedMessage => update.EditedMessage?.Chat, + UpdateType.ChannelPost => update.ChannelPost?.Chat, + UpdateType.EditedChannelPost => update.EditedChannelPost?.Chat, _ => default }; } public static TelegramConversation GetConversation(this Update update) { - var user = update.GetUserOrDefault(); - var chat = update.GetChatOrDefault(); + var rawUser = update.GetUserOrDefault(); + var rawChat = update.GetChatOrDefault(); - if (chat is null || user is null) + if (rawUser is null) { - throw new Exception("TODO NAvigator exception no conversation could be built."); + throw new NavigatorException("No conversation could be built, user not found."); } - return new TelegramConversation( - new TelegramUser(user.Id) - { - Username = user.Username, - FirstName = user.FirstName, - LastName = user.LastName, - LanguageCode = user.LanguageCode - }, - new TelegramChat(chat.Id) + var user = new TelegramUser(rawUser.Id) + { + Username = rawUser.Username, + FirstName = rawUser.FirstName, + LastName = rawUser.LastName, + LanguageCode = rawUser.LanguageCode + }; + + var chat = default(TelegramChat); + + if (rawChat is not null) + { + chat = new TelegramChat(rawChat.Id) { - Title = chat.Title - }); + Title = rawChat.Title + }; + } + + return new TelegramConversation(user, chat); } } \ No newline at end of file diff --git a/src/Navigator.Samples.Store/Actions/InlineAction.cs b/src/Navigator.Samples.Store/Actions/InlineAction.cs new file mode 100644 index 0000000..a7d5239 --- /dev/null +++ b/src/Navigator.Samples.Store/Actions/InlineAction.cs @@ -0,0 +1,16 @@ +using Navigator.Context; +using Navigator.Providers.Telegram.Actions.Updates; + +namespace Navigator.Samples.Store.Actions; + +public class InlineAction : InlineQueryAction +{ + public InlineAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) + { + } + + public override bool CanHandleCurrentContext() + { + return true; + } +} \ No newline at end of file diff --git a/src/Navigator.Samples.Store/Actions/InlineActionHandler.cs b/src/Navigator.Samples.Store/Actions/InlineActionHandler.cs new file mode 100644 index 0000000..9ee3704 --- /dev/null +++ b/src/Navigator.Samples.Store/Actions/InlineActionHandler.cs @@ -0,0 +1,27 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using Navigator.Actions; +using Navigator.Context; +using Navigator.Providers.Telegram; +using Telegram.Bot; +using Telegram.Bot.Types.InlineQueryResults; + +namespace Navigator.Samples.Store.Actions; + +public class InlineActionHandler : ActionHandler +{ + public InlineActionHandler(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) + { + } + + public override async Task Handle(InlineAction action, CancellationToken cancellationToken) + { + await NavigatorContext.GetTelegramClient().AnswerInlineQueryAsync(action.InlineQuery.Id, new InlineQueryResult[] + { + new InlineQueryResultArticle(Guid.NewGuid().ToString(), "Test", new InputTextMessageContent("Test Message")) + }, cancellationToken: cancellationToken); + + return Success(); + } +} \ No newline at end of file diff --git a/src/Navigator.Samples.Store/Migrations/20211223144637_InitialMigration.Designer.cs b/src/Navigator.Samples.Store/Migrations/20211223144637_InitialMigration.Designer.cs deleted file mode 100644 index 433ee4e..0000000 --- a/src/Navigator.Samples.Store/Migrations/20211223144637_InitialMigration.Designer.cs +++ /dev/null @@ -1,373 +0,0 @@ -// -using System; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Infrastructure; -using Microsoft.EntityFrameworkCore.Migrations; -using Microsoft.EntityFrameworkCore.Storage.ValueConversion; -using Navigator.Extensions.Store.Context; - -#nullable disable - -namespace Navigator.Samples.Store.Migrations -{ - [DbContext(typeof(NavigatorDbContext))] - [Migration("20211223144637_InitialMigration")] - partial class InitialMigration - { - protected override void BuildTargetModel(ModelBuilder modelBuilder) - { -#pragma warning disable 612, 618 - modelBuilder.HasAnnotation("ProductVersion", "6.0.1"); - - modelBuilder.Entity("Navigator.Entities.Chat", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("Discriminator") - .IsRequired() - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("Chat"); - - b.HasDiscriminator("Discriminator").HasValue("Chat"); - }); - - modelBuilder.Entity("Navigator.Entities.Conversation", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("Discriminator") - .IsRequired() - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("Conversation"); - - b.HasDiscriminator("Discriminator").HasValue("Conversation"); - }); - - modelBuilder.Entity("Navigator.Entities.User", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("Discriminator") - .IsRequired() - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("User"); - - b.HasDiscriminator("Discriminator").HasValue("User"); - }); - - modelBuilder.Entity("Navigator.Extensions.Store.Entities.UniversalProfile", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("CreatedAt") - .HasColumnType("TEXT"); - - b.Property("Discriminator") - .IsRequired() - .HasColumnType("TEXT"); - - b.Property("Identification") - .HasColumnType("TEXT"); - - b.Property("LastUpdatedAt") - .HasColumnType("TEXT"); - - b.Property("Provider") - .IsRequired() - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("Profiles"); - - b.HasDiscriminator("Discriminator").HasValue("UniversalProfile"); - }); - - modelBuilder.Entity("Navigator.Extensions.Store.Entities.ChatProfile", b => - { - b.HasBaseType("Navigator.Extensions.Store.Entities.UniversalProfile"); - - b.Property("DataId") - .HasColumnType("TEXT") - .HasColumnName("ChatProfile_DataId"); - - b.Property("UniversalChatId") - .HasColumnType("TEXT"); - - b.HasIndex("DataId") - .IsUnique(); - - b.HasIndex("UniversalChatId"); - - b.HasDiscriminator().HasValue("ChatProfile"); - }); - - modelBuilder.Entity("Navigator.Extensions.Store.Entities.ConversationProfile", b => - { - b.HasBaseType("Navigator.Extensions.Store.Entities.UniversalProfile"); - - b.Property("DataId") - .HasColumnType("TEXT"); - - b.Property("UniversalConversationId") - .HasColumnType("TEXT"); - - b.HasIndex("DataId") - .IsUnique(); - - b.HasIndex("UniversalConversationId"); - - b.HasDiscriminator().HasValue("ConversationProfile"); - }); - - modelBuilder.Entity("Navigator.Extensions.Store.Entities.Chat", b => - { - b.HasBaseType("Navigator.Entities.Chat"); - - b.Property("FirstInteractionAt") - .HasColumnType("TEXT"); - - b.HasDiscriminator().HasValue("Chat"); - }); - - modelBuilder.Entity("Navigator.Extensions.Store.Entities.Conversation", b => - { - b.HasBaseType("Navigator.Entities.Conversation"); - - b.Property("ChatId") - .HasColumnType("TEXT"); - - b.Property("FirstInteractionAt") - .HasColumnType("TEXT"); - - b.Property("UserId") - .HasColumnType("TEXT"); - - b.HasIndex("ChatId"); - - b.HasIndex("UserId"); - - b.HasDiscriminator().HasValue("Conversation"); - }); - - modelBuilder.Entity("Navigator.Extensions.Store.Entities.User", b => - { - b.HasBaseType("Navigator.Entities.User"); - - b.Property("FirstInteractionAt") - .HasColumnType("TEXT"); - - b.HasDiscriminator().HasValue("User"); - }); - - modelBuilder.Entity("Navigator.Extensions.Store.Entities.UserProfile", b => - { - b.HasBaseType("Navigator.Extensions.Store.Entities.UniversalProfile"); - - b.Property("DataId") - .HasColumnType("TEXT") - .HasColumnName("UserProfile_DataId"); - - b.Property("UniversalUserId") - .HasColumnType("TEXT"); - - b.HasIndex("DataId") - .IsUnique(); - - b.HasIndex("UniversalUserId"); - - b.HasDiscriminator().HasValue("UserProfile"); - }); - - modelBuilder.Entity("Navigator.Providers.Telegram.Entities.TelegramChat", b => - { - b.HasBaseType("Navigator.Entities.Chat"); - - b.Property("ExternalIdentifier") - .HasColumnType("INTEGER"); - - b.Property("Title") - .HasColumnType("TEXT"); - - b.HasDiscriminator().HasValue("TelegramChat"); - }); - - modelBuilder.Entity("Navigator.Providers.Telegram.Entities.TelegramConversation", b => - { - b.HasBaseType("Navigator.Entities.Conversation"); - - b.Property("ChatId") - .HasColumnType("TEXT") - .HasColumnName("TelegramConversation_ChatId"); - - b.Property("UserId") - .HasColumnType("TEXT") - .HasColumnName("TelegramConversation_UserId"); - - b.HasIndex("ChatId"); - - b.HasIndex("UserId"); - - b.HasDiscriminator().HasValue("TelegramConversation"); - }); - - modelBuilder.Entity("Navigator.Providers.Telegram.Entities.TelegramUser", b => - { - b.HasBaseType("Navigator.Entities.User"); - - b.Property("ExternalIdentifier") - .HasColumnType("INTEGER"); - - b.Property("FirstName") - .IsRequired() - .HasColumnType("TEXT"); - - b.Property("LanguageCode") - .HasColumnType("TEXT"); - - b.Property("LastName") - .HasColumnType("TEXT"); - - b.Property("Username") - .HasColumnType("TEXT"); - - b.HasDiscriminator().HasValue("TelegramUser"); - }); - - modelBuilder.Entity("Navigator.Extensions.Store.Telegram.TelegramChatProfile", b => - { - b.HasBaseType("Navigator.Extensions.Store.Entities.ChatProfile"); - - b.HasDiscriminator().HasValue("TelegramChatProfile"); - }); - - modelBuilder.Entity("Navigator.Extensions.Store.Telegram.TelegramConversationProfile", b => - { - b.HasBaseType("Navigator.Extensions.Store.Entities.ConversationProfile"); - - b.HasDiscriminator().HasValue("TelegramConversationProfile"); - }); - - modelBuilder.Entity("Navigator.Extensions.Store.Telegram.TelegramUserProfile", b => - { - b.HasBaseType("Navigator.Extensions.Store.Entities.UserProfile"); - - b.HasDiscriminator().HasValue("TelegramUserProfile"); - }); - - modelBuilder.Entity("Navigator.Extensions.Store.Entities.ChatProfile", b => - { - b.HasOne("Navigator.Entities.Chat", "Data") - .WithOne() - .HasForeignKey("Navigator.Extensions.Store.Entities.ChatProfile", "DataId"); - - b.HasOne("Navigator.Extensions.Store.Entities.Chat", null) - .WithMany("Profiles") - .HasForeignKey("UniversalChatId"); - - b.Navigation("Data"); - }); - - modelBuilder.Entity("Navigator.Extensions.Store.Entities.ConversationProfile", b => - { - b.HasOne("Navigator.Entities.Conversation", "Data") - .WithOne() - .HasForeignKey("Navigator.Extensions.Store.Entities.ConversationProfile", "DataId"); - - b.HasOne("Navigator.Extensions.Store.Entities.Conversation", null) - .WithMany("Profiles") - .HasForeignKey("UniversalConversationId"); - - b.Navigation("Data"); - }); - - modelBuilder.Entity("Navigator.Extensions.Store.Entities.Conversation", b => - { - b.HasOne("Navigator.Extensions.Store.Entities.Chat", "Chat") - .WithMany("Conversations") - .HasForeignKey("ChatId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.HasOne("Navigator.Extensions.Store.Entities.User", "User") - .WithMany("Conversations") - .HasForeignKey("UserId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("Chat"); - - b.Navigation("User"); - }); - - modelBuilder.Entity("Navigator.Extensions.Store.Entities.UserProfile", b => - { - b.HasOne("Navigator.Entities.User", "Data") - .WithOne() - .HasForeignKey("Navigator.Extensions.Store.Entities.UserProfile", "DataId"); - - b.HasOne("Navigator.Extensions.Store.Entities.User", null) - .WithMany("Profiles") - .HasForeignKey("UniversalUserId"); - - b.Navigation("Data"); - }); - - modelBuilder.Entity("Navigator.Providers.Telegram.Entities.TelegramConversation", b => - { - b.HasOne("Navigator.Providers.Telegram.Entities.TelegramChat", "Chat") - .WithMany() - .HasForeignKey("ChatId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.HasOne("Navigator.Providers.Telegram.Entities.TelegramUser", "User") - .WithMany() - .HasForeignKey("UserId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("Chat"); - - b.Navigation("User"); - }); - - modelBuilder.Entity("Navigator.Extensions.Store.Entities.Chat", b => - { - b.Navigation("Conversations"); - - b.Navigation("Profiles"); - }); - - modelBuilder.Entity("Navigator.Extensions.Store.Entities.Conversation", b => - { - b.Navigation("Profiles"); - }); - - modelBuilder.Entity("Navigator.Extensions.Store.Entities.User", b => - { - b.Navigation("Conversations"); - - b.Navigation("Profiles"); - }); -#pragma warning restore 612, 618 - } - } -} diff --git a/src/Navigator.Samples.Store/Migrations/20211223144637_InitialMigration.cs b/src/Navigator.Samples.Store/Migrations/20211223144637_InitialMigration.cs deleted file mode 100644 index c4f897f..0000000 --- a/src/Navigator.Samples.Store/Migrations/20211223144637_InitialMigration.cs +++ /dev/null @@ -1,207 +0,0 @@ -using System; -using Microsoft.EntityFrameworkCore.Migrations; - -#nullable disable - -namespace Navigator.Samples.Store.Migrations -{ - public partial class InitialMigration : Migration - { - protected override void Up(MigrationBuilder migrationBuilder) - { - migrationBuilder.CreateTable( - name: "Chat", - columns: table => new - { - Id = table.Column(type: "TEXT", nullable: false), - Discriminator = table.Column(type: "TEXT", nullable: false), - FirstInteractionAt = table.Column(type: "TEXT", nullable: true), - ExternalIdentifier = table.Column(type: "INTEGER", nullable: true), - Title = table.Column(type: "TEXT", nullable: true) - }, - constraints: table => - { - table.PrimaryKey("PK_Chat", x => x.Id); - }); - - migrationBuilder.CreateTable( - name: "User", - columns: table => new - { - Id = table.Column(type: "TEXT", nullable: false), - Discriminator = table.Column(type: "TEXT", nullable: false), - FirstInteractionAt = table.Column(type: "TEXT", nullable: true), - ExternalIdentifier = table.Column(type: "INTEGER", nullable: true), - Username = table.Column(type: "TEXT", nullable: true), - FirstName = table.Column(type: "TEXT", nullable: true), - LastName = table.Column(type: "TEXT", nullable: true), - LanguageCode = table.Column(type: "TEXT", nullable: true) - }, - constraints: table => - { - table.PrimaryKey("PK_User", x => x.Id); - }); - - migrationBuilder.CreateTable( - name: "Conversation", - columns: table => new - { - Id = table.Column(type: "TEXT", nullable: false), - Discriminator = table.Column(type: "TEXT", nullable: false), - ChatId = table.Column(type: "TEXT", nullable: true), - UserId = table.Column(type: "TEXT", nullable: true), - FirstInteractionAt = table.Column(type: "TEXT", nullable: true), - TelegramConversation_UserId = table.Column(type: "TEXT", nullable: true), - TelegramConversation_ChatId = table.Column(type: "TEXT", nullable: true) - }, - constraints: table => - { - table.PrimaryKey("PK_Conversation", x => x.Id); - table.ForeignKey( - name: "FK_Conversation_Chat_ChatId", - column: x => x.ChatId, - principalTable: "Chat", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - table.ForeignKey( - name: "FK_Conversation_Chat_TelegramConversation_ChatId", - column: x => x.TelegramConversation_ChatId, - principalTable: "Chat", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - table.ForeignKey( - name: "FK_Conversation_User_TelegramConversation_UserId", - column: x => x.TelegramConversation_UserId, - principalTable: "User", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - table.ForeignKey( - name: "FK_Conversation_User_UserId", - column: x => x.UserId, - principalTable: "User", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); - - migrationBuilder.CreateTable( - name: "Profiles", - columns: table => new - { - Id = table.Column(type: "TEXT", nullable: false), - Provider = table.Column(type: "TEXT", nullable: false), - Identification = table.Column(type: "TEXT", nullable: false), - CreatedAt = table.Column(type: "TEXT", nullable: false), - LastUpdatedAt = table.Column(type: "TEXT", nullable: false), - Discriminator = table.Column(type: "TEXT", nullable: false), - ChatProfile_DataId = table.Column(type: "TEXT", nullable: true), - UniversalChatId = table.Column(type: "TEXT", nullable: true), - DataId = table.Column(type: "TEXT", nullable: true), - UniversalConversationId = table.Column(type: "TEXT", nullable: true), - UserProfile_DataId = table.Column(type: "TEXT", nullable: true), - UniversalUserId = table.Column(type: "TEXT", nullable: true) - }, - constraints: table => - { - table.PrimaryKey("PK_Profiles", x => x.Id); - table.ForeignKey( - name: "FK_Profiles_Chat_ChatProfile_DataId", - column: x => x.ChatProfile_DataId, - principalTable: "Chat", - principalColumn: "Id"); - table.ForeignKey( - name: "FK_Profiles_Chat_UniversalChatId", - column: x => x.UniversalChatId, - principalTable: "Chat", - principalColumn: "Id"); - table.ForeignKey( - name: "FK_Profiles_Conversation_DataId", - column: x => x.DataId, - principalTable: "Conversation", - principalColumn: "Id"); - table.ForeignKey( - name: "FK_Profiles_Conversation_UniversalConversationId", - column: x => x.UniversalConversationId, - principalTable: "Conversation", - principalColumn: "Id"); - table.ForeignKey( - name: "FK_Profiles_User_UniversalUserId", - column: x => x.UniversalUserId, - principalTable: "User", - principalColumn: "Id"); - table.ForeignKey( - name: "FK_Profiles_User_UserProfile_DataId", - column: x => x.UserProfile_DataId, - principalTable: "User", - principalColumn: "Id"); - }); - - migrationBuilder.CreateIndex( - name: "IX_Conversation_ChatId", - table: "Conversation", - column: "ChatId"); - - migrationBuilder.CreateIndex( - name: "IX_Conversation_TelegramConversation_ChatId", - table: "Conversation", - column: "TelegramConversation_ChatId"); - - migrationBuilder.CreateIndex( - name: "IX_Conversation_TelegramConversation_UserId", - table: "Conversation", - column: "TelegramConversation_UserId"); - - migrationBuilder.CreateIndex( - name: "IX_Conversation_UserId", - table: "Conversation", - column: "UserId"); - - migrationBuilder.CreateIndex( - name: "IX_Profiles_ChatProfile_DataId", - table: "Profiles", - column: "ChatProfile_DataId", - unique: true); - - migrationBuilder.CreateIndex( - name: "IX_Profiles_DataId", - table: "Profiles", - column: "DataId", - unique: true); - - migrationBuilder.CreateIndex( - name: "IX_Profiles_UniversalChatId", - table: "Profiles", - column: "UniversalChatId"); - - migrationBuilder.CreateIndex( - name: "IX_Profiles_UniversalConversationId", - table: "Profiles", - column: "UniversalConversationId"); - - migrationBuilder.CreateIndex( - name: "IX_Profiles_UniversalUserId", - table: "Profiles", - column: "UniversalUserId"); - - migrationBuilder.CreateIndex( - name: "IX_Profiles_UserProfile_DataId", - table: "Profiles", - column: "UserProfile_DataId", - unique: true); - } - - protected override void Down(MigrationBuilder migrationBuilder) - { - migrationBuilder.DropTable( - name: "Profiles"); - - migrationBuilder.DropTable( - name: "Conversation"); - - migrationBuilder.DropTable( - name: "Chat"); - - migrationBuilder.DropTable( - name: "User"); - } - } -} diff --git a/src/Navigator.Samples.Store/Migrations/20220404102457_InitialMigration.Designer.cs b/src/Navigator.Samples.Store/Migrations/20220404102457_InitialMigration.Designer.cs new file mode 100644 index 0000000..2a196f5 --- /dev/null +++ b/src/Navigator.Samples.Store/Migrations/20220404102457_InitialMigration.Designer.cs @@ -0,0 +1,117 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Navigator.Extensions.Store.Context; + +#nullable disable + +namespace Navigator.Samples.Store.Migrations +{ + [DbContext(typeof(NavigatorDbContext))] + [Migration("20220404102457_InitialMigration")] + partial class InitialMigration + { + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "6.0.1"); + + modelBuilder.Entity("Navigator.Extensions.Store.Entities.Chat", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Data") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("FirstInteractionAt") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("Chats"); + }); + + modelBuilder.Entity("Navigator.Extensions.Store.Entities.Conversation", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ChatId") + .HasColumnType("TEXT"); + + b.Property("Data") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("FirstInteractionAt") + .HasColumnType("TEXT"); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("ChatId"); + + b.HasIndex("UserId"); + + b.ToTable("Conversations"); + }); + + modelBuilder.Entity("Navigator.Extensions.Store.Entities.User", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Data") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("FirstInteractionAt") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("Users"); + }); + + modelBuilder.Entity("Navigator.Extensions.Store.Entities.Conversation", b => + { + b.HasOne("Navigator.Extensions.Store.Entities.Chat", "Chat") + .WithMany("Conversations") + .HasForeignKey("ChatId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Navigator.Extensions.Store.Entities.User", "User") + .WithMany("Conversations") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Chat"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Navigator.Extensions.Store.Entities.Chat", b => + { + b.Navigation("Conversations"); + }); + + modelBuilder.Entity("Navigator.Extensions.Store.Entities.User", b => + { + b.Navigation("Conversations"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Navigator.Samples.Store/Migrations/20220404102457_InitialMigration.cs b/src/Navigator.Samples.Store/Migrations/20220404102457_InitialMigration.cs new file mode 100644 index 0000000..bdbd246 --- /dev/null +++ b/src/Navigator.Samples.Store/Migrations/20220404102457_InitialMigration.cs @@ -0,0 +1,88 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Navigator.Samples.Store.Migrations +{ + public partial class InitialMigration : Migration + { + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "Chats", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + Data = table.Column(type: "TEXT", nullable: false), + FirstInteractionAt = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Chats", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "Users", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + Data = table.Column(type: "TEXT", nullable: false), + FirstInteractionAt = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Users", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "Conversations", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + ChatId = table.Column(type: "TEXT", nullable: false), + UserId = table.Column(type: "TEXT", nullable: false), + Data = table.Column(type: "TEXT", nullable: false), + FirstInteractionAt = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Conversations", x => x.Id); + table.ForeignKey( + name: "FK_Conversations_Chats_ChatId", + column: x => x.ChatId, + principalTable: "Chats", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_Conversations_Users_UserId", + column: x => x.UserId, + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_Conversations_ChatId", + table: "Conversations", + column: "ChatId"); + + migrationBuilder.CreateIndex( + name: "IX_Conversations_UserId", + table: "Conversations", + column: "UserId"); + } + + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "Conversations"); + + migrationBuilder.DropTable( + name: "Chats"); + + migrationBuilder.DropTable( + name: "Users"); + } + } +} diff --git a/src/Navigator.Samples.Store/Migrations/NavigatorDbContextModelSnapshot.cs b/src/Navigator.Samples.Store/Migrations/NavigatorDbContextModelSnapshot.cs index 3903e92..5240e5d 100644 --- a/src/Navigator.Samples.Store/Migrations/NavigatorDbContextModelSnapshot.cs +++ b/src/Navigator.Samples.Store/Migrations/NavigatorDbContextModelSnapshot.cs @@ -17,283 +17,68 @@ protected override void BuildModel(ModelBuilder modelBuilder) #pragma warning disable 612, 618 modelBuilder.HasAnnotation("ProductVersion", "6.0.1"); - modelBuilder.Entity("Navigator.Entities.Chat", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("Discriminator") - .IsRequired() - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("Chat"); - - b.HasDiscriminator("Discriminator").HasValue("Chat"); - }); - - modelBuilder.Entity("Navigator.Entities.Conversation", b => + modelBuilder.Entity("Navigator.Extensions.Store.Entities.Chat", b => { b.Property("Id") .ValueGeneratedOnAdd() .HasColumnType("TEXT"); - b.Property("Discriminator") + b.Property("Data") .IsRequired() .HasColumnType("TEXT"); - b.HasKey("Id"); - - b.ToTable("Conversation"); - - b.HasDiscriminator("Discriminator").HasValue("Conversation"); - }); - - modelBuilder.Entity("Navigator.Entities.User", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("Discriminator") - .IsRequired() + b.Property("FirstInteractionAt") .HasColumnType("TEXT"); b.HasKey("Id"); - b.ToTable("User"); - - b.HasDiscriminator("Discriminator").HasValue("User"); + b.ToTable("Chats"); }); - modelBuilder.Entity("Navigator.Extensions.Store.Entities.UniversalProfile", b => + modelBuilder.Entity("Navigator.Extensions.Store.Entities.Conversation", b => { b.Property("Id") .ValueGeneratedOnAdd() .HasColumnType("TEXT"); - b.Property("CreatedAt") - .HasColumnType("TEXT"); - - b.Property("Discriminator") - .IsRequired() - .HasColumnType("TEXT"); - - b.Property("Identification") - .HasColumnType("TEXT"); - - b.Property("LastUpdatedAt") + b.Property("ChatId") .HasColumnType("TEXT"); - b.Property("Provider") + b.Property("Data") .IsRequired() .HasColumnType("TEXT"); - b.HasKey("Id"); - - b.ToTable("Profiles"); - - b.HasDiscriminator("Discriminator").HasValue("UniversalProfile"); - }); - - modelBuilder.Entity("Navigator.Extensions.Store.Entities.ChatProfile", b => - { - b.HasBaseType("Navigator.Extensions.Store.Entities.UniversalProfile"); - - b.Property("DataId") - .HasColumnType("TEXT") - .HasColumnName("ChatProfile_DataId"); - - b.Property("UniversalChatId") - .HasColumnType("TEXT"); - - b.HasIndex("DataId") - .IsUnique(); - - b.HasIndex("UniversalChatId"); - - b.HasDiscriminator().HasValue("ChatProfile"); - }); - - modelBuilder.Entity("Navigator.Extensions.Store.Entities.ConversationProfile", b => - { - b.HasBaseType("Navigator.Extensions.Store.Entities.UniversalProfile"); - - b.Property("DataId") - .HasColumnType("TEXT"); - - b.Property("UniversalConversationId") - .HasColumnType("TEXT"); - - b.HasIndex("DataId") - .IsUnique(); - - b.HasIndex("UniversalConversationId"); - - b.HasDiscriminator().HasValue("ConversationProfile"); - }); - - modelBuilder.Entity("Navigator.Extensions.Store.Entities.Chat", b => - { - b.HasBaseType("Navigator.Entities.Chat"); - - b.Property("FirstInteractionAt") - .HasColumnType("TEXT"); - - b.HasDiscriminator().HasValue("Chat"); - }); - - modelBuilder.Entity("Navigator.Extensions.Store.Entities.Conversation", b => - { - b.HasBaseType("Navigator.Entities.Conversation"); - - b.Property("ChatId") - .HasColumnType("TEXT"); - b.Property("FirstInteractionAt") .HasColumnType("TEXT"); b.Property("UserId") .HasColumnType("TEXT"); + b.HasKey("Id"); + b.HasIndex("ChatId"); b.HasIndex("UserId"); - b.HasDiscriminator().HasValue("Conversation"); + b.ToTable("Conversations"); }); modelBuilder.Entity("Navigator.Extensions.Store.Entities.User", b => { - b.HasBaseType("Navigator.Entities.User"); - - b.Property("FirstInteractionAt") - .HasColumnType("TEXT"); - - b.HasDiscriminator().HasValue("User"); - }); - - modelBuilder.Entity("Navigator.Extensions.Store.Entities.UserProfile", b => - { - b.HasBaseType("Navigator.Extensions.Store.Entities.UniversalProfile"); - - b.Property("DataId") - .HasColumnType("TEXT") - .HasColumnName("UserProfile_DataId"); - - b.Property("UniversalUserId") - .HasColumnType("TEXT"); - - b.HasIndex("DataId") - .IsUnique(); - - b.HasIndex("UniversalUserId"); - - b.HasDiscriminator().HasValue("UserProfile"); - }); - - modelBuilder.Entity("Navigator.Providers.Telegram.Entities.TelegramChat", b => - { - b.HasBaseType("Navigator.Entities.Chat"); - - b.Property("ExternalIdentifier") - .HasColumnType("INTEGER"); - - b.Property("Title") + b.Property("Id") + .ValueGeneratedOnAdd() .HasColumnType("TEXT"); - b.HasDiscriminator().HasValue("TelegramChat"); - }); - - modelBuilder.Entity("Navigator.Providers.Telegram.Entities.TelegramConversation", b => - { - b.HasBaseType("Navigator.Entities.Conversation"); - - b.Property("ChatId") - .HasColumnType("TEXT") - .HasColumnName("TelegramConversation_ChatId"); - - b.Property("UserId") - .HasColumnType("TEXT") - .HasColumnName("TelegramConversation_UserId"); - - b.HasIndex("ChatId"); - - b.HasIndex("UserId"); - - b.HasDiscriminator().HasValue("TelegramConversation"); - }); - - modelBuilder.Entity("Navigator.Providers.Telegram.Entities.TelegramUser", b => - { - b.HasBaseType("Navigator.Entities.User"); - - b.Property("ExternalIdentifier") - .HasColumnType("INTEGER"); - - b.Property("FirstName") + b.Property("Data") .IsRequired() .HasColumnType("TEXT"); - b.Property("LanguageCode") - .HasColumnType("TEXT"); - - b.Property("LastName") - .HasColumnType("TEXT"); - - b.Property("Username") + b.Property("FirstInteractionAt") .HasColumnType("TEXT"); - b.HasDiscriminator().HasValue("TelegramUser"); - }); - - modelBuilder.Entity("Navigator.Extensions.Store.Telegram.TelegramChatProfile", b => - { - b.HasBaseType("Navigator.Extensions.Store.Entities.ChatProfile"); - - b.HasDiscriminator().HasValue("TelegramChatProfile"); - }); - - modelBuilder.Entity("Navigator.Extensions.Store.Telegram.TelegramConversationProfile", b => - { - b.HasBaseType("Navigator.Extensions.Store.Entities.ConversationProfile"); - - b.HasDiscriminator().HasValue("TelegramConversationProfile"); - }); - - modelBuilder.Entity("Navigator.Extensions.Store.Telegram.TelegramUserProfile", b => - { - b.HasBaseType("Navigator.Extensions.Store.Entities.UserProfile"); - - b.HasDiscriminator().HasValue("TelegramUserProfile"); - }); - - modelBuilder.Entity("Navigator.Extensions.Store.Entities.ChatProfile", b => - { - b.HasOne("Navigator.Entities.Chat", "Data") - .WithOne() - .HasForeignKey("Navigator.Extensions.Store.Entities.ChatProfile", "DataId"); - - b.HasOne("Navigator.Extensions.Store.Entities.Chat", null) - .WithMany("Profiles") - .HasForeignKey("UniversalChatId"); - - b.Navigation("Data"); - }); - - modelBuilder.Entity("Navigator.Extensions.Store.Entities.ConversationProfile", b => - { - b.HasOne("Navigator.Entities.Conversation", "Data") - .WithOne() - .HasForeignKey("Navigator.Extensions.Store.Entities.ConversationProfile", "DataId"); - - b.HasOne("Navigator.Extensions.Store.Entities.Conversation", null) - .WithMany("Profiles") - .HasForeignKey("UniversalConversationId"); + b.HasKey("Id"); - b.Navigation("Data"); + b.ToTable("Users"); }); modelBuilder.Entity("Navigator.Extensions.Store.Entities.Conversation", b => @@ -315,55 +100,14 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.Navigation("User"); }); - modelBuilder.Entity("Navigator.Extensions.Store.Entities.UserProfile", b => - { - b.HasOne("Navigator.Entities.User", "Data") - .WithOne() - .HasForeignKey("Navigator.Extensions.Store.Entities.UserProfile", "DataId"); - - b.HasOne("Navigator.Extensions.Store.Entities.User", null) - .WithMany("Profiles") - .HasForeignKey("UniversalUserId"); - - b.Navigation("Data"); - }); - - modelBuilder.Entity("Navigator.Providers.Telegram.Entities.TelegramConversation", b => - { - b.HasOne("Navigator.Providers.Telegram.Entities.TelegramChat", "Chat") - .WithMany() - .HasForeignKey("ChatId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.HasOne("Navigator.Providers.Telegram.Entities.TelegramUser", "User") - .WithMany() - .HasForeignKey("UserId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("Chat"); - - b.Navigation("User"); - }); - modelBuilder.Entity("Navigator.Extensions.Store.Entities.Chat", b => { b.Navigation("Conversations"); - - b.Navigation("Profiles"); - }); - - modelBuilder.Entity("Navigator.Extensions.Store.Entities.Conversation", b => - { - b.Navigation("Profiles"); }); modelBuilder.Entity("Navigator.Extensions.Store.Entities.User", b => { b.Navigation("Conversations"); - - b.Navigation("Profiles"); }); #pragma warning restore 612, 618 } diff --git a/src/Navigator/Entities/Conversation.cs b/src/Navigator/Entities/Conversation.cs index fc4d36f..01046ee 100644 --- a/src/Navigator/Entities/Conversation.cs +++ b/src/Navigator/Entities/Conversation.cs @@ -14,9 +14,9 @@ protected Conversation() { } - protected Conversation(User user, Chat chat) + protected Conversation(User user, Chat? chat) { - Id = new Guid(SHA256.HashData(Encoding.UTF8.GetBytes($"{user.Id}+{chat.Id}")).Take(16).ToArray()); + Id = new Guid(SHA256.HashData(Encoding.UTF8.GetBytes($"{user.Id}+{chat?.Id}")).Take(16).ToArray()); User = user; Chat = chat; @@ -32,5 +32,5 @@ protected Conversation(User user, Chat chat) /// /// Chat /// - public Chat Chat { get; set; } + public Chat? Chat { get; set; } } \ No newline at end of file From 719e13b9f225570af09e7630be052a9745a0f411 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 4 Apr 2022 13:32:29 +0200 Subject: [PATCH 270/304] feat: improve metadata of projects --- .../Navigator.Extensions.Cooldown.csproj | 15 +++++++++++++-- .../Navigator.Extensions.Store.Telegram.csproj | 13 ++++++++++++- .../Navigator.Extensions.Store.csproj | 13 ++++++++++++- .../Navigator.Providers.Telegram.csproj | 14 +++++++------- src/Navigator/Navigator.csproj | 18 ++++++++++++------ 5 files changed, 56 insertions(+), 17 deletions(-) diff --git a/src/Navigator.Extensions.Cooldown/Navigator.Extensions.Cooldown.csproj b/src/Navigator.Extensions.Cooldown/Navigator.Extensions.Cooldown.csproj index ca35656..b80a304 100644 --- a/src/Navigator.Extensions.Cooldown/Navigator.Extensions.Cooldown.csproj +++ b/src/Navigator.Extensions.Cooldown/Navigator.Extensions.Cooldown.csproj @@ -1,9 +1,20 @@ - + net6.0 - enable + true enable + true + Navigator.Extensions.Cooldown + Lucas Maximiliano Marino + Drop-in cooldown extension for Navigator Framework bots + https://github.com/navigatorframework/navigator + https://github.com/navigatorframework/navigator + https://raw.githubusercontent.com/navigatorframework/navigator/master/assets/logo.png + Cooldown, Bot, Extension, Navigator + true + AGPL-3.0-only + Copyright © Lucas Maximiliano Marino 2022 diff --git a/src/Navigator.Extensions.Store.Telegram/Navigator.Extensions.Store.Telegram.csproj b/src/Navigator.Extensions.Store.Telegram/Navigator.Extensions.Store.Telegram.csproj index 55c98b6..df0cdb6 100644 --- a/src/Navigator.Extensions.Store.Telegram/Navigator.Extensions.Store.Telegram.csproj +++ b/src/Navigator.Extensions.Store.Telegram/Navigator.Extensions.Store.Telegram.csproj @@ -2,8 +2,19 @@ net6.0 - enable + true enable + true + Navigator.Extensions.Store + Lucas Maximiliano Marino + Telegram provider persistence implementation for Navigator Store Extension. + https://github.com/navigatorframework/navigator + https://github.com/navigatorframework/navigator + https://raw.githubusercontent.com/navigatorframework/navigator/master/assets/logo.png + Store, Bot, Telegram, Navigator + true + AGPL-3.0-only + Copyright © Lucas Maximiliano Marino 2022 diff --git a/src/Navigator.Extensions.Store/Navigator.Extensions.Store.csproj b/src/Navigator.Extensions.Store/Navigator.Extensions.Store.csproj index aecea51..8263d91 100644 --- a/src/Navigator.Extensions.Store/Navigator.Extensions.Store.csproj +++ b/src/Navigator.Extensions.Store/Navigator.Extensions.Store.csproj @@ -2,8 +2,19 @@ net6.0 - enable + true enable + true + Navigator.Extensions.Store + Lucas Maximiliano Marino + Persistence extension for Navigator Framework bots, requires provider implementations. + https://github.com/navigatorframework/navigator + https://github.com/navigatorframework/navigator + https://raw.githubusercontent.com/navigatorframework/navigator/master/assets/logo.png + Store, Bot, Extension, Navigator + true + AGPL-3.0-only + Copyright © Lucas Maximiliano Marino 2022 diff --git a/src/Navigator.Providers.Telegram/Navigator.Providers.Telegram.csproj b/src/Navigator.Providers.Telegram/Navigator.Providers.Telegram.csproj index 380430d..84629dd 100644 --- a/src/Navigator.Providers.Telegram/Navigator.Providers.Telegram.csproj +++ b/src/Navigator.Providers.Telegram/Navigator.Providers.Telegram.csproj @@ -2,21 +2,21 @@ net6.0 + true enable true - Telegram Provider for Navigator + Navigator.Providers.Telegram Lucas Maximiliano Marino - Telegram provider for Navigator Framework. Implementation based on Telegram.Bot. + Telegram provider for Navigator Framework. Implementation based on Telegram.Bot https://github.com/navigatorframework/navigator - https://github.com/navigatorframework/navigator/blob/master/LICENSE https://github.com/navigatorframework/navigator + https://raw.githubusercontent.com/navigatorframework/navigator/master/assets/logo.png Telegram, Bot, Framework, Navigator true - Copyright © Lucas Maximiliano Marino 2021 - https://raw.githubusercontent.com/navigatorframework/navigator/master/assets/logo.png + AGPL-3.0-only + Copyright © Lucas Maximiliano Marino 2022 - - + diff --git a/src/Navigator/Navigator.csproj b/src/Navigator/Navigator.csproj index 99a0901..5eeaab4 100644 --- a/src/Navigator/Navigator.csproj +++ b/src/Navigator/Navigator.csproj @@ -2,20 +2,26 @@ net6.0 + true enable true - Navigator Framework + Navigator Lucas Maximiliano Marino - A highly opinionated universal bot framework. + A highly opinionated universal bot framework for .NET https://github.com/navigatorframework/navigator - https://github.com/navigatorframework/navigator/blob/master/LICENSE https://github.com/navigatorframework/navigator + https://raw.githubusercontent.com/navigatorframework/navigator/master/assets/logo.png + README.md Telegram, Bot, Framework, Navigator true - Copyright © Lucas Maximiliano Marino 2021 - https://raw.githubusercontent.com/navigatorframework/navigator/master/assets/logo.png + AGPL-3.0-only + Copyright © Lucas Maximiliano Marino 2022 - + + + + + From 496277a76c37178fb56d60f41a513f65ce9bfb84 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 4 Apr 2022 14:54:12 +0200 Subject: [PATCH 271/304] build: add pipeline for navigator base package --- .github/workflows/package.navigator.yml | 80 +++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 .github/workflows/package.navigator.yml diff --git a/.github/workflows/package.navigator.yml b/.github/workflows/package.navigator.yml new file mode 100644 index 0000000..96b549e --- /dev/null +++ b/.github/workflows/package.navigator.yml @@ -0,0 +1,80 @@ +name: Build & Publish - Navigator +on: + push: + pull_request: + release: + types: + - published +env: + # Stop wasting time caching packages + DOTNET_SKIP_FIRST_TIME_EXPERIENCE: true + # Disable sending usage data to Microsoft + DOTNET_CLI_TELEMETRY_OPTOUT: true + # Project name to pack and publish + PROJECT_NAME: Navigator +jobs: + build: + runs-on: ${{ matrix.os }} + strategy: + matrix: + os: [ ubuntu-latest ] + steps: + - name: Checkout + uses: actions/checkout@v2 + - name: Setup .NET + uses: actions/setup-dotnet@v1 + with: + dotnet-version: '6.0.x' + - name: Restore + working-directory: ./src + run: dotnet restore + - name: Build + working-directory: ./src + run: dotnet build -c Release --no-restore + - name: Test + working-directory: ./src + run: dotnet test -c Release + - name: Pack + if: matrix.os == 'ubuntu-latest' + run: dotnet pack -v normal -c Release --no-restore --include-symbols --include-source -p:PackageVersion=$GITHUB_RUN_ID src/$PROJECT_NAME.sln + # - name: Upload Artifact + # if: matrix.os == 'ubuntu-latest' + # uses: actions/upload-artifact@v2 + # with: + # name: nupkg + # path: ./src/${{ env.PROJECT_NAME }}/bin/Release/*.nupkg + publish: + needs: build + if: github.event_name == 'release' + env: + # GitHub Packages Feed settings + GITHUB_FEED: https://nuget.pkg.github.com/navigatorframework/ + GITHUB_USER: navigatorframeworkbot + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + # Official NuGet Feed settings + NUGET_FEED: https://api.nuget.org/v3/index.json + NUGET_KEY: ${{ secrets.NUGET_KEY }} + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v2 + - name: Setup .NET + uses: actions/setup-dotnet@v1 + with: + dotnet-version: '6.0.x' + - name: Create Release NuGet package + run: | + arrTag=(${GITHUB_REF//\// }) + VERSION="${arrTag[2]}" + echo Version: $VERSION + VERSION="${VERSION//v}" + echo Clean Version: $VERSION + dotnet pack -v normal -c Release --include-symbols --include-source -p:PackageVersion=$VERSION -o nupkg src/$PROJECT_NAME.sln + - name: Push to GitHub Feed + run: | + for f in ./nupkg/*.nupkg + do + curl -vX PUT -u "$GITHUB_USER:$GITHUB_TOKEN" -F package=@$f $GITHUB_FEED + done + - name: Push to NuGet Feed + run: dotnet nuget push ./nupkg/*.nupkg --source $NUGET_FEED --skip-duplicate --api-key $NUGET_KEY From f570033cd1803f1a9f597c64f3cbca8ffa9d0c9f Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 4 Apr 2022 15:05:09 +0200 Subject: [PATCH 272/304] build: add pipeline for navigator.extensions.store --- .../package.navigator.extensions.store.yml | 80 +++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 .github/workflows/package.navigator.extensions.store.yml diff --git a/.github/workflows/package.navigator.extensions.store.yml b/.github/workflows/package.navigator.extensions.store.yml new file mode 100644 index 0000000..36787dd --- /dev/null +++ b/.github/workflows/package.navigator.extensions.store.yml @@ -0,0 +1,80 @@ +name: Build & Publish - Navigator.Extensions.Store +on: + push: + pull_request: + release: + types: + - published +env: + # Stop wasting time caching packages + DOTNET_SKIP_FIRST_TIME_EXPERIENCE: true + # Disable sending usage data to Microsoft + DOTNET_CLI_TELEMETRY_OPTOUT: true + # Project name to pack and publish + PROJECT_NAME: Navigator.Extensions.Store +jobs: + build: + runs-on: ${{ matrix.os }} + strategy: + matrix: + os: [ ubuntu-latest ] + steps: + - name: Checkout + uses: actions/checkout@v2 + - name: Setup .NET + uses: actions/setup-dotnet@v1 + with: + dotnet-version: '6.0.x' + - name: Restore + working-directory: ./src + run: dotnet restore + - name: Build + working-directory: ./src + run: dotnet build -c Release --no-restore + - name: Test + working-directory: ./src + run: dotnet test -c Release + - name: Pack + if: matrix.os == 'ubuntu-latest' + run: dotnet pack -v normal -c Release --no-restore --include-symbols --include-source -p:PackageVersion=$GITHUB_RUN_ID src/$PROJECT_NAME.sln + # - name: Upload Artifact + # if: matrix.os == 'ubuntu-latest' + # uses: actions/upload-artifact@v2 + # with: + # name: nupkg + # path: ./src/${{ env.PROJECT_NAME }}/bin/Release/*.nupkg + publish: + needs: build + if: github.event_name == 'release' + env: + # GitHub Packages Feed settings + GITHUB_FEED: https://nuget.pkg.github.com/navigatorframework/ + GITHUB_USER: navigatorframeworkbot + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + # Official NuGet Feed settings + NUGET_FEED: https://api.nuget.org/v3/index.json + NUGET_KEY: ${{ secrets.NUGET_KEY }} + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v2 + - name: Setup .NET + uses: actions/setup-dotnet@v1 + with: + dotnet-version: '6.0.x' + - name: Create Release NuGet package + run: | + arrTag=(${GITHUB_REF//\// }) + VERSION="${arrTag[2]}" + echo Version: $VERSION + VERSION="${VERSION//v}" + echo Clean Version: $VERSION + dotnet pack -v normal -c Release --include-symbols --include-source -p:PackageVersion=$VERSION -o nupkg src/$PROJECT_NAME.sln + - name: Push to GitHub Feed + run: | + for f in ./nupkg/*.nupkg + do + curl -vX PUT -u "$GITHUB_USER:$GITHUB_TOKEN" -F package=@$f $GITHUB_FEED + done + - name: Push to NuGet Feed + run: dotnet nuget push ./nupkg/*.nupkg --source $NUGET_FEED --skip-duplicate --api-key $NUGET_KEY From a90e507fc027a9fc0b798c8f2bab2667b35481c6 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 4 Apr 2022 15:05:28 +0200 Subject: [PATCH 273/304] build: add pipeline for navigator.extensions.store.telegram --- ...ge.navigator.extensions.store.telegram.yml | 80 +++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 .github/workflows/package.navigator.extensions.store.telegram.yml diff --git a/.github/workflows/package.navigator.extensions.store.telegram.yml b/.github/workflows/package.navigator.extensions.store.telegram.yml new file mode 100644 index 0000000..2950ebd --- /dev/null +++ b/.github/workflows/package.navigator.extensions.store.telegram.yml @@ -0,0 +1,80 @@ +name: Build & Publish - Navigator.Extensions.Store.Telegrma +on: + push: + pull_request: + release: + types: + - published +env: + # Stop wasting time caching packages + DOTNET_SKIP_FIRST_TIME_EXPERIENCE: true + # Disable sending usage data to Microsoft + DOTNET_CLI_TELEMETRY_OPTOUT: true + # Project name to pack and publish + PROJECT_NAME: Navigator.Extensions.Store.Telegram +jobs: + build: + runs-on: ${{ matrix.os }} + strategy: + matrix: + os: [ ubuntu-latest ] + steps: + - name: Checkout + uses: actions/checkout@v2 + - name: Setup .NET + uses: actions/setup-dotnet@v1 + with: + dotnet-version: '6.0.x' + - name: Restore + working-directory: ./src + run: dotnet restore + - name: Build + working-directory: ./src + run: dotnet build -c Release --no-restore + - name: Test + working-directory: ./src + run: dotnet test -c Release + - name: Pack + if: matrix.os == 'ubuntu-latest' + run: dotnet pack -v normal -c Release --no-restore --include-symbols --include-source -p:PackageVersion=$GITHUB_RUN_ID src/$PROJECT_NAME.sln + # - name: Upload Artifact + # if: matrix.os == 'ubuntu-latest' + # uses: actions/upload-artifact@v2 + # with: + # name: nupkg + # path: ./src/${{ env.PROJECT_NAME }}/bin/Release/*.nupkg + publish: + needs: build + if: github.event_name == 'release' + env: + # GitHub Packages Feed settings + GITHUB_FEED: https://nuget.pkg.github.com/navigatorframework/ + GITHUB_USER: navigatorframeworkbot + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + # Official NuGet Feed settings + NUGET_FEED: https://api.nuget.org/v3/index.json + NUGET_KEY: ${{ secrets.NUGET_KEY }} + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v2 + - name: Setup .NET + uses: actions/setup-dotnet@v1 + with: + dotnet-version: '6.0.x' + - name: Create Release NuGet package + run: | + arrTag=(${GITHUB_REF//\// }) + VERSION="${arrTag[2]}" + echo Version: $VERSION + VERSION="${VERSION//v}" + echo Clean Version: $VERSION + dotnet pack -v normal -c Release --include-symbols --include-source -p:PackageVersion=$VERSION -o nupkg src/$PROJECT_NAME.sln + - name: Push to GitHub Feed + run: | + for f in ./nupkg/*.nupkg + do + curl -vX PUT -u "$GITHUB_USER:$GITHUB_TOKEN" -F package=@$f $GITHUB_FEED + done + - name: Push to NuGet Feed + run: dotnet nuget push ./nupkg/*.nupkg --source $NUGET_FEED --skip-duplicate --api-key $NUGET_KEY From 670f5f0fc22d36251076ab5d36c90269fd5e045d Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 4 Apr 2022 15:05:46 +0200 Subject: [PATCH 274/304] build: add pipeline for navigator.providers.telegram --- .../package.navigator.providers.telegram.yml | 80 +++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 .github/workflows/package.navigator.providers.telegram.yml diff --git a/.github/workflows/package.navigator.providers.telegram.yml b/.github/workflows/package.navigator.providers.telegram.yml new file mode 100644 index 0000000..5e12a98 --- /dev/null +++ b/.github/workflows/package.navigator.providers.telegram.yml @@ -0,0 +1,80 @@ +name: Build & Publish - Navigator.Providers.Telegram +on: + push: + pull_request: + release: + types: + - published +env: + # Stop wasting time caching packages + DOTNET_SKIP_FIRST_TIME_EXPERIENCE: true + # Disable sending usage data to Microsoft + DOTNET_CLI_TELEMETRY_OPTOUT: true + # Project name to pack and publish + PROJECT_NAME: Navigator.Providers.Telegram +jobs: + build: + runs-on: ${{ matrix.os }} + strategy: + matrix: + os: [ ubuntu-latest ] + steps: + - name: Checkout + uses: actions/checkout@v2 + - name: Setup .NET + uses: actions/setup-dotnet@v1 + with: + dotnet-version: '6.0.x' + - name: Restore + working-directory: ./src + run: dotnet restore + - name: Build + working-directory: ./src + run: dotnet build -c Release --no-restore + - name: Test + working-directory: ./src + run: dotnet test -c Release + - name: Pack + if: matrix.os == 'ubuntu-latest' + run: dotnet pack -v normal -c Release --no-restore --include-symbols --include-source -p:PackageVersion=$GITHUB_RUN_ID src/$PROJECT_NAME.sln + # - name: Upload Artifact + # if: matrix.os == 'ubuntu-latest' + # uses: actions/upload-artifact@v2 + # with: + # name: nupkg + # path: ./src/${{ env.PROJECT_NAME }}/bin/Release/*.nupkg + publish: + needs: build + if: github.event_name == 'release' + env: + # GitHub Packages Feed settings + GITHUB_FEED: https://nuget.pkg.github.com/navigatorframework/ + GITHUB_USER: navigatorframeworkbot + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + # Official NuGet Feed settings + NUGET_FEED: https://api.nuget.org/v3/index.json + NUGET_KEY: ${{ secrets.NUGET_KEY }} + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v2 + - name: Setup .NET + uses: actions/setup-dotnet@v1 + with: + dotnet-version: '6.0.x' + - name: Create Release NuGet package + run: | + arrTag=(${GITHUB_REF//\// }) + VERSION="${arrTag[2]}" + echo Version: $VERSION + VERSION="${VERSION//v}" + echo Clean Version: $VERSION + dotnet pack -v normal -c Release --include-symbols --include-source -p:PackageVersion=$VERSION -o nupkg src/$PROJECT_NAME.sln + - name: Push to GitHub Feed + run: | + for f in ./nupkg/*.nupkg + do + curl -vX PUT -u "$GITHUB_USER:$GITHUB_TOKEN" -F package=@$f $GITHUB_FEED + done + - name: Push to NuGet Feed + run: dotnet nuget push ./nupkg/*.nupkg --source $NUGET_FEED --skip-duplicate --api-key $NUGET_KEY From 97615b76595c9dc13cf6cc6d246df283be6aa245 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 4 Apr 2022 15:06:04 +0200 Subject: [PATCH 275/304] build: add pipeline for navigator.extensions.cooldown --- .../package.navigator.extensions.cooldown.yml | 80 +++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 .github/workflows/package.navigator.extensions.cooldown.yml diff --git a/.github/workflows/package.navigator.extensions.cooldown.yml b/.github/workflows/package.navigator.extensions.cooldown.yml new file mode 100644 index 0000000..be1cc53 --- /dev/null +++ b/.github/workflows/package.navigator.extensions.cooldown.yml @@ -0,0 +1,80 @@ +name: Build & Publish - Navigator.Extensions.Cooldown +on: + push: + pull_request: + release: + types: + - published +env: + # Stop wasting time caching packages + DOTNET_SKIP_FIRST_TIME_EXPERIENCE: true + # Disable sending usage data to Microsoft + DOTNET_CLI_TELEMETRY_OPTOUT: true + # Project name to pack and publish + PROJECT_NAME: Navigator.Extensions.Cooldown +jobs: + build: + runs-on: ${{ matrix.os }} + strategy: + matrix: + os: [ ubuntu-latest ] + steps: + - name: Checkout + uses: actions/checkout@v2 + - name: Setup .NET + uses: actions/setup-dotnet@v1 + with: + dotnet-version: '6.0.x' + - name: Restore + working-directory: ./src + run: dotnet restore + - name: Build + working-directory: ./src + run: dotnet build -c Release --no-restore + - name: Test + working-directory: ./src + run: dotnet test -c Release + - name: Pack + if: matrix.os == 'ubuntu-latest' + run: dotnet pack -v normal -c Release --no-restore --include-symbols --include-source -p:PackageVersion=$GITHUB_RUN_ID src/$PROJECT_NAME.sln + # - name: Upload Artifact + # if: matrix.os == 'ubuntu-latest' + # uses: actions/upload-artifact@v2 + # with: + # name: nupkg + # path: ./src/${{ env.PROJECT_NAME }}/bin/Release/*.nupkg + publish: + needs: build + if: github.event_name == 'release' + env: + # GitHub Packages Feed settings + GITHUB_FEED: https://nuget.pkg.github.com/navigatorframework/ + GITHUB_USER: navigatorframeworkbot + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + # Official NuGet Feed settings + NUGET_FEED: https://api.nuget.org/v3/index.json + NUGET_KEY: ${{ secrets.NUGET_KEY }} + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v2 + - name: Setup .NET + uses: actions/setup-dotnet@v1 + with: + dotnet-version: '6.0.x' + - name: Create Release NuGet package + run: | + arrTag=(${GITHUB_REF//\// }) + VERSION="${arrTag[2]}" + echo Version: $VERSION + VERSION="${VERSION//v}" + echo Clean Version: $VERSION + dotnet pack -v normal -c Release --include-symbols --include-source -p:PackageVersion=$VERSION -o nupkg src/$PROJECT_NAME.sln + - name: Push to GitHub Feed + run: | + for f in ./nupkg/*.nupkg + do + curl -vX PUT -u "$GITHUB_USER:$GITHUB_TOKEN" -F package=@$f $GITHUB_FEED + done + - name: Push to NuGet Feed + run: dotnet nuget push ./nupkg/*.nupkg --source $NUGET_FEED --skip-duplicate --api-key $NUGET_KEY From 42c097149a24e9e7a1ecf7d77bc92828cfdf1c80 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 4 Apr 2022 15:11:34 +0200 Subject: [PATCH 276/304] fix: delete unnecessary pipelines --- .../package.navigator.extensions.cooldown.yml | 80 ------------------- ...ge.navigator.extensions.store.telegram.yml | 80 ------------------- .../package.navigator.extensions.store.yml | 80 ------------------- .../package.navigator.providers.telegram.yml | 80 ------------------- 4 files changed, 320 deletions(-) delete mode 100644 .github/workflows/package.navigator.extensions.cooldown.yml delete mode 100644 .github/workflows/package.navigator.extensions.store.telegram.yml delete mode 100644 .github/workflows/package.navigator.extensions.store.yml delete mode 100644 .github/workflows/package.navigator.providers.telegram.yml diff --git a/.github/workflows/package.navigator.extensions.cooldown.yml b/.github/workflows/package.navigator.extensions.cooldown.yml deleted file mode 100644 index be1cc53..0000000 --- a/.github/workflows/package.navigator.extensions.cooldown.yml +++ /dev/null @@ -1,80 +0,0 @@ -name: Build & Publish - Navigator.Extensions.Cooldown -on: - push: - pull_request: - release: - types: - - published -env: - # Stop wasting time caching packages - DOTNET_SKIP_FIRST_TIME_EXPERIENCE: true - # Disable sending usage data to Microsoft - DOTNET_CLI_TELEMETRY_OPTOUT: true - # Project name to pack and publish - PROJECT_NAME: Navigator.Extensions.Cooldown -jobs: - build: - runs-on: ${{ matrix.os }} - strategy: - matrix: - os: [ ubuntu-latest ] - steps: - - name: Checkout - uses: actions/checkout@v2 - - name: Setup .NET - uses: actions/setup-dotnet@v1 - with: - dotnet-version: '6.0.x' - - name: Restore - working-directory: ./src - run: dotnet restore - - name: Build - working-directory: ./src - run: dotnet build -c Release --no-restore - - name: Test - working-directory: ./src - run: dotnet test -c Release - - name: Pack - if: matrix.os == 'ubuntu-latest' - run: dotnet pack -v normal -c Release --no-restore --include-symbols --include-source -p:PackageVersion=$GITHUB_RUN_ID src/$PROJECT_NAME.sln - # - name: Upload Artifact - # if: matrix.os == 'ubuntu-latest' - # uses: actions/upload-artifact@v2 - # with: - # name: nupkg - # path: ./src/${{ env.PROJECT_NAME }}/bin/Release/*.nupkg - publish: - needs: build - if: github.event_name == 'release' - env: - # GitHub Packages Feed settings - GITHUB_FEED: https://nuget.pkg.github.com/navigatorframework/ - GITHUB_USER: navigatorframeworkbot - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - # Official NuGet Feed settings - NUGET_FEED: https://api.nuget.org/v3/index.json - NUGET_KEY: ${{ secrets.NUGET_KEY }} - runs-on: ubuntu-latest - steps: - - name: Checkout - uses: actions/checkout@v2 - - name: Setup .NET - uses: actions/setup-dotnet@v1 - with: - dotnet-version: '6.0.x' - - name: Create Release NuGet package - run: | - arrTag=(${GITHUB_REF//\// }) - VERSION="${arrTag[2]}" - echo Version: $VERSION - VERSION="${VERSION//v}" - echo Clean Version: $VERSION - dotnet pack -v normal -c Release --include-symbols --include-source -p:PackageVersion=$VERSION -o nupkg src/$PROJECT_NAME.sln - - name: Push to GitHub Feed - run: | - for f in ./nupkg/*.nupkg - do - curl -vX PUT -u "$GITHUB_USER:$GITHUB_TOKEN" -F package=@$f $GITHUB_FEED - done - - name: Push to NuGet Feed - run: dotnet nuget push ./nupkg/*.nupkg --source $NUGET_FEED --skip-duplicate --api-key $NUGET_KEY diff --git a/.github/workflows/package.navigator.extensions.store.telegram.yml b/.github/workflows/package.navigator.extensions.store.telegram.yml deleted file mode 100644 index 2950ebd..0000000 --- a/.github/workflows/package.navigator.extensions.store.telegram.yml +++ /dev/null @@ -1,80 +0,0 @@ -name: Build & Publish - Navigator.Extensions.Store.Telegrma -on: - push: - pull_request: - release: - types: - - published -env: - # Stop wasting time caching packages - DOTNET_SKIP_FIRST_TIME_EXPERIENCE: true - # Disable sending usage data to Microsoft - DOTNET_CLI_TELEMETRY_OPTOUT: true - # Project name to pack and publish - PROJECT_NAME: Navigator.Extensions.Store.Telegram -jobs: - build: - runs-on: ${{ matrix.os }} - strategy: - matrix: - os: [ ubuntu-latest ] - steps: - - name: Checkout - uses: actions/checkout@v2 - - name: Setup .NET - uses: actions/setup-dotnet@v1 - with: - dotnet-version: '6.0.x' - - name: Restore - working-directory: ./src - run: dotnet restore - - name: Build - working-directory: ./src - run: dotnet build -c Release --no-restore - - name: Test - working-directory: ./src - run: dotnet test -c Release - - name: Pack - if: matrix.os == 'ubuntu-latest' - run: dotnet pack -v normal -c Release --no-restore --include-symbols --include-source -p:PackageVersion=$GITHUB_RUN_ID src/$PROJECT_NAME.sln - # - name: Upload Artifact - # if: matrix.os == 'ubuntu-latest' - # uses: actions/upload-artifact@v2 - # with: - # name: nupkg - # path: ./src/${{ env.PROJECT_NAME }}/bin/Release/*.nupkg - publish: - needs: build - if: github.event_name == 'release' - env: - # GitHub Packages Feed settings - GITHUB_FEED: https://nuget.pkg.github.com/navigatorframework/ - GITHUB_USER: navigatorframeworkbot - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - # Official NuGet Feed settings - NUGET_FEED: https://api.nuget.org/v3/index.json - NUGET_KEY: ${{ secrets.NUGET_KEY }} - runs-on: ubuntu-latest - steps: - - name: Checkout - uses: actions/checkout@v2 - - name: Setup .NET - uses: actions/setup-dotnet@v1 - with: - dotnet-version: '6.0.x' - - name: Create Release NuGet package - run: | - arrTag=(${GITHUB_REF//\// }) - VERSION="${arrTag[2]}" - echo Version: $VERSION - VERSION="${VERSION//v}" - echo Clean Version: $VERSION - dotnet pack -v normal -c Release --include-symbols --include-source -p:PackageVersion=$VERSION -o nupkg src/$PROJECT_NAME.sln - - name: Push to GitHub Feed - run: | - for f in ./nupkg/*.nupkg - do - curl -vX PUT -u "$GITHUB_USER:$GITHUB_TOKEN" -F package=@$f $GITHUB_FEED - done - - name: Push to NuGet Feed - run: dotnet nuget push ./nupkg/*.nupkg --source $NUGET_FEED --skip-duplicate --api-key $NUGET_KEY diff --git a/.github/workflows/package.navigator.extensions.store.yml b/.github/workflows/package.navigator.extensions.store.yml deleted file mode 100644 index 36787dd..0000000 --- a/.github/workflows/package.navigator.extensions.store.yml +++ /dev/null @@ -1,80 +0,0 @@ -name: Build & Publish - Navigator.Extensions.Store -on: - push: - pull_request: - release: - types: - - published -env: - # Stop wasting time caching packages - DOTNET_SKIP_FIRST_TIME_EXPERIENCE: true - # Disable sending usage data to Microsoft - DOTNET_CLI_TELEMETRY_OPTOUT: true - # Project name to pack and publish - PROJECT_NAME: Navigator.Extensions.Store -jobs: - build: - runs-on: ${{ matrix.os }} - strategy: - matrix: - os: [ ubuntu-latest ] - steps: - - name: Checkout - uses: actions/checkout@v2 - - name: Setup .NET - uses: actions/setup-dotnet@v1 - with: - dotnet-version: '6.0.x' - - name: Restore - working-directory: ./src - run: dotnet restore - - name: Build - working-directory: ./src - run: dotnet build -c Release --no-restore - - name: Test - working-directory: ./src - run: dotnet test -c Release - - name: Pack - if: matrix.os == 'ubuntu-latest' - run: dotnet pack -v normal -c Release --no-restore --include-symbols --include-source -p:PackageVersion=$GITHUB_RUN_ID src/$PROJECT_NAME.sln - # - name: Upload Artifact - # if: matrix.os == 'ubuntu-latest' - # uses: actions/upload-artifact@v2 - # with: - # name: nupkg - # path: ./src/${{ env.PROJECT_NAME }}/bin/Release/*.nupkg - publish: - needs: build - if: github.event_name == 'release' - env: - # GitHub Packages Feed settings - GITHUB_FEED: https://nuget.pkg.github.com/navigatorframework/ - GITHUB_USER: navigatorframeworkbot - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - # Official NuGet Feed settings - NUGET_FEED: https://api.nuget.org/v3/index.json - NUGET_KEY: ${{ secrets.NUGET_KEY }} - runs-on: ubuntu-latest - steps: - - name: Checkout - uses: actions/checkout@v2 - - name: Setup .NET - uses: actions/setup-dotnet@v1 - with: - dotnet-version: '6.0.x' - - name: Create Release NuGet package - run: | - arrTag=(${GITHUB_REF//\// }) - VERSION="${arrTag[2]}" - echo Version: $VERSION - VERSION="${VERSION//v}" - echo Clean Version: $VERSION - dotnet pack -v normal -c Release --include-symbols --include-source -p:PackageVersion=$VERSION -o nupkg src/$PROJECT_NAME.sln - - name: Push to GitHub Feed - run: | - for f in ./nupkg/*.nupkg - do - curl -vX PUT -u "$GITHUB_USER:$GITHUB_TOKEN" -F package=@$f $GITHUB_FEED - done - - name: Push to NuGet Feed - run: dotnet nuget push ./nupkg/*.nupkg --source $NUGET_FEED --skip-duplicate --api-key $NUGET_KEY diff --git a/.github/workflows/package.navigator.providers.telegram.yml b/.github/workflows/package.navigator.providers.telegram.yml deleted file mode 100644 index 5e12a98..0000000 --- a/.github/workflows/package.navigator.providers.telegram.yml +++ /dev/null @@ -1,80 +0,0 @@ -name: Build & Publish - Navigator.Providers.Telegram -on: - push: - pull_request: - release: - types: - - published -env: - # Stop wasting time caching packages - DOTNET_SKIP_FIRST_TIME_EXPERIENCE: true - # Disable sending usage data to Microsoft - DOTNET_CLI_TELEMETRY_OPTOUT: true - # Project name to pack and publish - PROJECT_NAME: Navigator.Providers.Telegram -jobs: - build: - runs-on: ${{ matrix.os }} - strategy: - matrix: - os: [ ubuntu-latest ] - steps: - - name: Checkout - uses: actions/checkout@v2 - - name: Setup .NET - uses: actions/setup-dotnet@v1 - with: - dotnet-version: '6.0.x' - - name: Restore - working-directory: ./src - run: dotnet restore - - name: Build - working-directory: ./src - run: dotnet build -c Release --no-restore - - name: Test - working-directory: ./src - run: dotnet test -c Release - - name: Pack - if: matrix.os == 'ubuntu-latest' - run: dotnet pack -v normal -c Release --no-restore --include-symbols --include-source -p:PackageVersion=$GITHUB_RUN_ID src/$PROJECT_NAME.sln - # - name: Upload Artifact - # if: matrix.os == 'ubuntu-latest' - # uses: actions/upload-artifact@v2 - # with: - # name: nupkg - # path: ./src/${{ env.PROJECT_NAME }}/bin/Release/*.nupkg - publish: - needs: build - if: github.event_name == 'release' - env: - # GitHub Packages Feed settings - GITHUB_FEED: https://nuget.pkg.github.com/navigatorframework/ - GITHUB_USER: navigatorframeworkbot - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - # Official NuGet Feed settings - NUGET_FEED: https://api.nuget.org/v3/index.json - NUGET_KEY: ${{ secrets.NUGET_KEY }} - runs-on: ubuntu-latest - steps: - - name: Checkout - uses: actions/checkout@v2 - - name: Setup .NET - uses: actions/setup-dotnet@v1 - with: - dotnet-version: '6.0.x' - - name: Create Release NuGet package - run: | - arrTag=(${GITHUB_REF//\// }) - VERSION="${arrTag[2]}" - echo Version: $VERSION - VERSION="${VERSION//v}" - echo Clean Version: $VERSION - dotnet pack -v normal -c Release --include-symbols --include-source -p:PackageVersion=$VERSION -o nupkg src/$PROJECT_NAME.sln - - name: Push to GitHub Feed - run: | - for f in ./nupkg/*.nupkg - do - curl -vX PUT -u "$GITHUB_USER:$GITHUB_TOKEN" -F package=@$f $GITHUB_FEED - done - - name: Push to NuGet Feed - run: dotnet nuget push ./nupkg/*.nupkg --source $NUGET_FEED --skip-duplicate --api-key $NUGET_KEY From ade35b3392160899988f32b62ce173b4de6b3a0f Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 4 Apr 2022 16:08:28 +0200 Subject: [PATCH 277/304] feat: add EditedChannelPostAction --- .../Updates/EditedChannelPostAction.cs | 21 +++++++++++++++++++ .../TelegramMiddleware.cs | 2 +- 2 files changed, 22 insertions(+), 1 deletion(-) create mode 100644 src/Navigator.Providers.Telegram/Actions/Updates/EditedChannelPostAction.cs diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/EditedChannelPostAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/EditedChannelPostAction.cs new file mode 100644 index 0000000..25e5ca8 --- /dev/null +++ b/src/Navigator.Providers.Telegram/Actions/Updates/EditedChannelPostAction.cs @@ -0,0 +1,21 @@ +using Navigator.Actions; +using Navigator.Actions.Attributes; +using Navigator.Context; + +namespace Navigator.Providers.Telegram.Actions.Updates; + +/// +/// TODO +/// +[ActionType(nameof(EditedChannelPostAction))] +public abstract class EditedChannelPostAction : BaseAction +{ + /// + protected EditedChannelPostAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) + { + //TODO + } + + + +} \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/TelegramMiddleware.cs b/src/Navigator.Providers.Telegram/TelegramMiddleware.cs index 3538b9e..f808c50 100644 --- a/src/Navigator.Providers.Telegram/TelegramMiddleware.cs +++ b/src/Navigator.Providers.Telegram/TelegramMiddleware.cs @@ -84,7 +84,7 @@ await _navigatorContextFactory.Supply(builder => UpdateType.CallbackQuery => nameof(CallbackQueryAction), UpdateType.EditedMessage => nameof(EditedMessageAction), UpdateType.ChannelPost => nameof(ChannelPostAction), - // UpdateType.EditedChannelPost => ActionType.EditedChannelPost, + UpdateType.EditedChannelPost => nameof(EditedChannelPostAction), UpdateType.ShippingQuery => nameof(ShippingQueryAction), UpdateType.PreCheckoutQuery => nameof(PreCheckoutQuery), UpdateType.Poll => nameof(PollAction), From 40a71e9f17be554fdd0c9e2dc6a33633fcecbf20 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Mon, 4 Apr 2022 16:11:00 +0200 Subject: [PATCH 278/304] feat: update dependencies across solution --- .../Navigator.Extensions.Interop.csproj | 9 +++++++++ .../Navigator.Extensions.Store.csproj | 4 ++-- .../Navigator.Samples.Store.csproj | 7 +++++-- src/Navigator/Navigator.csproj | 6 +++--- 4 files changed, 19 insertions(+), 7 deletions(-) create mode 100644 src/Navigator.Extensions.Interop/Navigator.Extensions.Interop.csproj diff --git a/src/Navigator.Extensions.Interop/Navigator.Extensions.Interop.csproj b/src/Navigator.Extensions.Interop/Navigator.Extensions.Interop.csproj new file mode 100644 index 0000000..eb2460e --- /dev/null +++ b/src/Navigator.Extensions.Interop/Navigator.Extensions.Interop.csproj @@ -0,0 +1,9 @@ + + + + net6.0 + enable + enable + + + diff --git a/src/Navigator.Extensions.Store/Navigator.Extensions.Store.csproj b/src/Navigator.Extensions.Store/Navigator.Extensions.Store.csproj index 8263d91..ddfeffc 100644 --- a/src/Navigator.Extensions.Store/Navigator.Extensions.Store.csproj +++ b/src/Navigator.Extensions.Store/Navigator.Extensions.Store.csproj @@ -18,8 +18,8 @@ - - + + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/src/Navigator.Samples.Store/Navigator.Samples.Store.csproj b/src/Navigator.Samples.Store/Navigator.Samples.Store.csproj index 6d254a6..a3f0665 100644 --- a/src/Navigator.Samples.Store/Navigator.Samples.Store.csproj +++ b/src/Navigator.Samples.Store/Navigator.Samples.Store.csproj @@ -6,8 +6,11 @@ - - + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + diff --git a/src/Navigator/Navigator.csproj b/src/Navigator/Navigator.csproj index 5eeaab4..46ac8f8 100644 --- a/src/Navigator/Navigator.csproj +++ b/src/Navigator/Navigator.csproj @@ -27,11 +27,11 @@ - + - + - + From cce9b86fb8f2b083fe0a9c2eb6ad74a73520cb8a Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 5 Apr 2022 09:54:13 +0200 Subject: [PATCH 279/304] feat: upgrade implementation of action dictionary now we support multiple actions per type --- src/Navigator/Actions/ActionLauncher.cs | 8 +++++--- src/Navigator/Actions/NavigatorOptionsExtensions.cs | 10 +++++----- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/src/Navigator/Actions/ActionLauncher.cs b/src/Navigator/Actions/ActionLauncher.cs index 3bed45a..4618cc7 100644 --- a/src/Navigator/Actions/ActionLauncher.cs +++ b/src/Navigator/Actions/ActionLauncher.cs @@ -18,7 +18,7 @@ internal class ActionLauncher : IActionLauncher private readonly IServiceProvider _serviceProvider; private readonly ISender _sender; private readonly NavigatorOptions _navigatorOptions; - private readonly ImmutableDictionary _actions; + private readonly ImmutableDictionary _actions; private readonly ImmutableDictionary _priorities; public ActionLauncher(ILogger logger, NavigatorOptions navigatorOptions, INavigatorContextAccessor navigatorContextAccessor, IServiceProvider serviceProvider, ISender sender) @@ -63,7 +63,8 @@ private IEnumerable GetActions() if (_navigatorOptions.MultipleActionsUsageIsEnabled()) { return actions - .Select(pair => ((IAction) _serviceProvider.GetService(pair.Value)!, pair.Value.FullName)) + .SelectMany(groups => groups.Value) + .Select(actionType => ((IAction) _serviceProvider.GetService(actionType)!, actionType.FullName)) .Where(a => a.Item1.CanHandleCurrentContext()) .OrderBy(a => _priorities.GetValueOrDefault(a.FullName ?? string.Empty, Priority.Default)) .Select(a => a.Item1) @@ -71,7 +72,8 @@ private IEnumerable GetActions() } var action = actions - .Select(pair => ((IAction) _serviceProvider.GetService(pair.Value)!, pair.Value.FullName)) + .SelectMany(groups => groups.Value) + .Select(actionType => ((IAction) _serviceProvider.GetService(actionType)!, actionType.FullName)) .OrderBy(a => _priorities.GetValueOrDefault(a.FullName ?? string.Empty, Priority.Default)) .Select(a => a.Item1) .FirstOrDefault(a => a.CanHandleCurrentContext()); diff --git a/src/Navigator/Actions/NavigatorOptionsExtensions.cs b/src/Navigator/Actions/NavigatorOptionsExtensions.cs index 8ad25ab..7185d4b 100644 --- a/src/Navigator/Actions/NavigatorOptionsExtensions.cs +++ b/src/Navigator/Actions/NavigatorOptionsExtensions.cs @@ -15,14 +15,14 @@ internal static class NavigatorOptionsExtensions public static void RegisterActions(this NavigatorOptions navigatorOptions, IEnumerable actions) { - navigatorOptions.TryRegisterOption(NavigatorActionTypeCollection, actions.ToImmutableDictionary( - type => type.GetActionType(), - type => type)); + var actionsDictionary = actions.GroupBy(type => type.GetActionType()) + .ToImmutableDictionary(types => types.Key, types => types.ToArray()); + navigatorOptions.TryRegisterOption(NavigatorActionTypeCollection, actionsDictionary); } - public static ImmutableDictionary RetrieveActions(this NavigatorOptions navigatorOptions) + public static ImmutableDictionary RetrieveActions(this NavigatorOptions navigatorOptions) { - return navigatorOptions.RetrieveOption>(NavigatorActionTypeCollection) ?? ImmutableDictionary.Empty; + return navigatorOptions.RetrieveOption>(NavigatorActionTypeCollection) ?? ImmutableDictionary.Empty; } #endregion From b4a61ddd55a9e9e1391a47a29b8f217bdc85f978 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 5 Apr 2022 14:32:47 +0200 Subject: [PATCH 280/304] feat: add provider agnostic base actions --- src/Navigator/Actions/ActionLauncher.cs | 4 +++- .../Actions/ProviderAgnosticAction.cs | 19 +++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) create mode 100644 src/Navigator/Actions/ProviderAgnosticAction.cs diff --git a/src/Navigator/Actions/ActionLauncher.cs b/src/Navigator/Actions/ActionLauncher.cs index 4618cc7..e9fc469 100644 --- a/src/Navigator/Actions/ActionLauncher.cs +++ b/src/Navigator/Actions/ActionLauncher.cs @@ -57,7 +57,9 @@ private IEnumerable GetActions() } var actions = _actions - .Where(a => a.Key == _navigatorContextAccessor.NavigatorContext.ActionType) + .Where(a => + a.Key == _navigatorContextAccessor.NavigatorContext.ActionType || + a.Key == nameof(ProviderAgnosticAction)) .ToImmutableList(); if (_navigatorOptions.MultipleActionsUsageIsEnabled()) diff --git a/src/Navigator/Actions/ProviderAgnosticAction.cs b/src/Navigator/Actions/ProviderAgnosticAction.cs new file mode 100644 index 0000000..4244ee8 --- /dev/null +++ b/src/Navigator/Actions/ProviderAgnosticAction.cs @@ -0,0 +1,19 @@ +using Navigator.Actions.Attributes; +using Navigator.Context; + +namespace Navigator.Actions; + +/// +/// Base action for provider agnostic actions. +/// +[ActionType(nameof(ProviderAgnosticAction))] +public abstract class ProviderAgnosticAction : BaseAction +{ + /// + /// Default constructor. + /// + /// + protected ProviderAgnosticAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) + { + } +} \ No newline at end of file From 25500c798a3b9a165aada0f845e71924a1d9bed6 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 5 Apr 2022 15:00:59 +0200 Subject: [PATCH 281/304] refactor: make some internal methods public --- .../Actions/NavigatorOptionsExtensions.cs | 29 +++++++++++++++---- src/Navigator/ServiceCollectionExtensions.cs | 2 +- 2 files changed, 25 insertions(+), 6 deletions(-) diff --git a/src/Navigator/Actions/NavigatorOptionsExtensions.cs b/src/Navigator/Actions/NavigatorOptionsExtensions.cs index 7185d4b..acb42c0 100644 --- a/src/Navigator/Actions/NavigatorOptionsExtensions.cs +++ b/src/Navigator/Actions/NavigatorOptionsExtensions.cs @@ -7,19 +7,29 @@ namespace Navigator.Actions; -internal static class NavigatorOptionsExtensions +public static class NavigatorOptionsExtensions { #region NavigatorActionTypeCollection private const string NavigatorActionTypeCollection = "_navigator.options.action_type_collection"; - public static void RegisterActions(this NavigatorOptions navigatorOptions, IEnumerable actions) + /// + /// Pseudo-internal call, don't use it unless you know what you are doing. + /// + /// + /// + public static void RegisterActionsCore(this NavigatorOptions navigatorOptions, IEnumerable actions) { var actionsDictionary = actions.GroupBy(type => type.GetActionType()) .ToImmutableDictionary(types => types.Key, types => types.ToArray()); navigatorOptions.TryRegisterOption(NavigatorActionTypeCollection, actionsDictionary); } + /// + /// Pseudo-internal call, don't use it unless you know what you are doing. + /// + /// + /// public static ImmutableDictionary RetrieveActions(this NavigatorOptions navigatorOptions) { return navigatorOptions.RetrieveOption>(NavigatorActionTypeCollection) ?? ImmutableDictionary.Empty; @@ -31,6 +41,11 @@ public static ImmutableDictionary RetrieveActions(this NavigatorO private const string NavigatorActionPriorityCollection = "_navigator.options.action_priority_collection"; + /// + /// Pseudo-internal call, don't use it unless you know what you are doing. + /// + /// + /// public static void RegisterPriority(this NavigatorOptions navigatorOptions, IEnumerable actions) { navigatorOptions.TryRegisterOption(NavigatorActionPriorityCollection, actions.ToImmutableDictionary( @@ -38,6 +53,11 @@ public static void RegisterPriority(this NavigatorOptions navigatorOptions, IEnu type => type.GetActionPriority())); } + /// + /// Pseudo-internal call, don't use it unless you know what you are doing. + /// + /// + /// public static ImmutableDictionary RetrievePriorities(this NavigatorOptions navigatorOptions) { return navigatorOptions.RetrieveOption>(NavigatorActionPriorityCollection) ?? ImmutableDictionary.Empty; @@ -45,7 +65,7 @@ public static ImmutableDictionary RetrievePriorities(this Naviga #endregion - public static string GetActionType(this Type? type) + internal static string GetActionType(this Type? type) { ActionTypeAttribute? actionTypeAttribute = default; @@ -73,7 +93,7 @@ public static string GetActionType(this Type? type) return actionTypeAttribute?.ActionType ?? string.Empty; } - public static ushort GetActionPriority(this Type? type) + internal static ushort GetActionPriority(this Type? type) { if (type?.CustomAttributes.Any(data => data.AttributeType == typeof(ActionPriorityAttribute)) ?? false) { @@ -91,5 +111,4 @@ public static ushort GetActionPriority(this Type? type) return Priority.Default; } - } \ No newline at end of file diff --git a/src/Navigator/ServiceCollectionExtensions.cs b/src/Navigator/ServiceCollectionExtensions.cs index 0eae86a..3f4f00e 100644 --- a/src/Navigator/ServiceCollectionExtensions.cs +++ b/src/Navigator/ServiceCollectionExtensions.cs @@ -38,7 +38,7 @@ public static NavigatorConfiguration AddNavigator(this IServiceCollection servic .AsSelf() .WithScopedLifetime()); - navigatorBuilder.Options.RegisterActions(services + navigatorBuilder.Options.RegisterActionsCore(services .Where(descriptor => descriptor.ImplementationType?.IsAssignableTo(typeof(IAction)) ?? false) .Select(descriptor => descriptor.ImplementationType!)); From 7e0bd6f85dac00279d79ac1cd517ef107a16abf8 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 5 Apr 2022 15:01:37 +0200 Subject: [PATCH 282/304] refactor: remove unused directives in solution --- .../NavigatorExtensionConfigurationExtensions.cs | 2 -- .../Bundled/StoreConversationContextExtension.cs | 2 -- .../Context/Configuration/ChatEntityTypeConfiguration.cs | 1 - .../Context/NavigatorDbContext.cs | 2 -- src/Navigator.Extensions.Store/Entities/Conversation.cs | 2 -- src/Navigator.Extensions.Store/Entities/User.cs | 2 -- .../NavigatorExtensionConfigurationExtensions.cs | 1 - .../Actions/Messages/CommandAction.cs | 1 - .../Actions/Messages/MessageAction.cs | 4 ---- .../Actions/Updates/CallbackQueryAction.cs | 2 -- .../Actions/Updates/ChosenInlineResultAction.cs | 2 -- .../Actions/Updates/DocumentAction.cs | 1 - .../Actions/Updates/EditedMessageAction.cs | 2 -- .../Actions/Updates/InlineQueryAction.cs | 2 -- .../Actions/Updates/PollAction.cs | 2 -- src/Navigator.Providers.Telegram/Entities/TelegramChat.cs | 1 - .../Extensions/TelegramUpdateExtensions.cs | 2 -- .../Hosted/SetTelegramBotWebHookHostedService.cs | 3 --- .../NavigatorContextExtensions.cs | 3 --- .../NavigatorProviderConfigurationExtensions.cs | 1 - .../NavigatorProviderExtensions.cs | 2 -- .../NavigatorRouteProviderConfigurationExtensions.cs | 2 -- src/Navigator.Providers.Telegram/NavigatorTelegramClient.cs | 3 --- .../NavigatorTelegramProviderOptionsExtensions.cs | 1 - src/Navigator.Providers.Telegram/TelegramMiddleware.cs | 3 --- .../TelegramNavigatorContextBuilderConversationSource.cs | 2 -- .../TelegramNavigatorProvider.cs | 3 --- src/Navigator.Samples.Store/Actions/EchoActionHandler.cs | 6 +----- src/Navigator.Samples.Store/Program.cs | 1 - src/Navigator/Actions/ActionHandler.cs | 4 ---- src/Navigator/Actions/ActionLauncher.cs | 5 ----- src/Navigator/Actions/BaseAction.cs | 1 - src/Navigator/Actions/IAction.cs | 1 - src/Navigator/Actions/IActionLauncher.cs | 2 -- src/Navigator/Actions/NavigatorOptionsExtensions.cs | 3 --- .../Extension/NavigatorExtensionConfiguration.cs | 1 - src/Navigator/Configuration/INavigatorOptions.cs | 2 -- src/Navigator/Configuration/NavigatorConfiguration.cs | 1 - src/Navigator/Configuration/NavigatorOptions.cs | 2 -- .../Configuration/NavigatorOptionsCollectionExtensions.cs | 1 - .../Provider/NavigatorProviderConfiguration.cs | 1 - .../Provider/NavigatorRouteProviderConfiguration.cs | 1 - .../Bundled/OriginalEvent/NavigatorContextExtensions.cs | 2 -- .../Bundled/OriginalEvent/OriginalEventContextExtension.cs | 2 -- .../Context/Extensions/INavigatorContextExtension.cs | 2 -- src/Navigator/Context/INavigatorContext.cs | 1 - src/Navigator/Context/INavigatorContextBuilder.cs | 4 ---- .../Context/INavigatorContextBuilderConversationSource.cs | 1 - src/Navigator/Context/INavigatorContextBuilderOptions.cs | 2 -- src/Navigator/Context/INavigatorContextFactory.cs | 3 --- src/Navigator/Context/NavigatorContext.cs | 3 +-- src/Navigator/Context/NavigatorContextBuilder.cs | 5 ----- src/Navigator/Context/NavigatorContextBuilderOptions.cs | 3 --- .../Context/NavigatorContextBuilderOptionsExtensions.cs | 3 --- src/Navigator/Context/NavigatorContextFactory.cs | 2 -- src/Navigator/Entities/Bot.cs | 2 -- src/Navigator/Entities/Chat.cs | 2 -- src/Navigator/Entities/Conversation.cs | 2 -- src/Navigator/Entities/User.cs | 2 -- src/Navigator/INavigatorClient.cs | 2 -- src/Navigator/INavigatorProvider.cs | 3 --- src/Navigator/NavigatorException.cs | 1 - src/Navigator/ServiceCollectionExtensions.cs | 3 --- 63 files changed, 2 insertions(+), 134 deletions(-) diff --git a/src/Navigator.Extensions.Cooldown/NavigatorExtensionConfigurationExtensions.cs b/src/Navigator.Extensions.Cooldown/NavigatorExtensionConfigurationExtensions.cs index 641f92b..b4b0c3c 100644 --- a/src/Navigator.Extensions.Cooldown/NavigatorExtensionConfigurationExtensions.cs +++ b/src/Navigator.Extensions.Cooldown/NavigatorExtensionConfigurationExtensions.cs @@ -1,9 +1,7 @@ using MediatR; using Microsoft.Extensions.DependencyInjection; -using Navigator.Actions; using Navigator.Configuration; using Navigator.Configuration.Extension; -using Scrutor; namespace Navigator.Extensions.Cooldown; diff --git a/src/Navigator.Extensions.Store/Bundled/StoreConversationContextExtension.cs b/src/Navigator.Extensions.Store/Bundled/StoreConversationContextExtension.cs index 2ed047b..680648f 100644 --- a/src/Navigator.Extensions.Store/Bundled/StoreConversationContextExtension.cs +++ b/src/Navigator.Extensions.Store/Bundled/StoreConversationContextExtension.cs @@ -1,5 +1,3 @@ -using System.Text; -using System.Text.Json; using Microsoft.EntityFrameworkCore; using Navigator.Context; using Navigator.Context.Extensions; diff --git a/src/Navigator.Extensions.Store/Context/Configuration/ChatEntityTypeConfiguration.cs b/src/Navigator.Extensions.Store/Context/Configuration/ChatEntityTypeConfiguration.cs index 9aee2e8..696e9df 100644 --- a/src/Navigator.Extensions.Store/Context/Configuration/ChatEntityTypeConfiguration.cs +++ b/src/Navigator.Extensions.Store/Context/Configuration/ChatEntityTypeConfiguration.cs @@ -1,5 +1,4 @@ using System.Text.Json; -using System.Text.Json.Serialization; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; using Microsoft.EntityFrameworkCore.Metadata.Builders; diff --git a/src/Navigator.Extensions.Store/Context/NavigatorDbContext.cs b/src/Navigator.Extensions.Store/Context/NavigatorDbContext.cs index af79ab3..e079a3f 100644 --- a/src/Navigator.Extensions.Store/Context/NavigatorDbContext.cs +++ b/src/Navigator.Extensions.Store/Context/NavigatorDbContext.cs @@ -1,8 +1,6 @@ using Microsoft.EntityFrameworkCore; -using Navigator.Entities; using Navigator.Extensions.Store.Context.Configuration; using Navigator.Extensions.Store.Context.Extension; -using Navigator.Extensions.Store.Entities; using Chat = Navigator.Extensions.Store.Entities.Chat; using Conversation = Navigator.Extensions.Store.Entities.Conversation; using User = Navigator.Extensions.Store.Entities.User; diff --git a/src/Navigator.Extensions.Store/Entities/Conversation.cs b/src/Navigator.Extensions.Store/Entities/Conversation.cs index 0f5dd4f..c7447b8 100644 --- a/src/Navigator.Extensions.Store/Entities/Conversation.cs +++ b/src/Navigator.Extensions.Store/Entities/Conversation.cs @@ -1,5 +1,3 @@ -using Navigator.Entities; - namespace Navigator.Extensions.Store.Entities; public class Conversation : Navigator.Entities.Conversation diff --git a/src/Navigator.Extensions.Store/Entities/User.cs b/src/Navigator.Extensions.Store/Entities/User.cs index c10a3a4..d61d58d 100644 --- a/src/Navigator.Extensions.Store/Entities/User.cs +++ b/src/Navigator.Extensions.Store/Entities/User.cs @@ -1,5 +1,3 @@ -using Navigator.Entities; - namespace Navigator.Extensions.Store.Entities; public class User : Navigator.Entities.User diff --git a/src/Navigator.Extensions.Store/NavigatorExtensionConfigurationExtensions.cs b/src/Navigator.Extensions.Store/NavigatorExtensionConfigurationExtensions.cs index ec09692..fe35568 100644 --- a/src/Navigator.Extensions.Store/NavigatorExtensionConfigurationExtensions.cs +++ b/src/Navigator.Extensions.Store/NavigatorExtensionConfigurationExtensions.cs @@ -1,4 +1,3 @@ -using MediatR; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Navigator.Configuration; diff --git a/src/Navigator.Providers.Telegram/Actions/Messages/CommandAction.cs b/src/Navigator.Providers.Telegram/Actions/Messages/CommandAction.cs index 3c3e940..a3bc6c8 100644 --- a/src/Navigator.Providers.Telegram/Actions/Messages/CommandAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Messages/CommandAction.cs @@ -1,4 +1,3 @@ -using Navigator.Actions; using Navigator.Actions.Attributes; using Navigator.Context; using Navigator.Providers.Telegram.Entities; diff --git a/src/Navigator.Providers.Telegram/Actions/Messages/MessageAction.cs b/src/Navigator.Providers.Telegram/Actions/Messages/MessageAction.cs index 1d1cb91..2480797 100644 --- a/src/Navigator.Providers.Telegram/Actions/Messages/MessageAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Messages/MessageAction.cs @@ -1,10 +1,6 @@ -using System.ComponentModel; -using System.Reflection; using Navigator.Actions; using Navigator.Actions.Attributes; using Navigator.Context; -using Navigator.Context.Extensions; -using Navigator.Context.Extensions.Bundled; using Navigator.Context.Extensions.Bundled.OriginalEvent; using Telegram.Bot.Types; diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/CallbackQueryAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/CallbackQueryAction.cs index 5944f3d..085ab46 100644 --- a/src/Navigator.Providers.Telegram/Actions/Updates/CallbackQueryAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/CallbackQueryAction.cs @@ -1,8 +1,6 @@ using Navigator.Actions; using Navigator.Actions.Attributes; using Navigator.Context; -using Navigator.Context.Extensions; -using Navigator.Context.Extensions.Bundled; using Navigator.Context.Extensions.Bundled.OriginalEvent; using Telegram.Bot.Types; diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/ChosenInlineResultAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/ChosenInlineResultAction.cs index 8e5a00b..ccd0076 100644 --- a/src/Navigator.Providers.Telegram/Actions/Updates/ChosenInlineResultAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/ChosenInlineResultAction.cs @@ -1,8 +1,6 @@ using Navigator.Actions; using Navigator.Actions.Attributes; using Navigator.Context; -using Navigator.Context.Extensions; -using Navigator.Context.Extensions.Bundled; using Navigator.Context.Extensions.Bundled.OriginalEvent; using Telegram.Bot.Types; diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/DocumentAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/DocumentAction.cs index d3c8e7a..e47be23 100644 --- a/src/Navigator.Providers.Telegram/Actions/Updates/DocumentAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/DocumentAction.cs @@ -1,4 +1,3 @@ -using System; using Navigator.Actions; using Navigator.Actions.Attributes; using Navigator.Context; diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/EditedMessageAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/EditedMessageAction.cs index 022711b..0346180 100644 --- a/src/Navigator.Providers.Telegram/Actions/Updates/EditedMessageAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/EditedMessageAction.cs @@ -1,8 +1,6 @@ using Navigator.Actions; using Navigator.Actions.Attributes; using Navigator.Context; -using Navigator.Context.Extensions; -using Navigator.Context.Extensions.Bundled; using Navigator.Context.Extensions.Bundled.OriginalEvent; using Telegram.Bot.Types; diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/InlineQueryAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/InlineQueryAction.cs index b2e7e3f..2f2b7d1 100644 --- a/src/Navigator.Providers.Telegram/Actions/Updates/InlineQueryAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/InlineQueryAction.cs @@ -1,8 +1,6 @@ using Navigator.Actions; using Navigator.Actions.Attributes; using Navigator.Context; -using Navigator.Context.Extensions; -using Navigator.Context.Extensions.Bundled; using Navigator.Context.Extensions.Bundled.OriginalEvent; using Telegram.Bot.Types; diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/PollAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/PollAction.cs index cda0755..10ffd7e 100644 --- a/src/Navigator.Providers.Telegram/Actions/Updates/PollAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/PollAction.cs @@ -1,8 +1,6 @@ using Navigator.Actions; using Navigator.Actions.Attributes; using Navigator.Context; -using Navigator.Context.Extensions; -using Navigator.Context.Extensions.Bundled; using Navigator.Context.Extensions.Bundled.OriginalEvent; using Telegram.Bot.Types; diff --git a/src/Navigator.Providers.Telegram/Entities/TelegramChat.cs b/src/Navigator.Providers.Telegram/Entities/TelegramChat.cs index 273de0c..c266a88 100644 --- a/src/Navigator.Providers.Telegram/Entities/TelegramChat.cs +++ b/src/Navigator.Providers.Telegram/Entities/TelegramChat.cs @@ -1,4 +1,3 @@ -using System; using Navigator.Entities; namespace Navigator.Providers.Telegram.Entities; diff --git a/src/Navigator.Providers.Telegram/Extensions/TelegramUpdateExtensions.cs b/src/Navigator.Providers.Telegram/Extensions/TelegramUpdateExtensions.cs index 6e49fc1..9bcdeff 100644 --- a/src/Navigator.Providers.Telegram/Extensions/TelegramUpdateExtensions.cs +++ b/src/Navigator.Providers.Telegram/Extensions/TelegramUpdateExtensions.cs @@ -1,5 +1,3 @@ -using System; -using System.Linq; using Navigator.Providers.Telegram.Entities; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; diff --git a/src/Navigator.Providers.Telegram/Hosted/SetTelegramBotWebHookHostedService.cs b/src/Navigator.Providers.Telegram/Hosted/SetTelegramBotWebHookHostedService.cs index 938c550..7dc931a 100644 --- a/src/Navigator.Providers.Telegram/Hosted/SetTelegramBotWebHookHostedService.cs +++ b/src/Navigator.Providers.Telegram/Hosted/SetTelegramBotWebHookHostedService.cs @@ -1,6 +1,3 @@ -using System; -using System.Threading; -using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; diff --git a/src/Navigator.Providers.Telegram/NavigatorContextExtensions.cs b/src/Navigator.Providers.Telegram/NavigatorContextExtensions.cs index d7bf0ae..f1981d9 100644 --- a/src/Navigator.Providers.Telegram/NavigatorContextExtensions.cs +++ b/src/Navigator.Providers.Telegram/NavigatorContextExtensions.cs @@ -1,7 +1,4 @@ -using System; using Navigator.Context; -using Navigator.Context.Extensions; -using Navigator.Context.Extensions.Bundled; using Navigator.Context.Extensions.Bundled.OriginalEvent; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; diff --git a/src/Navigator.Providers.Telegram/NavigatorProviderConfigurationExtensions.cs b/src/Navigator.Providers.Telegram/NavigatorProviderConfigurationExtensions.cs index 108b416..544a66d 100644 --- a/src/Navigator.Providers.Telegram/NavigatorProviderConfigurationExtensions.cs +++ b/src/Navigator.Providers.Telegram/NavigatorProviderConfigurationExtensions.cs @@ -1,4 +1,3 @@ -using System; using Microsoft.Extensions.DependencyInjection; using Navigator.Configuration; using Navigator.Configuration.Provider; diff --git a/src/Navigator.Providers.Telegram/NavigatorProviderExtensions.cs b/src/Navigator.Providers.Telegram/NavigatorProviderExtensions.cs index 642f2ea..e9fdbfa 100644 --- a/src/Navigator.Providers.Telegram/NavigatorProviderExtensions.cs +++ b/src/Navigator.Providers.Telegram/NavigatorProviderExtensions.cs @@ -1,5 +1,3 @@ -using System; - namespace Navigator.Providers.Telegram; public static class NavigatorProviderExtensions diff --git a/src/Navigator.Providers.Telegram/NavigatorRouteProviderConfigurationExtensions.cs b/src/Navigator.Providers.Telegram/NavigatorRouteProviderConfigurationExtensions.cs index 0891d02..6526ea4 100644 --- a/src/Navigator.Providers.Telegram/NavigatorRouteProviderConfigurationExtensions.cs +++ b/src/Navigator.Providers.Telegram/NavigatorRouteProviderConfigurationExtensions.cs @@ -1,5 +1,3 @@ -using System.IO; -using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; diff --git a/src/Navigator.Providers.Telegram/NavigatorTelegramClient.cs b/src/Navigator.Providers.Telegram/NavigatorTelegramClient.cs index 0137232..2b13de0 100644 --- a/src/Navigator.Providers.Telegram/NavigatorTelegramClient.cs +++ b/src/Navigator.Providers.Telegram/NavigatorTelegramClient.cs @@ -1,6 +1,3 @@ -using System; -using System.Threading; -using System.Threading.Tasks; using Navigator.Configuration; using Navigator.Entities; using Navigator.Providers.Telegram.Entities; diff --git a/src/Navigator.Providers.Telegram/NavigatorTelegramProviderOptionsExtensions.cs b/src/Navigator.Providers.Telegram/NavigatorTelegramProviderOptionsExtensions.cs index c4a88aa..3bd1f43 100644 --- a/src/Navigator.Providers.Telegram/NavigatorTelegramProviderOptionsExtensions.cs +++ b/src/Navigator.Providers.Telegram/NavigatorTelegramProviderOptionsExtensions.cs @@ -1,4 +1,3 @@ -using System; using Navigator.Configuration; namespace Navigator.Providers.Telegram; diff --git a/src/Navigator.Providers.Telegram/TelegramMiddleware.cs b/src/Navigator.Providers.Telegram/TelegramMiddleware.cs index f808c50..c456fd6 100644 --- a/src/Navigator.Providers.Telegram/TelegramMiddleware.cs +++ b/src/Navigator.Providers.Telegram/TelegramMiddleware.cs @@ -1,12 +1,9 @@ -using System.Linq; -using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Navigator.Actions; using Navigator.Context; using Navigator.Providers.Telegram.Actions; using Navigator.Providers.Telegram.Actions.Messages; using Navigator.Providers.Telegram.Actions.Updates; -using Navigator.Providers.Telegram.Extensions; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; using Telegram.Bot.Types.Payments; diff --git a/src/Navigator.Providers.Telegram/TelegramNavigatorContextBuilderConversationSource.cs b/src/Navigator.Providers.Telegram/TelegramNavigatorContextBuilderConversationSource.cs index 55898c3..87613b1 100644 --- a/src/Navigator.Providers.Telegram/TelegramNavigatorContextBuilderConversationSource.cs +++ b/src/Navigator.Providers.Telegram/TelegramNavigatorContextBuilderConversationSource.cs @@ -1,5 +1,3 @@ -using System; -using System.Threading.Tasks; using Navigator.Context; using Navigator.Entities; using Navigator.Providers.Telegram.Extensions; diff --git a/src/Navigator.Providers.Telegram/TelegramNavigatorProvider.cs b/src/Navigator.Providers.Telegram/TelegramNavigatorProvider.cs index b3e2553..55224e1 100644 --- a/src/Navigator.Providers.Telegram/TelegramNavigatorProvider.cs +++ b/src/Navigator.Providers.Telegram/TelegramNavigatorProvider.cs @@ -1,7 +1,4 @@ -using System; -using System.Threading.Tasks; using Navigator.Providers.Telegram.Entities; -using Telegram.Bot.Types; namespace Navigator.Providers.Telegram; diff --git a/src/Navigator.Samples.Store/Actions/EchoActionHandler.cs b/src/Navigator.Samples.Store/Actions/EchoActionHandler.cs index d594bae..b8e9137 100644 --- a/src/Navigator.Samples.Store/Actions/EchoActionHandler.cs +++ b/src/Navigator.Samples.Store/Actions/EchoActionHandler.cs @@ -1,11 +1,7 @@ -using System.Globalization; -using System.Linq; -using System.Threading; +using System.Threading; using System.Threading.Tasks; -using Microsoft.EntityFrameworkCore; using Navigator.Actions; using Navigator.Context; -using Navigator.Extensions.Store; using Navigator.Providers.Telegram; using Telegram.Bot; diff --git a/src/Navigator.Samples.Store/Program.cs b/src/Navigator.Samples.Store/Program.cs index 4f8fbb2..21edb26 100644 --- a/src/Navigator.Samples.Store/Program.cs +++ b/src/Navigator.Samples.Store/Program.cs @@ -1,6 +1,5 @@ using Microsoft.AspNetCore.Builder; using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; diff --git a/src/Navigator/Actions/ActionHandler.cs b/src/Navigator/Actions/ActionHandler.cs index f67dfb5..d53a0ef 100644 --- a/src/Navigator/Actions/ActionHandler.cs +++ b/src/Navigator/Actions/ActionHandler.cs @@ -1,9 +1,5 @@ -using System; -using System.Threading; -using System.Threading.Tasks; using MediatR; using Navigator.Context; -using Navigator.Replies; namespace Navigator.Actions; diff --git a/src/Navigator/Actions/ActionLauncher.cs b/src/Navigator/Actions/ActionLauncher.cs index e9fc469..f6e0cf3 100644 --- a/src/Navigator/Actions/ActionLauncher.cs +++ b/src/Navigator/Actions/ActionLauncher.cs @@ -1,10 +1,5 @@ -using System; -using System.Collections.Generic; using System.Collections.Immutable; -using System.Linq; -using System.Threading.Tasks; using MediatR; -using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Navigator.Configuration; using Navigator.Context; diff --git a/src/Navigator/Actions/BaseAction.cs b/src/Navigator/Actions/BaseAction.cs index b3fe12d..f934e85 100644 --- a/src/Navigator/Actions/BaseAction.cs +++ b/src/Navigator/Actions/BaseAction.cs @@ -1,4 +1,3 @@ -using System; using Navigator.Actions.Attributes; using Navigator.Context; diff --git a/src/Navigator/Actions/IAction.cs b/src/Navigator/Actions/IAction.cs index b12d56f..822533b 100644 --- a/src/Navigator/Actions/IAction.cs +++ b/src/Navigator/Actions/IAction.cs @@ -1,5 +1,4 @@ using MediatR; -using Navigator.Context; namespace Navigator.Actions; diff --git a/src/Navigator/Actions/IActionLauncher.cs b/src/Navigator/Actions/IActionLauncher.cs index a3235ff..080895b 100644 --- a/src/Navigator/Actions/IActionLauncher.cs +++ b/src/Navigator/Actions/IActionLauncher.cs @@ -1,5 +1,3 @@ -using System.Threading.Tasks; - namespace Navigator.Actions; public interface IActionLauncher diff --git a/src/Navigator/Actions/NavigatorOptionsExtensions.cs b/src/Navigator/Actions/NavigatorOptionsExtensions.cs index acb42c0..2cebaac 100644 --- a/src/Navigator/Actions/NavigatorOptionsExtensions.cs +++ b/src/Navigator/Actions/NavigatorOptionsExtensions.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; using System.Collections.Immutable; -using System.Linq; using Navigator.Actions.Attributes; using Navigator.Configuration; diff --git a/src/Navigator/Configuration/Extension/NavigatorExtensionConfiguration.cs b/src/Navigator/Configuration/Extension/NavigatorExtensionConfiguration.cs index 7e377b0..f36b523 100644 --- a/src/Navigator/Configuration/Extension/NavigatorExtensionConfiguration.cs +++ b/src/Navigator/Configuration/Extension/NavigatorExtensionConfiguration.cs @@ -1,4 +1,3 @@ -using System; using Microsoft.Extensions.DependencyInjection; namespace Navigator.Configuration.Extension; diff --git a/src/Navigator/Configuration/INavigatorOptions.cs b/src/Navigator/Configuration/INavigatorOptions.cs index 3251d1f..8a5ae78 100644 --- a/src/Navigator/Configuration/INavigatorOptions.cs +++ b/src/Navigator/Configuration/INavigatorOptions.cs @@ -1,5 +1,3 @@ -using System.Collections.Generic; - namespace Navigator.Configuration; /// diff --git a/src/Navigator/Configuration/NavigatorConfiguration.cs b/src/Navigator/Configuration/NavigatorConfiguration.cs index 9b18ec0..3dd1465 100644 --- a/src/Navigator/Configuration/NavigatorConfiguration.cs +++ b/src/Navigator/Configuration/NavigatorConfiguration.cs @@ -1,4 +1,3 @@ -using System; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Navigator.Configuration.Extension; diff --git a/src/Navigator/Configuration/NavigatorOptions.cs b/src/Navigator/Configuration/NavigatorOptions.cs index f23dd4d..e3629b5 100644 --- a/src/Navigator/Configuration/NavigatorOptions.cs +++ b/src/Navigator/Configuration/NavigatorOptions.cs @@ -1,5 +1,3 @@ -using System.Collections.Generic; - namespace Navigator.Configuration; /// diff --git a/src/Navigator/Configuration/NavigatorOptionsCollectionExtensions.cs b/src/Navigator/Configuration/NavigatorOptionsCollectionExtensions.cs index 19b2ca6..3cc76cd 100644 --- a/src/Navigator/Configuration/NavigatorOptionsCollectionExtensions.cs +++ b/src/Navigator/Configuration/NavigatorOptionsCollectionExtensions.cs @@ -1,4 +1,3 @@ -using System.Collections.Generic; using System.Reflection; namespace Navigator.Configuration; diff --git a/src/Navigator/Configuration/Provider/NavigatorProviderConfiguration.cs b/src/Navigator/Configuration/Provider/NavigatorProviderConfiguration.cs index 8efc4e1..3a9ffe6 100644 --- a/src/Navigator/Configuration/Provider/NavigatorProviderConfiguration.cs +++ b/src/Navigator/Configuration/Provider/NavigatorProviderConfiguration.cs @@ -1,4 +1,3 @@ -using System; using Microsoft.Extensions.DependencyInjection; namespace Navigator.Configuration.Provider; diff --git a/src/Navigator/Configuration/Provider/NavigatorRouteProviderConfiguration.cs b/src/Navigator/Configuration/Provider/NavigatorRouteProviderConfiguration.cs index 2806757..2a29615 100644 --- a/src/Navigator/Configuration/Provider/NavigatorRouteProviderConfiguration.cs +++ b/src/Navigator/Configuration/Provider/NavigatorRouteProviderConfiguration.cs @@ -1,4 +1,3 @@ -using System; using Microsoft.AspNetCore.Routing; namespace Navigator.Configuration.Provider; diff --git a/src/Navigator/Context/Extensions/Bundled/OriginalEvent/NavigatorContextExtensions.cs b/src/Navigator/Context/Extensions/Bundled/OriginalEvent/NavigatorContextExtensions.cs index 58c0142..4a14fc9 100644 --- a/src/Navigator/Context/Extensions/Bundled/OriginalEvent/NavigatorContextExtensions.cs +++ b/src/Navigator/Context/Extensions/Bundled/OriginalEvent/NavigatorContextExtensions.cs @@ -1,5 +1,3 @@ -using System.Collections.Generic; - namespace Navigator.Context.Extensions.Bundled.OriginalEvent; public static class NavigatorContextExtensions diff --git a/src/Navigator/Context/Extensions/Bundled/OriginalEvent/OriginalEventContextExtension.cs b/src/Navigator/Context/Extensions/Bundled/OriginalEvent/OriginalEventContextExtension.cs index ccd6b53..905a860 100644 --- a/src/Navigator/Context/Extensions/Bundled/OriginalEvent/OriginalEventContextExtension.cs +++ b/src/Navigator/Context/Extensions/Bundled/OriginalEvent/OriginalEventContextExtension.cs @@ -1,5 +1,3 @@ -using System.Threading.Tasks; - namespace Navigator.Context.Extensions.Bundled.OriginalEvent; internal class OriginalEventContextExtension : INavigatorContextExtension diff --git a/src/Navigator/Context/Extensions/INavigatorContextExtension.cs b/src/Navigator/Context/Extensions/INavigatorContextExtension.cs index 9022d9c..674f97c 100644 --- a/src/Navigator/Context/Extensions/INavigatorContextExtension.cs +++ b/src/Navigator/Context/Extensions/INavigatorContextExtension.cs @@ -1,5 +1,3 @@ -using System.Threading.Tasks; - namespace Navigator.Context.Extensions; public interface INavigatorContextExtension diff --git a/src/Navigator/Context/INavigatorContext.cs b/src/Navigator/Context/INavigatorContext.cs index c659530..7c5a7ef 100644 --- a/src/Navigator/Context/INavigatorContext.cs +++ b/src/Navigator/Context/INavigatorContext.cs @@ -1,4 +1,3 @@ -using System.Collections.Generic; using Navigator.Entities; namespace Navigator.Context; diff --git a/src/Navigator/Context/INavigatorContextBuilder.cs b/src/Navigator/Context/INavigatorContextBuilder.cs index eda60a9..83b0cfa 100644 --- a/src/Navigator/Context/INavigatorContextBuilder.cs +++ b/src/Navigator/Context/INavigatorContextBuilder.cs @@ -1,7 +1,3 @@ -using System; -using System.Threading.Tasks; -using Navigator.Entities; - namespace Navigator.Context; public interface INavigatorContextBuilder diff --git a/src/Navigator/Context/INavigatorContextBuilderConversationSource.cs b/src/Navigator/Context/INavigatorContextBuilderConversationSource.cs index e272b68..d0e1937 100644 --- a/src/Navigator/Context/INavigatorContextBuilderConversationSource.cs +++ b/src/Navigator/Context/INavigatorContextBuilderConversationSource.cs @@ -1,4 +1,3 @@ -using System.Threading.Tasks; using Navigator.Entities; namespace Navigator.Context; diff --git a/src/Navigator/Context/INavigatorContextBuilderOptions.cs b/src/Navigator/Context/INavigatorContextBuilderOptions.cs index a7c34c1..5022aac 100644 --- a/src/Navigator/Context/INavigatorContextBuilderOptions.cs +++ b/src/Navigator/Context/INavigatorContextBuilderOptions.cs @@ -1,5 +1,3 @@ -using System.Collections.Generic; - namespace Navigator.Context; public interface INavigatorContextBuilderOptions diff --git a/src/Navigator/Context/INavigatorContextFactory.cs b/src/Navigator/Context/INavigatorContextFactory.cs index d18a77c..d061c68 100644 --- a/src/Navigator/Context/INavigatorContextFactory.cs +++ b/src/Navigator/Context/INavigatorContextFactory.cs @@ -1,6 +1,3 @@ -using System; -using System.Threading.Tasks; - namespace Navigator.Context; /// diff --git a/src/Navigator/Context/NavigatorContext.cs b/src/Navigator/Context/NavigatorContext.cs index fa53af0..5e887af 100644 --- a/src/Navigator/Context/NavigatorContext.cs +++ b/src/Navigator/Context/NavigatorContext.cs @@ -1,5 +1,4 @@ -using System.Collections.Generic; -using Navigator.Entities; +using Navigator.Entities; namespace Navigator.Context; diff --git a/src/Navigator/Context/NavigatorContextBuilder.cs b/src/Navigator/Context/NavigatorContextBuilder.cs index 15c5fe8..f6d6bd7 100644 --- a/src/Navigator/Context/NavigatorContextBuilder.cs +++ b/src/Navigator/Context/NavigatorContextBuilder.cs @@ -1,10 +1,5 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Navigator.Context.Extensions; -using Navigator.Entities; namespace Navigator.Context; diff --git a/src/Navigator/Context/NavigatorContextBuilderOptions.cs b/src/Navigator/Context/NavigatorContextBuilderOptions.cs index 86a78dc..503f406 100644 --- a/src/Navigator/Context/NavigatorContextBuilderOptions.cs +++ b/src/Navigator/Context/NavigatorContextBuilderOptions.cs @@ -1,6 +1,3 @@ -using System.Collections.Generic; -using Navigator.Entities; - namespace Navigator.Context; public class NavigatorContextBuilderOptions : INavigatorContextBuilderOptions diff --git a/src/Navigator/Context/NavigatorContextBuilderOptionsExtensions.cs b/src/Navigator/Context/NavigatorContextBuilderOptionsExtensions.cs index 0d9bf07..3d26233 100644 --- a/src/Navigator/Context/NavigatorContextBuilderOptionsExtensions.cs +++ b/src/Navigator/Context/NavigatorContextBuilderOptionsExtensions.cs @@ -1,6 +1,3 @@ -using System; -using Navigator.Entities; - namespace Navigator.Context; public static class NavigatorContextBuilderOptionsExtensions diff --git a/src/Navigator/Context/NavigatorContextFactory.cs b/src/Navigator/Context/NavigatorContextFactory.cs index 1baa1c8..85f8285 100644 --- a/src/Navigator/Context/NavigatorContextFactory.cs +++ b/src/Navigator/Context/NavigatorContextFactory.cs @@ -1,5 +1,3 @@ -using System; -using System.Threading.Tasks; using Microsoft.Extensions.Logging; namespace Navigator.Context; diff --git a/src/Navigator/Entities/Bot.cs b/src/Navigator/Entities/Bot.cs index 7fe0234..b3000b1 100644 --- a/src/Navigator/Entities/Bot.cs +++ b/src/Navigator/Entities/Bot.cs @@ -1,5 +1,3 @@ -using System; -using System.Linq; using System.Security.Cryptography; using System.Text; diff --git a/src/Navigator/Entities/Chat.cs b/src/Navigator/Entities/Chat.cs index f4bb710..3135045 100644 --- a/src/Navigator/Entities/Chat.cs +++ b/src/Navigator/Entities/Chat.cs @@ -1,5 +1,3 @@ -using System; -using System.Linq; using System.Security.Cryptography; using System.Text; diff --git a/src/Navigator/Entities/Conversation.cs b/src/Navigator/Entities/Conversation.cs index 01046ee..e2a27ac 100644 --- a/src/Navigator/Entities/Conversation.cs +++ b/src/Navigator/Entities/Conversation.cs @@ -1,5 +1,3 @@ -using System; -using System.Linq; using System.Security.Cryptography; using System.Text; diff --git a/src/Navigator/Entities/User.cs b/src/Navigator/Entities/User.cs index 93373ab..902c3da 100644 --- a/src/Navigator/Entities/User.cs +++ b/src/Navigator/Entities/User.cs @@ -1,5 +1,3 @@ -using System; -using System.Linq; using System.Security.Cryptography; using System.Text; diff --git a/src/Navigator/INavigatorClient.cs b/src/Navigator/INavigatorClient.cs index f1e0fda..49e218a 100644 --- a/src/Navigator/INavigatorClient.cs +++ b/src/Navigator/INavigatorClient.cs @@ -1,5 +1,3 @@ -using System.Threading; -using System.Threading.Tasks; using Navigator.Entities; namespace Navigator; diff --git a/src/Navigator/INavigatorProvider.cs b/src/Navigator/INavigatorProvider.cs index cb944fc..fcb802c 100644 --- a/src/Navigator/INavigatorProvider.cs +++ b/src/Navigator/INavigatorProvider.cs @@ -1,6 +1,3 @@ -using System; -using System.Threading.Tasks; - namespace Navigator; /// diff --git a/src/Navigator/NavigatorException.cs b/src/Navigator/NavigatorException.cs index a598fe0..92fd54d 100644 --- a/src/Navigator/NavigatorException.cs +++ b/src/Navigator/NavigatorException.cs @@ -1,4 +1,3 @@ -using System; using System.Runtime.Serialization; namespace Navigator; diff --git a/src/Navigator/ServiceCollectionExtensions.cs b/src/Navigator/ServiceCollectionExtensions.cs index 3f4f00e..7f8dbbd 100644 --- a/src/Navigator/ServiceCollectionExtensions.cs +++ b/src/Navigator/ServiceCollectionExtensions.cs @@ -1,12 +1,9 @@ -using System; -using System.Linq; using MediatR; using Microsoft.Extensions.DependencyInjection; using Navigator.Actions; using Navigator.Configuration; using Navigator.Context; using Navigator.Context.Extensions; -using Navigator.Context.Extensions.Bundled; using Navigator.Context.Extensions.Bundled.OriginalEvent; using Scrutor; From d14fea5d0f5c4b04a1491934dc5e9c271d59deab Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 5 Apr 2022 15:27:06 +0200 Subject: [PATCH 283/304] refactor: simplify extension configuration --- ...vigatorExtensionConfigurationExtensions.cs | 24 +++++++++---------- ...vigatorExtensionConfigurationExtensions.cs | 23 +++++++++--------- .../NavigatorExtensionConfiguration.cs | 9 +++---- 3 files changed, 26 insertions(+), 30 deletions(-) diff --git a/src/Navigator.Extensions.Cooldown/NavigatorExtensionConfigurationExtensions.cs b/src/Navigator.Extensions.Cooldown/NavigatorExtensionConfigurationExtensions.cs index b4b0c3c..2718b15 100644 --- a/src/Navigator.Extensions.Cooldown/NavigatorExtensionConfigurationExtensions.cs +++ b/src/Navigator.Extensions.Cooldown/NavigatorExtensionConfigurationExtensions.cs @@ -5,23 +5,23 @@ namespace Navigator.Extensions.Cooldown; +/// +/// Extensions to NavigatorConfiguration +/// public static class NavigatorExtensionConfigurationExtensions { - public static NavigatorConfiguration Cooldown(this NavigatorExtensionConfiguration providerConfiguration) + /// + /// Configures the Cooldown extension. + /// + /// + /// + public static NavigatorConfiguration Cooldown(this NavigatorExtensionConfiguration extensionConfiguration) { - return providerConfiguration.Extension( - _ => {}, - services => + return extensionConfiguration.Extension( + configuration => { - // services.Scan(source => source - // .FromAssemblyOf() - // .AddClasses(filter => filter.AssignableTo(typeof(IPipelineBehavior<,>))) - // .UsingRegistrationStrategy(RegistrationStrategy.Append) - // .AsImplementedInterfaces() - // .WithScopedLifetime()); - - services.AddScoped(typeof(IPipelineBehavior<,>), typeof(CooldownActionMiddleware<,>)); + configuration.Services.AddScoped(typeof(IPipelineBehavior<,>), typeof(CooldownActionMiddleware<,>)); }); } } \ No newline at end of file diff --git a/src/Navigator.Extensions.Store/NavigatorExtensionConfigurationExtensions.cs b/src/Navigator.Extensions.Store/NavigatorExtensionConfigurationExtensions.cs index fe35568..3db4867 100644 --- a/src/Navigator.Extensions.Store/NavigatorExtensionConfigurationExtensions.cs +++ b/src/Navigator.Extensions.Store/NavigatorExtensionConfigurationExtensions.cs @@ -11,24 +11,23 @@ namespace Navigator.Extensions.Store; public static class NavigatorExtensionConfigurationExtensions { - public static NavigatorConfiguration Store(this NavigatorExtensionConfiguration providerConfiguration, Action? dbContextOptions = default) + public static NavigatorConfiguration Store(this NavigatorExtensionConfiguration extensionConfiguration, Action? dbContextOptions = default) { var temporal = new DbContextOptionsBuilder(); dbContextOptions?.Invoke(temporal); - return providerConfiguration.Extension( - _ => {}, - services => - { - services.AddDbContext(dbContextOptions); + return extensionConfiguration.Extension(configuration => + { + + configuration.Services.AddDbContext(dbContextOptions); - services.AddScoped(); + configuration.Services.AddScoped(); - foreach (var extension in temporal.Options.Extensions.OfType()) - { - extension.ExtensionServices?.Invoke(services); - } - }); + foreach (var extension in temporal.Options.Extensions.OfType()) + { + extension.ExtensionServices?.Invoke(configuration.Services); + } + }); } } \ No newline at end of file diff --git a/src/Navigator/Configuration/Extension/NavigatorExtensionConfiguration.cs b/src/Navigator/Configuration/Extension/NavigatorExtensionConfiguration.cs index f36b523..1c5e63c 100644 --- a/src/Navigator/Configuration/Extension/NavigatorExtensionConfiguration.cs +++ b/src/Navigator/Configuration/Extension/NavigatorExtensionConfiguration.cs @@ -21,14 +21,11 @@ public NavigatorExtensionConfiguration(NavigatorConfiguration navigatorConfigura /// /// Configure a new extension using this method. /// - /// - /// + /// /// - public NavigatorConfiguration Extension(Action? optionsAction, Action? servicesAction) + public NavigatorConfiguration Extension(Action<(NavigatorOptions Options, IServiceCollection Services)> configuration) { - optionsAction?.Invoke(_navigatorConfiguration.Options); - - servicesAction?.Invoke(_navigatorConfiguration.Services); + configuration.Invoke((_navigatorConfiguration.Options, _navigatorConfiguration.Services)); _navigatorConfiguration.RegisterOrReplaceOptions(); From f5848439ffda954b7ee3af16aa23a507c7adfdfa Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 5 Apr 2022 15:32:38 +0200 Subject: [PATCH 284/304] refactor: simplify provider configuration --- ...avigatorProviderConfigurationExtensions.cs | 27 ++++++++----------- .../NavigatorProviderConfiguration.cs | 11 +++----- 2 files changed, 15 insertions(+), 23 deletions(-) diff --git a/src/Navigator.Providers.Telegram/NavigatorProviderConfigurationExtensions.cs b/src/Navigator.Providers.Telegram/NavigatorProviderConfigurationExtensions.cs index 544a66d..6279f99 100644 --- a/src/Navigator.Providers.Telegram/NavigatorProviderConfigurationExtensions.cs +++ b/src/Navigator.Providers.Telegram/NavigatorProviderConfigurationExtensions.cs @@ -14,21 +14,16 @@ public static NavigatorConfiguration Telegram(this NavigatorProviderConfiguratio var telegramProviderOptions = new NavigatorTelegramProviderOptions(); options.Invoke(telegramProviderOptions); - return providerConfiguration.Provider( - optionsAction => optionsAction.Import(telegramProviderOptions.RetrieveAllOptions()), - services => - { - services.AddSingleton(); - services.AddSingleton(sp => sp.GetRequiredService()); - - services.AddScoped(); - - services.AddScoped(); - - services.AddScoped(); - - services.AddHostedService(); - - }); + return providerConfiguration.Provider(configuration => + { + configuration.Options.Import(telegramProviderOptions.RetrieveAllOptions()); + + configuration.Services.AddSingleton(); + configuration.Services.AddSingleton(sp => sp.GetRequiredService()); + configuration.Services.AddScoped(); + configuration.Services.AddScoped(); + configuration.Services.AddScoped(); + configuration.Services.AddHostedService(); + }); } } \ No newline at end of file diff --git a/src/Navigator/Configuration/Provider/NavigatorProviderConfiguration.cs b/src/Navigator/Configuration/Provider/NavigatorProviderConfiguration.cs index 3a9ffe6..7ea31de 100644 --- a/src/Navigator/Configuration/Provider/NavigatorProviderConfiguration.cs +++ b/src/Navigator/Configuration/Provider/NavigatorProviderConfiguration.cs @@ -21,15 +21,12 @@ public NavigatorProviderConfiguration(NavigatorConfiguration navigatorConfigurat /// /// Configure a new provider using this method. /// - /// - /// + /// /// - public NavigatorConfiguration Provider(Action? optionsAction, Action? servicesAction) + public NavigatorConfiguration Provider(Action<(NavigatorOptions Options, IServiceCollection Services)> configuration) { - optionsAction?.Invoke(_navigatorConfiguration.Options); - - servicesAction?.Invoke(_navigatorConfiguration.Services); - + configuration.Invoke((_navigatorConfiguration.Options, _navigatorConfiguration.Services)); + _navigatorConfiguration.RegisterOrReplaceOptions(); return _navigatorConfiguration; From 497fa225487c81b4dcb525a93912c0a41a65acf1 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 5 Apr 2022 15:47:47 +0200 Subject: [PATCH 285/304] feat: add force parameter to some options extensions --- .../Actions/NavigatorOptionsExtensions.cs | 31 ++++++++++++++++--- src/Navigator/ServiceCollectionExtensions.cs | 4 +++ 2 files changed, 30 insertions(+), 5 deletions(-) diff --git a/src/Navigator/Actions/NavigatorOptionsExtensions.cs b/src/Navigator/Actions/NavigatorOptionsExtensions.cs index 2cebaac..d4c5d67 100644 --- a/src/Navigator/Actions/NavigatorOptionsExtensions.cs +++ b/src/Navigator/Actions/NavigatorOptionsExtensions.cs @@ -15,11 +15,20 @@ public static class NavigatorOptionsExtensions /// /// /// - public static void RegisterActionsCore(this NavigatorOptions navigatorOptions, IEnumerable actions) + /// + public static void RegisterActionsCore(this NavigatorOptions navigatorOptions, IEnumerable actions, bool force = false) { var actionsDictionary = actions.GroupBy(type => type.GetActionType()) .ToImmutableDictionary(types => types.Key, types => types.ToArray()); - navigatorOptions.TryRegisterOption(NavigatorActionTypeCollection, actionsDictionary); + + if (force) + { + navigatorOptions.ForceRegisterOption(NavigatorActionTypeCollection, actionsDictionary); + } + else + { + navigatorOptions.TryRegisterOption(NavigatorActionTypeCollection, actionsDictionary); + } } /// @@ -42,12 +51,24 @@ public static ImmutableDictionary RetrieveActions(this NavigatorO /// Pseudo-internal call, don't use it unless you know what you are doing. /// /// + /// + /// /// - public static void RegisterPriority(this NavigatorOptions navigatorOptions, IEnumerable actions) + public static void RegisterActionsPriorityCore(this NavigatorOptions navigatorOptions, IEnumerable actions, bool force = false) { - navigatorOptions.TryRegisterOption(NavigatorActionPriorityCollection, actions.ToImmutableDictionary( + var priorityTable = actions.ToImmutableDictionary( type => type.FullName ?? string.Empty, - type => type.GetActionPriority())); + type => type.GetActionPriority()); + + if (force) + { + navigatorOptions.ForceRegisterOption(NavigatorActionPriorityCollection, priorityTable); + + } + else + { + navigatorOptions.TryRegisterOption(NavigatorActionPriorityCollection, priorityTable); + } } /// diff --git a/src/Navigator/ServiceCollectionExtensions.cs b/src/Navigator/ServiceCollectionExtensions.cs index 7f8dbbd..774184f 100644 --- a/src/Navigator/ServiceCollectionExtensions.cs +++ b/src/Navigator/ServiceCollectionExtensions.cs @@ -38,6 +38,10 @@ public static NavigatorConfiguration AddNavigator(this IServiceCollection servic navigatorBuilder.Options.RegisterActionsCore(services .Where(descriptor => descriptor.ImplementationType?.IsAssignableTo(typeof(IAction)) ?? false) .Select(descriptor => descriptor.ImplementationType!)); + + navigatorBuilder.Options.RegisterActionsPriorityCore(services + .Where(descriptor => descriptor.ImplementationType?.IsAssignableTo(typeof(IAction)) ?? false) + .Select(descriptor => descriptor.ImplementationType!)); navigatorBuilder.RegisterOrReplaceOptions(); From 89c90deaf238cf70b0a96e4972438d78e7f11db0 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Tue, 5 Apr 2022 16:49:18 +0200 Subject: [PATCH 286/304] feat: implement basic GetOriginalEvent with no type casting --- .../Bundled/OriginalEvent/NavigatorContextExtensions.cs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/Navigator/Context/Extensions/Bundled/OriginalEvent/NavigatorContextExtensions.cs b/src/Navigator/Context/Extensions/Bundled/OriginalEvent/NavigatorContextExtensions.cs index 4a14fc9..07096ff 100644 --- a/src/Navigator/Context/Extensions/Bundled/OriginalEvent/NavigatorContextExtensions.cs +++ b/src/Navigator/Context/Extensions/Bundled/OriginalEvent/NavigatorContextExtensions.cs @@ -4,6 +4,11 @@ public static class NavigatorContextExtensions { #region OriginalEvent + public static object? GetOriginalEvent(this INavigatorContext navigatorContext) + { + return navigatorContext.Extensions.GetValueOrDefault(OriginalEventContextExtension.OriginalEventKey); + } + public static TEvent GetOriginalEvent(this INavigatorContext navigatorContext) where TEvent : class { var update = navigatorContext.GetOriginalEventOrDefault(); From e59c346555a2e949b760a039300bc72b60cc7562 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Wed, 6 Apr 2022 16:32:59 +0200 Subject: [PATCH 287/304] fix: correct memory leak on store --- ...vigatorExtensionConfigurationExtensions.cs | 21 ++++++++++++++++ .../NavigatorStoreTelegramExtension.cs | 25 ------------------- .../NavigatorStoreTelegramExtensionInfo.cs | 21 ---------------- src/Navigator.Samples.Store/Program.cs | 4 +-- 4 files changed, 22 insertions(+), 49 deletions(-) create mode 100644 src/Navigator.Extensions.Store.Telegram/NavigatorExtensionConfigurationExtensions.cs delete mode 100644 src/Navigator.Extensions.Store.Telegram/NavigatorStoreTelegramExtension.cs delete mode 100644 src/Navigator.Extensions.Store.Telegram/NavigatorStoreTelegramExtensionInfo.cs diff --git a/src/Navigator.Extensions.Store.Telegram/NavigatorExtensionConfigurationExtensions.cs b/src/Navigator.Extensions.Store.Telegram/NavigatorExtensionConfigurationExtensions.cs new file mode 100644 index 0000000..6b6445b --- /dev/null +++ b/src/Navigator.Extensions.Store.Telegram/NavigatorExtensionConfigurationExtensions.cs @@ -0,0 +1,21 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Navigator.Configuration; +using Navigator.Configuration.Extension; +using Navigator.Extensions.Store.Extractors; +using Navigator.Extensions.Store.Telegram.Extractors; + +namespace Navigator.Extensions.Store.Telegram; + +public static class NavigatorExtensionConfigurationExtensions +{ + public static NavigatorConfiguration StoreForTelegram(this NavigatorExtensionConfiguration extensionConfiguration, Action? dbContextOptions = default) + { + return extensionConfiguration.Extension(configuration => + { + configuration.Services.AddSingleton(); + configuration.Services.AddSingleton(); + configuration.Services.AddSingleton(); + }); + } +} \ No newline at end of file diff --git a/src/Navigator.Extensions.Store.Telegram/NavigatorStoreTelegramExtension.cs b/src/Navigator.Extensions.Store.Telegram/NavigatorStoreTelegramExtension.cs deleted file mode 100644 index b9ec9a5..0000000 --- a/src/Navigator.Extensions.Store.Telegram/NavigatorStoreTelegramExtension.cs +++ /dev/null @@ -1,25 +0,0 @@ -using Microsoft.EntityFrameworkCore.Infrastructure; -using Microsoft.Extensions.DependencyInjection; -using Navigator.Extensions.Store.Context.Extension; -using Navigator.Extensions.Store.Extractors; -using Navigator.Extensions.Store.Telegram.Extractors; - -namespace Navigator.Extensions.Store.Telegram; - - -public class NavigatorStoreTelegramExtension : NavigatorStoreModelExtension -{ - public NavigatorStoreTelegramExtension() - { - ExtensionServices = services => - { - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - }; - - Info = new NavigatorStoreTelegramExtensionInfo(this); - } - - public override DbContextOptionsExtensionInfo Info { get; } -} \ No newline at end of file diff --git a/src/Navigator.Extensions.Store.Telegram/NavigatorStoreTelegramExtensionInfo.cs b/src/Navigator.Extensions.Store.Telegram/NavigatorStoreTelegramExtensionInfo.cs deleted file mode 100644 index e0b214f..0000000 --- a/src/Navigator.Extensions.Store.Telegram/NavigatorStoreTelegramExtensionInfo.cs +++ /dev/null @@ -1,21 +0,0 @@ -using Microsoft.EntityFrameworkCore.Infrastructure; -using Navigator.Extensions.Store.Context.Extension; - -namespace Navigator.Extensions.Store.Telegram; - -public class NavigatorStoreTelegramExtensionInfo : NavigatorStoreModelExtensionInfo -{ - public NavigatorStoreTelegramExtensionInfo(IDbContextOptionsExtension extension) : base(extension) - { - } - - public override int GetServiceProviderHashCode() - { - var hashCode = new HashCode(); - - hashCode.Add(base.GetServiceProviderHashCode()); - hashCode.Add(Extension); - - return hashCode.ToHashCode(); - } -} \ No newline at end of file diff --git a/src/Navigator.Samples.Store/Program.cs b/src/Navigator.Samples.Store/Program.cs index 21edb26..243bca6 100644 --- a/src/Navigator.Samples.Store/Program.cs +++ b/src/Navigator.Samples.Store/Program.cs @@ -32,9 +32,7 @@ { dbBuilder.UseSqlite(builder.Configuration.GetConnectionString("DefaultConnection"), b => b.MigrationsAssembly("Navigator.Samples.Store")); - - dbBuilder.UsingStoreExtension(); - }); + }).WithExtension.StoreForTelegram(); var app = builder.Build(); From eda1d351833656bd9a1dedb57c527b28046f4c92 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Thu, 7 Apr 2022 10:40:51 +0200 Subject: [PATCH 288/304] fix: correct conversation context update --- .../StoreConversationContextExtension.cs | 2 ++ src/Navigator.Samples.Store/app.db-shm | Bin 0 -> 32768 bytes src/Navigator.Samples.Store/app.db-wal | 0 3 files changed, 2 insertions(+) create mode 100644 src/Navigator.Samples.Store/app.db-shm create mode 100644 src/Navigator.Samples.Store/app.db-wal diff --git a/src/Navigator.Extensions.Store/Bundled/StoreConversationContextExtension.cs b/src/Navigator.Extensions.Store/Bundled/StoreConversationContextExtension.cs index 680648f..2f5dde7 100644 --- a/src/Navigator.Extensions.Store/Bundled/StoreConversationContextExtension.cs +++ b/src/Navigator.Extensions.Store/Bundled/StoreConversationContextExtension.cs @@ -65,6 +65,8 @@ public async Task Extend(INavigatorContext navigatorContext, private async Task TryStoreChatAsync(Navigator.Entities.Conversation source) { if (source.Chat is null) return default; + + if (await _dbContext.Chats.AnyAsync(chat => chat.Id == source.Chat.Id)) return default; var chat = new Chat { diff --git a/src/Navigator.Samples.Store/app.db-shm b/src/Navigator.Samples.Store/app.db-shm new file mode 100644 index 0000000000000000000000000000000000000000..fe9ac2845eca6fe6da8a63cd096d9cf9e24ece10 GIT binary patch literal 32768 zcmeIuAr62r3 Date: Thu, 7 Apr 2022 13:51:37 +0200 Subject: [PATCH 289/304] feat: make ActionLauncher capable of launching multiple actions of the same type --- src/Navigator/Actions/ActionLauncher.cs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/Navigator/Actions/ActionLauncher.cs b/src/Navigator/Actions/ActionLauncher.cs index f6e0cf3..4d74114 100644 --- a/src/Navigator/Actions/ActionLauncher.cs +++ b/src/Navigator/Actions/ActionLauncher.cs @@ -1,5 +1,6 @@ using System.Collections.Immutable; using MediatR; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Navigator.Configuration; using Navigator.Context; @@ -61,7 +62,8 @@ private IEnumerable GetActions() { return actions .SelectMany(groups => groups.Value) - .Select(actionType => ((IAction) _serviceProvider.GetService(actionType)!, actionType.FullName)) + .SelectMany(actionType => _serviceProvider.GetServices(actionType) + .Select(action =>((IAction) action!, actionType.FullName))) .Where(a => a.Item1.CanHandleCurrentContext()) .OrderBy(a => _priorities.GetValueOrDefault(a.FullName ?? string.Empty, Priority.Default)) .Select(a => a.Item1) @@ -70,7 +72,8 @@ private IEnumerable GetActions() var action = actions .SelectMany(groups => groups.Value) - .Select(actionType => ((IAction) _serviceProvider.GetService(actionType)!, actionType.FullName)) + .SelectMany(actionType => _serviceProvider.GetServices(actionType) + .Select(action =>((IAction) action!, actionType.FullName))) .OrderBy(a => _priorities.GetValueOrDefault(a.FullName ?? string.Empty, Priority.Default)) .Select(a => a.Item1) .FirstOrDefault(a => a.CanHandleCurrentContext()); From d0a9355ccdde2d684114f1fec82a9d1dbc4beaa6 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Fri, 8 Apr 2022 14:32:50 +0200 Subject: [PATCH 290/304] feat: move cooldown extension to its own repository --- .../CooldownActionMiddleware.cs | 45 ------------------- .../CooldownAttribute.cs | 7 --- .../Extensions/TypeExtensions.cs | 14 ------ .../Navigator.Extensions.Cooldown.csproj | 24 ---------- ...vigatorExtensionConfigurationExtensions.cs | 27 ----------- .../Navigator.Extensions.Interop.csproj | 9 ---- .../Actions/CooldownAction.cs | 18 -------- .../Actions/CooldownActionHandler.cs | 23 ---------- .../Navigator.Samples.Echo.csproj | 1 - src/Navigator.Samples.Echo/Program.cs | 2 - .../Actions/CooldownAction.cs | 18 -------- .../Actions/CooldownActionHandler.cs | 23 ---------- .../Navigator.Samples.Store.csproj | 1 - src/Navigator.Samples.Store/Program.cs | 3 -- src/Navigator.sln | 7 --- 15 files changed, 222 deletions(-) delete mode 100644 src/Navigator.Extensions.Cooldown/CooldownActionMiddleware.cs delete mode 100644 src/Navigator.Extensions.Cooldown/CooldownAttribute.cs delete mode 100644 src/Navigator.Extensions.Cooldown/Extensions/TypeExtensions.cs delete mode 100644 src/Navigator.Extensions.Cooldown/Navigator.Extensions.Cooldown.csproj delete mode 100644 src/Navigator.Extensions.Cooldown/NavigatorExtensionConfigurationExtensions.cs delete mode 100644 src/Navigator.Extensions.Interop/Navigator.Extensions.Interop.csproj delete mode 100644 src/Navigator.Samples.Echo/Actions/CooldownAction.cs delete mode 100644 src/Navigator.Samples.Echo/Actions/CooldownActionHandler.cs delete mode 100644 src/Navigator.Samples.Store/Actions/CooldownAction.cs delete mode 100644 src/Navigator.Samples.Store/Actions/CooldownActionHandler.cs diff --git a/src/Navigator.Extensions.Cooldown/CooldownActionMiddleware.cs b/src/Navigator.Extensions.Cooldown/CooldownActionMiddleware.cs deleted file mode 100644 index ec4fc1c..0000000 --- a/src/Navigator.Extensions.Cooldown/CooldownActionMiddleware.cs +++ /dev/null @@ -1,45 +0,0 @@ -using MediatR; -using Microsoft.Extensions.Caching.Distributed; -using Navigator.Actions; -using Navigator.Context; -using Navigator.Extensions.Cooldown.Extensions; - -namespace Navigator.Extensions.Cooldown; - -internal class CooldownActionMiddleware : IActionMiddleware where TAction : IAction -{ - private readonly IDistributedCache _cache; - private readonly INavigatorContext _navigatorContext; - - public CooldownActionMiddleware(IDistributedCache cache, INavigatorContextAccessor navigatorContextAccessor) - { - _cache = cache; - _navigatorContext = navigatorContextAccessor.NavigatorContext; - } - - public async Task Handle(TAction action, CancellationToken cancellationToken, RequestHandlerDelegate next) - { - var key = GenerateKey(action); - - var cooldownStatus = await _cache.GetAsync(key, cancellationToken); - - if (cooldownStatus is not null) - { - return new Status(true); - } - - var status = await next(); - - if (status.IsSuccess && typeof(TAction).GetCooldown() is { } cooldown) - { - await _cache.SetStringAsync(key, key, new DistributedCacheEntryOptions().SetAbsoluteExpiration(cooldown), cancellationToken); - } - - return status; - } - - private string GenerateKey(TAction action) - { - return $"{action.GetType().FullName}:{_navigatorContext.Conversation.Chat?.Id.ToString() ?? "no_chat"}"; - } -} \ No newline at end of file diff --git a/src/Navigator.Extensions.Cooldown/CooldownAttribute.cs b/src/Navigator.Extensions.Cooldown/CooldownAttribute.cs deleted file mode 100644 index 62922aa..0000000 --- a/src/Navigator.Extensions.Cooldown/CooldownAttribute.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace Navigator.Extensions.Cooldown; - -[AttributeUsage(AttributeTargets.Class)] -public class CooldownAttribute : Attribute -{ - public int Seconds { get; set; } = 300; -} diff --git a/src/Navigator.Extensions.Cooldown/Extensions/TypeExtensions.cs b/src/Navigator.Extensions.Cooldown/Extensions/TypeExtensions.cs deleted file mode 100644 index 3b04dd6..0000000 --- a/src/Navigator.Extensions.Cooldown/Extensions/TypeExtensions.cs +++ /dev/null @@ -1,14 +0,0 @@ -namespace Navigator.Extensions.Cooldown.Extensions; - -internal static class TypeExtensions -{ - public static TimeSpan? GetCooldown(this Type type) - { - if (Attribute.GetCustomAttribute(type, typeof(CooldownAttribute)) is CooldownAttribute cooldownAttribute) - { - return TimeSpan.FromSeconds(cooldownAttribute.Seconds); - } - - return default; - } -} \ No newline at end of file diff --git a/src/Navigator.Extensions.Cooldown/Navigator.Extensions.Cooldown.csproj b/src/Navigator.Extensions.Cooldown/Navigator.Extensions.Cooldown.csproj deleted file mode 100644 index b80a304..0000000 --- a/src/Navigator.Extensions.Cooldown/Navigator.Extensions.Cooldown.csproj +++ /dev/null @@ -1,24 +0,0 @@ - - - - net6.0 - true - enable - true - Navigator.Extensions.Cooldown - Lucas Maximiliano Marino - Drop-in cooldown extension for Navigator Framework bots - https://github.com/navigatorframework/navigator - https://github.com/navigatorframework/navigator - https://raw.githubusercontent.com/navigatorframework/navigator/master/assets/logo.png - Cooldown, Bot, Extension, Navigator - true - AGPL-3.0-only - Copyright © Lucas Maximiliano Marino 2022 - - - - - - - diff --git a/src/Navigator.Extensions.Cooldown/NavigatorExtensionConfigurationExtensions.cs b/src/Navigator.Extensions.Cooldown/NavigatorExtensionConfigurationExtensions.cs deleted file mode 100644 index 2718b15..0000000 --- a/src/Navigator.Extensions.Cooldown/NavigatorExtensionConfigurationExtensions.cs +++ /dev/null @@ -1,27 +0,0 @@ -using MediatR; -using Microsoft.Extensions.DependencyInjection; -using Navigator.Configuration; -using Navigator.Configuration.Extension; - -namespace Navigator.Extensions.Cooldown; - -/// -/// Extensions to NavigatorConfiguration -/// -public static class NavigatorExtensionConfigurationExtensions -{ - /// - /// Configures the Cooldown extension. - /// - /// - /// - public static NavigatorConfiguration Cooldown(this NavigatorExtensionConfiguration extensionConfiguration) - { - - return extensionConfiguration.Extension( - configuration => - { - configuration.Services.AddScoped(typeof(IPipelineBehavior<,>), typeof(CooldownActionMiddleware<,>)); - }); - } -} \ No newline at end of file diff --git a/src/Navigator.Extensions.Interop/Navigator.Extensions.Interop.csproj b/src/Navigator.Extensions.Interop/Navigator.Extensions.Interop.csproj deleted file mode 100644 index eb2460e..0000000 --- a/src/Navigator.Extensions.Interop/Navigator.Extensions.Interop.csproj +++ /dev/null @@ -1,9 +0,0 @@ - - - - net6.0 - enable - enable - - - diff --git a/src/Navigator.Samples.Echo/Actions/CooldownAction.cs b/src/Navigator.Samples.Echo/Actions/CooldownAction.cs deleted file mode 100644 index 776c81e..0000000 --- a/src/Navigator.Samples.Echo/Actions/CooldownAction.cs +++ /dev/null @@ -1,18 +0,0 @@ -using Navigator.Context; -using Navigator.Extensions.Cooldown; -using Navigator.Providers.Telegram.Actions.Messages; - -namespace Navigator.Samples.Echo.Actions; - -[Cooldown(Seconds = 10)] -public class CooldownAction : CommandAction -{ - public CooldownAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) - { - } - - public override bool CanHandleCurrentContext() - { - return Command.StartsWith("/cooldown", true, default); - } -} \ No newline at end of file diff --git a/src/Navigator.Samples.Echo/Actions/CooldownActionHandler.cs b/src/Navigator.Samples.Echo/Actions/CooldownActionHandler.cs deleted file mode 100644 index 573e08c..0000000 --- a/src/Navigator.Samples.Echo/Actions/CooldownActionHandler.cs +++ /dev/null @@ -1,23 +0,0 @@ -using System.Threading; -using System.Threading.Tasks; -using Navigator.Actions; -using Navigator.Context; -using Navigator.Providers.Telegram; -using Telegram.Bot; - -namespace Navigator.Samples.Echo.Actions; - -public class CooldownActionHandler : ActionHandler -{ - public CooldownActionHandler(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) - { - } - - public override async Task Handle(CooldownAction action, CancellationToken cancellationToken) - { - await this.GetTelegramClient().SendTextMessageAsync(this.GetTelegramChat().Id, - "not in cooldown", cancellationToken: cancellationToken); - - return Success(); - } -} \ No newline at end of file diff --git a/src/Navigator.Samples.Echo/Navigator.Samples.Echo.csproj b/src/Navigator.Samples.Echo/Navigator.Samples.Echo.csproj index ed9f8e7..0744581 100644 --- a/src/Navigator.Samples.Echo/Navigator.Samples.Echo.csproj +++ b/src/Navigator.Samples.Echo/Navigator.Samples.Echo.csproj @@ -6,7 +6,6 @@ - diff --git a/src/Navigator.Samples.Echo/Program.cs b/src/Navigator.Samples.Echo/Program.cs index 19eb0f8..36c82cd 100644 --- a/src/Navigator.Samples.Echo/Program.cs +++ b/src/Navigator.Samples.Echo/Program.cs @@ -3,7 +3,6 @@ using Microsoft.Extensions.Hosting; using Navigator; using Navigator.Configuration; -using Navigator.Extensions.Cooldown; using Navigator.Providers.Telegram; using Navigator.Samples.Echo.Actions; @@ -20,7 +19,6 @@ options.SetWebHookBaseUrl(builder.Configuration["BASE_WEBHOOK_URL"]); options.RegisterActionsFromAssemblies(typeof(EchoAction).Assembly); }) - .WithExtension.Cooldown() .WithProvider.Telegram(options => { options.SetTelegramToken(builder.Configuration["BOT_TOKEN"]); }); var app = builder.Build(); diff --git a/src/Navigator.Samples.Store/Actions/CooldownAction.cs b/src/Navigator.Samples.Store/Actions/CooldownAction.cs deleted file mode 100644 index f436cbf..0000000 --- a/src/Navigator.Samples.Store/Actions/CooldownAction.cs +++ /dev/null @@ -1,18 +0,0 @@ -using Navigator.Context; -using Navigator.Extensions.Cooldown; -using Navigator.Providers.Telegram.Actions.Messages; - -namespace Navigator.Samples.Store.Actions; - -[Cooldown(Seconds = 10)] -public class CooldownAction : CommandAction -{ - public CooldownAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) - { - } - - public override bool CanHandleCurrentContext() - { - return Command.StartsWith("/cooldown", true, default); - } -} \ No newline at end of file diff --git a/src/Navigator.Samples.Store/Actions/CooldownActionHandler.cs b/src/Navigator.Samples.Store/Actions/CooldownActionHandler.cs deleted file mode 100644 index cb1940c..0000000 --- a/src/Navigator.Samples.Store/Actions/CooldownActionHandler.cs +++ /dev/null @@ -1,23 +0,0 @@ -using System.Threading; -using System.Threading.Tasks; -using Navigator.Actions; -using Navigator.Context; -using Navigator.Providers.Telegram; -using Telegram.Bot; - -namespace Navigator.Samples.Store.Actions; - -public class CooldownActionHandler : ActionHandler -{ - public CooldownActionHandler(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) - { - } - - public override async Task Handle(CooldownAction action, CancellationToken cancellationToken) - { - await this.GetTelegramClient().SendTextMessageAsync(this.GetTelegramChat().Id, - "not in cooldown", cancellationToken: cancellationToken); - - return Success(); - } -} \ No newline at end of file diff --git a/src/Navigator.Samples.Store/Navigator.Samples.Store.csproj b/src/Navigator.Samples.Store/Navigator.Samples.Store.csproj index a3f0665..579f5d0 100644 --- a/src/Navigator.Samples.Store/Navigator.Samples.Store.csproj +++ b/src/Navigator.Samples.Store/Navigator.Samples.Store.csproj @@ -14,7 +14,6 @@ - diff --git a/src/Navigator.Samples.Store/Program.cs b/src/Navigator.Samples.Store/Program.cs index 243bca6..855083c 100644 --- a/src/Navigator.Samples.Store/Program.cs +++ b/src/Navigator.Samples.Store/Program.cs @@ -5,10 +5,8 @@ using Microsoft.Extensions.Hosting; using Navigator; using Navigator.Configuration; -using Navigator.Extensions.Cooldown; using Navigator.Extensions.Store; using Navigator.Extensions.Store.Context; -using Navigator.Extensions.Store.Context.Extension; using Navigator.Extensions.Store.Telegram; using Navigator.Providers.Telegram; using Navigator.Samples.Store.Actions; @@ -27,7 +25,6 @@ options.RegisterActionsFromAssemblies(typeof(EchoAction).Assembly); }) .WithProvider.Telegram(options => { options.SetTelegramToken(builder.Configuration["BOT_TOKEN"]); }) - .WithExtension.Cooldown() .WithExtension.Store(dbBuilder => { dbBuilder.UseSqlite(builder.Configuration.GetConnectionString("DefaultConnection"), diff --git a/src/Navigator.sln b/src/Navigator.sln index b0ddcdd..1032ab6 100644 --- a/src/Navigator.sln +++ b/src/Navigator.sln @@ -11,8 +11,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Navigator.Providers.Telegra EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Navigator.Samples.Echo", "Navigator.Samples.Echo\Navigator.Samples.Echo.csproj", "{4F4CEC5E-5FAF-4914-8EC0-E6BC9EB1B975}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Navigator.Extensions.Cooldown", "Navigator.Extensions.Cooldown\Navigator.Extensions.Cooldown.csproj", "{B7013C91-C736-4041-9952-5AC2471D9E9A}" -EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Extensions", "Extensions", "{A6DF6F5F-F784-4EF1-97D1-C3DDD2E66B5E}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Navigator.Extensions.Store", "Navigator.Extensions.Store\Navigator.Extensions.Store.csproj", "{E7D6F33B-C30E-4ED2-878C-B2F899CF1805}" @@ -39,10 +37,6 @@ Global {4F4CEC5E-5FAF-4914-8EC0-E6BC9EB1B975}.Debug|Any CPU.Build.0 = Debug|Any CPU {4F4CEC5E-5FAF-4914-8EC0-E6BC9EB1B975}.Release|Any CPU.ActiveCfg = Release|Any CPU {4F4CEC5E-5FAF-4914-8EC0-E6BC9EB1B975}.Release|Any CPU.Build.0 = Release|Any CPU - {B7013C91-C736-4041-9952-5AC2471D9E9A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {B7013C91-C736-4041-9952-5AC2471D9E9A}.Debug|Any CPU.Build.0 = Debug|Any CPU - {B7013C91-C736-4041-9952-5AC2471D9E9A}.Release|Any CPU.ActiveCfg = Release|Any CPU - {B7013C91-C736-4041-9952-5AC2471D9E9A}.Release|Any CPU.Build.0 = Release|Any CPU {E7D6F33B-C30E-4ED2-878C-B2F899CF1805}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {E7D6F33B-C30E-4ED2-878C-B2F899CF1805}.Debug|Any CPU.Build.0 = Debug|Any CPU {E7D6F33B-C30E-4ED2-878C-B2F899CF1805}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -60,7 +54,6 @@ Global {6DBAD041-6623-4903-9939-254FDC4EBD60} = {E6F24E3B-A066-4572-94F0-14665E19EFC7} {8E0F6DCA-FAA4-4FA8-B9E0-75E9DC0F3573} = {DAA22477-BB29-475C-AD2C-905F81B4AD8E} {4F4CEC5E-5FAF-4914-8EC0-E6BC9EB1B975} = {6D6A8E40-8C40-49AA-BEAD-B046D43F511A} - {B7013C91-C736-4041-9952-5AC2471D9E9A} = {A6DF6F5F-F784-4EF1-97D1-C3DDD2E66B5E} {DAA22477-BB29-475C-AD2C-905F81B4AD8E} = {E6F24E3B-A066-4572-94F0-14665E19EFC7} {A6DF6F5F-F784-4EF1-97D1-C3DDD2E66B5E} = {E6F24E3B-A066-4572-94F0-14665E19EFC7} {E7D6F33B-C30E-4ED2-878C-B2F899CF1805} = {A6DF6F5F-F784-4EF1-97D1-C3DDD2E66B5E} From 14754b64d185546250fb63e97ba36b51ec8f2724 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sat, 9 Apr 2022 19:22:38 +0200 Subject: [PATCH 291/304] feat: implement INavigatorStore --- .../INavigatorStore.cs | 16 ++ .../NavigatorStore.cs | 189 ++++++++++++++++++ 2 files changed, 205 insertions(+) create mode 100644 src/Navigator.Extensions.Store/INavigatorStore.cs create mode 100644 src/Navigator.Extensions.Store/NavigatorStore.cs diff --git a/src/Navigator.Extensions.Store/INavigatorStore.cs b/src/Navigator.Extensions.Store/INavigatorStore.cs new file mode 100644 index 0000000..6286319 --- /dev/null +++ b/src/Navigator.Extensions.Store/INavigatorStore.cs @@ -0,0 +1,16 @@ +using Navigator.Entities; + +namespace Navigator.Extensions.Store; + +public interface INavigatorStore +{ + public IDictionary? GetData(User? user = default); + public IDictionary? GetData(Chat? chat = default); + public Task?> GetDataAsync(User? user = default, CancellationToken cancellationToken = default); + public Task?> GetDataAsync(Chat? chat = default, CancellationToken cancellationToken = default); + + public bool TryAddData(User user, string key, object data, bool force = false); + public bool TryAddData(Chat chat, string key, object data, bool force = false); + public Task TryAddDataAsync(User user, string key, object data, bool force = false, CancellationToken cancellationToken = default); + public Task TryAddDataAsync(Chat chat, string key, object data, bool force = false, CancellationToken cancellationToken = default); +} \ No newline at end of file diff --git a/src/Navigator.Extensions.Store/NavigatorStore.cs b/src/Navigator.Extensions.Store/NavigatorStore.cs new file mode 100644 index 0000000..d70d423 --- /dev/null +++ b/src/Navigator.Extensions.Store/NavigatorStore.cs @@ -0,0 +1,189 @@ +using System.Text.Json; +using System.Text.Json.Serialization; +using Navigator.Context; +using Navigator.Entities; +using Navigator.Extensions.Store.Context; + +namespace Navigator.Extensions.Store; + +public class NavigatorStore : INavigatorStore +{ + private readonly INavigatorContextAccessor _navigatorContextAccessor; + private readonly NavigatorDbContext _dbContext; + + public NavigatorStore(INavigatorContextAccessor navigatorContextAccessor, NavigatorDbContext dbContext) + { + _navigatorContextAccessor = navigatorContextAccessor; + _dbContext = dbContext; + } + + public IDictionary? GetData(User? user = default) + { + user ??= _navigatorContextAccessor.NavigatorContext.Conversation.User; + + return _dbContext.Users.Find(user.Id)?.Data; + } + + public IDictionary? GetData(Chat? chat = default) + { + chat ??= _navigatorContextAccessor.NavigatorContext.Conversation.Chat; + + return _dbContext.Users.Find(chat?.Id)?.Data; + } + + public async Task?> GetDataAsync(User? user = default, CancellationToken cancellationToken = default) + { + user ??= _navigatorContextAccessor.NavigatorContext.Conversation.User; + + return (await _dbContext.Users.FindAsync(new object?[] { user.Id }, cancellationToken))?.Data; + } + + public async Task?> GetDataAsync(Chat? chat = default, CancellationToken cancellationToken = default) + { + chat ??= _navigatorContextAccessor.NavigatorContext.Conversation.Chat; + + return (await _dbContext.Chats.FindAsync(new object?[] { chat?.Id }, cancellationToken))?.Data; + } + + public bool TryAddData(User user, string key, object data, bool force = false) + { + var storedUser = _dbContext.Users.Find(user.Id); + + if (storedUser is null) return false; + + try + { + switch (force) + { + case true: + if (storedUser.Data.ContainsKey(key)) storedUser.Data.Remove(key); + return TryAddKeyValue(); + case false: + return TryAddKeyValue(); + } + } + catch (Exception) + { + return false; + } + + bool TryAddKeyValue() + { + if (!storedUser.Data.TryAdd(key, JsonSerializer.Serialize(data))) + { + return false; + } + + _dbContext.SaveChanges(); + + return true; + } + } + + public bool TryAddData(Chat chat, string key, object data, bool force = false) + { + var storedChat = _dbContext.Chats.Find(chat.Id); + + if (storedChat is null) return false; + + try + { + switch (force) + { + case true: + if (storedChat.Data.ContainsKey(key)) storedChat.Data.Remove(key); + return TryAddKeyValue(); + case false: + return TryAddKeyValue(); + } + } + catch (Exception) + { + return false; + } + + bool TryAddKeyValue() + { + if (!storedChat.Data.TryAdd(key, JsonSerializer.Serialize(data))) + { + return false; + } + + _dbContext.SaveChanges(); + + return true; + } + } + + public async Task TryAddDataAsync(User user, string key, object data, bool force = false, CancellationToken cancellationToken = default) + { + var storedUser = await _dbContext.Chats.FindAsync(new object?[] { user.Id }, cancellationToken); + + if (storedUser is null) return false; + + try + { + switch (force) + { + case true: + if (storedUser.Data.ContainsKey(key)) storedUser.Data.Remove(key); + return await TryAddKeyValueAsync(); + case false: + return await TryAddKeyValueAsync(); + } + } + catch (Exception e) + { + Console.WriteLine(e); + throw; + } + + async Task TryAddKeyValueAsync() + { + if (!storedUser.Data.TryAdd(key, JsonSerializer.Serialize(data))) + { + return false; + } + + await _dbContext.SaveChangesAsync(cancellationToken); + + return true; + } + } + + public async Task TryAddDataAsync(Chat chat, string key, object data, bool force = false, CancellationToken cancellationToken = default) + { + var storedChat = await _dbContext.Chats.FindAsync(new object?[] { chat.Id }, cancellationToken); + + if (storedChat is null) return false; + + try + { + switch (force) + { + case true: + if (storedChat.Data.ContainsKey(key)) storedChat.Data.Remove(key); + return await TryAddKeyValueAsync(); + case false: + return await TryAddKeyValueAsync(); + } + } + catch (Exception e) + { + Console.WriteLine(e); + throw; + } + + async Task TryAddKeyValueAsync() + { + if (!storedChat.Data.TryAdd(key, JsonSerializer.Serialize(data))) + { + return false; + } + + await _dbContext.SaveChangesAsync(cancellationToken); + + return true; + } + } +} \ No newline at end of file From 35fbcc2ff917d097ff462fbac6ef1dacc0e4d99e Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sat, 9 Apr 2022 19:23:06 +0200 Subject: [PATCH 292/304] feat: add INavigatorStore to DI --- .../NavigatorExtensionConfigurationExtensions.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/Navigator.Extensions.Store/NavigatorExtensionConfigurationExtensions.cs b/src/Navigator.Extensions.Store/NavigatorExtensionConfigurationExtensions.cs index 3db4867..916a559 100644 --- a/src/Navigator.Extensions.Store/NavigatorExtensionConfigurationExtensions.cs +++ b/src/Navigator.Extensions.Store/NavigatorExtensionConfigurationExtensions.cs @@ -23,7 +23,9 @@ public static NavigatorConfiguration Store(this NavigatorExtensionConfiguration configuration.Services.AddDbContext(dbContextOptions); configuration.Services.AddScoped(); - + + configuration.Services.AddScoped(); + foreach (var extension in temporal.Options.Extensions.OfType()) { extension.ExtensionServices?.Invoke(configuration.Services); From c762f75918e1e3822beffdfd9bcce069eaa75358 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sat, 9 Apr 2022 19:23:17 +0200 Subject: [PATCH 293/304] feat: add extensions to use store --- .../Extensions/NavigatorContextExtensions.cs | 25 +++++++++++++++++++ .../Bundled/StoreContextExtensions.cs | 23 +++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 src/Navigator.Extensions.Store/Bundled/Extensions/NavigatorContextExtensions.cs create mode 100644 src/Navigator.Extensions.Store/Bundled/StoreContextExtensions.cs diff --git a/src/Navigator.Extensions.Store/Bundled/Extensions/NavigatorContextExtensions.cs b/src/Navigator.Extensions.Store/Bundled/Extensions/NavigatorContextExtensions.cs new file mode 100644 index 0000000..792110a --- /dev/null +++ b/src/Navigator.Extensions.Store/Bundled/Extensions/NavigatorContextExtensions.cs @@ -0,0 +1,25 @@ +using Navigator.Context; + +namespace Navigator.Extensions.Store.Bundled.Extensions; + +public static class NavigatorContextExtensions +{ + public static INavigatorStore GetStore(this INavigatorContext navigatorContext) where TEvent : class + { + var store = navigatorContext.GetStoreOrDefault(); + + return store ?? throw new NavigatorException("Store was not found."); + } + + public static INavigatorStore GetStoreOrDefault(this INavigatorContext navigatorContext) where TEvent : class + { + var @store = navigatorContext.Extensions.GetValueOrDefault(StoreContextExtension.NavigatorStoreKey); + + if (store is INavigatorStore navigatorStore) + { + return navigatorStore; + } + + return default; + } +} \ No newline at end of file diff --git a/src/Navigator.Extensions.Store/Bundled/StoreContextExtensions.cs b/src/Navigator.Extensions.Store/Bundled/StoreContextExtensions.cs new file mode 100644 index 0000000..41bf192 --- /dev/null +++ b/src/Navigator.Extensions.Store/Bundled/StoreContextExtensions.cs @@ -0,0 +1,23 @@ +using Navigator.Context; +using Navigator.Context.Extensions; + +namespace Navigator.Extensions.Store.Bundled; + +internal class StoreContextExtension : INavigatorContextExtension +{ + public const string NavigatorStoreKey = "_navigator.extensions.store.navigator_store"; + + private readonly INavigatorStore _navigatorStore; + + public StoreContextExtension(INavigatorStore navigatorStore) + { + _navigatorStore = navigatorStore; + } + + public Task Extend(INavigatorContext navigatorContext, INavigatorContextBuilderOptions builderOptions) + { + navigatorContext.Extensions.TryAdd(NavigatorStoreKey, _navigatorStore); + + return Task.FromResult(navigatorContext); + } +} \ No newline at end of file From a558e9d58862a6909ee93332e113e116850367fb Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sat, 9 Apr 2022 19:34:55 +0200 Subject: [PATCH 294/304] feat: make it work --- .../Extensions/NavigatorContextExtensions.cs | 6 +++--- .../INavigatorStore.cs | 8 ++++---- .../NavigatorExtensionConfigurationExtensions.cs | 1 + src/Navigator.Extensions.Store/NavigatorStore.cs | 16 ++-------------- .../Actions/EchoActionHandler.cs | 8 +++++++- 5 files changed, 17 insertions(+), 22 deletions(-) diff --git a/src/Navigator.Extensions.Store/Bundled/Extensions/NavigatorContextExtensions.cs b/src/Navigator.Extensions.Store/Bundled/Extensions/NavigatorContextExtensions.cs index 792110a..30bc9d1 100644 --- a/src/Navigator.Extensions.Store/Bundled/Extensions/NavigatorContextExtensions.cs +++ b/src/Navigator.Extensions.Store/Bundled/Extensions/NavigatorContextExtensions.cs @@ -4,14 +4,14 @@ namespace Navigator.Extensions.Store.Bundled.Extensions; public static class NavigatorContextExtensions { - public static INavigatorStore GetStore(this INavigatorContext navigatorContext) where TEvent : class + public static INavigatorStore GetStore(this INavigatorContext navigatorContext) { - var store = navigatorContext.GetStoreOrDefault(); + var store = navigatorContext.GetStoreOrDefault(); return store ?? throw new NavigatorException("Store was not found."); } - public static INavigatorStore GetStoreOrDefault(this INavigatorContext navigatorContext) where TEvent : class + public static INavigatorStore? GetStoreOrDefault(this INavigatorContext navigatorContext) { var @store = navigatorContext.Extensions.GetValueOrDefault(StoreContextExtension.NavigatorStoreKey); diff --git a/src/Navigator.Extensions.Store/INavigatorStore.cs b/src/Navigator.Extensions.Store/INavigatorStore.cs index 6286319..7d700df 100644 --- a/src/Navigator.Extensions.Store/INavigatorStore.cs +++ b/src/Navigator.Extensions.Store/INavigatorStore.cs @@ -4,10 +4,10 @@ namespace Navigator.Extensions.Store; public interface INavigatorStore { - public IDictionary? GetData(User? user = default); - public IDictionary? GetData(Chat? chat = default); - public Task?> GetDataAsync(User? user = default, CancellationToken cancellationToken = default); - public Task?> GetDataAsync(Chat? chat = default, CancellationToken cancellationToken = default); + public IDictionary? GetData(User user); + public IDictionary? GetData(Chat chat); + public Task?> GetDataAsync(User user, CancellationToken cancellationToken = default); + public Task?> GetDataAsync(Chat chat, CancellationToken cancellationToken = default); public bool TryAddData(User user, string key, object data, bool force = false); public bool TryAddData(Chat chat, string key, object data, bool force = false); diff --git a/src/Navigator.Extensions.Store/NavigatorExtensionConfigurationExtensions.cs b/src/Navigator.Extensions.Store/NavigatorExtensionConfigurationExtensions.cs index 916a559..fb3adfa 100644 --- a/src/Navigator.Extensions.Store/NavigatorExtensionConfigurationExtensions.cs +++ b/src/Navigator.Extensions.Store/NavigatorExtensionConfigurationExtensions.cs @@ -23,6 +23,7 @@ public static NavigatorConfiguration Store(this NavigatorExtensionConfiguration configuration.Services.AddDbContext(dbContextOptions); configuration.Services.AddScoped(); + configuration.Services.AddScoped(); configuration.Services.AddScoped(); diff --git a/src/Navigator.Extensions.Store/NavigatorStore.cs b/src/Navigator.Extensions.Store/NavigatorStore.cs index d70d423..ba1ee50 100644 --- a/src/Navigator.Extensions.Store/NavigatorStore.cs +++ b/src/Navigator.Extensions.Store/NavigatorStore.cs @@ -1,6 +1,4 @@ using System.Text.Json; -using System.Text.Json.Serialization; -using Navigator.Context; using Navigator.Entities; using Navigator.Extensions.Store.Context; @@ -8,40 +6,30 @@ namespace Navigator.Extensions.Store; public class NavigatorStore : INavigatorStore { - private readonly INavigatorContextAccessor _navigatorContextAccessor; private readonly NavigatorDbContext _dbContext; - public NavigatorStore(INavigatorContextAccessor navigatorContextAccessor, NavigatorDbContext dbContext) + public NavigatorStore(NavigatorDbContext dbContext) { - _navigatorContextAccessor = navigatorContextAccessor; _dbContext = dbContext; } - public IDictionary? GetData(User? user = default) + public IDictionary? GetData(User user) { - user ??= _navigatorContextAccessor.NavigatorContext.Conversation.User; - return _dbContext.Users.Find(user.Id)?.Data; } public IDictionary? GetData(Chat? chat = default) { - chat ??= _navigatorContextAccessor.NavigatorContext.Conversation.Chat; - return _dbContext.Users.Find(chat?.Id)?.Data; } public async Task?> GetDataAsync(User? user = default, CancellationToken cancellationToken = default) { - user ??= _navigatorContextAccessor.NavigatorContext.Conversation.User; - return (await _dbContext.Users.FindAsync(new object?[] { user.Id }, cancellationToken))?.Data; } public async Task?> GetDataAsync(Chat? chat = default, CancellationToken cancellationToken = default) { - chat ??= _navigatorContextAccessor.NavigatorContext.Conversation.Chat; - return (await _dbContext.Chats.FindAsync(new object?[] { chat?.Id }, cancellationToken))?.Data; } diff --git a/src/Navigator.Samples.Store/Actions/EchoActionHandler.cs b/src/Navigator.Samples.Store/Actions/EchoActionHandler.cs index b8e9137..fc6287e 100644 --- a/src/Navigator.Samples.Store/Actions/EchoActionHandler.cs +++ b/src/Navigator.Samples.Store/Actions/EchoActionHandler.cs @@ -1,7 +1,9 @@ -using System.Threading; +using System.Text.Json; +using System.Threading; using System.Threading.Tasks; using Navigator.Actions; using Navigator.Context; +using Navigator.Extensions.Store.Bundled.Extensions; using Navigator.Providers.Telegram; using Telegram.Bot; @@ -18,6 +20,10 @@ public override async Task Handle(EchoAction action, CancellationToken c await this.GetTelegramClient().SendTextMessageAsync(this.GetTelegramChat().Id, action.MessageToEcho, cancellationToken: cancellationToken); + await this.GetTelegramClient().SendTextMessageAsync(this.GetTelegramChat().Id, + JsonSerializer.Serialize(await NavigatorContext.GetStore().GetDataAsync(NavigatorContext.Conversation.User, cancellationToken)), + cancellationToken: cancellationToken); + return Success(); } } \ No newline at end of file From 657fceaca2b261152c83ffe2aa5f4fbe6beda52b Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sat, 7 May 2022 16:26:30 +0200 Subject: [PATCH 295/304] feat: extend navigator store with more methods --- .../INavigatorStore.cs | 15 ++-- .../NavigatorStore.cs | 73 +++++++++++++++++-- 2 files changed, 78 insertions(+), 10 deletions(-) diff --git a/src/Navigator.Extensions.Store/INavigatorStore.cs b/src/Navigator.Extensions.Store/INavigatorStore.cs index 7d700df..f6ddc28 100644 --- a/src/Navigator.Extensions.Store/INavigatorStore.cs +++ b/src/Navigator.Extensions.Store/INavigatorStore.cs @@ -4,11 +4,16 @@ namespace Navigator.Extensions.Store; public interface INavigatorStore { - public IDictionary? GetData(User user); - public IDictionary? GetData(Chat chat); - public Task?> GetDataAsync(User user, CancellationToken cancellationToken = default); - public Task?> GetDataAsync(Chat chat, CancellationToken cancellationToken = default); - + public IDictionary? GetAllData(User user); + public IDictionary? GetAllData(Chat chat); + public Task?> GetAllDataAsync(User user, CancellationToken cancellationToken = default); + public Task?> GetAllDataAsync(Chat chat, CancellationToken cancellationToken = default); + + public string? TryGetData(User user, string key); + public string? TryGetData(Chat chat, string key); + public Task TryGetDataAsync(User user, string key, CancellationToken cancellationToken = default); + public Task TryGetDataAsync(Chat chat, string key, CancellationToken cancellationToken = default); + public bool TryAddData(User user, string key, object data, bool force = false); public bool TryAddData(Chat chat, string key, object data, bool force = false); public Task TryAddDataAsync(User user, string key, object data, bool force = false, CancellationToken cancellationToken = default); diff --git a/src/Navigator.Extensions.Store/NavigatorStore.cs b/src/Navigator.Extensions.Store/NavigatorStore.cs index ba1ee50..76ed7a6 100644 --- a/src/Navigator.Extensions.Store/NavigatorStore.cs +++ b/src/Navigator.Extensions.Store/NavigatorStore.cs @@ -8,31 +8,91 @@ public class NavigatorStore : INavigatorStore { private readonly NavigatorDbContext _dbContext; + /// + /// Default constructor. + /// + /// public NavigatorStore(NavigatorDbContext dbContext) { _dbContext = dbContext; } - public IDictionary? GetData(User user) + /// + public IDictionary? GetAllData(User user) { return _dbContext.Users.Find(user.Id)?.Data; } - public IDictionary? GetData(Chat? chat = default) + /// + public IDictionary? GetAllData(Chat chat) { - return _dbContext.Users.Find(chat?.Id)?.Data; + return _dbContext.Users.Find(chat.Id)?.Data; } - public async Task?> GetDataAsync(User? user = default, CancellationToken cancellationToken = default) + /// + public async Task?> GetAllDataAsync(User user, CancellationToken cancellationToken = default) { return (await _dbContext.Users.FindAsync(new object?[] { user.Id }, cancellationToken))?.Data; } - public async Task?> GetDataAsync(Chat? chat = default, CancellationToken cancellationToken = default) + /// + public async Task?> GetAllDataAsync(Chat chat, CancellationToken cancellationToken = default) { return (await _dbContext.Chats.FindAsync(new object?[] { chat?.Id }, cancellationToken))?.Data; } + /// + public string? TryGetData(User user, string key) + { + var data = GetAllData(user); + + if (data?.TryGetValue(key, out var value) is not null) + { + return value; + } + + return default; + } + + public string? TryGetData(Chat chat, string key) + { + var data = GetAllData(chat); + + if (data?.TryGetValue(key, out var value) is not null) + { + return value; + } + + return default; + } + + /// + public async Task TryGetDataAsync(User user, string key, CancellationToken cancellationToken = default) + { + var data = await GetAllDataAsync(user, cancellationToken); + + if (data?.TryGetValue(key, out var value) is not null) + { + return value; + } + + return default; + } + + /// + public async Task TryGetDataAsync(Chat chat, string key, CancellationToken cancellationToken = default) + { + var data = await GetAllDataAsync(chat, cancellationToken); + + if (data?.TryGetValue(key, out var value) is not null) + { + return value; + } + + return default; + } + + /// public bool TryAddData(User user, string key, object data, bool force = false) { var storedUser = _dbContext.Users.Find(user.Id); @@ -68,6 +128,7 @@ bool TryAddKeyValue() } } + /// public bool TryAddData(Chat chat, string key, object data, bool force = false) { var storedChat = _dbContext.Chats.Find(chat.Id); @@ -103,6 +164,7 @@ bool TryAddKeyValue() } } + /// public async Task TryAddDataAsync(User user, string key, object data, bool force = false, CancellationToken cancellationToken = default) { var storedUser = await _dbContext.Chats.FindAsync(new object?[] { user.Id }, cancellationToken); @@ -139,6 +201,7 @@ async Task TryAddKeyValueAsync() } } + /// public async Task TryAddDataAsync(Chat chat, string key, object data, bool force = false, CancellationToken cancellationToken = default) { var storedChat = await _dbContext.Chats.FindAsync(new object?[] { chat.Id }, cancellationToken); From 18397a88153b9fd6248f88b7ecbe80e659942bb5 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sat, 7 May 2022 16:36:25 +0200 Subject: [PATCH 296/304] chore: move command action to new namespace --- .../Actions/{Messages => Bundled}/CommandAction.cs | 3 ++- src/Navigator.Providers.Telegram/TelegramMiddleware.cs | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) rename src/Navigator.Providers.Telegram/Actions/{Messages => Bundled}/CommandAction.cs (89%) diff --git a/src/Navigator.Providers.Telegram/Actions/Messages/CommandAction.cs b/src/Navigator.Providers.Telegram/Actions/Bundled/CommandAction.cs similarity index 89% rename from src/Navigator.Providers.Telegram/Actions/Messages/CommandAction.cs rename to src/Navigator.Providers.Telegram/Actions/Bundled/CommandAction.cs index a3bc6c8..f4c0217 100644 --- a/src/Navigator.Providers.Telegram/Actions/Messages/CommandAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Bundled/CommandAction.cs @@ -1,9 +1,10 @@ using Navigator.Actions.Attributes; using Navigator.Context; +using Navigator.Providers.Telegram.Actions.Messages; using Navigator.Providers.Telegram.Entities; using Navigator.Providers.Telegram.Extensions; -namespace Navigator.Providers.Telegram.Actions.Messages; +namespace Navigator.Providers.Telegram.Actions.Bundled; /// /// Command based action. diff --git a/src/Navigator.Providers.Telegram/TelegramMiddleware.cs b/src/Navigator.Providers.Telegram/TelegramMiddleware.cs index c456fd6..c28a61b 100644 --- a/src/Navigator.Providers.Telegram/TelegramMiddleware.cs +++ b/src/Navigator.Providers.Telegram/TelegramMiddleware.cs @@ -2,6 +2,7 @@ using Navigator.Actions; using Navigator.Context; using Navigator.Providers.Telegram.Actions; +using Navigator.Providers.Telegram.Actions.Bundled; using Navigator.Providers.Telegram.Actions.Messages; using Navigator.Providers.Telegram.Actions.Updates; using Telegram.Bot.Types; From 054716d09c902fd68cfa8d57bd07c8cd8fa5de0e Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sat, 7 May 2022 16:36:44 +0200 Subject: [PATCH 297/304] feat: implement PollAnswerAction --- .../Actions/Updates/PollAnswerAction.cs | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 src/Navigator.Providers.Telegram/Actions/Updates/PollAnswerAction.cs diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/PollAnswerAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/PollAnswerAction.cs new file mode 100644 index 0000000..affd707 --- /dev/null +++ b/src/Navigator.Providers.Telegram/Actions/Updates/PollAnswerAction.cs @@ -0,0 +1,24 @@ +using Navigator.Actions; +using Navigator.Actions.Attributes; +using Navigator.Context; +using Navigator.Context.Extensions.Bundled.OriginalEvent; +using Telegram.Bot.Types; + +namespace Navigator.Providers.Telegram.Actions.Updates; + +[ActionType(nameof(PollAnswerAction))] +public abstract class PollAnswerAction : BaseAction +{ + /// + /// The original Poll. + /// + public PollAnswer Answer { get; protected set; } + + /// + protected PollAnswerAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) + { + var update = NavigatorContextAccessor.NavigatorContext.GetOriginalEvent(); + + Answer = update.PollAnswer!; + } +} \ No newline at end of file From 3bc2a3ef015fc4d16417b6cdb34877dafc828f25 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sat, 7 May 2022 16:37:01 +0200 Subject: [PATCH 298/304] feat: implement MyChatMemberAction --- .../Actions/Updates/MyChatMemberAction.cs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 src/Navigator.Providers.Telegram/Actions/Updates/MyChatMemberAction.cs diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/MyChatMemberAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/MyChatMemberAction.cs new file mode 100644 index 0000000..afb8e0a --- /dev/null +++ b/src/Navigator.Providers.Telegram/Actions/Updates/MyChatMemberAction.cs @@ -0,0 +1,19 @@ +using Navigator.Actions; +using Navigator.Actions.Attributes; +using Navigator.Context; + +namespace Navigator.Providers.Telegram.Actions.Updates; + +/// +/// TODO +/// +[ActionType(nameof(MyChatMemberAction))] +public abstract class MyChatMemberAction : BaseAction +{ + /// + protected MyChatMemberAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) + { + //TODO + } + +} \ No newline at end of file From e449c2be18a5282f150632e46ccf35e4e7e3ddcf Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sat, 7 May 2022 16:37:11 +0200 Subject: [PATCH 299/304] feat: implement ChatMemberAction --- .../Actions/Updates/ChatMemberAction.cs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 src/Navigator.Providers.Telegram/Actions/Updates/ChatMemberAction.cs diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/ChatMemberAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/ChatMemberAction.cs new file mode 100644 index 0000000..a987066 --- /dev/null +++ b/src/Navigator.Providers.Telegram/Actions/Updates/ChatMemberAction.cs @@ -0,0 +1,19 @@ +using Navigator.Actions; +using Navigator.Actions.Attributes; +using Navigator.Context; + +namespace Navigator.Providers.Telegram.Actions.Updates; + +/// +/// TODO +/// +[ActionType(nameof(ChatMemberAction))] +public abstract class ChatMemberAction : BaseAction +{ + /// + protected ChatMemberAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) + { + //TODO + } + +} \ No newline at end of file From 90a208421c84f4b5d67e9ecb28361e607793ce3f Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sat, 7 May 2022 16:37:21 +0200 Subject: [PATCH 300/304] feat: implement ChatJoinRequestAction --- .../Actions/Updates/ChatJoinRequestAction.cs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 src/Navigator.Providers.Telegram/Actions/Updates/ChatJoinRequestAction.cs diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/ChatJoinRequestAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/ChatJoinRequestAction.cs new file mode 100644 index 0000000..1295d46 --- /dev/null +++ b/src/Navigator.Providers.Telegram/Actions/Updates/ChatJoinRequestAction.cs @@ -0,0 +1,19 @@ +using Navigator.Actions; +using Navigator.Actions.Attributes; +using Navigator.Context; + +namespace Navigator.Providers.Telegram.Actions.Updates; + +/// +/// TODO +/// +[ActionType(nameof(ChatJoinRequestAction))] +public abstract class ChatJoinRequestAction : BaseAction +{ + /// + protected ChatJoinRequestAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) + { + //TODO + } + +} \ No newline at end of file From 202d2e126cefd8e30b26e2ceb49c2c906b31b180 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sat, 7 May 2022 16:37:45 +0200 Subject: [PATCH 301/304] feat: correct warnings in InlineQueryAction and PollAction --- .../Actions/Updates/InlineQueryAction.cs | 10 +++++----- .../Actions/Updates/PollAction.cs | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/InlineQueryAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/InlineQueryAction.cs index 2f2b7d1..254c78a 100644 --- a/src/Navigator.Providers.Telegram/Actions/Updates/InlineQueryAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/InlineQueryAction.cs @@ -15,25 +15,25 @@ public abstract class InlineQueryAction : BaseAction /// /// The original /// - public InlineQuery InlineQuery { get; protected set; } = null!; + public InlineQuery InlineQuery { get; protected set; } /// /// The query from the user. /// - public string Query { get; protected set; } = string.Empty; + public string Query { get; protected set; } /// /// The offset. /// - public string Offset { get; protected set; } = string.Empty; + public string Offset { get; protected set; } /// protected InlineQueryAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) { var update = NavigatorContextAccessor.NavigatorContext.GetOriginalEvent(); - InlineQuery = update.InlineQuery; - Query = update.InlineQuery.Query; + InlineQuery = update.InlineQuery!; + Query = update.InlineQuery!.Query; Offset = update.InlineQuery.Offset; } } \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/PollAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/PollAction.cs index 10ffd7e..2980c5c 100644 --- a/src/Navigator.Providers.Telegram/Actions/Updates/PollAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/PollAction.cs @@ -22,6 +22,6 @@ protected PollAction(INavigatorContextAccessor navigatorContextAccessor) : base( { var update = NavigatorContextAccessor.NavigatorContext.GetOriginalEvent(); - Poll = update.Poll; + Poll = update.Poll!; } } \ No newline at end of file From c65d8ebd1a86cdcbd1f05ca185ae11a25715ba6b Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sat, 7 May 2022 16:37:59 +0200 Subject: [PATCH 302/304] feat: update TelegramMiddleware to recognize new actions --- src/Navigator.Providers.Telegram/TelegramMiddleware.cs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/Navigator.Providers.Telegram/TelegramMiddleware.cs b/src/Navigator.Providers.Telegram/TelegramMiddleware.cs index c28a61b..eac5b08 100644 --- a/src/Navigator.Providers.Telegram/TelegramMiddleware.cs +++ b/src/Navigator.Providers.Telegram/TelegramMiddleware.cs @@ -86,9 +86,10 @@ await _navigatorContextFactory.Supply(builder => UpdateType.ShippingQuery => nameof(ShippingQueryAction), UpdateType.PreCheckoutQuery => nameof(PreCheckoutQuery), UpdateType.Poll => nameof(PollAction), - // UpdateType.PollAnswer => typeof(PollAction).FullName, - // UpdateType.MyChatMember => typeof(UnknownAction).FullName, - // UpdateType.ChatMember => typeof(UnknownAction).FullName, + UpdateType.PollAnswer => nameof(PollAnswerAction), + UpdateType.MyChatMember => nameof(MyChatMemberAction), + UpdateType.ChatMember => nameof(ChatMemberAction), + UpdateType.ChatJoinRequest => nameof(ChatJoinRequestAction), UpdateType.Unknown => nameof(UnknownAction), _ => default }; From e81d49fdd4bdb67269429adf0970dd4cfac63411 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Sat, 7 May 2022 16:44:46 +0200 Subject: [PATCH 303/304] feat: improve some update actions --- .../Actions/Updates/ChannelCreatedAction.cs | 7 +++---- .../Actions/Updates/ChannelPostAction.cs | 14 ++++++++++---- .../Actions/Updates/ChatJoinRequestAction.cs | 12 ++++++++++-- .../Actions/Updates/ChatMemberAction.cs | 12 ++++++++++-- .../Actions/Updates/MyChatMemberAction.cs | 12 ++++++++++-- 5 files changed, 43 insertions(+), 14 deletions(-) diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/ChannelCreatedAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/ChannelCreatedAction.cs index 0293ad2..3a30fbf 100644 --- a/src/Navigator.Providers.Telegram/Actions/Updates/ChannelCreatedAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/ChannelCreatedAction.cs @@ -1,6 +1,8 @@ using Navigator.Actions; using Navigator.Actions.Attributes; using Navigator.Context; +using Navigator.Context.Extensions.Bundled.OriginalEvent; +using Telegram.Bot.Types; namespace Navigator.Providers.Telegram.Actions.Updates; @@ -13,9 +15,6 @@ public abstract class ChannelCreatedAction : BaseAction /// protected ChannelCreatedAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) { - //TODO - } - - + } } \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/ChannelPostAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/ChannelPostAction.cs index 2e1a5e7..ee6df97 100644 --- a/src/Navigator.Providers.Telegram/Actions/Updates/ChannelPostAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/ChannelPostAction.cs @@ -1,6 +1,8 @@ using Navigator.Actions; using Navigator.Actions.Attributes; using Navigator.Context; +using Navigator.Context.Extensions.Bundled.OriginalEvent; +using Telegram.Bot.Types; namespace Navigator.Providers.Telegram.Actions.Updates; @@ -10,12 +12,16 @@ namespace Navigator.Providers.Telegram.Actions.Updates; [ActionType(nameof(ChannelPostAction))] public abstract class ChannelPostAction : BaseAction { + /// + /// Channel post message. + /// + public Message ChannelPost { get; protected set; } + /// protected ChannelPostAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) { - //TODO - } - - + var update = NavigatorContextAccessor.NavigatorContext.GetOriginalEvent(); + ChannelPost = update.ChannelPost!; + } } \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/ChatJoinRequestAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/ChatJoinRequestAction.cs index 1295d46..0e3f0ed 100644 --- a/src/Navigator.Providers.Telegram/Actions/Updates/ChatJoinRequestAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/ChatJoinRequestAction.cs @@ -1,6 +1,8 @@ using Navigator.Actions; using Navigator.Actions.Attributes; using Navigator.Context; +using Navigator.Context.Extensions.Bundled.OriginalEvent; +using Telegram.Bot.Types; namespace Navigator.Providers.Telegram.Actions.Updates; @@ -10,10 +12,16 @@ namespace Navigator.Providers.Telegram.Actions.Updates; [ActionType(nameof(ChatJoinRequestAction))] public abstract class ChatJoinRequestAction : BaseAction { + /// + /// Chat join request. + /// + public ChatJoinRequest Request { get; protected set; } + /// protected ChatJoinRequestAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) { - //TODO - } + var update = NavigatorContextAccessor.NavigatorContext.GetOriginalEvent(); + Request = update.ChatJoinRequest!; + } } \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/ChatMemberAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/ChatMemberAction.cs index a987066..f8bfb07 100644 --- a/src/Navigator.Providers.Telegram/Actions/Updates/ChatMemberAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/ChatMemberAction.cs @@ -1,6 +1,8 @@ using Navigator.Actions; using Navigator.Actions.Attributes; using Navigator.Context; +using Navigator.Context.Extensions.Bundled.OriginalEvent; +using Telegram.Bot.Types; namespace Navigator.Providers.Telegram.Actions.Updates; @@ -10,10 +12,16 @@ namespace Navigator.Providers.Telegram.Actions.Updates; [ActionType(nameof(ChatMemberAction))] public abstract class ChatMemberAction : BaseAction { + /// + /// Chat member updated. + /// + public ChatMemberUpdated ChatMemberUpdated { get; set; } + /// protected ChatMemberAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) { - //TODO - } + var update = NavigatorContextAccessor.NavigatorContext.GetOriginalEvent(); + ChatMemberUpdated = update.ChatMember!; + } } \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/MyChatMemberAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/MyChatMemberAction.cs index afb8e0a..30b1395 100644 --- a/src/Navigator.Providers.Telegram/Actions/Updates/MyChatMemberAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/MyChatMemberAction.cs @@ -1,6 +1,8 @@ using Navigator.Actions; using Navigator.Actions.Attributes; using Navigator.Context; +using Navigator.Context.Extensions.Bundled.OriginalEvent; +using Telegram.Bot.Types; namespace Navigator.Providers.Telegram.Actions.Updates; @@ -10,10 +12,16 @@ namespace Navigator.Providers.Telegram.Actions.Updates; [ActionType(nameof(MyChatMemberAction))] public abstract class MyChatMemberAction : BaseAction { + /// + /// Chat member updated. + /// + public ChatMemberUpdated ChatMemberUpdated { get; set; } + /// protected MyChatMemberAction(INavigatorContextAccessor navigatorContextAccessor) : base(navigatorContextAccessor) { - //TODO - } + var update = NavigatorContextAccessor.NavigatorContext.GetOriginalEvent(); + ChatMemberUpdated = update.MyChatMember!; + } } \ No newline at end of file From 9294ccce63746f33e33ae95b02976f4bfef09ca3 Mon Sep 17 00:00:00 2001 From: Lucas Maximiliano Marino Date: Fri, 6 Oct 2023 23:29:14 +0200 Subject: [PATCH 304/304] feat: some correction --- .../Actions/Updates/CallbackQueryAction.cs | 8 ++++---- .../TelegramNavigatorProvider.cs | 7 ++++--- src/Navigator/INavigatorProvider.cs | 2 +- 3 files changed, 9 insertions(+), 8 deletions(-) diff --git a/src/Navigator.Providers.Telegram/Actions/Updates/CallbackQueryAction.cs b/src/Navigator.Providers.Telegram/Actions/Updates/CallbackQueryAction.cs index 085ab46..dc3c3e4 100644 --- a/src/Navigator.Providers.Telegram/Actions/Updates/CallbackQueryAction.cs +++ b/src/Navigator.Providers.Telegram/Actions/Updates/CallbackQueryAction.cs @@ -37,9 +37,9 @@ protected CallbackQueryAction(INavigatorContextAccessor navigatorContextAccessor { var update = NavigatorContextAccessor.NavigatorContext.GetOriginalEvent(); - CallbackQuery = update.CallbackQuery; - OriginalMessage = update.CallbackQuery.Message; - Data = string.IsNullOrWhiteSpace(update.CallbackQuery.Data) ? update.CallbackQuery.Data : default; - IsGameQuery = update.CallbackQuery.IsGameQuery; + CallbackQuery = update.CallbackQuery!; + OriginalMessage = CallbackQuery.Message; + Data = string.IsNullOrWhiteSpace(CallbackQuery.Data) ? CallbackQuery.Data : default; + IsGameQuery = CallbackQuery.IsGameQuery; } } \ No newline at end of file diff --git a/src/Navigator.Providers.Telegram/TelegramNavigatorProvider.cs b/src/Navigator.Providers.Telegram/TelegramNavigatorProvider.cs index 55224e1..2dbc2f3 100644 --- a/src/Navigator.Providers.Telegram/TelegramNavigatorProvider.cs +++ b/src/Navigator.Providers.Telegram/TelegramNavigatorProvider.cs @@ -5,14 +5,15 @@ namespace Navigator.Providers.Telegram; internal class TelegramNavigatorProvider : INavigatorProvider { private readonly NavigatorTelegramClient _client; - - public string Name => "navigator.provider.telegram"; + + public string Name { get; init; } = "navigator.provider.telegram"; public TelegramNavigatorProvider(NavigatorTelegramClient client) { _client = client; } - + + public INavigatorClient GetClient() { return _client; diff --git a/src/Navigator/INavigatorProvider.cs b/src/Navigator/INavigatorProvider.cs index fcb802c..674ed60 100644 --- a/src/Navigator/INavigatorProvider.cs +++ b/src/Navigator/INavigatorProvider.cs @@ -5,7 +5,7 @@ namespace Navigator; /// public interface INavigatorProvider { - string Name { get; } + public string Name { get; init; } /// /// Gets the specific client for this provider.