Files
actions/sh.actions.package-cleanup/Service/GiteaPackageService.cs
edraft 98abbe661c
Some checks failed
Build on push / prepare (push) Successful in 5s
Build on push / build (push) Failing after 15s
Added package filtering
2026-02-14 20:48:40 +01:00

95 lines
3.4 KiB
C#

namespace sh.actions.package_cleanup.Service;
using System.Net.Http.Json;
using Microsoft.Extensions.Logging;
using sh.actions.package_cleanup.Models;
public class GiteaPackageService(
ILogger<GiteaPackageService> logger,
IConfiguration configuration,
HttpClient httpClient)
: IGiteaPackageService
{
public async Task<IEnumerable<GiteaPackage>> GetPackagesByOwnerAsync(CancellationToken cancellationToken = default)
{
try
{
var baseUrl =
$"{configuration["URL"]?.TrimEnd('/')}/packages/{configuration["OWNER"]}/{configuration["TYPE"]}/{configuration["NAME"]}";
var allPackages = new List<GiteaPackage>();
var page = 1;
while (true)
{
var url = $"{baseUrl}?page={page}";
logger.LogInformation("Fetching packages from Gitea: {Url}", url);
var request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.Add("Authorization", $"token {configuration["API_TOKEN"]}");
var response = await httpClient.SendAsync(request, cancellationToken);
response.EnsureSuccessStatusCode();
var packages =
await response.Content.ReadFromJsonAsync<List<GiteaPackage>>(cancellationToken: cancellationToken)
?? [];
if (packages.Count == 0)
{
break;
}
allPackages.AddRange(packages);
logger.LogInformation("Fetched {Count} packages from page {Page}", packages.Count, page);
page++;
}
logger.LogInformation("Successfully fetched {Count} packages in total", allPackages.Count);
return allPackages;
}
catch (HttpRequestException ex)
{
logger.LogError(ex, "Error fetching packages from Gitea");
throw;
}
catch (Exception ex)
{
logger.LogError(ex, "Unexpected error fetching packages");
throw;
}
}
public async Task DeletePackage(GiteaPackage package, CancellationToken cancellationToken = default)
{
try
{
var url =
$"{configuration["URL"]?.TrimEnd('/')}/packages/{configuration["OWNER"]}/{package.Type}/{package.Name}/{package.Version}";
logger.LogInformation("Deleting package {PackageName} (ID: {PackageId}) from Gitea: {Url}", package.Name,
package.Id, url);
var request = new HttpRequestMessage(HttpMethod.Delete, url);
request.Headers.Add("Authorization", $"token {configuration["API_TOKEN"]}");
var response = await httpClient.SendAsync(request, cancellationToken);
response.EnsureSuccessStatusCode();
logger.LogInformation("Successfully deleted package {PackageName} (ID: {PackageId})", package.Name,
package.Id);
}
catch (HttpRequestException ex)
{
logger.LogError(ex, "Error deleting package {PackageName} (ID: {PackageId}) from Gitea", package.Name,
package.Id);
throw;
}
catch (Exception ex)
{
logger.LogError(ex, "Unexpected error deleting package {PackageName} (ID: {PackageId})", package.Name,
package.Id);
throw;
}
}
}