using HyperBooru.ApiModels; using System.Net; using System.Net.Http.Json; namespace HyperBooru.ApiClient; public class HBSession : IDisposable { public Media Media { get; private init; } public Tag Tag { get; private init; } public Feed Feed { get; private init; } public User User { get; private init; } public Statistics Statistics { get; private init; } public bool HasNsfwClaim => false; public Uri BaseUri { get => HttpClient.BaseAddress!; set => HttpClient.BaseAddress = new($"{value.Scheme}://{value.Host}:{value.Port}/"); } public bool SkipCertificateCheck { get => httpClientHandler.ClientCertificateOptions == ClientCertificateOption.Manual; set { if(value) { httpClientHandler.ClientCertificateOptions = ClientCertificateOption.Manual; httpClientHandler.ServerCertificateCustomValidationCallback = (request, cert, certChain, policyErrors) => true; } else { httpClientHandler.ClientCertificateOptions = ClientCertificateOption.Automatic; httpClientHandler.ServerCertificateCustomValidationCallback = null; } } } internal HttpClient HttpClient { get; private init; } private HttpClientHandler httpClientHandler; private bool toDispose = true; public HBSession() { httpClientHandler = new() { AllowAutoRedirect = true, UseCookies = true, CookieContainer = new CookieContainer() }; HttpClient = new(new ErrorHandler(httpClientHandler)); Media = new(this); Tag = new(this); Feed = new(this); User = new(this); Statistics = new(this); } public HBSession(HttpClient httpClient) { HttpClient = httpClient; toDispose = false; Media = new(this); Tag = new(this); Feed = new(this); User = new(this); Statistics = new(this); } public Task LoginAsync(string username, string password) => Task.CompletedTask; public Task LogoutAsync() => Task.CompletedTask; public void Dispose() { if(toDispose) HttpClient.Dispose(); } } public class ErrorHandler : DelegatingHandler { public ErrorHandler(HttpMessageHandler innerHandler) : base(innerHandler) {} protected override async Task SendAsync(HttpRequestMessage request, CancellationToken ct) { var resp = await base.SendAsync(request, ct); if(resp.IsSuccessStatusCode) return resp; HBException e; try { e = await resp.Content.ReadFromJsonAsync(ct) ?? throw new NullReferenceException(); } catch { throw new HBException("An unknown error occurred"); } throw e; } }