using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; using ChaosBot.Lodestone; using Newtonsoft.Json; using NLog; using NLog.Fluent; namespace ChaosBot.Services { public static class LodestoneHttpProxy { public static T Fetch(string endpoint) { // TODO: implement some sort of local caching return Fetch(endpoint, new Dictionary()); } public static T Fetch(string endpoint, Dictionary parameters) { // TODO: implement some sort of local caching return LodestoneHttpConnection.Fetch(endpoint, parameters).GetAwaiter().GetResult(); } } static class LodestoneHttpConnection { private static readonly ILogger _logger = Program.Logger; static HttpClient client = new HttpClient(); private static bool _firstRun = true; public static async Task Fetch(string endpoint, Dictionary parameters) { try { if (_firstRun) { _firstRun = false; client.BaseAddress = new Uri("https://xivapi.com/"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); } string queryString = String.Join("&",parameters.Select(param => $"{param.Key}={param.Value}").ToArray()); HttpResponseMessage response = await client.GetAsync($"{endpoint}?{queryString}"); string output = null; if (response.IsSuccessStatusCode) { output = await response.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject(output); } throw new HttpRequestException($"HTTP Response for '{response.RequestMessage.RequestUri}' returned status code {response.StatusCode}"); } catch (Exception ex) { _logger.Error(ex, $"HttpProxy.fetch<{typeof(T)}>: Exception [{ex}] thrown, <[{ex.Message}]>."); throw; } } } }