From 49310439e0d12dc9a37891b0f9c4c927e566228c Mon Sep 17 00:00:00 2001 From: Rikitav Date: Fri, 1 Aug 2025 13:50:21 +0400 Subject: [PATCH] * Renamed "LeveledDebug" to "Alligator", cuz its funny name * Changed debug writing to trace writing inside "Alligator" * Added "HostedTelegramBotInfo" representing hosted version of ITelegramBotInfo. Provides access to services and configuration * Filters now can acces services and configuration using new "HostedTelegramBotInfo" through context.BotInfo property --- Telegrator.Hosting/HostedTelegramBotInfo.cs | 17 +++++++ Telegrator.Hosting/TelegramBotHost.cs | 9 ++++ Telegrator.Hosting/TypesExtensions.cs | 5 +- Telegrator/{LeveledDebug.cs => Alligator.cs} | 50 ++++++++++++------- .../Components/AnonymousCompiledFilter.cs | 2 +- .../Filters/Components/AnonymousTypeFilter.cs | 2 +- .../Filters/Components/CompiledFilter.cs | 2 +- .../Descriptors/DescriptorFiltersSet.cs | 6 +-- Telegrator/Polling/UpdateRouter.cs | 30 +++++------ Telegrator/Providers/HandlersProvider.cs | 6 +-- 10 files changed, 84 insertions(+), 45 deletions(-) create mode 100644 Telegrator.Hosting/HostedTelegramBotInfo.cs rename Telegrator/{LeveledDebug.cs => Alligator.cs} (62%) diff --git a/Telegrator.Hosting/HostedTelegramBotInfo.cs b/Telegrator.Hosting/HostedTelegramBotInfo.cs new file mode 100644 index 0000000..a8c3ecb --- /dev/null +++ b/Telegrator.Hosting/HostedTelegramBotInfo.cs @@ -0,0 +1,17 @@ +using Microsoft.Extensions.Configuration; +using Telegram.Bot; +using Telegram.Bot.Types; +using Telegrator.Configuration; + +namespace Telegrator.Hosting +{ + public class HostedTelegramBotInfo(ITelegramBotClient client, IServiceProvider services, IConfigurationManager configuration) : ITelegramBotInfo + { + /// + public User User { get; } = client.GetMe().Result; + + public IServiceProvider Services { get; } = services; + + public IConfigurationManager Configuration { get; } = configuration; + } +} diff --git a/Telegrator.Hosting/TelegramBotHost.cs b/Telegrator.Hosting/TelegramBotHost.cs index 878db88..96744c2 100644 --- a/Telegrator.Hosting/TelegramBotHost.cs +++ b/Telegrator.Hosting/TelegramBotHost.cs @@ -3,6 +3,7 @@ using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using System.Text; using Telegram.Bot.Types.Enums; +using Telegrator.Configuration; using Telegrator.Hosting.Components; using Telegrator.Hosting.Providers; using Telegrator.MadiatorCore; @@ -39,12 +40,20 @@ namespace Telegrator.Hosting /// internal TelegramBotHost(HostApplicationBuilder hostApplicationBuilder, HostHandlersCollection handlers) { + // Registering this host in services for easy access RegisterHostServices(hostApplicationBuilder, handlers); + + // Building proxy hoster _innerHost = hostApplicationBuilder.Build(); + // Initializing bot info, as it requires to make a request via tg bot + Services.GetRequiredService(); + + // Reruesting services for this host _updateRouter = Services.GetRequiredService(); _logger = Services.GetRequiredService>(); + // Logging registering handlers in DEBUG purposes LogHandlers(handlers); } diff --git a/Telegrator.Hosting/TypesExtensions.cs b/Telegrator.Hosting/TypesExtensions.cs index 3ea32be..f1a4331 100644 --- a/Telegrator.Hosting/TypesExtensions.cs +++ b/Telegrator.Hosting/TypesExtensions.cs @@ -47,8 +47,9 @@ namespace Telegrator.Hosting services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); - services.AddSingleton(services => new TelegramBotInfo(services.GetRequiredService().GetMe().Result)); - + //services.AddSingleton(services => new TelegramBotInfo(services.GetRequiredService().GetMe().Result)); + services.AddSingleton(); + return services; } diff --git a/Telegrator/LeveledDebug.cs b/Telegrator/Alligator.cs similarity index 62% rename from Telegrator/LeveledDebug.cs rename to Telegrator/Alligator.cs index 6f810d9..6f0cc30 100644 --- a/Telegrator/LeveledDebug.cs +++ b/Telegrator/Alligator.cs @@ -3,14 +3,14 @@ namespace Telegrator { /// - /// Telegrator's Debug logger helper + /// Telegrator's FUNNY debug logger helper /// - public static class LeveledDebug + public static class Alligator { /// /// Gets or sets flags of what debug messages to write /// - public static DebugLevel IndentFlags { get; set; } = DebugLevel.None; + public static DebugLevel Allowed { get; set; } = DebugLevel.None; /// /// Writes debug message if Indent level has Router flag @@ -18,8 +18,8 @@ namespace Telegrator /// public static void RouterWriteLine(string message) { - if (IndentFlags.HasFlag(DebugLevel.Router)) - Debug.WriteLine(message); + if (Allowed.HasFlag(DebugLevel.Router)) + Trace.WriteLine(message); } /// @@ -29,8 +29,8 @@ namespace Telegrator /// public static void RouterWriteLine(string message, params object[] args) { - if (IndentFlags.HasFlag(DebugLevel.Router)) - Debug.WriteLine(message, args); + if (Allowed.HasFlag(DebugLevel.Router)) + Trace.WriteLine(string.Format(message, args)); } /// @@ -39,8 +39,8 @@ namespace Telegrator /// public static void ProviderWriteLine(string message) { - if (IndentFlags.HasFlag(DebugLevel.Providers)) - Debug.WriteLine(message); + if (Allowed.HasFlag(DebugLevel.Providers)) + Trace.WriteLine(message); } /// @@ -50,8 +50,8 @@ namespace Telegrator /// public static void ProviderWriteLine(string message, params object[] args) { - if (IndentFlags.HasFlag(DebugLevel.Providers)) - Debug.WriteLine(message, args); + if (Allowed.HasFlag(DebugLevel.Providers)) + Trace.WriteLine(string.Format(message, args)); } /// @@ -60,8 +60,8 @@ namespace Telegrator /// public static void FilterWriteLine(string message) { - if (IndentFlags.HasFlag(DebugLevel.Filters)) - Debug.WriteLine(message); + if (Allowed.HasFlag(DebugLevel.Filters)) + Trace.WriteLine(message); } /// @@ -71,8 +71,8 @@ namespace Telegrator /// public static void FilterWriteLine(string message, params object[] args) { - if (IndentFlags.HasFlag(DebugLevel.Filters)) - Debug.WriteLine(message, args); + if (Allowed.HasFlag(DebugLevel.Filters)) + Trace.WriteLine(string.Format(message, args)); } /// @@ -81,8 +81,8 @@ namespace Telegrator /// public static void PoolWriteLine(string message) { - if (IndentFlags.HasFlag(DebugLevel.HandlersPool)) - Debug.WriteLine(message); + if (Allowed.HasFlag(DebugLevel.HandlersPool)) + Trace.WriteLine(message); } /// @@ -92,8 +92,20 @@ namespace Telegrator /// public static void PoolWriteLine(string message, params object[] args) { - if (IndentFlags.HasFlag(DebugLevel.HandlersPool)) - Debug.WriteLine(message, args); + if (Allowed.HasFlag(DebugLevel.HandlersPool)) + Trace.WriteLine(string.Format(message, args)); + } + + public static void WriteLine(DebugLevel level, string message) + { + if (Allowed.HasFlag(level)) + Trace.WriteLine(message); + } + + public static void WriteLine(DebugLevel level, string message, params object[] args) + { + if (Allowed.HasFlag(level)) + Trace.WriteLine(string.Format(message, args)); } } } diff --git a/Telegrator/Filters/Components/AnonymousCompiledFilter.cs b/Telegrator/Filters/Components/AnonymousCompiledFilter.cs index 443c0e5..7939b6c 100644 --- a/Telegrator/Filters/Components/AnonymousCompiledFilter.cs +++ b/Telegrator/Filters/Components/AnonymousCompiledFilter.cs @@ -47,7 +47,7 @@ namespace Telegrator.Filters.Components if (!filter.CanPass(context)) { if (filter is not AnonymousCompiledFilter && filter is not AnonymousTypeFilter) - LeveledDebug.FilterWriteLine("(E) {0} filter of {1} didnt pass!", filter.GetType().Name, context.Data["handler_name"]); + Alligator.FilterWriteLine("(E) {0} filter of {1} didnt pass!", filter.GetType().Name, context.Data["handler_name"]); return false; } diff --git a/Telegrator/Filters/Components/AnonymousTypeFilter.cs b/Telegrator/Filters/Components/AnonymousTypeFilter.cs index 91442f3..9809a0a 100644 --- a/Telegrator/Filters/Components/AnonymousTypeFilter.cs +++ b/Telegrator/Filters/Components/AnonymousTypeFilter.cs @@ -49,7 +49,7 @@ namespace Telegrator.Filters.Components if (!filter.CanPass(context)) { if (filter is not AnonymousCompiledFilter && filter is not AnonymousTypeFilter) - LeveledDebug.FilterWriteLine("(E) {0} filter of {1} didnt pass!", filter.GetType().Name, context.Data["handler_name"]); + Alligator.FilterWriteLine("(E) {0} filter of {1} didnt pass!", filter.GetType().Name, context.Data["handler_name"]); return false; } diff --git a/Telegrator/Filters/Components/CompiledFilter.cs b/Telegrator/Filters/Components/CompiledFilter.cs index 3eb2666..45b723d 100644 --- a/Telegrator/Filters/Components/CompiledFilter.cs +++ b/Telegrator/Filters/Components/CompiledFilter.cs @@ -39,7 +39,7 @@ if (!filter.CanPass(context)) { if (filter is not AnonymousCompiledFilter && filter is not AnonymousTypeFilter) - LeveledDebug.FilterWriteLine("(E) {0} filter of {1} didnt pass!", filter.GetType().Name, context.Data["handler_name"]); + Alligator.FilterWriteLine("(E) {0} filter of {1} didnt pass!", filter.GetType().Name, context.Data["handler_name"]); return false; } diff --git a/Telegrator/MadiatorCore/Descriptors/DescriptorFiltersSet.cs b/Telegrator/MadiatorCore/Descriptors/DescriptorFiltersSet.cs index fc73f62..461f3aa 100644 --- a/Telegrator/MadiatorCore/Descriptors/DescriptorFiltersSet.cs +++ b/Telegrator/MadiatorCore/Descriptors/DescriptorFiltersSet.cs @@ -47,7 +47,7 @@ namespace Telegrator.MadiatorCore.Descriptors { if (!UpdateValidator.CanPass(filterContext)) { - LeveledDebug.FilterWriteLine("(E) UpdateValidator filter of {0} for Update ({1}) didnt pass!", filterContext.Data["handler_name"], filterContext.Update.Id); + Alligator.FilterWriteLine("(E) UpdateValidator filter of {0} for Update ({1}) didnt pass!", filterContext.Data["handler_name"], filterContext.Update.Id); return false; } @@ -59,7 +59,7 @@ namespace Telegrator.MadiatorCore.Descriptors { if (!StateKeeperValidator.CanPass(filterContext)) { - LeveledDebug.FilterWriteLine("(E) StateKeeperValidator filter of {0} for Update ({1}) didnt pass!", filterContext.Data["handler_name"], filterContext.Update.Id); + Alligator.FilterWriteLine("(E) StateKeeperValidator filter of {0} for Update ({1}) didnt pass!", filterContext.Data["handler_name"], filterContext.Update.Id); return false; } @@ -74,7 +74,7 @@ namespace Telegrator.MadiatorCore.Descriptors if (!filter.CanPass(filterContext)) { if (filter is not AnonymousCompiledFilter && filter is not AnonymousTypeFilter) - LeveledDebug.FilterWriteLine("(E) {0} filter of {1} for Update ({2}) didnt pass!", filter.GetType().Name, filterContext.Data["handler_name"], filterContext.Update.Id); + Alligator.FilterWriteLine("(E) {0} filter of {1} for Update ({2}) didnt pass!", filter.GetType().Name, filterContext.Data["handler_name"], filterContext.Update.Id); return false; } diff --git a/Telegrator/Polling/UpdateRouter.cs b/Telegrator/Polling/UpdateRouter.cs index fb6811c..691fc13 100644 --- a/Telegrator/Polling/UpdateRouter.cs +++ b/Telegrator/Polling/UpdateRouter.cs @@ -84,7 +84,7 @@ namespace Telegrator.Polling /// A task representing the asynchronous error handling operation. public virtual Task HandleErrorAsync(ITelegramBotClient botClient, Exception exception, HandleErrorSource source, CancellationToken cancellationToken) { - LeveledDebug.RouterWriteLine("Handling exception {0}", exception.GetType().Name); + Alligator.RouterWriteLine("Handling exception {0}", exception.GetType().Name); ExceptionHandler?.HandleException(botClient, exception, source, cancellationToken); return Task.CompletedTask; } @@ -99,7 +99,7 @@ namespace Telegrator.Polling public virtual Task HandleUpdateAsync(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken) { // Logging - LeveledDebug.RouterWriteLine("Received Update ({0}) of type \"{1}\"", update.Id, update.Type); + Alligator.RouterWriteLine("Received Update ({0}) of type \"{1}\"", update.Id, update.Type); LogUpdate(update); try @@ -114,24 +114,24 @@ namespace Telegrator.Polling // Chicking if awaiting handlers has exclusive routing if (Options.ExclusiveAwaitingHandlerRouting) { - LeveledDebug.RouterWriteLine("Receiving Update ({0}) completed with only awaiting handlers", update.Id); + Alligator.RouterWriteLine("Receiving Update ({0}) completed with only awaiting handlers", update.Id); return Task.CompletedTask; } } // Queuing reagular handlers for execution HandlersPool.Enqueue(GetHandlers(HandlersProvider, this, botClient, update, cancellationToken)); - LeveledDebug.RouterWriteLine("Receiving Update ({0}) finished", update.Id); + Alligator.RouterWriteLine("Receiving Update ({0}) finished", update.Id); return Task.CompletedTask; } catch (OperationCanceledException) { - LeveledDebug.RouterWriteLine("Receiving Update ({0}) cancelled", update.Id); + Alligator.RouterWriteLine("Receiving Update ({0}) cancelled", update.Id); return Task.CompletedTask; } catch (Exception ex) { - LeveledDebug.RouterWriteLine("Receiving Update ({0}) finished with exception {1}", update.Id, ex.Message); + Alligator.RouterWriteLine("Receiving Update ({0}) finished with exception {1}", update.Id, ex.Message); ExceptionHandler?.HandleException(botClient, ex, HandleErrorSource.PollingError, cancellationToken); return Task.CompletedTask; } @@ -149,22 +149,22 @@ namespace Telegrator.Polling /// A collection of described handler information for the update protected virtual IEnumerable GetHandlers(IHandlersProvider provider, IUpdateRouter updateRouter, ITelegramBotClient client, Update update, CancellationToken cancellationToken = default) { - LeveledDebug.RouterWriteLine("Requested handlers for UpdateType.{0}", update.Type); + Alligator.RouterWriteLine("Requested handlers for UpdateType.{0}", update.Type); if (!provider.TryGetDescriptorList(update.Type, out HandlerDescriptorList? descriptors)) { - LeveledDebug.RouterWriteLine("No registered, providing Any"); + Alligator.RouterWriteLine("No registered, providing Any"); provider.TryGetDescriptorList(UpdateType.Unknown, out descriptors); } if (descriptors == null || descriptors.Count == 0) { - LeveledDebug.RouterWriteLine("No handlers provided"); + Alligator.RouterWriteLine("No handlers provided"); return []; } IEnumerable described = DescribeDescriptors(provider, descriptors, updateRouter, client, update, cancellationToken); - LeveledDebug.RouterWriteLine("Described total of {0} handlers for Update ({1}) from {2} provider", described.Count(), update.Id, provider.GetType().Name); - LeveledDebug.RouterWriteLine("Described handlers : {0}", string.Join(", ", described)); + Alligator.RouterWriteLine("Described total of {0} handlers for Update ({1}) from {2} provider", described.Count(), update.Id, provider.GetType().Name); + Alligator.RouterWriteLine("Described handlers : {0}", string.Join(", ", described)); return described; } @@ -183,7 +183,7 @@ namespace Telegrator.Polling { try { - LeveledDebug.RouterWriteLine("Describing descriptors of descriptorsList.HandlingType.{0} for Update ({1})", descriptors.HandlingType, update.Id); + Alligator.RouterWriteLine("Describing descriptors of descriptorsList.HandlingType.{0} for Update ({1})", descriptors.HandlingType, update.Id); foreach (HandlerDescriptor descriptor in descriptors.Reverse()) { cancellationToken.ThrowIfCancellationRequested(); @@ -198,7 +198,7 @@ namespace Telegrator.Polling } finally { - LeveledDebug.RouterWriteLine("Describing for Update ({0}) finished", update.Id); + Alligator.RouterWriteLine("Describing for Update ({0}) finished", update.Id); } } @@ -252,7 +252,7 @@ namespace Telegrator.Polling if (msg.Sticker != null) sb.AppendFormat(" with sticker '{0}'", msg.Sticker.Emoji); - LeveledDebug.RouterWriteLine(sb.ToString()); + Alligator.RouterWriteLine(sb.ToString()); break; } @@ -267,7 +267,7 @@ namespace Telegrator.Polling if (cq.From != null) sb.AppendFormat(" with data '{0}'", cq.Data); - LeveledDebug.RouterWriteLine(sb.ToString()); + Alligator.RouterWriteLine(sb.ToString()); break; } } diff --git a/Telegrator/Providers/HandlersProvider.cs b/Telegrator/Providers/HandlersProvider.cs index fb8a7f9..46d5e6e 100644 --- a/Telegrator/Providers/HandlersProvider.cs +++ b/Telegrator/Providers/HandlersProvider.cs @@ -40,7 +40,7 @@ namespace Telegrator.Providers AllowedTypes = handlers.AllowedTypes; HandlersDictionary = handlers.Values.ForEach(list => list.Freeze()).ToReadOnlyDictionary(list => list.HandlingType); Options = options ?? throw new ArgumentNullException(nameof(options)); - LeveledDebug.ProviderWriteLine("{0} created!", GetType().Name); + Alligator.ProviderWriteLine("{0} created!", GetType().Name); } /// @@ -54,7 +54,7 @@ namespace Telegrator.Providers AllowedTypes = Update.AllTypes; HandlersDictionary = handlers.ForEach(list => list.Freeze()).ToReadOnlyDictionary(list => list.HandlingType); Options = options ?? throw new ArgumentNullException(nameof(options)); - LeveledDebug.ProviderWriteLine("{0} created!", GetType().Name); + Alligator.ProviderWriteLine("{0} created!", GetType().Name); } /// @@ -76,7 +76,7 @@ namespace Telegrator.Providers } catch { - LeveledDebug.ProviderWriteLine("Failed to create instance of {0}", descriptor.ToString()); + Alligator.ProviderWriteLine("Failed to create instance of {0}", descriptor.ToString()); throw; } }