diff --git a/Cajetan.OF-DL/Services/CajetanApiService.cs b/Cajetan.OF-DL/Services/CajetanApiService.cs index fcc5d5f..7c1b8ca 100644 --- a/Cajetan.OF-DL/Services/CajetanApiService.cs +++ b/Cajetan.OF-DL/Services/CajetanApiService.cs @@ -459,4 +459,45 @@ public class CajetanApiService(IAuthService authService, IConfigService configSe MediasCount = userDto.MediasCount, }; } + + protected new async Task BuildHeaderAndExecuteRequests(Dictionary getParams, string endpoint, HttpClient client, HttpMethod? method = null, object? reqBody = null) + { + const int RETRY_ATTEMPTS = 3; + + Log.Debug("Calling BuildHeaderAndExecuteRequests"); + + for (int i = 0; i < RETRY_ATTEMPTS; i++) + { + using HttpResponseMessage response = await BuildAndExecuteAsync(); + + if (response.IsSuccessStatusCode) + return await ReadBodyAsync(response); + + if (response.StatusCode != System.Net.HttpStatusCode.TooManyRequests) + response.EnsureSuccessStatusCode(); + + string errorBody = await response.Content.ReadAsStringAsync(); + Log.ForContext("ErrorBody", errorBody) + .ForContext("ErrorHeaders", response.Headers) + .Warning("Too Many Requests -- Waiting and retrying"); + await Task.Delay(1000); + continue; + } + + throw new Exception($"Request failed after {RETRY_ATTEMPTS} attempts!"); + + async Task BuildAndExecuteAsync() + { + HttpRequestMessage request = await BuildHttpRequestMessage(getParams, endpoint, method, reqBody); + HttpResponseMessage response = await client.SendAsync(request); + return response; + } + + async Task ReadBodyAsync(HttpResponseMessage response) + { + string body = await response.Content.ReadAsStringAsync(); + Log.Debug(body); + return body; + } + } }