diff --git a/WebAPI/Data/PterodactylService.cs b/WebAPI/Data/PterodactylService.cs index 20bef49..77a00fe 100644 --- a/WebAPI/Data/PterodactylService.cs +++ b/WebAPI/Data/PterodactylService.cs @@ -1,18 +1,78 @@ +using System; +using System.Collections; using System.Net.Http; +using System.Net.Http.Headers; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Components; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; namespace WebAPI.Data { public class PterodactylService { + [Inject] private ILogger logger { get; set; } private HttpClient _client { get; set; } private string _apiToken { get; set; } + private string _pterodactylHost { get; set; } + private string _apiPath => "api/"; + private string _applicationApiPath => "application/"; + private string _clientApiPath => "client/"; public PterodactylService() { _client = new HttpClient(); _apiToken = AppSettings.PterodactylAPIKey; + _pterodactylHost = AppSettings.PterodactylPanelURL; + if (_pterodactylHost.EndsWith('/')) + { + _pterodactylHost = _pterodactylHost.TrimEnd('/'); + } + _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _apiToken); + _client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + } + + private string ConstructAPIUrl(string endpoint, bool client = false) + { + return $"{_pterodactylHost}{_apiPath}{(client ? _clientApiPath : _applicationApiPath)}{endpoint}"; + } + + private async Task SendRequest(HttpRequestMessage request) + { + var response = await _client.SendAsync(request); + response.EnsureSuccessStatusCode(); + string responsedata = await response.Content.ReadAsStringAsync(); + return JsonConvert.DeserializeObject(responsedata); } - + public async Task SendGet(string endpoint, IEnumerable includeParameters, bool client=false) + { + try + { + HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, new Uri(ConstructAPIUrl(endpoint))); + return await SendRequest(request); + } + catch (Exception e) + { + logger.LogError(e.Message); + return default; + } + + } + + public async Task SendPost(string endpoint, object obj, IEnumerable includeParameters, bool client = false) + { + try + { + HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, new Uri(ConstructAPIUrl(endpoint))); + request.Content = new StringContent(JsonConvert.SerializeObject(obj)); + return await SendRequest(request); + } + catch (Exception e) + { + logger.LogError(e.Message); + return default; + } + } } } \ No newline at end of file