860 lines
30 KiB
C#
860 lines
30 KiB
C#
using EonaCat.Json;
|
|
using EonaCat.Json.Linq;
|
|
using EonaCat.Connections.EventArguments;
|
|
using EonaCat.Connections.Helpers;
|
|
using EonaCat.Connections.Models;
|
|
using EonaCat.Connections.ConnectionDiagnostics;
|
|
using Microsoft.AspNetCore.Builder;
|
|
using Microsoft.AspNetCore.Hosting;
|
|
using Microsoft.AspNetCore.Http;
|
|
using Microsoft.AspNetCore.Server.Kestrel.Core;
|
|
using System.Net;
|
|
using System.Security.Cryptography;
|
|
using System.Text;
|
|
using ErrorEventArgs = EonaCat.Connections.EventArguments.ErrorEventArgs;
|
|
|
|
namespace EonaCat.Connections.REST
|
|
{
|
|
public class RestNetworkClient : IAsyncDisposable, IDisposable
|
|
{
|
|
public static event EventHandler<LogMessage> OnLog;
|
|
private readonly Configuration _config;
|
|
private HttpClient? _httpClient;
|
|
private Task? _pollTask;
|
|
private Task? _autoReconnectTask;
|
|
private Task? _pingTask;
|
|
private Task? _pongMonitorTask;
|
|
private CancellationTokenSource? _clientCts;
|
|
private CancellationTokenSource? _autoReconnectSource;
|
|
private bool _disposed;
|
|
private bool _stopAutoReconnecting;
|
|
private bool _wasConnected;
|
|
private DisconnectReason _reason;
|
|
private Aes? _aesInstance;
|
|
|
|
private WebApplication? _webhookApp;
|
|
private CancellationTokenSource? _webhookCts;
|
|
private Task? _webhookTask;
|
|
private int _webhookPort;
|
|
|
|
private readonly SemaphoreSlim _connectLock = new(1, 1);
|
|
|
|
public string? ClientId { get; private set; }
|
|
public bool IsConnected { get; private set; }
|
|
public string? Nickname { get; private set; }
|
|
public DateTime ConnectionTime { get; private set; }
|
|
public TimeSpan Uptime => DateTime.UtcNow - ConnectionTime;
|
|
public DateTime LastActive { get; internal set; }
|
|
public DateTime LastDataSent { get; private set; }
|
|
public DateTime LastDataReceived { get; private set; }
|
|
public DateTime LastPingSent { get; private set; }
|
|
public DateTime LastPongReceived { get; private set; }
|
|
public DateTime DisconnectionTime { get; private set; }
|
|
public bool IsAutoConnectStarted => _autoReconnectTask != null && !_autoReconnectTask.IsCompleted;
|
|
public bool IsWebhookListenerActive => _webhookApp != null && _webhookCts != null && !_webhookCts.IsCancellationRequested;
|
|
|
|
public long BytesSent { get; private set; }
|
|
public long BytesReceived { get; private set; }
|
|
public long MessagesSent { get; private set; }
|
|
public long MessagesReceived { get; private set; }
|
|
|
|
public event EventHandler<ConnectionEventArgs>? OnConnected;
|
|
public event EventHandler<ConnectionEventArgs>? OnNicknameSend;
|
|
public event EventHandler<DataReceivedEventArgs>? OnDataReceived;
|
|
public event EventHandler<ConnectionEventArgs>? OnDisconnected;
|
|
public event EventHandler<ErrorEventArgs>? OnGeneralError;
|
|
public event EventHandler<PingEventArgs>? OnPingResponse;
|
|
public event EventHandler<PingEventArgs>? OnPongResponse;
|
|
|
|
public WebhookManager Webhooks { get; } = new();
|
|
|
|
public RestNetworkClient(Configuration config)
|
|
{
|
|
_config = config ?? throw new ArgumentNullException(nameof(config));
|
|
_clientCts = new CancellationTokenSource();
|
|
}
|
|
|
|
private string BaseUrl
|
|
{
|
|
get
|
|
{
|
|
var scheme = _config.UseSsl ? "https" : "http";
|
|
return $"{scheme}://{_config.Host}:{_config.Port}";
|
|
}
|
|
}
|
|
|
|
public async Task<bool> ConnectAsync()
|
|
{
|
|
await _connectLock.WaitAsync().ConfigureAwait(false);
|
|
|
|
try
|
|
{
|
|
if (_clientCts == null || _clientCts.IsCancellationRequested)
|
|
{
|
|
_clientCts?.Dispose();
|
|
_clientCts = new CancellationTokenSource();
|
|
}
|
|
|
|
if (IsConnected)
|
|
{
|
|
return true;
|
|
}
|
|
|
|
_httpClient?.Dispose();
|
|
|
|
var handler = new HttpClientHandler();
|
|
if (_config.UseSsl && _config.IsSelfSignedEnabled)
|
|
{
|
|
handler.ServerCertificateCustomValidationCallback = (_, _, _, _) => true;
|
|
}
|
|
|
|
_httpClient = new HttpClient(handler)
|
|
{
|
|
BaseAddress = new Uri(BaseUrl),
|
|
Timeout = _config.ConnectionTimeout
|
|
};
|
|
|
|
var response = await _httpClient.PostAsync("/api/connect",
|
|
new StringContent("{}", Encoding.UTF8, "application/json")).ConfigureAwait(false);
|
|
|
|
if (!response.IsSuccessStatusCode)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
var json = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
|
|
var doc = JObject.Parse(json);
|
|
ClientId = (string)doc["clientId"];
|
|
|
|
if (string.IsNullOrEmpty(ClientId))
|
|
{
|
|
return false;
|
|
}
|
|
|
|
IsConnected = true;
|
|
ConnectionTime = DateTime.UtcNow;
|
|
LastActive = DateTime.UtcNow;
|
|
LastPongReceived = DateTime.UtcNow;
|
|
|
|
if (_config.UseAesEncryption && !string.IsNullOrEmpty(_config.AesPassword))
|
|
{
|
|
await InitAesEncryptionAsync().ConfigureAwait(false);
|
|
}
|
|
|
|
_pollTask = Task.Run(() => PollLoopAsync(_clientCts.Token), _clientCts.Token);
|
|
|
|
if (_config.EnableHeartbeat)
|
|
{
|
|
_pingTask = Task.Run(() => PingLoopAsync(_clientCts.Token), _clientCts.Token);
|
|
_pongMonitorTask = Task.Run(() => PongMonitorAsync(_clientCts.Token), _clientCts.Token);
|
|
}
|
|
|
|
if (!string.IsNullOrEmpty(Nickname))
|
|
{
|
|
await SendNicknameAsync(Nickname).ConfigureAwait(false);
|
|
}
|
|
|
|
if (_config.EnableAutoReconnect &&
|
|
(_autoReconnectTask == null || _autoReconnectTask.IsCompleted))
|
|
{
|
|
if (_autoReconnectSource == null || _autoReconnectSource.IsCancellationRequested)
|
|
{
|
|
_autoReconnectSource?.Dispose();
|
|
_autoReconnectSource = new CancellationTokenSource();
|
|
}
|
|
_autoReconnectTask = Task.Run(() => AutoReconnectAsync(_autoReconnectSource.Token), _autoReconnectSource.Token);
|
|
}
|
|
|
|
_wasConnected = true;
|
|
|
|
HandlingHelpers.SafeInvokeEventHandler(
|
|
OnConnected,
|
|
this,
|
|
new ConnectionEventArgs
|
|
{
|
|
ClientId = ClientId,
|
|
RemoteEndPoint = new IPEndPoint(IPAddress.Parse(_config.Host), _config.Port)
|
|
},
|
|
nameof(OnConnected));
|
|
|
|
return true;
|
|
}
|
|
catch (Exception exception)
|
|
{
|
|
HandlingHelpers.SafeInvokeEventHandler(
|
|
OnGeneralError,
|
|
this,
|
|
new ErrorEventArgs
|
|
{
|
|
Exception = exception,
|
|
Message = "REST connection error"
|
|
},
|
|
nameof(OnGeneralError));
|
|
return false;
|
|
}
|
|
finally
|
|
{
|
|
try
|
|
{
|
|
_connectLock.Release();
|
|
}
|
|
catch
|
|
{
|
|
|
|
}
|
|
}
|
|
}
|
|
|
|
private async Task PollLoopAsync(CancellationToken token)
|
|
{
|
|
try
|
|
{
|
|
while (!token.IsCancellationRequested && IsConnected)
|
|
{
|
|
try
|
|
{
|
|
if (_httpClient == null || string.IsNullOrEmpty(ClientId))
|
|
{
|
|
break;
|
|
}
|
|
|
|
var response = await _httpClient.GetAsync($"/api/poll/{ClientId}", token).ConfigureAwait(false);
|
|
|
|
if (!response.IsSuccessStatusCode)
|
|
{
|
|
if (response.StatusCode == System.Net.HttpStatusCode.NotFound)
|
|
{
|
|
await DisconnectAsync(DisconnectReason.RemoteClosed).ConfigureAwait(false);
|
|
break;
|
|
}
|
|
await Task.Delay(1000, token).ConfigureAwait(false);
|
|
continue;
|
|
}
|
|
|
|
var json = await response.Content.ReadAsStringAsync(token).ConfigureAwait(false);
|
|
var doc = JObject.Parse(json);
|
|
|
|
if (doc.TryGetValue("messages", out var messagesToken) && messagesToken is JArray messagesArray)
|
|
{
|
|
foreach (var msg in messagesArray)
|
|
{
|
|
var base64 = (string)msg;
|
|
if (string.IsNullOrEmpty(base64))
|
|
{
|
|
continue;
|
|
}
|
|
|
|
var data = Convert.FromBase64String(base64);
|
|
|
|
if (_config.UseAesEncryption && _aesInstance != null)
|
|
{
|
|
data = await AesKeyExchange.DecryptDataAsync(data, data.Length, _aesInstance).ConfigureAwait(false);
|
|
}
|
|
|
|
LastActive = DateTime.UtcNow;
|
|
LastDataReceived = DateTime.UtcNow;
|
|
BytesReceived += data.Length;
|
|
MessagesReceived++;
|
|
|
|
HandlingHelpers.SafeInvokeEventHandler(
|
|
OnDataReceived,
|
|
this,
|
|
new DataReceivedEventArgs
|
|
{
|
|
ClientId = ClientId ?? "self",
|
|
Data = data,
|
|
RemoteEndPoint = new IPEndPoint(IPAddress.Parse(_config.Host), _config.Port),
|
|
Nickname = Nickname
|
|
},
|
|
nameof(OnDataReceived));
|
|
}
|
|
}
|
|
|
|
await Task.Delay(500, token).ConfigureAwait(false);
|
|
}
|
|
catch (OperationCanceledException)
|
|
{
|
|
break;
|
|
}
|
|
catch (HttpRequestException)
|
|
{
|
|
await DisconnectAsync(DisconnectReason.RemoteClosed).ConfigureAwait(false);
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
catch (OperationCanceledException)
|
|
{
|
|
|
|
}
|
|
catch (Exception exception)
|
|
{
|
|
HandlingHelpers.SafeInvokeEventHandler(
|
|
OnGeneralError,
|
|
this,
|
|
new ErrorEventArgs
|
|
{
|
|
Exception = exception,
|
|
Message = "Error in REST poll loop"
|
|
},
|
|
nameof(OnGeneralError));
|
|
await DisconnectAsync(DisconnectReason.Error, exception).ConfigureAwait(false);
|
|
}
|
|
}
|
|
|
|
public async Task<bool> SendAsync(byte[] data)
|
|
{
|
|
if (!IsConnected || _httpClient == null || string.IsNullOrEmpty(ClientId) || data == null || data.Length == 0)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
try
|
|
{
|
|
var sendData = data;
|
|
if (_config.UseAesEncryption && _aesInstance != null)
|
|
{
|
|
sendData = await AesKeyExchange.EncryptDataAsync(data, data.Length, _aesInstance).ConfigureAwait(false);
|
|
}
|
|
|
|
var payload = JsonHelper.ToJson(new
|
|
{
|
|
clientId = ClientId,
|
|
data = Convert.ToBase64String(sendData)
|
|
});
|
|
|
|
var response = await _httpClient.PostAsync("/api/send",
|
|
new StringContent(payload, Encoding.UTF8, "application/json")).ConfigureAwait(false);
|
|
|
|
LastActive = DateTime.UtcNow;
|
|
LastDataSent = DateTime.UtcNow;
|
|
BytesSent += data.Length;
|
|
MessagesSent++;
|
|
return response.IsSuccessStatusCode;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
await DisconnectAsync(DisconnectReason.Error, ex).ConfigureAwait(false);
|
|
return false;
|
|
}
|
|
}
|
|
|
|
public async Task<bool> SendAsync(string message) => await SendAsync(Encoding.UTF8.GetBytes(message)).ConfigureAwait(false);
|
|
|
|
public async Task<bool> BroadcastAsync(byte[] data)
|
|
{
|
|
if (!IsConnected || _httpClient == null || string.IsNullOrEmpty(ClientId) || data == null || data.Length == 0)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
try
|
|
{
|
|
var broadcast_data = data;
|
|
if (_config.UseAesEncryption && _aesInstance != null)
|
|
{
|
|
broadcast_data = await AesKeyExchange.EncryptDataAsync(data, data.Length, _aesInstance).ConfigureAwait(false);
|
|
}
|
|
|
|
var payload = JsonHelper.ToJson(new
|
|
{
|
|
clientId = ClientId,
|
|
data = Convert.ToBase64String(broadcast_data)
|
|
});
|
|
|
|
var response = await _httpClient.PostAsync("/api/broadcast",
|
|
new StringContent(payload, Encoding.UTF8, "application/json")).ConfigureAwait(false);
|
|
|
|
return response.IsSuccessStatusCode;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
HandlingHelpers.SafeInvokeEventHandler(
|
|
OnGeneralError,
|
|
this,
|
|
new ErrorEventArgs
|
|
{
|
|
Exception = ex,
|
|
Message = "Error broadcasting via REST"
|
|
},
|
|
nameof(OnGeneralError));
|
|
return false;
|
|
}
|
|
}
|
|
|
|
public async Task<bool> BroadcastAsync(string message) => await BroadcastAsync(Encoding.UTF8.GetBytes(message)).ConfigureAwait(false);
|
|
|
|
public async Task SendNicknameAsync(string nickname)
|
|
{
|
|
Nickname = nickname;
|
|
if (IsConnected && _httpClient != null && !string.IsNullOrEmpty(ClientId))
|
|
{
|
|
var payload = JsonHelper.ToJson(new { clientId = ClientId, nickname });
|
|
await _httpClient.PostAsync("/api/nickname",
|
|
new StringContent(payload, Encoding.UTF8, "application/json")).ConfigureAwait(false);
|
|
|
|
OnNicknameSend?.Invoke(this, new ConnectionEventArgs
|
|
{
|
|
ClientId = ClientId,
|
|
Nickname = nickname
|
|
});
|
|
}
|
|
}
|
|
|
|
public async Task StartWebhookListenerAsync(int port)
|
|
{
|
|
_webhookPort = port;
|
|
_webhookCts?.Cancel();
|
|
_webhookCts?.Dispose();
|
|
_webhookCts = new CancellationTokenSource();
|
|
|
|
var builder = WebApplication.CreateBuilder(new WebApplicationOptions
|
|
{
|
|
Args = Array.Empty<string>()
|
|
});
|
|
|
|
builder.WebHost.ConfigureKestrel(options =>
|
|
{
|
|
options.Listen(IPAddress.Loopback, port, listenOptions =>
|
|
{
|
|
listenOptions.Protocols = HttpProtocols.Http1AndHttp2;
|
|
});
|
|
});
|
|
|
|
_webhookApp = builder.Build();
|
|
|
|
_webhookApp.MapPost("/webhook", async (HttpContext ctx) =>
|
|
{
|
|
try
|
|
{
|
|
using var reader = new System.IO.StreamReader(ctx.Request.Body);
|
|
var json = await reader.ReadToEndAsync().ConfigureAwait(false);
|
|
var doc = JObject.Parse(json);
|
|
|
|
if (doc.TryGetValue("data", out var dataToken))
|
|
{
|
|
var base64 = (string)dataToken;
|
|
if (!string.IsNullOrEmpty(base64))
|
|
{
|
|
var data = Convert.FromBase64String(base64);
|
|
LastActive = DateTime.UtcNow;
|
|
LastDataReceived = DateTime.UtcNow;
|
|
BytesReceived += data.Length;
|
|
MessagesReceived++;
|
|
|
|
HandlingHelpers.SafeInvokeEventHandler(
|
|
OnDataReceived,
|
|
this,
|
|
new DataReceivedEventArgs
|
|
{
|
|
ClientId = ClientId ?? "self",
|
|
Data = data,
|
|
RemoteEndPoint = new IPEndPoint(IPAddress.Parse(_config.Host), _config.Port),
|
|
Nickname = Nickname
|
|
},
|
|
nameof(OnDataReceived));
|
|
}
|
|
}
|
|
}
|
|
catch
|
|
{
|
|
|
|
}
|
|
|
|
return Results.Ok();
|
|
});
|
|
|
|
_webhookTask = _webhookApp.RunAsync();
|
|
}
|
|
|
|
public async Task RegisterWebhookAsync(string webhookServer = "https://127.0.0.1")
|
|
{
|
|
if (!IsConnected || _httpClient == null || string.IsNullOrEmpty(ClientId))
|
|
{
|
|
return;
|
|
}
|
|
|
|
var webhookUrl = $"{webhookServer}:{_webhookPort}/webhook";
|
|
var payload = JsonHelper.ToJson(new { clientId = ClientId, url = webhookUrl });
|
|
await _httpClient.PostAsync("/api/webhooks/register",
|
|
new StringContent(payload, Encoding.UTF8, "application/json")).ConfigureAwait(false);
|
|
}
|
|
|
|
public async Task UnregisterWebhookAsync()
|
|
{
|
|
if (!IsConnected || _httpClient == null || string.IsNullOrEmpty(ClientId))
|
|
{
|
|
return;
|
|
}
|
|
|
|
var payload = JsonHelper.ToJson(new { clientId = ClientId });
|
|
await _httpClient.PostAsync("/api/webhooks/unregister",
|
|
new StringContent(payload, Encoding.UTF8, "application/json")).ConfigureAwait(false);
|
|
}
|
|
|
|
public async Task StopWebhookListenerAsync()
|
|
{
|
|
await UnregisterWebhookAsync().ConfigureAwait(false);
|
|
|
|
_webhookCts?.Cancel();
|
|
|
|
try
|
|
{
|
|
if (_webhookApp != null)
|
|
{
|
|
await _webhookApp.StopAsync().ConfigureAwait(false);
|
|
await _webhookApp.DisposeAsync().ConfigureAwait(false);
|
|
}
|
|
}
|
|
catch
|
|
{
|
|
|
|
}
|
|
|
|
_webhookApp = null;
|
|
}
|
|
|
|
public async Task DisconnectAsync(DisconnectReason reason = DisconnectReason.ClientRequested, Exception? exception = null)
|
|
{
|
|
if (!IsConnected && _httpClient == null)
|
|
{
|
|
return;
|
|
}
|
|
|
|
IsConnected = false;
|
|
DisconnectionTime = DateTime.UtcNow;
|
|
_reason = reason;
|
|
|
|
_clientCts?.Cancel();
|
|
|
|
_aesInstance?.Dispose();
|
|
_aesInstance = null;
|
|
|
|
try
|
|
{
|
|
if (_httpClient != null && !string.IsNullOrEmpty(ClientId))
|
|
{
|
|
var payload = JsonHelper.ToJson(new { clientId = ClientId });
|
|
await _httpClient.PostAsync("/api/disconnect",
|
|
new StringContent(payload, Encoding.UTF8, "application/json")).ConfigureAwait(false);
|
|
}
|
|
}
|
|
catch
|
|
{
|
|
|
|
}
|
|
|
|
try
|
|
{
|
|
_httpClient?.Dispose();
|
|
_httpClient = null;
|
|
}
|
|
catch
|
|
{
|
|
|
|
}
|
|
|
|
var determinedReason = ConnectionEventArgs.Determine(reason, exception);
|
|
var initiator = DisconnectionDiagnostics.DetermineInitiator(determinedReason, exception);
|
|
var reasonDetails = DisconnectionDiagnostics.GetDetailedReasonDescription(determinedReason, exception);
|
|
|
|
var diagnosticContext = new Dictionary<string, string>();
|
|
if (exception is System.Net.Sockets.SocketException socketEx)
|
|
{
|
|
var socketContext = DisconnectionDiagnostics.AnalyzeSocketException(socketEx);
|
|
foreach (var kvp in socketContext)
|
|
{
|
|
diagnosticContext[$"Socket_{kvp.Key}"] = kvp.Value;
|
|
}
|
|
}
|
|
|
|
diagnosticContext["IsLocalInitiated"] = initiator == "Local" ? "true" : "false";
|
|
|
|
var remoteEndPoint = new IPEndPoint(IPAddress.Parse(_config.Host), _config.Port);
|
|
var connectionEventArgs = new ConnectionEventArgs
|
|
{
|
|
ClientId = ClientId ?? "self",
|
|
Reason = determinedReason,
|
|
Exception = exception,
|
|
RemoteEndPoint = remoteEndPoint,
|
|
Initiator = initiator,
|
|
ReasonDetails = reasonDetails,
|
|
DiagnosticContext = diagnosticContext
|
|
};
|
|
|
|
try
|
|
{
|
|
var clientLogger = ConnectionLogManager.GetClientLogger();
|
|
var localEndPoint = IsWebhookListenerActive ? $"127.0.0.1:{_webhookPort}" : "[Client-Local]";
|
|
clientLogger.LogDisconnection(
|
|
ClientId ?? "self",
|
|
"[REST Client]",
|
|
remoteEndPoint.ToString(),
|
|
localEndPoint,
|
|
determinedReason.ToString(),
|
|
initiator,
|
|
exception,
|
|
diagnosticContext
|
|
);
|
|
}
|
|
catch (Exception logEx)
|
|
{
|
|
|
|
System.Diagnostics.Debug.WriteLine($"Failed to log disconnection: {logEx.Message}");
|
|
}
|
|
|
|
HandlingHelpers.SafeInvokeEventHandler(
|
|
OnDisconnected,
|
|
this,
|
|
connectionEventArgs,
|
|
nameof(OnDisconnected));
|
|
}
|
|
|
|
private async Task PingLoopAsync(CancellationToken token)
|
|
{
|
|
var interval = TimeSpan.FromSeconds(_config.HeartbeatIntervalSeconds);
|
|
|
|
while (!token.IsCancellationRequested && IsConnected)
|
|
{
|
|
try
|
|
{
|
|
await Task.Delay(interval, token).ConfigureAwait(false);
|
|
|
|
if (_httpClient == null || string.IsNullOrEmpty(ClientId))
|
|
{
|
|
break;
|
|
}
|
|
|
|
var response = await _httpClient.GetAsync($"/api/ping/{ClientId}", token).ConfigureAwait(false);
|
|
LastPingSent = DateTime.UtcNow;
|
|
|
|
if (response.IsSuccessStatusCode)
|
|
{
|
|
LastPongReceived = DateTime.UtcNow;
|
|
LastActive = DateTime.UtcNow;
|
|
|
|
if (_config.EnablePingPongLogs)
|
|
{
|
|
OnLog?.Invoke(this, new LogMessage { Type = LogType.Trace, Message = $"[REST PING] Pong received at {DateTime.UtcNow:O}" });
|
|
}
|
|
|
|
OnPongResponse?.Invoke(this, new PingEventArgs
|
|
{
|
|
Id = ClientId,
|
|
Nickname = Nickname,
|
|
ReceivedTime = DateTime.UtcNow,
|
|
RemoteEndPoint = new IPEndPoint(IPAddress.Parse(_config.Host), _config.Port)
|
|
});
|
|
}
|
|
else if (response.StatusCode == HttpStatusCode.NotFound)
|
|
{
|
|
await DisconnectAsync(DisconnectReason.RemoteClosed).ConfigureAwait(false);
|
|
break;
|
|
}
|
|
}
|
|
catch (OperationCanceledException)
|
|
{
|
|
break;
|
|
}
|
|
catch (HttpRequestException)
|
|
{
|
|
await DisconnectAsync(DisconnectReason.RemoteClosed).ConfigureAwait(false);
|
|
break;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
HandlingHelpers.SafeInvokeEventHandler(
|
|
OnGeneralError,
|
|
this,
|
|
new ErrorEventArgs
|
|
{
|
|
Exception = ex,
|
|
Message = "Error in REST ping loop"
|
|
},
|
|
nameof(OnGeneralError));
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
private async Task PongMonitorAsync(CancellationToken token)
|
|
{
|
|
while (!token.IsCancellationRequested && IsConnected)
|
|
{
|
|
try
|
|
{
|
|
await Task.Delay(1000, token).ConfigureAwait(false);
|
|
|
|
var elapsed = (DateTime.UtcNow - LastPongReceived).TotalSeconds;
|
|
|
|
if (LastPongReceived != DateTime.MinValue &&
|
|
elapsed > _config.HeartbeatIntervalSeconds * 5)
|
|
{
|
|
if (_config.DisconectOnMissedPong)
|
|
{
|
|
OnLog?.Invoke(this, new LogMessage { Type = LogType.Trace, Message = $"[REST PONG] No pong for {elapsed:F0}s, disconnecting" });
|
|
await DisconnectAsync(DisconnectReason.NoPongReceived).ConfigureAwait(false);
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
catch (OperationCanceledException)
|
|
{
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
private async Task InitAesEncryptionAsync()
|
|
{
|
|
var salt = new byte[32];
|
|
var iv = new byte[16];
|
|
using (var rng = RandomNumberGenerator.Create())
|
|
{
|
|
rng.GetBytes(salt);
|
|
rng.GetBytes(iv);
|
|
}
|
|
|
|
var payload = JsonHelper.ToJson(new
|
|
{
|
|
salt = Convert.ToBase64String(salt),
|
|
iv = Convert.ToBase64String(iv)
|
|
});
|
|
|
|
var response = await _httpClient!.PostAsync($"/api/aes/init/{ClientId}",
|
|
new StringContent(payload, Encoding.UTF8, "application/json")).ConfigureAwait(false);
|
|
|
|
if (!response.IsSuccessStatusCode)
|
|
{
|
|
throw new InvalidOperationException("Failed to initialize AES encryption with server");
|
|
}
|
|
|
|
using var pbkdf2 = new Rfc2898DeriveBytes(_config.AesPassword, salt, 800_000, HashAlgorithmName.SHA256);
|
|
var key = pbkdf2.GetBytes(32);
|
|
|
|
_aesInstance?.Dispose();
|
|
_aesInstance = Aes.Create();
|
|
_aesInstance.KeySize = 256;
|
|
_aesInstance.Mode = CipherMode.CBC;
|
|
_aesInstance.Padding = PaddingMode.PKCS7;
|
|
_aesInstance.Key = key;
|
|
_aesInstance.IV = iv;
|
|
}
|
|
|
|
private async Task AutoReconnectAsync(CancellationToken token)
|
|
{
|
|
while (!token.IsCancellationRequested && !_stopAutoReconnecting)
|
|
{
|
|
try
|
|
{
|
|
await Task.Delay(TimeSpan.FromSeconds(_config.ReconnectDelayInSeconds), token).ConfigureAwait(false);
|
|
|
|
if (!IsConnected && _wasConnected)
|
|
{
|
|
OnLog?.Invoke(this, new LogMessage { Type = LogType.Trace, Message = "REST auto-reconnect: attempting reconnection..." });
|
|
await ConnectAsync().ConfigureAwait(false);
|
|
}
|
|
}
|
|
catch (OperationCanceledException)
|
|
{
|
|
break;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
OnLog?.Invoke(this, new LogMessage { Type = LogType.Error, Message = $"REST auto-reconnect error: {ex.Message}" });
|
|
}
|
|
}
|
|
}
|
|
|
|
public void StopAutoReconnect()
|
|
{
|
|
_stopAutoReconnecting = true;
|
|
_autoReconnectSource?.Cancel();
|
|
}
|
|
|
|
public void Dispose()
|
|
{
|
|
if (_disposed)
|
|
{
|
|
return;
|
|
}
|
|
|
|
_disposed = true;
|
|
|
|
_clientCts?.Cancel();
|
|
_clientCts?.Dispose();
|
|
_autoReconnectSource?.Cancel();
|
|
_autoReconnectSource?.Dispose();
|
|
_webhookCts?.Cancel();
|
|
_webhookCts?.Dispose();
|
|
|
|
try
|
|
{
|
|
_httpClient?.Dispose();
|
|
}
|
|
catch
|
|
{
|
|
|
|
}
|
|
|
|
try
|
|
{
|
|
_webhookApp?.DisposeAsync().AsTask().GetAwaiter().GetResult();
|
|
}
|
|
catch
|
|
{
|
|
|
|
}
|
|
|
|
_aesInstance?.Dispose();
|
|
_aesInstance = null;
|
|
_connectLock.Dispose();
|
|
Webhooks.Dispose();
|
|
}
|
|
|
|
public async ValueTask DisposeAsync()
|
|
{
|
|
if (_disposed)
|
|
{
|
|
return;
|
|
}
|
|
|
|
_disposed = true;
|
|
|
|
_clientCts?.Cancel();
|
|
_clientCts?.Dispose();
|
|
_autoReconnectSource?.Cancel();
|
|
_autoReconnectSource?.Dispose();
|
|
_webhookCts?.Cancel();
|
|
_webhookCts?.Dispose();
|
|
|
|
try
|
|
{
|
|
_httpClient?.Dispose();
|
|
}
|
|
catch
|
|
{
|
|
|
|
}
|
|
|
|
try
|
|
{
|
|
if (_webhookApp != null)
|
|
{
|
|
await _webhookApp.DisposeAsync().ConfigureAwait(false);
|
|
}
|
|
}
|
|
catch
|
|
{
|
|
|
|
}
|
|
|
|
_aesInstance?.Dispose();
|
|
_aesInstance = null;
|
|
|
|
_connectLock.Dispose();
|
|
Webhooks.Dispose();
|
|
}
|
|
}
|
|
}
|