using System; using System.Net; using System.Text; using System.IO; using Newtonsoft.Json; namespace Leadercraft.Server { internal class LeadercraftApi { private readonly ulong _userId; private readonly string _tokenUrl; private readonly string _criteriaUrl; public LeadercraftApi(ulong userId, string tokenUrl, string criteriaUrl) { this._userId = userId; this._tokenUrl = tokenUrl; this._criteriaUrl = criteriaUrl; } public LeadercraftResult RequestPOSTToken(string playerName = "???") { NewKeyStruct reqBodyObj = new NewKeyStruct{ PlayerID = _userId, PlayerName = playerName }; string reqBodyStr = JsonConvert.SerializeObject(reqBodyObj); // Request WebRequest request = WebRequest.Create(_tokenUrl); request.Method = "POST"; request.ContentLength = reqBodyStr.Length; request.ContentType = "application/json"; StreamWriter body; try { body = new StreamWriter(request.GetRequestStream()); body.Write(reqBodyStr); body.Close(); } catch (WebException e) { int status = (int) e.Status; if (e.Response != null && e.Response is HttpWebResponse webResponse) status = (int)webResponse.StatusCode; return new LeadercraftResult(new byte[] { }, status); } // Response HttpWebResponse response = null; try { response = (HttpWebResponse)request.GetResponse(); } catch (WebException e) { int status = (int) e.Status; if (e.Response != null && e.Response is HttpWebResponse webResponse) status = (int)webResponse.StatusCode; return new LeadercraftResult(new byte[] { }, status); } StreamReader respBody = new StreamReader(response.GetResponseStream()); string respBodyStr = respBody.ReadToEnd(); response.Close(); return new LeadercraftResult(respBodyStr, (int)response.StatusCode); } public LeadercraftResult RequestPOSTCriteria(CriteriaStruct criteria, string token) { criteria.PlayerID = _userId; string reqBodyStr = JsonConvert.SerializeObject(criteria); // Request WebRequest request = WebRequest.Create(_criteriaUrl); request.Method = "POST"; request.ContentLength = reqBodyStr.Length; request.ContentType = "application/json"; request.Headers.Add(HttpRequestHeader.Authorization, "leadercraft "+token); StreamWriter body; try { body = new StreamWriter(request.GetRequestStream()); body.Write(reqBodyStr); body.Close(); } catch (WebException e) { int status = (int) e.Status; if (e.Response != null && e.Response is HttpWebResponse webResponse) status = (int)webResponse.StatusCode; return new LeadercraftResult(new byte[] { }, status); } // Response HttpWebResponse response = null; try { response = (HttpWebResponse)request.GetResponse(); } catch (WebException e) { int status = (int) e.Status; if (e.Response != null && e.Response is HttpWebResponse webResponse) status = (int)webResponse.StatusCode; return new LeadercraftResult(new byte[] { }, status); } StreamReader respBody = new StreamReader(response.GetResponseStream()); string respBodyStr = respBody.ReadToEnd(); response.Close(); return new LeadercraftResult(respBodyStr, (int)response.StatusCode); } } }