using Newtonsoft.Json; using NLog; using Sony.Filtr.ApolloAPI.Models; using Sony.Filtr.Utility.Extensions; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; namespace Sony.Filtr.ApolloAPI { public abstract class ApolloWebApiBase { protected readonly TimeSpan NoCacheTime = TimeSpan.FromSeconds(0); private readonly HttpClient httpClient; protected readonly Logger _logger; public ApolloWebApiBase(HttpClient httpClient) { this.httpClient = httpClient; this._logger = LogManager.GetLogger(this.GetLoggerName()); } protected abstract string GetLoggerName(); protected async Task GetFromApollo(string url, TimeSpan cacheExpiration) { return await this.GetFromApollo(url, ParseResponse, cacheExpiration); } protected async Task GetFromApollo(string url, Func responseParser, TimeSpan cacheExpiration) { var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, url); httpRequestMessage.Headers.Add("X-Data-Timeout", cacheExpiration.TotalSeconds.ToString()); httpRequestMessage.Headers.Add("X-App-Slug", "apollo"); HttpResponseMessage response = await this.httpClient.SendAsync(httpRequestMessage); if (response.IsSuccessStatusCode) { string responseString = await response.Content.ReadAsStringAsync(); var responseDto = responseParser(responseString); IHeaderTracker headerTracker = responseDto as IHeaderTracker; if (headerTracker != null) { headerTracker.AddHeaders( response.RequestMessage.RequestUri.ToString(), GetVendorResponseHeaders(response)); } IRawResponseTracker rawResponseTracker = responseDto as IRawResponseTracker; if (rawResponseTracker != null) { rawResponseTracker.AddRawResponseToModel( response.RequestMessage.RequestUri.ToString(), await response.Content.ReadAsStringAsync()); } return responseDto; } if (response.StatusCode == System.Net.HttpStatusCode.NotFound) { return default(T); } throw ApolloWebAPIException.FromHttpResponseMessage(response); } protected static T ParseResponse(string responseString) { try { return JsonConvert.DeserializeObject(responseString); } catch (Exception ex) { throw new ApolloWebAPIException($"Could not parse '{typeof(T)}' response. Response: '{responseString}'"); } } private static IEnumerable> GetVendorResponseHeaders(HttpResponseMessage response) { return response .Headers .Where(h => h.Key.ToLower().StartsWith("x-")) .Select(h => new KeyValuePair(h.Key, h.Value.FirstOrDefault())) .ToList(); } } }