using Grpc.Core; using Grpc.Net.Client; using GrpcShared.DTO.Db; using GrpcShared.Interfaces; using Microsoft.Net.Http.Headers; using NemAnBlazor.Services.Interfaces; using Newtonsoft.Json; namespace SpotifyService.HttpUtils { public static class HttpUtils where T : new() { public static async Task GetData (IHttpClientFactory _httpClientFactory, string url, string userId, IIdentityService identityService, IAuthService authService) { try { var client = _httpClientFactory.CreateClient("HttpClient"); var userResponse = await identityService.GetTokenByIdAsync(new DbRequestMessage { Id = userId }); //add header client.DefaultRequestHeaders.Add(HeaderNames.Authorization, "Bearer " + userResponse.Token); //get request var req = await client.GetAsync(url); //read response var response = JsonConvert.DeserializeObject(await req.Content.ReadAsStringAsync())!; if (req.StatusCode == System.Net.HttpStatusCode.Unauthorized) { string newToken = await SpotifyHelper.TryRefreshToken(authService, userResponse, identityService); if (newToken != null) { client.DefaultRequestHeaders.Add(HeaderNames.Authorization, "Bearer " + newToken); req = await client.GetAsync(url); response = JsonConvert.DeserializeObject(await req.Content.ReadAsStringAsync())!; } //ako to ne radi to znaci da je refresh token isteko, treba da se refreshuje } return response; } catch (RpcException e) { if (e.StatusCode == StatusCode.Cancelled) { //vrati message sa status kodom? return new T(); } throw; } } public static async Task PutData(HttpClient client, string url, string userId, IIdentityService identityService, IAuthService authService) { try { var tokenMessage = await identityService.GetTokenByIdAsync(new GrpcShared.DTO.Db.DbRequestMessage { Id = userId }); //add header client.DefaultRequestHeaders.Add(HeaderNames.Authorization, "Bearer " + tokenMessage.Token); //get request var responseMessage = await client.PutAsync(url, null); if(responseMessage.StatusCode == System.Net.HttpStatusCode.Unauthorized) { string newToken = await SpotifyHelper.TryRefreshToken(authService, tokenMessage, identityService); if (newToken != null) { responseMessage = await client.PutAsync(url, null); } } } catch (RpcException e) { if (e.StatusCode == StatusCode.Cancelled) { //vrati message sa status kodom? return; } throw; } } } }