blob: f4d75678f6ab877993e92b0c667409f7b476f65d (
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
95
96
97
98
99
|
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<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;
}
}
|