63 lines
1.7 KiB
C#
63 lines
1.7 KiB
C#
using System;
|
|
using System.Threading.Tasks;
|
|
using Flawless.Client.Remote;
|
|
using Refit;
|
|
|
|
namespace Flawless.Client;
|
|
|
|
public static class ApiHelper
|
|
{
|
|
private static IFlawlessServer? _gateway;
|
|
|
|
public static void ClearGateway()
|
|
{
|
|
Status = null;
|
|
ServerUrl = null;
|
|
_gateway = null;
|
|
Token = null;
|
|
}
|
|
|
|
public static async Task SetGatewayAsync(string host)
|
|
{
|
|
var setting = new RefitSettings
|
|
{
|
|
AuthorizationHeaderValueGetter = (req, ct) => ApiHelper.Token != null ?
|
|
Task.FromResult<string>($"Bearer {ApiHelper.Token}") : Task.FromResult(string.Empty)
|
|
};
|
|
|
|
var tempGateway = RestService.For<IFlawlessServer>(host, setting);
|
|
Status = await tempGateway.Status();
|
|
ServerUrl = host;
|
|
_gateway = tempGateway;
|
|
}
|
|
|
|
public static string? ServerUrl { get; private set; }
|
|
|
|
public static ServerStatusResponse? Status { get; private set; }
|
|
|
|
public static TokenInfo? Token { get; set; }
|
|
|
|
public static bool IsGatewayReady => _gateway != null;
|
|
public static IFlawlessServer Gateway => _gateway ?? throw new InvalidProgramException("Not set gateway yet!");
|
|
|
|
|
|
public static bool RequireRefreshToken()
|
|
{
|
|
if (Token == null) return true;
|
|
if (DateTime.UtcNow.AddMinutes(1) > Token.Expiration) return true;
|
|
return false;
|
|
}
|
|
|
|
public static async ValueTask<bool> TryRefreshTokenAsync()
|
|
{
|
|
if (Token == null) return false;
|
|
try { Token = await Gateway.Refresh(Token); }
|
|
catch (Exception e)
|
|
{
|
|
await Console.Error.WriteLineAsync(e.ToString());
|
|
return false;
|
|
}
|
|
|
|
return true;
|
|
}
|
|
} |