2021-02-24 20:59:43 +01:00

84 lines
2.6 KiB
C#

using Borepin.Model;
using Borepin.Service.Credentials;
using System.Threading.Tasks;
using Capnp.Rpc;
using System.Collections.Generic;
using System.Threading;
using System;
namespace Borepin.Service.BFFH
{
public class BFFHService : IBFFHService
{
private readonly ICredentialService _CredentialService;
private FabAccessAPI.Connection _Connection;
public BFFHService(ICredentialService credentialService)
{
_CredentialService = credentialService;
}
public Model.Connection ActiveConnection { get; private set; }
public bool IsAuthenticated { get; private set; }
public async Task Connect(Model.Connection connection)
{
if (_Connection != null || ActiveConnection != null)
{
throw new System.Exception("Still connected");
}
TcpRpcClient rpcClient = new TcpRpcClient();
rpcClient.Connect(connection.Address.Host, connection.Address.Port);
// IMPORTANT: without ConfigureAwait(false) every Call for CapnProto Runtime deadlocks on Android
await rpcClient.WhenConnected.ConfigureAwait(false);
FabAccessAPI.Connection connection_test = new FabAccessAPI.Connection(rpcClient);
_Connection = connection_test;
ActiveConnection = connection;
}
public void Disconnect()
{
_Connection.RpcClient?.Dispose();
_Connection = null;
ActiveConnection = null;
}
public bool CanAuthenticate()
{
return ActiveConnection.AuthenticationTyp == AuthenticationTyp.PLAIN && ActiveConnection.Username != string.Empty;
}
public async Task<bool> Authenticate()
{
string password = await _CredentialService.GetPasswordAsync(ActiveConnection);
await _Connection.Auth("PLAIN", new Dictionary<string, object> { { "Username", ActiveConnection.Username }, { "Password", password } });
return await Task.FromResult(true);
}
public async Task<bool> Authenticate(Model.Connection connection, string password)
{
await _Connection.Auth("PLAIN", new Dictionary<string, object> { { "Username", ActiveConnection.Username }, { "Password", password } });
await _CredentialService.AddCredentialsAsync(connection, password);
ActiveConnection = connection;
return await Task.FromResult(true);
}
public Task<FabAccessAPI.Machines> GetMachineInterface()
{
return _Connection.AccessMachines();
}
}
}