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; using WebAPI.Data.Dto; namespace WebAPI.Data { public class PterodactylService { 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(ILogger logger) { this.logger = logger; _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); } private 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; } } private 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; } } public async Task SendPterodactylUserCreate(string username, string email, string firstname, string lastname, string externalId) { var requestObj = new PterodactylCreateUserRequest() { Email = email, ExternalId = externalId, FirstName = firstname, LastName = lastname, Username = username }; return await SendPost("users", requestObj, null); } } }