81 lines
2.5 KiB
C#
81 lines
2.5 KiB
C#
using Shogi.Contracts.Api;
|
|
using Shogi.Contracts.Types;
|
|
using Shogi.UI.Pages.Home.Account;
|
|
using System.Net;
|
|
using System.Net.Http.Json;
|
|
using System.Text.Json;
|
|
|
|
namespace Shogi.UI.Pages.Home.Api
|
|
{
|
|
public class ShogiApi : IShogiApi
|
|
{
|
|
public const string GuestClientName = "Guest";
|
|
public const string MsalClientName = "Msal";
|
|
public const string AnonymouseClientName = "Anonymous";
|
|
|
|
private readonly JsonSerializerOptions serializerOptions;
|
|
private readonly IHttpClientFactory clientFactory;
|
|
private readonly AccountState accountState;
|
|
|
|
public ShogiApi(IHttpClientFactory clientFactory, AccountState accountState)
|
|
{
|
|
serializerOptions = new JsonSerializerOptions(JsonSerializerDefaults.Web);
|
|
this.clientFactory = clientFactory;
|
|
this.accountState = accountState;
|
|
}
|
|
|
|
private HttpClient HttpClient => accountState.User?.WhichAccountPlatform switch
|
|
{
|
|
WhichAccountPlatform.Guest => clientFactory.CreateClient(GuestClientName),
|
|
WhichAccountPlatform.Microsoft => clientFactory.CreateClient(MsalClientName),
|
|
_ => clientFactory.CreateClient(AnonymouseClientName)
|
|
};
|
|
|
|
public async Task GuestLogout()
|
|
{
|
|
var response = await HttpClient.PutAsync(new Uri("User/GuestLogout", UriKind.Relative), null);
|
|
response.EnsureSuccessStatusCode();
|
|
}
|
|
|
|
public async Task<Session?> GetSession(string name)
|
|
{
|
|
var response = await HttpClient.GetAsync(new Uri($"Sessions/{name}", UriKind.Relative));
|
|
if (response.IsSuccessStatusCode)
|
|
{
|
|
return (await response.Content.ReadFromJsonAsync<ReadSessionResponse>(serializerOptions))?.Session;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
public async Task<ReadSessionsPlayerCountResponse?> GetSessionsPlayerCount()
|
|
{
|
|
var response = await HttpClient.GetAsync(new Uri("Sessions/PlayerCount", UriKind.Relative));
|
|
if (response.IsSuccessStatusCode)
|
|
{
|
|
return await response.Content.ReadFromJsonAsync<ReadSessionsPlayerCountResponse>(serializerOptions);
|
|
}
|
|
return null;
|
|
}
|
|
|
|
public async Task<CreateTokenResponse?> GetToken()
|
|
{
|
|
var response = await HttpClient.GetFromJsonAsync<CreateTokenResponse>(new Uri("User/Token", UriKind.Relative), serializerOptions);
|
|
return response;
|
|
}
|
|
|
|
public async Task PostMove(string sessionName, MovePieceCommand command)
|
|
{
|
|
await this.HttpClient.PostAsJsonAsync($"Sessions{sessionName}/Move", command);
|
|
}
|
|
|
|
public async Task<HttpStatusCode> PostSession(string name, bool isPrivate)
|
|
{
|
|
var response = await HttpClient.PostAsJsonAsync(new Uri("Sessions", UriKind.Relative), new CreateSessionCommand
|
|
{
|
|
Name = name,
|
|
});
|
|
return response.StatusCode;
|
|
}
|
|
}
|
|
}
|