using Cleanuparr.Domain.Enums;
using Cleanuparr.Infrastructure.Http.DynamicHttpClientSystem;
using Cleanuparr.Persistence;
using Cleanuparr.Persistence.Models.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace Cleanuparr.Infrastructure.Http;
///
/// Provides dynamically configured HTTP clients for download services
///
public class DynamicHttpClientProvider : IDynamicHttpClientProvider
{
private readonly ILogger _logger;
private readonly IServiceProvider _serviceProvider;
private readonly IDynamicHttpClientFactory _dynamicHttpClientFactory;
public DynamicHttpClientProvider(
ILogger logger,
IServiceProvider serviceProvider,
IDynamicHttpClientFactory dynamicHttpClientFactory)
{
_logger = logger;
_serviceProvider = serviceProvider;
_dynamicHttpClientFactory = dynamicHttpClientFactory;
}
///
public HttpClient CreateClient(DownloadClientConfig downloadClientConfig)
{
return CreateGenericClient(downloadClientConfig);
}
///
/// Gets the client name for a specific client configuration
///
/// The client configuration
/// The client name for use with IHttpClientFactory
private string GetClientName(DownloadClientConfig downloadClientConfig)
{
return $"DownloadClient_{downloadClientConfig.Id}";
}
///
/// Creates a generic HTTP client with appropriate configuration using the dynamic system
///
/// The client configuration
/// A configured HttpClient instance
private HttpClient CreateGenericClient(DownloadClientConfig downloadClientConfig)
{
var dataContext = _serviceProvider.GetRequiredService();
var httpConfig = dataContext.GeneralConfigs.First();
var clientName = GetClientName(downloadClientConfig);
// Determine the client type based on the download client type
var clientType = downloadClientConfig.TypeName switch
{
DownloadClientTypeName.Deluge => HttpClientType.Deluge,
_ => HttpClientType.WithRetry
};
// Create retry configuration
var retryConfig = new RetryConfig
{
MaxRetries = httpConfig.HttpMaxRetries,
ExcludeUnauthorized = true
};
// Register the client configuration dynamically
_dynamicHttpClientFactory.RegisterDownloadClient(
clientName,
httpConfig.HttpTimeout,
clientType,
retryConfig,
httpConfig.HttpCertificateValidation
);
// Create and configure the client
var client = _dynamicHttpClientFactory.CreateClient(clientName);
// Set base address if needed
if (downloadClientConfig.Url != null)
{
client.BaseAddress = downloadClientConfig.Url;
}
_logger.LogTrace("Created HTTP client for download client {Name} (ID: {Id}) with type {Type}",
downloadClientConfig.Name, downloadClientConfig.Id, clientType);
return client;
}
}