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