| | | 1 | | using Microsoft.Extensions.DependencyInjection; |
| | | 2 | | using Microsoft.Extensions.DependencyInjection.Extensions; |
| | | 3 | | using Microsoft.Extensions.Hosting; |
| | | 4 | | using TeleFlow.Framework.Updates; |
| | | 5 | | using TeleFlow.Telegram.Internal; |
| | | 6 | | using TeleFlow.Telegram.Webhooks.Internal; |
| | | 7 | | |
| | | 8 | | namespace TeleFlow.Telegram.Webhooks; |
| | | 9 | | |
| | | 10 | | public static class TelegramWebhookServiceCollectionExtensions |
| | | 11 | | { |
| | | 12 | | public static IServiceCollection AddWebhook( |
| | | 13 | | this IServiceCollection services, |
| | | 14 | | Action<TelegramWebhookOptions>? configure = null) |
| | | 15 | | { |
| | 19 | 16 | | ArgumentNullException.ThrowIfNull(services); |
| | | 17 | | |
| | 19 | 18 | | EnsureNotRegistered<IUpdateSource>(services, nameof(AddWebhook)); |
| | 18 | 19 | | EnsureTelegramBotRegistered(services, nameof(AddWebhook)); |
| | | 20 | | |
| | 17 | 21 | | var options = new TelegramWebhookOptions(); |
| | 17 | 22 | | configure?.Invoke(options); |
| | 17 | 23 | | TelegramWebhookOptionsValidator.Validate(options); |
| | | 24 | | |
| | 15 | 25 | | services.AddSingleton(options); |
| | 15 | 26 | | services.TryAddSingleton<IUpdateProcessor, DefaultUpdateProcessor>(); |
| | 15 | 27 | | services.AddSingleton<IUpdateSource, TelegramWebhookUpdateSource>(); |
| | 15 | 28 | | services.TryAddEnumerable(ServiceDescriptor.Singleton<IHostedService, TelegramBotIdentityStartupService>()); |
| | | 29 | | |
| | 15 | 30 | | return services; |
| | | 31 | | } |
| | | 32 | | |
| | | 33 | | private static void EnsureTelegramBotRegistered(IServiceCollection services, string apiName) |
| | | 34 | | { |
| | 1288 | 35 | | if (services.All(static descriptor => descriptor.ServiceType != typeof(TelegramBotOptions))) |
| | | 36 | | { |
| | 1 | 37 | | throw new InvalidOperationException( |
| | 1 | 38 | | $"{nameof(TelegramServiceCollectionExtensions.AddTelegramBot)} must be called before {apiName}."); |
| | | 39 | | } |
| | 17 | 40 | | } |
| | | 41 | | |
| | | 42 | | private static void EnsureNotRegistered<TService>(IServiceCollection services, string apiName) |
| | | 43 | | { |
| | 1578 | 44 | | if (services.Any(descriptor => descriptor.ServiceType == typeof(TService))) |
| | | 45 | | { |
| | 1 | 46 | | throw new InvalidOperationException( |
| | 1 | 47 | | $"{apiName} cannot be called more than once for service '{typeof(TService).Name}'."); |
| | | 48 | | } |
| | 18 | 49 | | } |
| | | 50 | | } |