- Replaced direct `HttpClient` dependencies with `IHttpClientFactory` in `GithubService`, `ForgejoService`, and `ReleaseAssetDownloadService`. - Added DI-configured HTTP client registrations for GitHub, Forgejo, and asset downloads in `Program.cs`. - Consolidated HTTP client setup to enhance maintainability, configurability, and resource lifecycle management.
43 lines
1.4 KiB
C#
43 lines
1.4 KiB
C#
using Microsoft.Extensions.Logging;
|
|
|
|
namespace ForgejoReleaseSync.Services;
|
|
|
|
public class ReleaseAssetDownloadService(IHttpClientFactory httpClientFactory, ILogger<ReleaseAssetDownloadService> logger)
|
|
{
|
|
public async Task<string> DownloadReleaseAssetAsync(Uri url, CancellationToken token = default)
|
|
{
|
|
try
|
|
{
|
|
var httpClient = httpClientFactory.CreateClient("asset-download");
|
|
|
|
var fileName = Path.GetFileName(url.AbsoluteUri);
|
|
var filePath = Path.Combine(Path.GetTempPath(), fileName);
|
|
|
|
await using var resource = await httpClient.GetStreamAsync(url, token);
|
|
await using var fs = new FileStream(
|
|
filePath, FileMode.Create, FileAccess.Write, FileShare.None, 8192, useAsync: true);
|
|
await resource.CopyToAsync(fs, token);
|
|
|
|
return filePath;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
logger.LogError(ex, "Failed to download asset from {Url}", url);
|
|
throw;
|
|
}
|
|
}
|
|
|
|
public async Task DeleteReleaseAssetAsync(string downloadPath, CancellationToken token = default)
|
|
{
|
|
try
|
|
{
|
|
File.Delete(downloadPath);
|
|
await Task.CompletedTask;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
logger.LogError(ex, "Failed to delete asset {Path}", downloadPath);
|
|
throw;
|
|
}
|
|
}
|
|
} |