using System; using System.Collections.Generic; using System.Net.Http; using System.Text.Json; using System.Threading.Tasks; namespace LibreAuth.Sdk { public class LibreAuth { public string Name { get; set; } public string OwnerId { get; set; } public string Version { get; set; } public string Url { get; set; } public string SessionId { get; private set; } public string EncKey { get; private set; } private static readonly HttpClient Http = new HttpClient(); public LibreAuth(string name, string ownerId, string version, string url) { Name = name; OwnerId = ownerId; Version = version; Url = url.TrimEnd('/') + "/"; } public async Task InitAsync(string enckey = null) { EncKey = (enckey ?? Guid.NewGuid().ToString("N")).Substring(0, 35); var res = await ReqAsync(new Dictionary { ["type"] = "init", ["ver"] = Version, ["enckey"] = EncKey, }); if (!res.RootElement.GetProperty("success").GetBoolean()) throw new Exception(res.RootElement.GetProperty("message").GetString()); SessionId = res.RootElement.GetProperty("sessionid").GetString(); return res; } public async Task LoginAsync(string user, string pass, string hwid = "", string code = "") { return await AuthAsync(new Dictionary { ["type"] = "login", ["username"] = user, ["pass"] = pass, ["hwid"] = hwid, ["code"] = code, }); } public async Task LicenseAsync(string key, string hwid = "") { return await AuthAsync(new Dictionary { ["type"] = "license", ["key"] = key, ["hwid"] = hwid, }); } public async Task TokenAsync(string token, string hwid = "") { return await AuthAsync(new Dictionary { ["type"] = "token", ["token"] = token, ["hwid"] = hwid, }); } async Task AuthAsync(Dictionary data) { var res = await ReqAsync(data); if (!res.RootElement.GetProperty("success").GetBoolean()) throw new Exception(res.RootElement.GetProperty("message").GetString()); return res.RootElement.GetProperty("info"); } async Task ReqAsync(Dictionary data) { data["name"] = Name; data["ownerid"] = OwnerId; if (SessionId != null) data["sessionid"] = SessionId; var content = new FormUrlEncodedContent(data); var resp = await Http.PostAsync(Url, content); if ((int)resp.StatusCode == 429) throw new Exception("Rate limited"); var json = await resp.Content.ReadAsStringAsync(); return JsonDocument.Parse(json); } } }