All the code

This commit is contained in:
2020-12-13 14:31:23 -06:00
parent 9c3d67a07e
commit 1bbab8fe8f
49 changed files with 1878 additions and 0 deletions

View File

@@ -0,0 +1,127 @@
using Gameboard.Shogi.Api.ServiceModels.Messages;
using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Websockets.Repositories.Utility;
namespace Websockets.Repositories
{
public interface IGameboardRepository
{
Task DeleteGame(string gameName);
Task<GetGameResponse> GetGame(string gameName);
Task<GetGamesResponse> GetGames();
Task<GetGamesResponse> GetGames(string playerName);
Task<GetMovesResponse> GetMoves(string gameName);
Task<PostGameResponse> PostGame(PostGame request);
Task<PostJoinByCodeResponse> PostJoinByCode(PostJoinByCode request);
Task<PostJoinGameResponse> PostJoinGame(string gameName, PostJoinGame request);
Task PostMove(string gameName, PostMove request);
Task<PostJoinCodeResponse> PostJoinCode(string gameName, string userName);
Task<GetPlayerResponse> GetPlayer(string userName);
Task<HttpResponseMessage> PostPlayer(PostPlayer request);
}
public class GameboardRepository : IGameboardRepository
{
private readonly IAuthenticatedHttpClient client;
public GameboardRepository(IAuthenticatedHttpClient client)
{
this.client = client;
}
public async Task<GetGamesResponse> GetGames()
{
var response = await client.GetAsync("Games");
var json = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<GetGamesResponse>(json);
}
public async Task<GetGamesResponse> GetGames(string playerName)
{
var uri = $"Games/{playerName}";
var response = await client.GetAsync(Uri.EscapeUriString(uri));
var json = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<GetGamesResponse>(json);
}
public async Task<GetGameResponse> GetGame(string gameName)
{
var uri = $"Game/{gameName}";
var response = await client.GetAsync(Uri.EscapeUriString(uri));
var json = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<GetGameResponse>(json);
}
public async Task DeleteGame(string gameName)
{
var uri = $"Game/{gameName}";
await client.DeleteAsync(Uri.EscapeUriString(uri));
}
public async Task<PostGameResponse> PostGame(PostGame request)
{
var content = new StringContent(JsonConvert.SerializeObject(request), Encoding.UTF8, "application/json");
var response = await client.PostAsync("Game", content);
var json = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<PostGameResponse>(json);
}
public async Task<PostJoinGameResponse> PostJoinGame(string gameName, PostJoinGame request)
{
var uri = $"Game/{gameName}/Join";
var content = new StringContent(JsonConvert.SerializeObject(request), Encoding.UTF8, "application/json");
var response = await client.PostAsync(Uri.EscapeUriString(uri), content);
var json = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<PostJoinGameResponse>(json);
}
public async Task<PostJoinByCodeResponse> PostJoinByCode(PostJoinByCode request)
{
var content = new StringContent(JsonConvert.SerializeObject(request), Encoding.UTF8, "application/json");
var response = await client.PostAsync("Game/Join", content);
var json = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<PostJoinByCodeResponse>(json);
}
public async Task<GetMovesResponse> GetMoves(string gameName)
{
var uri = $"Game/{gameName}/Moves";
var response = await client.GetAsync(Uri.EscapeUriString(uri));
var json = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<GetMovesResponse>(json);
}
public async Task PostMove(string gameName, PostMove request)
{
var uri = $"Game/{gameName}/Move";
var content = new StringContent(JsonConvert.SerializeObject(request), Encoding.UTF8, "application/json");
await client.PostAsync(Uri.EscapeUriString(uri), content);
}
public async Task<PostJoinCodeResponse> PostJoinCode(string gameName, string userName)
{
var uri = $"JoinCode/{gameName}";
var serialized = JsonConvert.SerializeObject(new PostJoinCode { PlayerName = userName });
var content = new StringContent(serialized, Encoding.UTF8, "application/json");
var json = await (await client.PostAsync(Uri.EscapeUriString(uri), content)).Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<PostJoinCodeResponse>(json);
}
public async Task<GetPlayerResponse> GetPlayer(string playerName)
{
var uri = $"Player/{playerName}";
var response = await client.GetAsync(Uri.EscapeUriString(uri));
var json = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<GetPlayerResponse>(json);
}
public async Task<HttpResponseMessage> PostPlayer(PostPlayer request)
{
var content = new StringContent(JsonConvert.SerializeObject(request), Encoding.UTF8, "application/json");
return await client.PostAsync("Player", content);
}
}
}

View File

@@ -0,0 +1,32 @@
using Gameboard.Shogi.Api.ServiceModels.Messages;
using Newtonsoft.Json;
using System;
using System.Threading.Tasks;
using Websockets.Repositories.Utility;
namespace Websockets.Repositories
{
[Obsolete("Use GameboardRepository. Functions from PlayerRepository will be moved.")]
public class PlayerRepository
{
private readonly IAuthenticatedHttpClient client;
public PlayerRepository(IAuthenticatedHttpClient client)
{
this.client = client;
}
public async Task<GetPlayerResponse> GetPlayer(string playerName)
{
var response = await client.GetAsync($"/Player/{playerName}");
var json = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<GetPlayerResponse>(json);
}
public async Task DeletePlayer(string playerName)
{
var response = await client.DeleteAsync($"/Player/{playerName}");
await response.Content.ReadAsStringAsync();
}
}
}

View File

@@ -0,0 +1,43 @@
using Gameboard.Shogi.Api.ServiceModels.Messages;
using System;
using System.Threading.Tasks;
using Websockets.Repositories;
namespace AspShogiSockets.Repositories.RepositoryManagers
{
public interface IGameboardRepositoryManager
{
Task<string> CreateGuestUser();
}
public class GameboardRepositoryManager : IGameboardRepositoryManager
{
private readonly IGameboardRepository repository;
private const int MaxTries = 3;
public GameboardRepositoryManager(IGameboardRepository repository)
{
this.repository = repository;
}
public async Task<string> CreateGuestUser()
{
var count = 0;
while (count < MaxTries)
{
count++;
var clientId = $"Guest-{Guid.NewGuid()}";
var request = new PostPlayer
{
PlayerName = clientId
};
var response = await repository.PostPlayer(request);
if (response.IsSuccessStatusCode)
{
return clientId;
}
}
throw new OperationCanceledException($"Failed to create guest user after {MaxTries} tries.");
}
}
}

View File

@@ -0,0 +1,103 @@
using IdentityModel.Client;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
namespace Websockets.Repositories.Utility
{
public interface IAuthenticatedHttpClient
{
Task<HttpResponseMessage> DeleteAsync(string requestUri);
Task<HttpResponseMessage> GetAsync(string requestUri);
Task<HttpResponseMessage> PostAsync(string requestUri, HttpContent content);
}
public class AuthenticatedHttpClient : HttpClient, IAuthenticatedHttpClient
{
private readonly ILogger<AuthenticatedHttpClient> logger;
private readonly string identityServerUrl;
private TokenResponse tokenResponse;
private readonly string clientId;
private readonly string clientSecret;
public AuthenticatedHttpClient(ILogger<AuthenticatedHttpClient> logger, IConfiguration configuration) : base()
{
this.logger = logger;
identityServerUrl = configuration["AppSettings:IdentityServer"];
clientId = configuration["AppSettings:ClientId"];
clientSecret = configuration["AppSettings:ClientSecret"];
BaseAddress = new Uri(configuration["AppSettings:GameboardShogiApi"]);
}
private async Task RefreshBearerToken()
{
var disco = await this.GetDiscoveryDocumentAsync(identityServerUrl);
if (disco.IsError)
{
logger.LogError("{DiscoveryErrorType}", disco.ErrorType);
throw new Exception(disco.Error);
}
var request = new ClientCredentialsTokenRequest
{
Address = disco.TokenEndpoint,
ClientId = clientId,
ClientSecret = clientSecret
};
var response = await this.RequestClientCredentialsTokenAsync(request);
if (response.IsError)
{
throw new Exception(response.Error);
}
tokenResponse = response;
logger.LogInformation("Refreshing Bearer Token to {BaseAddress}", BaseAddress);
this.SetBearerToken(tokenResponse.AccessToken);
}
public async new Task<HttpResponseMessage> GetAsync(string requestUri)
{
var response = await base.GetAsync(requestUri);
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
await RefreshBearerToken();
response = await base.GetAsync(requestUri);
}
logger.LogInformation(
"Repository GET to {BaseUrl}{RequestUrl} \nResponse: {Response}\n",
BaseAddress,
requestUri,
await response.Content.ReadAsStringAsync());
return response;
}
public async new Task<HttpResponseMessage> PostAsync(string requestUri, HttpContent content)
{
var response = await base.PostAsync(requestUri, content);
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
await RefreshBearerToken();
response = await base.PostAsync(requestUri, content);
}
logger.LogInformation(
"Repository POST to {BaseUrl}{RequestUrl} \nRequest: {Request}\nResponse: {Response}\n",
BaseAddress,
requestUri,
await content.ReadAsStringAsync(),
await response.Content.ReadAsStringAsync());
return response;
}
public async new Task<HttpResponseMessage> DeleteAsync(string requestUri)
{
var response = await base.DeleteAsync(requestUri);
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
await RefreshBearerToken();
response = await base.DeleteAsync(requestUri);
}
logger.LogInformation("Repository DELETE to {BaseUrl}{RequestUrl}", BaseAddress, requestUri);
return response;
}
}
}