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 logger, IConfiguration configuration, HttpClient httpClient) : IGiteaPackageService { public async Task> GetPackagesByOwnerAsync(CancellationToken cancellationToken = default) { try { var baseUrl = $"{configuration["URL"]?.TrimEnd('/')}/packages/{configuration["OWNER"]}/{configuration["TYPE"]}/{configuration["NAME"]}"; var allPackages = new List(); 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>(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; } } }