using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace ClassNotify.Client.Services
{
public enum ServerReachabilityState
{
Checking,
Reachable,
Unreachable
}
///
/// Turn 117 独立云服务 HTTPS 连通性探测服务
/// 遵循规范:仅探测服务端 HTTPS 可达性,绝不耦合 SignalR/授权状态/本地证书
///
public sealed class ServerReachabilityService : IDisposable
{
private static readonly Lazy _instance =
new Lazy(() => new ServerReachabilityService());
public static ServerReachabilityService Instance => _instance.Value;
private readonly HttpClient _httpClient;
private readonly Timer _timer;
private int _consecutiveFailures = 0;
private bool _isDisposed = false;
private string _targetHealthUrl = "https://classnotify.paradise.eu.org/api/health";
public ServerReachabilityState CurrentState { get; private set; } = ServerReachabilityState.Checking;
public event Action? ReachabilityChanged;
private ServerReachabilityService()
{
var handler = new HttpClientHandler
{
ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => true
};
_httpClient = new HttpClient(handler)
{
Timeout = TimeSpan.FromSeconds(5)
};
// Start immediately, then every 20 seconds
_timer = new Timer(OnTimerTick, null, 0, 20000);
}
public void ConfigureServerUrl(string? baseUrl)
{
if (!string.IsNullOrWhiteSpace(baseUrl))
{
var uri = new Uri(baseUrl);
_targetHealthUrl = $"{uri.Scheme}://{uri.Authority}/api/health";
}
}
private async void OnTimerTick(object? state)
{
if (_isDisposed) return;
await CheckReachabilityAsync();
}
public async Task CheckReachabilityAsync()
{
try
{
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
var response = await _httpClient.GetAsync(_targetHealthUrl, HttpCompletionOption.ResponseHeadersRead, cts.Token);
if (response.IsSuccessStatusCode)
{
_consecutiveFailures = 0;
SetState(ServerReachabilityState.Reachable);
return;
}
}
catch
{
// Network or HTTP error
}
_consecutiveFailures++;
if (_consecutiveFailures >= 3)
{
SetState(ServerReachabilityState.Unreachable);
}
else if (CurrentState == ServerReachabilityState.Checking)
{
// Still checking during startup retries
}
}
private void SetState(ServerReachabilityState newState)
{
if (CurrentState == newState) return;
CurrentState = newState;
ReachabilityChanged?.Invoke(newState);
}
public void Dispose()
{
if (_isDisposed) return;
_isDisposed = true;
_timer.Dispose();
_httpClient.Dispose();
}
}
}