59 lines
1.7 KiB
C#
59 lines
1.7 KiB
C#
using Telegram.Bot.SpaceApi.Backend.Utils;
|
|
|
|
namespace Telegram.Bot.SpaceApi.Backend;
|
|
|
|
public class SpaceApiClient {
|
|
private readonly string _apiUrl;
|
|
private readonly HttpClient _client;
|
|
|
|
public SpaceApiClient(string apiUrl) {
|
|
_apiUrl = apiUrl;
|
|
_client = new HttpClient();
|
|
}
|
|
|
|
public SpaceApiClient(string apiUrl, string overrideAddress) {
|
|
_apiUrl = apiUrl;
|
|
_client = new HttpClient(new DnsHandler(new CustomDnsResolver(overrideAddress)));
|
|
}
|
|
|
|
public bool IsOpen() {
|
|
using var rq = new HttpRequestMessage(HttpMethod.Get, _apiUrl);
|
|
rq.Headers.ConnectionClose = true;
|
|
rq.Headers.UserAgent.ParseAdd($"Mozilla/5.0 (compatible; {ApplicationInformation.Project}/1.0; +{ApplicationInformation.Repository})");
|
|
rq.Headers.Host = new Uri(_apiUrl).Host;
|
|
|
|
using var resp = _client.SendAsync(rq, HttpCompletionOption.ResponseContentRead).Result;
|
|
|
|
return SpaceApiResponse.FromJson(resp.Content.ReadAsStringAsync().Result).State.Open ?? false;
|
|
}
|
|
|
|
private class DnsHandler : HttpClientHandler {
|
|
private readonly CustomDnsResolver _dnsResolver;
|
|
|
|
public DnsHandler(CustomDnsResolver dnsResolver) {
|
|
_dnsResolver = dnsResolver;
|
|
}
|
|
|
|
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) {
|
|
var host = request.RequestUri!.Host;
|
|
var ip = _dnsResolver.Resolve(host);
|
|
|
|
var builder = new UriBuilder(request.RequestUri) { Host = ip };
|
|
|
|
request.RequestUri = builder.Uri;
|
|
|
|
return base.SendAsync(request, cancellationToken);
|
|
}
|
|
}
|
|
|
|
private class CustomDnsResolver {
|
|
private readonly string _address;
|
|
|
|
public CustomDnsResolver(string address) => _address = address;
|
|
|
|
public string Resolve(string host) {
|
|
return _address;
|
|
}
|
|
}
|
|
}
|