using System; using System.Linq; using System.Net; using System.Threading.Tasks; using RestSharp; using Sony.ChartBot.Entities.ChartApi; using Sony.ChartBot.Entities.MessengerApi; namespace Sony.ChartBot.ChartApi { public class ChartApiClient { public IRestClient RestClient { get { return new RestClient("https://partnerapi-internal.filtr.com"); } } public async Task GetChartPositionsAsync(string artistName, string countryCode, string trackName = null) { var request = new RestRequest("chartPositions", Method.GET); request.AddQueryParameter("artistName", artistName); request.AddQueryParameter("countryCode", countryCode); if (!string.IsNullOrWhiteSpace(trackName)) { request.AddQueryParameter("trackName", trackName); } var response = await RestClient.ExecuteTaskAsync(request); if (response?.StatusCode == HttpStatusCode.NotFound) { return null; } ValidateResponse(response); return response?.Data; } // ReSharper disable once UnusedParameter.Local private void ValidateResponse(IRestResponse response, params HttpStatusCode[] allowedStatusCodes) { if (response == null || response.ErrorException != null || !allowedStatusCodes.Contains(response.StatusCode)) throw new Exception( $"Failed response: {response?.Request?.Resource} {response?.Request?.Method} {response?.StatusCode} {response?.Content} {response?.ErrorMessage}", response?.ErrorException); } private void ValidateResponse(IRestResponse response) { ValidateResponse(response, HttpStatusCode.OK); } private void ValidateResponse(IRestResponse response, params HttpStatusCode[] allowedStatusCodes) { ValidateResponse((IRestResponse)response, allowedStatusCodes); } } }