@using LANCommander.Launcher.Models
@using LANCommander.SDK.Models
@using ListItem = AntDesign.ListItem
@inject NavigationManager NavigationManager
@inject SDK.Client Client
@inject AuthenticationService AuthenticationService
@inject LocalizationService LocalizationService
@LocalizationService.GetString("Connect")
@if (BeaconActive)
{
}
else
{
}
@code {
[Parameter] public EventCallback OnSelected { get; set; }
[Parameter] public bool Connecting { get; set; } = false;
bool IsInitializing = false;
bool BeaconActive = false;
bool OfflineModeAvailable = false;
string ServerAddress = String.Empty;
AuthRequest Model = new();
List DiscoveredServers = new();
private CancellationTokenSource DiscoveryToken = new CancellationTokenSource();
Models.Settings Settings = SettingService.GetSettings();
protected override async Task OnInitializedAsync()
{
IsInitializing = true;
if (Client.IsConfigured())
{
ServerAddress = Client.GetServerAddress() ?? string.Empty;
}
Connecting = true;
OfflineModeAvailable = await AuthenticationService.OfflineModeAvailableAsync();
Client.Beacon.OnBeaconResponse += OnBeaconResponse;
if (!OfflineModeAvailable)
{
ActivateBeacon();
}
Connecting = false;
IsInitializing = false;
}
private void OnBeaconResponse(object sender, BeaconResponseArgs e)
{
var discoveredServer = new DiscoveredServer(e.Message, e.EndPoint);
if (DiscoveredServers.All(s => s.Address != discoveredServer.Address))
DiscoveredServers.Add(discoveredServer);
}
async Task SelectServer(string serverAddress)
{
await Client.Beacon.StopProbeAsync();
BeaconActive = false;
if (OnSelected.HasDelegate)
await OnSelected.InvokeAsync(serverAddress);
}
void OfflineMode()
{
AuthenticationService.LoginOffline();
NavigationManager.NavigateTo("/", forceLoad: true);
}
void CancelBeacon()
{
DiscoveryToken?.Cancel();
}
async Task ActivateBeacon()
{
try
{
BeaconActive = true;
await InvokeAsync(StateHasChanged);
// give the UI a chance to render:
await Task.Yield();
if ((DiscoveryToken?.TryReset() ?? false) == false)
{
DiscoveryToken = new();
}
await Client.Beacon.StartProbeAsync(cancellationToken: DiscoveryToken.Token);
await Task.Delay(10000, DiscoveryToken.Token);
await Client.Beacon.StopProbeAsync();
}
catch (OperationCanceledException)
{
// ignore, handled in finally
}
finally
{
Client.Beacon.CleanupProbe();
BeaconActive = false;
await InvokeAsync(StateHasChanged);
}
}
public void Dispose()
{
DiscoveryToken?.Cancel();
DiscoveryToken?.Dispose();
}
}