* Added RemapWebhook method to WebHost

* Updatetd dependencues
* Fixed some warnings
This commit is contained in:
2026-04-03 19:23:53 +04:00
parent ba772f3f7c
commit 233a67f2b0
14 changed files with 184 additions and 183 deletions
@@ -65,11 +65,11 @@ public class TelegramBotWebHost : IHost, IApplicationBuilder, IEndpointRouteBuil
/// Creates new <see cref="TelegramBotHostBuilder"/> with default services and webhook update receiving scheme
/// </summary>
/// <returns></returns>
public static TelegramBotWebHostBuilder CreateBuilder(WebApplicationOptions settings)
public static TelegramBotWebHostBuilder CreateBuilder(WebApplicationOptions? settings)
{
ArgumentNullException.ThrowIfNull(settings, nameof(settings));
WebApplicationBuilder innerApp = WebApplication.CreateBuilder(settings);
TelegramBotWebHostBuilder builder = new TelegramBotWebHostBuilder(innerApp, settings);
TelegramBotWebHostBuilder builder = new TelegramBotWebHostBuilder(innerApp);
builder.AddTelegratorWeb();
return builder;
}
@@ -78,11 +78,11 @@ public class TelegramBotWebHost : IHost, IApplicationBuilder, IEndpointRouteBuil
/// Creates new SLIM <see cref="TelegramBotHostBuilder"/> with default services and webhook update receiving scheme
/// </summary>
/// <returns></returns>
public static TelegramBotWebHostBuilder CreateSlimBuilder(WebApplicationOptions settings)
public static TelegramBotWebHostBuilder CreateSlimBuilder(WebApplicationOptions? settings)
{
ArgumentNullException.ThrowIfNull(settings, nameof(settings));
WebApplicationBuilder innerApp = WebApplication.CreateSlimBuilder(settings);
TelegramBotWebHostBuilder builder = new TelegramBotWebHostBuilder(innerApp, settings);
TelegramBotWebHostBuilder builder = new TelegramBotWebHostBuilder(innerApp);
builder.AddTelegratorWeb();
return builder;
}
@@ -91,11 +91,11 @@ public class TelegramBotWebHost : IHost, IApplicationBuilder, IEndpointRouteBuil
/// Creates new EMPTY <see cref="TelegramBotHostBuilder"/> WITHOUT any services or update receiving schemes
/// </summary>
/// <returns></returns>
public static TelegramBotWebHostBuilder CreateEmptyBuilder(WebApplicationOptions settings)
public static TelegramBotWebHostBuilder CreateEmptyBuilder(WebApplicationOptions? settings)
{
ArgumentNullException.ThrowIfNull(settings, nameof(settings));
WebApplicationBuilder innerApp = WebApplication.CreateEmptyBuilder(settings);
TelegramBotWebHostBuilder builder = new TelegramBotWebHostBuilder(innerApp, settings);
TelegramBotWebHostBuilder builder = new TelegramBotWebHostBuilder(innerApp);
builder.AddTelegratorWeb();
return builder;
}
@@ -9,13 +9,10 @@ using Telegrator.Core;
#pragma warning disable IDE0001
namespace Telegrator.Hosting.Web;
/// <summary>
/// Represents a web hosted telegram bots and services builder that helps manage configuration, logging, lifetime, and more.
/// </summary>
/// <inheritdoc/>
public class TelegramBotWebHostBuilder : ITelegramBotHostBuilder
{
private readonly WebApplicationBuilder _innerBuilder;
private readonly WebApplicationOptions _settings;
internal IHandlersCollection _handlers = null!;
/// <inheritdoc/>
@@ -43,23 +40,9 @@ public class TelegramBotWebHostBuilder : ITelegramBotHostBuilder
/// Initializes a new instance of the <see cref="TelegramBotWebHostBuilder"/> class.
/// </summary>
/// <param name="webApplicationBuilder"></param>
/// <param name="settings"></param>
public TelegramBotWebHostBuilder(WebApplicationBuilder webApplicationBuilder, WebApplicationOptions? settings = null)
public TelegramBotWebHostBuilder(WebApplicationBuilder webApplicationBuilder)
{
_innerBuilder = webApplicationBuilder ?? throw new ArgumentNullException(nameof(webApplicationBuilder));
_settings = settings ?? throw new ArgumentNullException(nameof(settings));
}
/// <summary>
/// Initializes a new instance of the <see cref="TelegramBotWebHostBuilder"/> class.
/// </summary>
/// <param name="webApplicationBuilder"></param>
/// <param name="options"></param>
/// <param name="settings"></param>
public TelegramBotWebHostBuilder(WebApplicationBuilder webApplicationBuilder, TelegratorOptions? options, WebApplicationOptions? settings)
{
_innerBuilder = webApplicationBuilder ?? throw new ArgumentNullException(nameof(webApplicationBuilder));
_settings = settings ?? throw new ArgumentNullException(nameof(settings));
}
/// <summary>
@@ -67,24 +50,10 @@ public class TelegramBotWebHostBuilder : ITelegramBotHostBuilder
/// </summary>
/// <param name="webApplicationBuilder"></param>
/// <param name="handlers"></param>
/// <param name="settings"></param>
public TelegramBotWebHostBuilder(WebApplicationBuilder webApplicationBuilder, IHandlersCollection handlers, WebApplicationOptions settings)
public TelegramBotWebHostBuilder(WebApplicationBuilder webApplicationBuilder, IHandlersCollection handlers)
{
_innerBuilder = webApplicationBuilder ?? throw new ArgumentNullException(nameof(webApplicationBuilder));
_settings = settings ?? throw new ArgumentNullException(nameof(settings));
}
/// <summary>
/// Initializes a new instance of the <see cref="TelegramBotWebHostBuilder"/> class.
/// </summary>
/// <param name="webApplicationBuilder"></param>
/// <param name="handlers"></param>
/// <param name="options"></param>
/// <param name="settings"></param>
public TelegramBotWebHostBuilder(WebApplicationBuilder webApplicationBuilder, IHandlersCollection handlers, TelegratorOptions? options, WebApplicationOptions settings)
{
_innerBuilder = webApplicationBuilder ?? throw new ArgumentNullException(nameof(webApplicationBuilder));
_settings = settings ?? throw new ArgumentNullException(nameof(settings));
_handlers = handlers ?? throw new ArgumentNullException(nameof(handlers));
}
/// <summary>
@@ -26,7 +26,6 @@ public class HostedUpdateWebhooker : IHostedService
/// <summary>
/// Initiallizes new instance of <see cref="HostedUpdateWebhooker"/>
/// </summary>
/// <param name="botHost"></param>
/// <param name="botClient"></param>
/// <param name="updateRouter"></param>
/// <param name="options"></param>
@@ -48,17 +47,6 @@ public class HostedUpdateWebhooker : IHostedService
return Task.CompletedTask;
}
private async void StartInternal(CancellationToken cancellationToken)
{
await _botClient.SetWebhook(
url: _options.WebhookUri,
maxConnections: _options.MaxConnections,
allowedUpdates: _updateRouter.HandlersProvider.AllowedTypes,
dropPendingUpdates: _options.DropPendingUpdates,
secretToken: _options.SecretToken,
cancellationToken: cancellationToken);
}
/// <inheritdoc/>
public Task StopAsync(CancellationToken cancellationToken)
{
@@ -66,16 +54,50 @@ public class HostedUpdateWebhooker : IHostedService
return Task.CompletedTask;
}
/// <summary>
/// Allows to remap receiving webhook endpoint and map new route to webhost.
/// </summary>
/// <param name="routeBuilder"></param>
/// <param name="webhookUri"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
/// <exception cref="ArgumentException"></exception>
public async Task RemapWebhook(IEndpointRouteBuilder routeBuilder, string webhookUri, CancellationToken cancellationToken = default)
{
if (!Uri.TryCreate(webhookUri, UriKind.Absolute, out Uri? result))
throw new ArgumentException("invalid URL");
_options.WebhookUri = result.ToString();
await SetWebhook(cancellationToken);
MapWebhook(routeBuilder);
}
/// <summary>
/// Maps bot webhook to application builder
/// </summary>
/// <param name="routeBuilder"></param>
public void MapWebhook(IEndpointRouteBuilder routeBuilder)
internal void MapWebhook(IEndpointRouteBuilder routeBuilder)
{
string pattern = new UriBuilder(_options.WebhookUri).Path;
routeBuilder.MapPost(pattern, (Delegate)ReceiveUpdate);
}
private async void StartInternal(CancellationToken cancellationToken)
{
await SetWebhook(cancellationToken);
}
private async Task SetWebhook(CancellationToken cancellationToken)
{
await _botClient.SetWebhook(
url: _options.WebhookUri,
maxConnections: _options.MaxConnections,
allowedUpdates: _updateRouter.HandlersProvider.AllowedTypes,
dropPendingUpdates: _options.DropPendingUpdates,
secretToken: _options.SecretToken,
cancellationToken: cancellationToken);
}
private async Task<IResult> ReceiveUpdate(HttpContext ctx)
{
if (_options.SecretToken != null)
@@ -15,7 +15,7 @@
<EnforceCodeStyleInBuild>True</EnforceCodeStyleInBuild>
<Title>Telegrator.Hosting.Web</Title>
<Version>1.16.7</Version>
<Version>1.16.8</Version>
<Authors>Rikitav Tim4ik</Authors>
<Company>Rikitav Tim4ik</Company>
<RepositoryUrl>https://github.com/Rikitav/Telegrator</RepositoryUrl>
+41 -14
View File
@@ -6,6 +6,7 @@ using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System.Diagnostics.CodeAnalysis;
using Telegram.Bot;
using Telegrator.Core;
using Telegrator.Hosting;
@@ -45,7 +46,10 @@ namespace Telegrator
/// </summary>
public static ITelegramBotHostBuilder AddTelegratorWeb(this ITelegramBotHostBuilder builder, TelegratorOptions? options = null, IHandlersCollection? handlers = null, Action<ITelegramBotHostBuilder>? action = null)
{
builder.AddTelegratorWebInternal(options, handlers);
AddTelegratorWebInternal(builder.Services, builder.Configuration, builder.Properties, ref handlers, options);
if (builder is TelegramBotWebHostBuilder telegramBotHostBuilder)
telegramBotHostBuilder._handlers = handlers;
action?.Invoke(builder);
return builder;
}
@@ -55,7 +59,7 @@ namespace Telegrator
/// </summary>
public static IHostApplicationBuilder AddTelegratorWeb(this WebApplicationBuilder builder, TelegratorOptions? options = null, IHandlersCollection? handlers = null, Action<ITelegramBotHostBuilder>? action = null)
{
builder.AddTelegratorWebInternal(options, handlers);
AddTelegratorWebInternal(builder.Services, builder.Configuration, ((IHostApplicationBuilder)builder).Properties, ref handlers, options);
action?.Invoke(new TelegramBotWebHostBuilder(builder));
return builder;
}
@@ -63,11 +67,8 @@ namespace Telegrator
/// <summary>
/// Replaces TelegramBotWebHostBuilder. Configures DI, options, and handlers.
/// </summary>
internal static IHostApplicationBuilder AddTelegratorWebInternal(this IHostApplicationBuilder builder, TelegratorOptions? options = null, IHandlersCollection? handlers = null)
internal static void AddTelegratorWebInternal(IServiceCollection services, IConfiguration configuration, IDictionary<object, object> properties, [NotNull] ref IHandlersCollection? handlers, TelegratorOptions? options = null)
{
IServiceCollection services = builder.Services;
IConfigurationManager configuration = builder.Configuration;
if (options == null)
{
options = configuration.GetSection(nameof(TelegratorOptions)).Get<TelegratorOptions>();
@@ -92,10 +93,7 @@ namespace Telegrator
handlers ??= new HostHandlersCollection(services, options);
services.AddSingleton(handlers);
builder.Properties.Add(HandlersCollectionPropertyKey, handlers);
if (builder is TelegramBotWebHostBuilder botHostBuilder)
botHostBuilder._handlers = handlers;
properties.Add(HandlersCollectionPropertyKey, handlers);
if (!services.Any(srvc => srvc.ImplementationType == typeof(IOptions<WebhookerOptions>)))
{
@@ -117,16 +115,27 @@ namespace Telegrator
services.AddTelegramBotHostDefaults();
services.AddTelegramWebhook();
return builder;
}
/// <summary>
/// Searchs for <see cref="HostedUpdateWebhooker"/> hosted service inside hosts services
/// </summary>
/// <param name="services"></param>
/// <param name="webhooker"></param>
/// <returns></returns>
public static bool TryFindWebhooker(this IServiceProvider services, [NotNullWhen(true)] out HostedUpdateWebhooker? webhooker)
{
webhooker = services.GetServices<IHostedService>().FirstOrDefault(s => s is HostedUpdateWebhooker) as HostedUpdateWebhooker;
return webhooker != null;
}
/// <summary>
/// Replaces the initialization logic from TelegramBotWebHost constructor.
/// Initializes the bot and logs handlers on application startup.
/// </summary>
public static T UseTelegratorWeb<T>(this T app) where T : IEndpointRouteBuilder, IHost
public static T UseTelegratorWeb<T>(this T app, bool dontMap = false) where T : IEndpointRouteBuilder, IHost
{
if (app.ServiceProvider.GetServices<IHostedService>().FirstOrDefault(s => s is HostedUpdateWebhooker) is not HostedUpdateWebhooker webhooker)
if (!app.ServiceProvider.TryFindWebhooker(out HostedUpdateWebhooker? webhooker))
throw new InvalidOperationException("No service for type 'Telegrator.Mediation.HostedUpdateWebhooker' has been registered.");
ITelegramBotInfo info = app.ServiceProvider.GetRequiredService<ITelegramBotInfo>();
@@ -141,7 +150,25 @@ namespace Telegrator
logger.LogHandlers(handlers);
}
webhooker.MapWebhook(app);
if (!dontMap)
webhooker.MapWebhook(app);
return app;
}
/// <summary>
/// Allows to remap receiving webhook endpoint and map new route to webhost.
/// </summary>
/// <param name="app"></param>
/// <param name="webhookUri"></param>
/// <returns></returns>
/// <exception cref="ArgumentException"></exception>
public static T RemapWebhook<T>(this T app, string webhookUri) where T : IEndpointRouteBuilder, IHost
{
if (!app.ServiceProvider.TryFindWebhooker(out HostedUpdateWebhooker? webhooker))
throw new InvalidOperationException("No service for type 'Telegrator.Mediation.HostedUpdateWebhooker' has been registered.");
webhooker.RemapWebhook(app, webhookUri, default).GetAwaiter().GetResult();
return app;
}