summaryrefslogtreecommitdiff
path: root/HyperBooru.cs
blob: 99fd38af66457900b9c4928a864ea4681e00e291 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
using HyperBooru.ApiModels;
using System.Net;
using System.Net.Http.Json;

namespace HyperBooru.ApiClient;

public sealed 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 Uri        BaseUri    { get; private init; }

    internal HttpClient HttpClient { get; private init; }

    public HBSession (
        Uri baseUri,
        bool skipCertificateCheck) {

        BaseUri = new($"{baseUri.Scheme}://{baseUri.Host}:{baseUri.Port}/");

        var handler = new HttpClientHandler() {
            AllowAutoRedirect = true,
            UseCookies        = true,
            CookieContainer   = new CookieContainer()
        };

        if(skipCertificateCheck) {
            handler.ClientCertificateOptions = ClientCertificateOption.Manual;
            handler.ServerCertificateCustomValidationCallback =
                (request, cert, certChain, policyErrors) => true;
        }

        HttpClient = new(new ErrorHandler(handler)) {
            BaseAddress = BaseUri
        };

        Media      = new(this);
        Tag        = new(this);
        Feed       = new(this);
        User       = new(this);
        Statistics = new(this);
    }

    public async Task LoginAsync(string username, string password) {
        var formData = new FormUrlEncodedContent(new[] {
            new KeyValuePair<string, string>("username", username),
            new KeyValuePair<string, string>("password", password)
        });

        var resp = await HttpClient.PostAsync($"/Login", formData);

        if(resp.StatusCode == HttpStatusCode.Forbidden) {
            throw new Exception("Invalid username or password");
        } else if(!resp.IsSuccessStatusCode) {
            var content = await resp.Content.ReadAsStringAsync();
            throw new Exception($"Unknown error while logging in: {content}");
        }

        Media      = new(this);
        Tag        = new(this);
        Feed       = new(this);
        User       = new(this);
        Statistics = new(this);
    }

    public async Task LogoutAsync() =>
        await HttpClient.PostAsync("/Logout", null);

    public void Dispose() =>
        HttpClient.Dispose();
}

public class ErrorHandler : DelegatingHandler {
    public ErrorHandler(HttpMessageHandler innerHandler) : base(innerHandler) {}

    protected override async Task<HttpResponseMessage> 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<HBException>(ct) ??
                throw new NullReferenceException();
        } catch {
            throw new HBException("An unknown error occurred");
        }

        throw e;
    }
}