2025-09-22 00:29:51 -05:00
|
|
|
using System;
|
2025-08-28 19:57:23 -05:00
|
|
|
using System.Threading.Tasks;
|
2025-10-28 22:21:16 -05:00
|
|
|
using LANCommander.SDK.Abstractions;
|
2025-08-28 19:57:23 -05:00
|
|
|
using LANCommander.SDK.Extensions;
|
|
|
|
|
using LANCommander.SDK.Rpc.Client;
|
|
|
|
|
using LANCommander.SDK.Rpc.Server;
|
2025-10-25 22:00:50 -05:00
|
|
|
using LANCommander.SDK.Services;
|
2025-08-28 19:57:23 -05:00
|
|
|
using Microsoft.AspNetCore.SignalR.Client;
|
2025-12-11 12:09:58 +11:00
|
|
|
using Microsoft.Extensions.Logging;
|
2025-08-28 19:57:23 -05:00
|
|
|
|
2025-10-25 22:00:50 -05:00
|
|
|
namespace LANCommander.SDK.Rpc.Clients;
|
2025-08-28 19:57:23 -05:00
|
|
|
|
2025-12-11 12:09:58 +11:00
|
|
|
internal partial class RpcSubscriber(ITokenProvider tokenProvider, ILogger<RpcSubscriber> logger) : IRpcSubscriber
|
2025-08-28 19:57:23 -05:00
|
|
|
{
|
|
|
|
|
private HubConnection _connection = default!;
|
|
|
|
|
|
2025-10-05 17:52:37 -05:00
|
|
|
public async Task<bool> ConnectAsync(Uri serverAddress)
|
2025-08-28 19:57:23 -05:00
|
|
|
{
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
_connection = new HubConnectionBuilder()
|
2025-10-28 22:21:16 -05:00
|
|
|
.WithUrl(serverAddress.Join("rpc"), options =>
|
|
|
|
|
{
|
2025-11-19 00:36:03 -06:00
|
|
|
options.AccessTokenProvider = () => Task.FromResult(tokenProvider.GetToken().AccessToken);
|
2025-10-28 22:21:16 -05:00
|
|
|
})
|
2025-08-28 19:57:23 -05:00
|
|
|
.Build();
|
|
|
|
|
|
2025-10-25 22:00:50 -05:00
|
|
|
RpcClient.Hub = _connection.ServerProxy<IRpcHub>();
|
2025-08-28 19:57:23 -05:00
|
|
|
|
2025-10-25 22:00:50 -05:00
|
|
|
_ = _connection.ClientRegistration<IRpcSubscriber>(this);
|
2025-08-28 19:57:23 -05:00
|
|
|
|
|
|
|
|
await _connection.StartAsync();
|
2025-09-22 00:29:51 -05:00
|
|
|
|
|
|
|
|
return true;
|
|
|
|
|
}
|
2025-12-11 12:09:58 +11:00
|
|
|
catch(Exception ex)
|
2025-09-22 00:29:51 -05:00
|
|
|
{
|
2025-12-11 12:09:58 +11:00
|
|
|
logger.LogError(ex, "Failed to connect to RPC server at {ServerAddress}", serverAddress);
|
2025-09-22 00:29:51 -05:00
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public async Task<bool> DisconnectAsync()
|
|
|
|
|
{
|
|
|
|
|
try
|
|
|
|
|
{
|
2026-01-17 17:46:12 +01:00
|
|
|
if (_connection != null)
|
|
|
|
|
{
|
|
|
|
|
await _connection.StopAsync();
|
2026-05-09 19:40:58 -05:00
|
|
|
await _connection.DisposeAsync();
|
2026-01-17 17:46:12 +01:00
|
|
|
}
|
2025-09-22 00:29:51 -05:00
|
|
|
|
|
|
|
|
return true;
|
2025-08-28 19:57:23 -05:00
|
|
|
}
|
2025-12-11 12:09:58 +11:00
|
|
|
catch (Exception ex)
|
2025-08-28 19:57:23 -05:00
|
|
|
{
|
2025-12-11 12:09:58 +11:00
|
|
|
logger.LogError(ex, "Failed to disconnect from RPC server");
|
2025-09-22 00:29:51 -05:00
|
|
|
return false;
|
2025-08-28 19:57:23 -05:00
|
|
|
}
|
2025-09-22 00:29:51 -05:00
|
|
|
}
|
2025-08-28 19:57:23 -05:00
|
|
|
}
|