before deleting Rules
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
using Gameboard.ShogiUI.Sockets.Repositories;
|
||||
using Gameboard.ShogiUI.Sockets.Managers;
|
||||
using Gameboard.ShogiUI.Sockets.Repositories;
|
||||
using Gameboard.ShogiUI.Sockets.Repositories.RepositoryManagers;
|
||||
using Gameboard.ShogiUI.Sockets.ServiceModels.Api.Messages;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
@@ -14,17 +15,20 @@ namespace Gameboard.ShogiUI.Sockets.Controllers
|
||||
public class GameController : ControllerBase
|
||||
{
|
||||
private readonly IGameboardRepositoryManager manager;
|
||||
private readonly ISocketCommunicationManager communicationManager;
|
||||
private readonly IGameboardRepository repository;
|
||||
|
||||
public GameController(
|
||||
IGameboardRepository repository,
|
||||
IGameboardRepositoryManager manager)
|
||||
IGameboardRepositoryManager manager,
|
||||
ISocketCommunicationManager communicationManager)
|
||||
{
|
||||
this.manager = manager;
|
||||
this.communicationManager = communicationManager;
|
||||
this.repository = repository;
|
||||
}
|
||||
|
||||
[Route("JoinCode")]
|
||||
[HttpPost("JoinCode")]
|
||||
public async Task<IActionResult> PostGameInvitation([FromBody] PostGameInvitation request)
|
||||
{
|
||||
var userName = HttpContext.User.Claims.First(c => c.Type == "preferred_username").Value;
|
||||
@@ -41,7 +45,7 @@ namespace Gameboard.ShogiUI.Sockets.Controllers
|
||||
}
|
||||
|
||||
[AllowAnonymous]
|
||||
[Route("GuestJoinCode")]
|
||||
[HttpPost("GuestJoinCode")]
|
||||
public async Task<IActionResult> PostGuestGameInvitation([FromBody] PostGuestGameInvitation request)
|
||||
{
|
||||
|
||||
@@ -57,5 +61,26 @@ namespace Gameboard.ShogiUI.Sockets.Controllers
|
||||
return new UnauthorizedResult();
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Use JWT tokens for guests so they can authenticate and use API routes, too.
|
||||
//[Route("")]
|
||||
//public async Task<IActionResult> PostSession([FromBody] PostSession request)
|
||||
//{
|
||||
// var model = new Models.Session(request.Name, request.IsPrivate, request.Player1, request.Player2);
|
||||
// var success = await repository.CreateSession(model);
|
||||
// if (success)
|
||||
// {
|
||||
// var message = new ServiceModels.Socket.Messages.CreateGameResponse(ServiceModels.Socket.Types.ClientAction.CreateGame)
|
||||
// {
|
||||
// Game = model.ToServiceModel(),
|
||||
// PlayerName =
|
||||
// }
|
||||
// var task = request.IsPrivate
|
||||
// ? communicationManager.BroadcastToPlayers(response, userName)
|
||||
// : communicationManager.BroadcastToAll(response);
|
||||
// return new CreatedResult("", null);
|
||||
// }
|
||||
// return new ConflictResult();
|
||||
//}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
using Gameboard.ShogiUI.Sockets.Managers;
|
||||
using Gameboard.ShogiUI.Sockets.Repositories;
|
||||
using Gameboard.ShogiUI.Sockets.Repositories.RepositoryManagers;
|
||||
using Gameboard.ShogiUI.Sockets.ServiceModels.Api.Messages;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
@@ -13,18 +15,24 @@ namespace Gameboard.ShogiUI.Sockets.Controllers
|
||||
[ApiController]
|
||||
public class SocketController : ControllerBase
|
||||
{
|
||||
private readonly ILogger<SocketController> logger;
|
||||
private readonly ISocketTokenManager tokenManager;
|
||||
private readonly IGameboardRepositoryManager gameboardManager;
|
||||
private readonly IGameboardRepository gameboardRepository;
|
||||
|
||||
public SocketController(
|
||||
ISocketTokenManager tokenManager,
|
||||
IGameboardRepositoryManager gameboardManager)
|
||||
ILogger<SocketController> logger,
|
||||
ISocketTokenManager tokenManager,
|
||||
IGameboardRepositoryManager gameboardManager,
|
||||
IGameboardRepository gameboardRepository)
|
||||
{
|
||||
this.logger = logger;
|
||||
this.tokenManager = tokenManager;
|
||||
this.gameboardManager = gameboardManager;
|
||||
this.gameboardRepository = gameboardRepository;
|
||||
}
|
||||
|
||||
[Route("Token")]
|
||||
[HttpGet("Token")]
|
||||
public IActionResult GetToken()
|
||||
{
|
||||
var userName = HttpContext.User.Claims.First(c => c.Type == "preferred_username").Value;
|
||||
@@ -33,7 +41,7 @@ namespace Gameboard.ShogiUI.Sockets.Controllers
|
||||
}
|
||||
|
||||
[AllowAnonymous]
|
||||
[Route("GuestToken")]
|
||||
[HttpGet("GuestToken")]
|
||||
public async Task<IActionResult> GetGuestToken([FromQuery] GetGuestToken request)
|
||||
{
|
||||
if (request.ClientId == null)
|
||||
@@ -44,7 +52,7 @@ namespace Gameboard.ShogiUI.Sockets.Controllers
|
||||
}
|
||||
else
|
||||
{
|
||||
if (await gameboardManager.PlayerExists(request.ClientId))
|
||||
if (await gameboardRepository.IsGuestUser(request.ClientId))
|
||||
{
|
||||
var token = tokenManager.GenerateToken(request.ClientId);
|
||||
return new JsonResult(new GetGuestTokenResponse(request.ClientId, token));
|
||||
|
||||
@@ -4,10 +4,18 @@
|
||||
<TargetFramework>net5.0</TargetFramework>
|
||||
<EnableNETAnalyzers>true</EnableNETAnalyzers>
|
||||
<AnalysisLevel>5</AnalysisLevel>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Gameboard.Shogi.Api.ServiceModels" Version="2.13.0" />
|
||||
<None Remove="Repositories\CouchModels\Readme.md" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Include="Repositories\CouchModels\Readme.md" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="IdentityModel" Version="5.0.0" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.AzureAD.UI" Version="5.0.2" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="5.0.2" />
|
||||
@@ -17,7 +25,8 @@
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Gameboard.ShogiUI.BoardState\Gameboard.ShogiUI.Rules.csproj" />
|
||||
<ProjectReference Include="..\CouchDB\CouchDB.csproj" />
|
||||
<ProjectReference Include="..\Gameboard.ShogiUI.Rules\Gameboard.ShogiUI.Rules.csproj" />
|
||||
<ProjectReference Include="..\Gameboard.ShogiUI.Sockets.ServiceModels\Gameboard.ShogiUI.Sockets.ServiceModels.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ namespace Gameboard.ShogiUI.Sockets.Managers
|
||||
public interface IBoardManager
|
||||
{
|
||||
void Add(string sessionName, ShogiBoard board);
|
||||
ShogiBoard Get(string sessionName);
|
||||
ShogiBoard? Get(string sessionName);
|
||||
}
|
||||
|
||||
public class BoardManager : IBoardManager
|
||||
@@ -20,10 +20,12 @@ namespace Gameboard.ShogiUI.Sockets.Managers
|
||||
|
||||
public void Add(string sessionName, ShogiBoard board) => Boards.TryAdd(sessionName, board);
|
||||
|
||||
public ShogiBoard Get(string sessionName)
|
||||
public ShogiBoard? Get(string sessionName)
|
||||
{
|
||||
if (Boards.TryGetValue(sessionName, out var board))
|
||||
{
|
||||
return board;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,61 +1,55 @@
|
||||
using Gameboard.Shogi.Api.ServiceModels.Messages;
|
||||
using Gameboard.ShogiUI.Sockets.Repositories;
|
||||
using Gameboard.ShogiUI.Sockets.Models;
|
||||
using Gameboard.ShogiUI.Sockets.Repositories.RepositoryManagers;
|
||||
using Gameboard.ShogiUI.Sockets.ServiceModels.Socket.Messages;
|
||||
using Gameboard.ShogiUI.Sockets.ServiceModels.Socket.Types;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Newtonsoft.Json;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Gameboard.ShogiUI.Sockets.Managers.ClientActionHandlers
|
||||
{
|
||||
public interface ICreateGameHandler
|
||||
{
|
||||
Task Handle(CreateGameRequest request, string userName);
|
||||
}
|
||||
|
||||
// TODO: This doesn't need to be a socket action.
|
||||
// It can be an API route and still tell socket connections about the new session.
|
||||
public class CreateGameHandler : IActionHandler
|
||||
public class CreateGameHandler : ICreateGameHandler
|
||||
{
|
||||
private readonly IGameboardRepository repository;
|
||||
private readonly IGameboardRepositoryManager manager;
|
||||
private readonly ISocketCommunicationManager communicationManager;
|
||||
|
||||
public CreateGameHandler(
|
||||
ISocketCommunicationManager communicationManager,
|
||||
IGameboardRepository repository)
|
||||
IGameboardRepositoryManager manager)
|
||||
{
|
||||
this.repository = repository;
|
||||
this.manager = manager;
|
||||
this.communicationManager = communicationManager;
|
||||
}
|
||||
|
||||
public async Task Handle(string json, string userName)
|
||||
public async Task Handle(CreateGameRequest request, string userName)
|
||||
{
|
||||
var request = JsonConvert.DeserializeObject<CreateGameRequest>(json);
|
||||
var sessionName = await repository.PostSession(new PostSession
|
||||
var model = new Session(request.GameName, request.IsPrivate, userName);
|
||||
var success = await manager.CreateSession(model);
|
||||
|
||||
if (!success)
|
||||
{
|
||||
SessionName = request.GameName,
|
||||
PlayerName = userName,
|
||||
IsPrivate = request.IsPrivate
|
||||
});
|
||||
var error = new CreateGameResponse(request.Action)
|
||||
{
|
||||
Error = "Unable to create game with this name."
|
||||
};
|
||||
await communicationManager.BroadcastToPlayers(error, userName);
|
||||
}
|
||||
|
||||
var response = new CreateGameResponse(request.Action)
|
||||
{
|
||||
PlayerName = userName,
|
||||
Game = new Game
|
||||
{
|
||||
GameName = sessionName,
|
||||
Players = new[] { userName }
|
||||
}
|
||||
Game = model.ToServiceModel()
|
||||
};
|
||||
|
||||
if (string.IsNullOrWhiteSpace(sessionName))
|
||||
{
|
||||
response.Error = "Game already exists.";
|
||||
}
|
||||
var task = request.IsPrivate
|
||||
? communicationManager.BroadcastToPlayers(response, userName)
|
||||
: communicationManager.BroadcastToAll(response);
|
||||
|
||||
if (request.IsPrivate)
|
||||
{
|
||||
await communicationManager.BroadcastToPlayers(response, userName);
|
||||
}
|
||||
else
|
||||
{
|
||||
await communicationManager.BroadcastToAll(response);
|
||||
}
|
||||
await task;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
using Gameboard.ShogiUI.Sockets.ServiceModels.Socket.Types;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Gameboard.ShogiUI.Sockets.Managers.ClientActionHandlers
|
||||
{
|
||||
public interface IActionHandler
|
||||
{
|
||||
/// <summary>
|
||||
/// Responsible for parsing json and handling the request.
|
||||
/// </summary>
|
||||
Task Handle(string json, string userName);
|
||||
}
|
||||
|
||||
public delegate IActionHandler ActionHandlerResolver(ClientAction action);
|
||||
}
|
||||
@@ -1,13 +1,14 @@
|
||||
using Gameboard.Shogi.Api.ServiceModels.Messages;
|
||||
using Gameboard.ShogiUI.Sockets.Repositories;
|
||||
using Gameboard.ShogiUI.Sockets.Repositories;
|
||||
using Gameboard.ShogiUI.Sockets.ServiceModels.Socket.Messages;
|
||||
using Gameboard.ShogiUI.Sockets.ServiceModels.Socket.Types;
|
||||
using Newtonsoft.Json;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Gameboard.ShogiUI.Sockets.Managers.ClientActionHandlers
|
||||
{
|
||||
public class JoinByCodeHandler : IActionHandler
|
||||
public interface IJoinByCodeHandler
|
||||
{
|
||||
Task Handle(JoinByCodeRequest request, string userName);
|
||||
}
|
||||
public class JoinByCodeHandler : IJoinByCodeHandler
|
||||
{
|
||||
private readonly IGameboardRepository repository;
|
||||
private readonly ISocketCommunicationManager communicationManager;
|
||||
@@ -20,44 +21,44 @@ namespace Gameboard.ShogiUI.Sockets.Managers.ClientActionHandlers
|
||||
this.communicationManager = communicationManager;
|
||||
}
|
||||
|
||||
public async Task Handle(string json, string userName)
|
||||
public async Task Handle(JoinByCodeRequest request, string userName)
|
||||
{
|
||||
var request = JsonConvert.DeserializeObject<JoinByCode>(json);
|
||||
var sessionName = await repository.PostJoinPrivateSession(new PostJoinPrivateSession
|
||||
{
|
||||
PlayerName = userName,
|
||||
JoinCode = request.JoinCode
|
||||
});
|
||||
//var request = JsonConvert.DeserializeObject<JoinByCode>(json);
|
||||
//var sessionName = await repository.PostJoinPrivateSession(new PostJoinPrivateSession
|
||||
//{
|
||||
// PlayerName = userName,
|
||||
// JoinCode = request.JoinCode
|
||||
//});
|
||||
|
||||
if (sessionName == null)
|
||||
{
|
||||
var response = new JoinGameResponse(ClientAction.JoinByCode)
|
||||
{
|
||||
PlayerName = userName,
|
||||
GameName = sessionName,
|
||||
Error = "Error joining game."
|
||||
};
|
||||
await communicationManager.BroadcastToPlayers(response, userName);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Other members of the game see a regular JoinGame occur.
|
||||
var response = new JoinGameResponse(ClientAction.JoinGame)
|
||||
{
|
||||
PlayerName = userName,
|
||||
GameName = sessionName
|
||||
};
|
||||
// At this time, userName hasn't subscribed and won't receive this message.
|
||||
await communicationManager.BroadcastToGame(sessionName, response);
|
||||
//if (sessionName == null)
|
||||
//{
|
||||
// var response = new JoinGameResponse(ClientAction.JoinByCode)
|
||||
// {
|
||||
// PlayerName = userName,
|
||||
// GameName = sessionName,
|
||||
// Error = "Error joining game."
|
||||
// };
|
||||
// await communicationManager.BroadcastToPlayers(response, userName);
|
||||
//}
|
||||
//else
|
||||
//{
|
||||
// // Other members of the game see a regular JoinGame occur.
|
||||
// var response = new JoinGameResponse(ClientAction.JoinGame)
|
||||
// {
|
||||
// PlayerName = userName,
|
||||
// GameName = sessionName
|
||||
// };
|
||||
// // At this time, userName hasn't subscribed and won't receive this message.
|
||||
// await communicationManager.BroadcastToGame(sessionName, response);
|
||||
|
||||
// The player joining sees the JoinByCode occur.
|
||||
response = new JoinGameResponse(ClientAction.JoinByCode)
|
||||
{
|
||||
PlayerName = userName,
|
||||
GameName = sessionName
|
||||
};
|
||||
await communicationManager.BroadcastToPlayers(response, userName);
|
||||
}
|
||||
// // The player joining sees the JoinByCode occur.
|
||||
// response = new JoinGameResponse(ClientAction.JoinByCode)
|
||||
// {
|
||||
// PlayerName = userName,
|
||||
// GameName = sessionName
|
||||
// };
|
||||
// await communicationManager.BroadcastToPlayers(response, userName);
|
||||
//}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
using Gameboard.Shogi.Api.ServiceModels.Messages;
|
||||
using Gameboard.ShogiUI.Sockets.Repositories;
|
||||
using Gameboard.ShogiUI.Sockets.Repositories;
|
||||
using Gameboard.ShogiUI.Sockets.ServiceModels.Socket.Messages;
|
||||
using Gameboard.ShogiUI.Sockets.ServiceModels.Socket.Types;
|
||||
using Newtonsoft.Json;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Gameboard.ShogiUI.Sockets.Managers.ClientActionHandlers
|
||||
{
|
||||
public class JoinGameHandler : IActionHandler
|
||||
public interface IJoinGameHandler
|
||||
{
|
||||
Task Handle(JoinGameRequest request, string userName);
|
||||
}
|
||||
public class JoinGameHandler : IJoinGameHandler
|
||||
{
|
||||
private readonly IGameboardRepository gameboardRepository;
|
||||
private readonly ISocketCommunicationManager communicationManager;
|
||||
@@ -19,30 +20,30 @@ namespace Gameboard.ShogiUI.Sockets.Managers.ClientActionHandlers
|
||||
this.communicationManager = communicationManager;
|
||||
}
|
||||
|
||||
public async Task Handle(string json, string userName)
|
||||
public async Task Handle(JoinGameRequest request, string userName)
|
||||
{
|
||||
var request = JsonConvert.DeserializeObject<JoinGameRequest>(json);
|
||||
//var request = JsonConvert.DeserializeObject<JoinGameRequest>(json);
|
||||
|
||||
var joinSucceeded = await gameboardRepository.PutJoinPublicSession(new PutJoinPublicSession
|
||||
{
|
||||
PlayerName = userName,
|
||||
SessionName = request.GameName
|
||||
});
|
||||
//var joinSucceeded = await gameboardRepository.PutJoinPublicSession(new PutJoinPublicSession
|
||||
//{
|
||||
// PlayerName = userName,
|
||||
// SessionName = request.GameName
|
||||
//});
|
||||
|
||||
var response = new JoinGameResponse(ClientAction.JoinGame)
|
||||
{
|
||||
PlayerName = userName,
|
||||
GameName = request.GameName
|
||||
};
|
||||
if (joinSucceeded)
|
||||
{
|
||||
await communicationManager.BroadcastToAll(response);
|
||||
}
|
||||
else
|
||||
{
|
||||
response.Error = "Game is full.";
|
||||
await communicationManager.BroadcastToPlayers(response, userName);
|
||||
}
|
||||
//var response = new JoinGameResponse(ClientAction.JoinGame)
|
||||
//{
|
||||
// PlayerName = userName,
|
||||
// GameName = request.GameName
|
||||
//};
|
||||
//if (joinSucceeded)
|
||||
//{
|
||||
// await communicationManager.BroadcastToAll(response);
|
||||
//}
|
||||
//else
|
||||
//{
|
||||
// response.Error = "Game is full.";
|
||||
// await communicationManager.BroadcastToPlayers(response, userName);
|
||||
//}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,16 +1,19 @@
|
||||
using Gameboard.ShogiUI.Sockets.Models;
|
||||
using Gameboard.ShogiUI.Sockets.Repositories;
|
||||
using Gameboard.ShogiUI.Sockets.Repositories;
|
||||
using Gameboard.ShogiUI.Sockets.ServiceModels.Socket.Messages;
|
||||
using Gameboard.ShogiUI.Sockets.ServiceModels.Socket.Types;
|
||||
using Newtonsoft.Json;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Gameboard.ShogiUI.Sockets.Managers.ClientActionHandlers
|
||||
{
|
||||
public interface IListGamesHandler
|
||||
{
|
||||
Task Handle(ListGamesRequest request, string userName);
|
||||
}
|
||||
|
||||
// TODO: This doesn't need to be a socket action.
|
||||
// It can be an HTTP route.
|
||||
public class ListGamesHandler : IActionHandler
|
||||
public class ListGamesHandler : IListGamesHandler
|
||||
{
|
||||
private readonly ISocketCommunicationManager communicationManager;
|
||||
private readonly IGameboardRepository repository;
|
||||
@@ -23,16 +26,10 @@ namespace Gameboard.ShogiUI.Sockets.Managers.ClientActionHandlers
|
||||
this.repository = repository;
|
||||
}
|
||||
|
||||
public async Task Handle(string json, string userName)
|
||||
public async Task Handle(ListGamesRequest _, string userName)
|
||||
{
|
||||
var request = JsonConvert.DeserializeObject<ListGamesRequest>(json);
|
||||
var getGamesResponse = string.IsNullOrWhiteSpace(userName)
|
||||
? await repository.GetGames()
|
||||
: await repository.GetGames(userName);
|
||||
|
||||
var games = getGamesResponse.Sessions
|
||||
.OrderBy(s => s.Player1 == userName || s.Player2 == userName)
|
||||
.Select(s => new Session(s).ToServiceModel()); // yuck
|
||||
var sessions = await repository.ReadSessions();
|
||||
var games = sessions.Select(s => s.ToServiceModel()); // yuck
|
||||
|
||||
var response = new ListGamesResponse(ClientAction.ListGames)
|
||||
{
|
||||
|
||||
@@ -3,16 +3,20 @@ using Gameboard.ShogiUI.Sockets.Repositories;
|
||||
using Gameboard.ShogiUI.Sockets.ServiceModels.Socket.Messages;
|
||||
using Gameboard.ShogiUI.Sockets.ServiceModels.Socket.Types;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Newtonsoft.Json;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Gameboard.ShogiUI.Sockets.Managers.ClientActionHandlers
|
||||
{
|
||||
public interface ILoadGameHandler
|
||||
{
|
||||
Task Handle(LoadGameRequest request, string userName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Subscribes a user to messages for a session and loads that session into the BoardManager for playing.
|
||||
/// </summary>
|
||||
public class LoadGameHandler : IActionHandler
|
||||
public class LoadGameHandler : ILoadGameHandler
|
||||
{
|
||||
private readonly ILogger<LoadGameHandler> logger;
|
||||
private readonly IGameboardRepository gameboardRepository;
|
||||
@@ -31,35 +35,35 @@ namespace Gameboard.ShogiUI.Sockets.Managers.ClientActionHandlers
|
||||
this.boardManager = boardManager;
|
||||
}
|
||||
|
||||
public async Task Handle(string json, string userName)
|
||||
public async Task Handle(LoadGameRequest request, string userName)
|
||||
{
|
||||
var request = JsonConvert.DeserializeObject<LoadGameRequest>(json);
|
||||
var gameTask = gameboardRepository.GetGame(request.GameName);
|
||||
var moveTask = gameboardRepository.GetMoves(request.GameName);
|
||||
var readSession = gameboardRepository.ReadSession(request.GameName);
|
||||
var readStates = gameboardRepository.ReadBoardStates(request.GameName);
|
||||
|
||||
var sessionModel = await gameTask;
|
||||
var sessionModel = await readSession;
|
||||
if (sessionModel == null)
|
||||
{
|
||||
logger.LogWarning("{action} - {user} was unable to load session named {session}.", ClientAction.LoadGame, userName, request.GameName);
|
||||
var response = new LoadGameResponse(ClientAction.LoadGame) { Error = "Game not found." };
|
||||
await communicationManager.BroadcastToPlayers(response, userName);
|
||||
var error = new LoadGameResponse(ClientAction.LoadGame) { Error = "Game not found." };
|
||||
await communicationManager.BroadcastToPlayers(error, userName);
|
||||
return;
|
||||
}
|
||||
else
|
||||
|
||||
communicationManager.SubscribeToGame(sessionModel, userName);
|
||||
var boardStates = await readStates;
|
||||
var moveModels = boardStates
|
||||
.Where(_ => _.Move != null)
|
||||
.Select(_ => _.Move!.ToRulesModel())
|
||||
.ToList();
|
||||
var shogiBoard = new ShogiBoard(moveModels);
|
||||
boardManager.Add(sessionModel.Name, shogiBoard);
|
||||
|
||||
var response = new LoadGameResponse(ClientAction.LoadGame)
|
||||
{
|
||||
var moveModels = await moveTask;
|
||||
|
||||
communicationManager.SubscribeToGame(sessionModel, userName);
|
||||
var boardMoves = moveModels.Select(_ => _.ToBoardModel()).ToList();
|
||||
var shogiBoard = new ShogiBoard(boardMoves);
|
||||
boardManager.Add(sessionModel.Name, shogiBoard);
|
||||
|
||||
var response = new LoadGameResponse(ClientAction.LoadGame)
|
||||
{
|
||||
Game = sessionModel.ToServiceModel(),
|
||||
BoardState = new Models.BoardState(shogiBoard).ToServiceModel()
|
||||
};
|
||||
await communicationManager.BroadcastToPlayers(response, userName);
|
||||
}
|
||||
Game = sessionModel.ToServiceModel(),
|
||||
BoardState = new Models.BoardState(shogiBoard).ToServiceModel()
|
||||
};
|
||||
await communicationManager.BroadcastToPlayers(response, userName);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,14 +1,17 @@
|
||||
using Gameboard.Shogi.Api.ServiceModels.Messages;
|
||||
using Gameboard.ShogiUI.Sockets.Models;
|
||||
using Gameboard.ShogiUI.Sockets.Models;
|
||||
using Gameboard.ShogiUI.Sockets.Repositories;
|
||||
using Gameboard.ShogiUI.Sockets.ServiceModels.Socket.Messages;
|
||||
using Newtonsoft.Json;
|
||||
using System.Threading.Tasks;
|
||||
using Service = Gameboard.ShogiUI.Sockets.ServiceModels.Socket;
|
||||
|
||||
|
||||
namespace Gameboard.ShogiUI.Sockets.Managers.ClientActionHandlers
|
||||
{
|
||||
public class MoveHandler : IActionHandler
|
||||
public interface IMoveHandler
|
||||
{
|
||||
Task Handle(MoveRequest request, string userName);
|
||||
}
|
||||
public class MoveHandler : IMoveHandler
|
||||
{
|
||||
private readonly IBoardManager boardManager;
|
||||
private readonly IGameboardRepository gameboardRepository;
|
||||
@@ -23,43 +26,43 @@ namespace Gameboard.ShogiUI.Sockets.Managers.ClientActionHandlers
|
||||
this.communicationManager = communicationManager;
|
||||
}
|
||||
|
||||
public async Task Handle(string json, string userName)
|
||||
public async Task Handle(MoveRequest request, string userName)
|
||||
{
|
||||
var request = JsonConvert.DeserializeObject<Service.Messages.MoveRequest>(json);
|
||||
var moveModel = new Move(request.Move);
|
||||
var board = boardManager.Get(request.GameName);
|
||||
if (board == null)
|
||||
{
|
||||
// TODO: Find a flow for this
|
||||
var response = new Service.Messages.MoveResponse(Service.Types.ClientAction.Move)
|
||||
{
|
||||
Error = $"Game isn't loaded. Send a message with the {Service.Types.ClientAction.LoadGame} action first."
|
||||
};
|
||||
await communicationManager.BroadcastToPlayers(response, userName);
|
||||
//var request = JsonConvert.DeserializeObject<Service.Messages.MoveRequest>(json);
|
||||
//var moveModel = new Move(request.Move);
|
||||
//var board = boardManager.Get(request.GameName);
|
||||
//if (board == null)
|
||||
//{
|
||||
// // TODO: Find a flow for this
|
||||
// var response = new Service.Messages.MoveResponse(Service.Types.ClientAction.Move)
|
||||
// {
|
||||
// Error = $"Game isn't loaded. Send a message with the {Service.Types.ClientAction.LoadGame} action first."
|
||||
// };
|
||||
// await communicationManager.BroadcastToPlayers(response, userName);
|
||||
|
||||
}
|
||||
var boardMove = moveModel.ToBoardModel();
|
||||
var moveSuccess = board.Move(boardMove);
|
||||
if (moveSuccess)
|
||||
{
|
||||
await gameboardRepository.PostMove(request.GameName, new PostMove(moveModel.ToApiModel()));
|
||||
var boardState = new BoardState(board);
|
||||
var response = new Service.Messages.MoveResponse(Service.Types.ClientAction.Move)
|
||||
{
|
||||
GameName = request.GameName,
|
||||
PlayerName = userName,
|
||||
BoardState = boardState.ToServiceModel()
|
||||
};
|
||||
await communicationManager.BroadcastToGame(request.GameName, response);
|
||||
}
|
||||
else
|
||||
{
|
||||
var response = new Service.Messages.MoveResponse(Service.Types.ClientAction.Move)
|
||||
{
|
||||
Error = "Invalid move."
|
||||
};
|
||||
await communicationManager.BroadcastToPlayers(response, userName);
|
||||
}
|
||||
//}
|
||||
//var boardMove = moveModel.ToBoardModel();
|
||||
//var moveSuccess = board.Move(boardMove);
|
||||
//if (moveSuccess)
|
||||
//{
|
||||
// await gameboardRepository.PostMove(request.GameName, new PostMove(moveModel.ToApiModel()));
|
||||
// var boardState = new BoardState(board);
|
||||
// var response = new Service.Messages.MoveResponse(Service.Types.ClientAction.Move)
|
||||
// {
|
||||
// GameName = request.GameName,
|
||||
// PlayerName = userName,
|
||||
// BoardState = boardState.ToServiceModel()
|
||||
// };
|
||||
// await communicationManager.BroadcastToGame(request.GameName, response);
|
||||
//}
|
||||
//else
|
||||
//{
|
||||
// var response = new Service.Messages.MoveResponse(Service.Types.ClientAction.Move)
|
||||
// {
|
||||
// Error = "Invalid move."
|
||||
// };
|
||||
// await communicationManager.BroadcastToPlayers(response, userName);
|
||||
//}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ using Gameboard.ShogiUI.Sockets.Managers.ClientActionHandlers;
|
||||
using Gameboard.ShogiUI.Sockets.Managers.Utility;
|
||||
using Gameboard.ShogiUI.Sockets.Models;
|
||||
using Gameboard.ShogiUI.Sockets.ServiceModels.Socket.Interfaces;
|
||||
using Gameboard.ShogiUI.Sockets.ServiceModels.Socket.Messages;
|
||||
using Gameboard.ShogiUI.Sockets.ServiceModels.Socket.Types;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Newtonsoft.Json;
|
||||
@@ -16,10 +17,9 @@ namespace Gameboard.ShogiUI.Sockets.Managers
|
||||
{
|
||||
public interface ISocketCommunicationManager
|
||||
{
|
||||
Task CommunicateWith(WebSocket w, string s);
|
||||
Task BroadcastToAll(IResponse response);
|
||||
Task BroadcastToGame(string gameName, IResponse response);
|
||||
Task BroadcastToGame(string gameName, IResponse forPlayer1, IResponse forPlayer2);
|
||||
//Task BroadcastToGame(string gameName, IResponse response);
|
||||
//Task BroadcastToGame(string gameName, IResponse forPlayer1, IResponse forPlayer2);
|
||||
void SubscribeToGame(Session session, string playerName);
|
||||
void SubscribeToBroadcast(WebSocket socket, string playerName);
|
||||
void UnsubscribeFromBroadcastAndGames(string playerName);
|
||||
@@ -34,54 +34,14 @@ namespace Gameboard.ShogiUI.Sockets.Managers
|
||||
/// <summary>Dictionary key is game name.</summary>
|
||||
private readonly ConcurrentDictionary<string, Session> sessions;
|
||||
private readonly ILogger<SocketCommunicationManager> logger;
|
||||
private readonly ActionHandlerResolver handlerResolver;
|
||||
|
||||
public SocketCommunicationManager(
|
||||
ILogger<SocketCommunicationManager> logger,
|
||||
ActionHandlerResolver handlerResolver)
|
||||
public SocketCommunicationManager(ILogger<SocketCommunicationManager> logger)
|
||||
{
|
||||
this.logger = logger;
|
||||
this.handlerResolver = handlerResolver;
|
||||
connections = new ConcurrentDictionary<string, WebSocket>();
|
||||
sessions = new ConcurrentDictionary<string, Session>();
|
||||
}
|
||||
|
||||
public async Task CommunicateWith(WebSocket socket, string userName)
|
||||
{
|
||||
SubscribeToBroadcast(socket, userName);
|
||||
|
||||
while (!socket.CloseStatus.HasValue)
|
||||
{
|
||||
try
|
||||
{
|
||||
var message = await socket.ReceiveTextAsync();
|
||||
if (string.IsNullOrWhiteSpace(message)) continue;
|
||||
logger.LogInformation("Request \n{0}\n", message);
|
||||
var request = JsonConvert.DeserializeObject<Request>(message);
|
||||
if (!Enum.IsDefined(typeof(ClientAction), request.Action))
|
||||
{
|
||||
await socket.SendTextAsync("Error: Action not recognized.");
|
||||
}
|
||||
else
|
||||
{
|
||||
var handler = handlerResolver(request.Action);
|
||||
await handler.Handle(message, userName);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException ex)
|
||||
{
|
||||
logger.LogError(ex.Message);
|
||||
}
|
||||
catch (WebSocketException ex)
|
||||
{
|
||||
logger.LogInformation($"{nameof(WebSocketException)} in {nameof(SocketCommunicationManager)}.");
|
||||
logger.LogInformation("Probably tried writing to a closed socket.");
|
||||
logger.LogError(ex.Message);
|
||||
}
|
||||
}
|
||||
UnsubscribeFromBroadcastAndGames(userName);
|
||||
}
|
||||
|
||||
public void SubscribeToBroadcast(WebSocket socket, string playerName)
|
||||
{
|
||||
connections.TryAdd(playerName, socket);
|
||||
@@ -154,27 +114,27 @@ namespace Gameboard.ShogiUI.Sockets.Managers
|
||||
return Task.WhenAll(tasks);
|
||||
}
|
||||
|
||||
public Task BroadcastToGame(string gameName, IResponse forPlayer1, IResponse forPlayer2)
|
||||
{
|
||||
if (sessions.TryGetValue(gameName, out var session))
|
||||
{
|
||||
var serialized1 = JsonConvert.SerializeObject(forPlayer1);
|
||||
var serialized2 = JsonConvert.SerializeObject(forPlayer2);
|
||||
return Task.WhenAll(
|
||||
session.SendToPlayer1(serialized1),
|
||||
session.SendToPlayer2(serialized2));
|
||||
}
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
//public Task BroadcastToGame(string gameName, IResponse forPlayer1, IResponse forPlayer2)
|
||||
//{
|
||||
// if (sessions.TryGetValue(gameName, out var session))
|
||||
// {
|
||||
// var serialized1 = JsonConvert.SerializeObject(forPlayer1);
|
||||
// var serialized2 = JsonConvert.SerializeObject(forPlayer2);
|
||||
// return Task.WhenAll(
|
||||
// session.SendToPlayer1(serialized1),
|
||||
// session.SendToPlayer2(serialized2));
|
||||
// }
|
||||
// return Task.CompletedTask;
|
||||
//}
|
||||
|
||||
public Task BroadcastToGame(string gameName, IResponse messageForAllPlayers)
|
||||
{
|
||||
if (sessions.TryGetValue(gameName, out var session))
|
||||
{
|
||||
var serialized = JsonConvert.SerializeObject(messageForAllPlayers);
|
||||
return session.Broadcast(serialized);
|
||||
}
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
//public Task BroadcastToGame(string gameName, IResponse messageForAllPlayers)
|
||||
//{
|
||||
// if (sessions.TryGetValue(gameName, out var session))
|
||||
// {
|
||||
// var serialized = JsonConvert.SerializeObject(messageForAllPlayers);
|
||||
// return session.Broadcast(serialized);
|
||||
// }
|
||||
// return Task.CompletedTask;
|
||||
//}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,14 @@
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Gameboard.ShogiUI.Sockets.Extensions;
|
||||
using Gameboard.ShogiUI.Sockets.Managers.ClientActionHandlers;
|
||||
using Gameboard.ShogiUI.Sockets.Managers.Utility;
|
||||
using Gameboard.ShogiUI.Sockets.ServiceModels.Socket.Messages;
|
||||
using Gameboard.ShogiUI.Sockets.ServiceModels.Socket.Types;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Newtonsoft.Json;
|
||||
using System;
|
||||
using System.Net;
|
||||
using System.Net.WebSockets;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Gameboard.ShogiUI.Sockets.Managers
|
||||
@@ -12,14 +20,36 @@ namespace Gameboard.ShogiUI.Sockets.Managers
|
||||
|
||||
public class SocketConnectionManager : ISocketConnectionManager
|
||||
{
|
||||
private readonly ILogger<SocketConnectionManager> logger;
|
||||
private readonly ISocketCommunicationManager communicationManager;
|
||||
private readonly ISocketTokenManager tokenManager;
|
||||
private readonly ICreateGameHandler createGameHandler;
|
||||
private readonly IJoinByCodeHandler joinByCodeHandler;
|
||||
private readonly IJoinGameHandler joinGameHandler;
|
||||
private readonly IListGamesHandler listGamesHandler;
|
||||
private readonly ILoadGameHandler loadGameHandler;
|
||||
private readonly IMoveHandler moveHandler;
|
||||
|
||||
public SocketConnectionManager(ISocketCommunicationManager communicationManager, ISocketTokenManager tokenManager) : base()
|
||||
public SocketConnectionManager(
|
||||
ILogger<SocketConnectionManager> logger,
|
||||
ISocketCommunicationManager communicationManager,
|
||||
ISocketTokenManager tokenManager,
|
||||
ICreateGameHandler createGameHandler,
|
||||
IJoinByCodeHandler joinByCodeHandler,
|
||||
IJoinGameHandler joinGameHandler,
|
||||
IListGamesHandler listGamesHandler,
|
||||
ILoadGameHandler loadGameHandler,
|
||||
IMoveHandler moveHandler) : base()
|
||||
{
|
||||
this.logger = logger;
|
||||
this.communicationManager = communicationManager;
|
||||
this.tokenManager = tokenManager;
|
||||
|
||||
this.createGameHandler = createGameHandler;
|
||||
this.joinByCodeHandler = joinByCodeHandler;
|
||||
this.joinGameHandler = joinGameHandler;
|
||||
this.listGamesHandler = listGamesHandler;
|
||||
this.loadGameHandler = loadGameHandler;
|
||||
this.moveHandler = moveHandler;
|
||||
}
|
||||
|
||||
public async Task HandleSocketRequest(HttpContext context)
|
||||
@@ -33,7 +63,74 @@ namespace Gameboard.ShogiUI.Sockets.Managers
|
||||
if (userName != null)
|
||||
{
|
||||
var socket = await context.WebSockets.AcceptWebSocketAsync();
|
||||
await communicationManager.CommunicateWith(socket, userName);
|
||||
|
||||
communicationManager.SubscribeToBroadcast(socket, userName);
|
||||
while (!socket.CloseStatus.HasValue)
|
||||
{
|
||||
try
|
||||
{
|
||||
var message = await socket.ReceiveTextAsync();
|
||||
if (string.IsNullOrWhiteSpace(message)) continue;
|
||||
logger.LogInformation("Request \n{0}\n", message);
|
||||
var request = JsonConvert.DeserializeObject<Request>(message);
|
||||
if (!Enum.IsDefined(typeof(ClientAction), request.Action))
|
||||
{
|
||||
await socket.SendTextAsync("Error: Action not recognized.");
|
||||
continue;
|
||||
}
|
||||
switch (request.Action)
|
||||
{
|
||||
case ClientAction.ListGames:
|
||||
{
|
||||
var req = JsonConvert.DeserializeObject<ListGamesRequest>(message);
|
||||
await listGamesHandler.Handle(req, userName);
|
||||
break;
|
||||
}
|
||||
case ClientAction.CreateGame:
|
||||
{
|
||||
var req = JsonConvert.DeserializeObject<CreateGameRequest>(message);
|
||||
await createGameHandler.Handle(req, userName);
|
||||
break;
|
||||
}
|
||||
case ClientAction.JoinGame:
|
||||
{
|
||||
var req = JsonConvert.DeserializeObject<JoinGameRequest>(message);
|
||||
await joinGameHandler.Handle(req, userName);
|
||||
break;
|
||||
}
|
||||
case ClientAction.JoinByCode:
|
||||
{
|
||||
var req = JsonConvert.DeserializeObject<JoinByCodeRequest>(message);
|
||||
await joinByCodeHandler.Handle(req, userName);
|
||||
break;
|
||||
}
|
||||
case ClientAction.LoadGame:
|
||||
{
|
||||
var req = JsonConvert.DeserializeObject<LoadGameRequest>(message);
|
||||
await loadGameHandler.Handle(req, userName);
|
||||
break;
|
||||
}
|
||||
case ClientAction.Move:
|
||||
{
|
||||
var req = JsonConvert.DeserializeObject<MoveRequest>(message);
|
||||
await moveHandler.Handle(req, userName);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException ex)
|
||||
{
|
||||
logger.LogError(ex.Message);
|
||||
}
|
||||
catch (WebSocketException ex)
|
||||
{
|
||||
logger.LogInformation($"{nameof(WebSocketException)} in {nameof(SocketCommunicationManager)}.");
|
||||
logger.LogInformation("Probably tried writing to a closed socket.");
|
||||
logger.LogError(ex.Message);
|
||||
}
|
||||
}
|
||||
communicationManager.UnsubscribeFromBroadcastAndGames(userName);
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
@@ -16,27 +17,24 @@ namespace Gameboard.ShogiUI.Sockets.Managers
|
||||
/// <summary>
|
||||
/// Key is userName
|
||||
/// </summary>
|
||||
private readonly Dictionary<string, Guid> Tokens;
|
||||
private readonly ConcurrentDictionary<string, Guid> Tokens;
|
||||
|
||||
public SocketTokenManager()
|
||||
{
|
||||
Tokens = new Dictionary<string, Guid>();
|
||||
Tokens = new ConcurrentDictionary<string, Guid>();
|
||||
}
|
||||
|
||||
public Guid GenerateToken(string userName)
|
||||
{
|
||||
var guid = Guid.NewGuid();
|
||||
Tokens.Remove(userName, out _);
|
||||
|
||||
if (Tokens.ContainsKey(userName))
|
||||
{
|
||||
Tokens.Remove(userName);
|
||||
}
|
||||
Tokens.Add(userName, guid);
|
||||
var guid = Guid.NewGuid();
|
||||
Tokens.TryAdd(userName, guid);
|
||||
|
||||
_ = Task.Run(async () =>
|
||||
{
|
||||
await Task.Delay(TimeSpan.FromMinutes(1));
|
||||
Tokens.Remove(userName);
|
||||
Tokens.Remove(userName, out _);
|
||||
});
|
||||
|
||||
return guid;
|
||||
@@ -45,13 +43,12 @@ namespace Gameboard.ShogiUI.Sockets.Managers
|
||||
/// <returns>User name associated to the guid or null.</returns>
|
||||
public string GetUsername(Guid guid)
|
||||
{
|
||||
if (Tokens.ContainsValue(guid))
|
||||
var userName = Tokens.FirstOrDefault(kvp => kvp.Value == guid).Key;
|
||||
if (userName != null)
|
||||
{
|
||||
var username = Tokens.First(kvp => kvp.Value == guid).Key;
|
||||
Tokens.Remove(username);
|
||||
return username;
|
||||
Tokens.Remove(userName, out _);
|
||||
}
|
||||
return null;
|
||||
return userName;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,5 @@ namespace Gameboard.ShogiUI.Sockets.Managers.Utility
|
||||
public class Request : IRequest
|
||||
{
|
||||
public ClientAction Action { get; set; }
|
||||
public string PlayerName { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using Gameboard.ShogiUI.Rules;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Linq;
|
||||
using ServiceTypes = Gameboard.ShogiUI.Sockets.ServiceModels.Socket.Types;
|
||||
|
||||
@@ -7,28 +8,53 @@ namespace Gameboard.ShogiUI.Sockets.Models
|
||||
{
|
||||
public class BoardState
|
||||
{
|
||||
public Piece[,] Board { get; set; }
|
||||
public IReadOnlyCollection<Piece> Player1Hand { get; set; }
|
||||
public IReadOnlyCollection<Piece> Player2Hand { get; set; }
|
||||
// TODO: Create a custom 2D array implementation which removes the (x,y) or (y,x) ambiguity.
|
||||
public Piece?[,] Board { get; }
|
||||
public IReadOnlyCollection<Piece> Player1Hand { get; }
|
||||
public IReadOnlyCollection<Piece> Player2Hand { get; }
|
||||
/// <summary>
|
||||
/// Move is null in the first BoardState of a Session, before any moves have been made.
|
||||
/// </summary>
|
||||
public Move? Move { get; }
|
||||
|
||||
public BoardState() : this(new ShogiBoard()) { }
|
||||
|
||||
public BoardState(Piece?[,] board, IList<Piece> player1Hand, ICollection<Piece> player2Hand, Move move)
|
||||
{
|
||||
Board = board;
|
||||
Player1Hand = new ReadOnlyCollection<Piece>(player1Hand);
|
||||
}
|
||||
|
||||
public BoardState(ShogiBoard shogi)
|
||||
{
|
||||
Board = new Piece[9, 9];
|
||||
for (var x = 0; x < 9; x++)
|
||||
for (var y = 0; y < 9; y++)
|
||||
Board[x, y] = new Piece(shogi.Board[x, y]);
|
||||
{
|
||||
var piece = shogi.Board[x, y];
|
||||
if (piece != null)
|
||||
{
|
||||
Board[x, y] = new Piece(piece);
|
||||
}
|
||||
}
|
||||
|
||||
Player1Hand = shogi.Hands[WhichPlayer.Player1].Select(_ => new Piece(_)).ToList();
|
||||
Player2Hand = shogi.Hands[WhichPlayer.Player2].Select(_ => new Piece(_)).ToList();
|
||||
Move = new Move(shogi.MoveHistory[^1]);
|
||||
}
|
||||
|
||||
public ServiceTypes.BoardState ToServiceModel()
|
||||
{
|
||||
var board = new ServiceTypes.Piece[9, 9];
|
||||
Board = new Piece[9, 9];
|
||||
for (var x = 0; x < 9; x++)
|
||||
for (var y = 0; y < 9; y++)
|
||||
board[x, y] = Board[x, y].ToServiceModel();
|
||||
{
|
||||
var piece = Board[x, y];
|
||||
if (piece != null)
|
||||
{
|
||||
board[x, y] = piece.ToServiceModel();
|
||||
}
|
||||
}
|
||||
return new ServiceTypes.BoardState
|
||||
{
|
||||
Board = board,
|
||||
|
||||
@@ -1,88 +1,41 @@
|
||||
using Gameboard.ShogiUI.Rules;
|
||||
using Microsoft.FSharp.Core;
|
||||
using System;
|
||||
using Gameboard.ShogiUI.Sockets.ServiceModels.Socket.Types;
|
||||
using System.Numerics;
|
||||
using BoardStateMove = Gameboard.ShogiUI.Rules.Move;
|
||||
using ShogiApi = Gameboard.Shogi.Api.ServiceModels.Types;
|
||||
|
||||
namespace Gameboard.ShogiUI.Sockets.Models
|
||||
{
|
||||
public class Move
|
||||
{
|
||||
public string PieceFromCaptured { get; set; }
|
||||
public Coords From { get; set; }
|
||||
public Coords To { get; set; }
|
||||
public Coords? From { get; set; }
|
||||
public bool IsPromotion { get; set; }
|
||||
public WhichPiece? PieceFromHand { get; set; }
|
||||
public Coords To { get; set; }
|
||||
|
||||
public Move(ServiceModels.Socket.Types.Move move)
|
||||
public Move(Coords from, Coords to, bool isPromotion)
|
||||
{
|
||||
From = Coords.FromBoardNotation(move.From);
|
||||
To = Coords.FromBoardNotation(move.To);
|
||||
PieceFromCaptured = move.PieceFromCaptured;
|
||||
IsPromotion = move.IsPromotion;
|
||||
From = from;
|
||||
To = to;
|
||||
IsPromotion = isPromotion;
|
||||
}
|
||||
public Move(ShogiApi.Move move)
|
||||
|
||||
public Move(WhichPiece pieceFromHand, Coords to)
|
||||
{
|
||||
string pieceFromCaptured = null;
|
||||
if (move.PieceFromCaptured != null)
|
||||
{
|
||||
pieceFromCaptured = move.PieceFromCaptured.Value switch
|
||||
{
|
||||
ShogiApi.WhichPieceName.Bishop => "",
|
||||
ShogiApi.WhichPieceName.GoldenGeneral => "G",
|
||||
ShogiApi.WhichPieceName.King => "K",
|
||||
ShogiApi.WhichPieceName.Knight => "k",
|
||||
ShogiApi.WhichPieceName.Lance => "L",
|
||||
ShogiApi.WhichPieceName.Pawn => "P",
|
||||
ShogiApi.WhichPieceName.Rook => "R",
|
||||
ShogiApi.WhichPieceName.SilverGeneral => "S",
|
||||
_ => ""
|
||||
};
|
||||
}
|
||||
From = new Coords(move.Origin.X, move.Origin.Y);
|
||||
To = new Coords(move.Destination.X, move.Destination.Y);
|
||||
IsPromotion = move.IsPromotion;
|
||||
PieceFromCaptured = pieceFromCaptured;
|
||||
PieceFromHand = pieceFromHand;
|
||||
To = to;
|
||||
}
|
||||
|
||||
public ServiceModels.Socket.Types.Move ToServiceModel() => new()
|
||||
{
|
||||
From = From.ToBoardNotation(),
|
||||
From = From?.ToBoardNotation(),
|
||||
IsPromotion = IsPromotion,
|
||||
PieceFromCaptured = PieceFromCaptured,
|
||||
To = To.ToBoardNotation()
|
||||
To = To.ToBoardNotation(),
|
||||
PieceFromCaptured = PieceFromHand
|
||||
};
|
||||
public ShogiApi.Move ToApiModel()
|
||||
|
||||
public Rules.Move ToRulesModel()
|
||||
{
|
||||
var pieceFromCaptured = PieceFromCaptured switch
|
||||
{
|
||||
"B" => new FSharpOption<ShogiApi.WhichPieceName>(ShogiApi.WhichPieceName.Bishop),
|
||||
"G" => new FSharpOption<ShogiApi.WhichPieceName>(ShogiApi.WhichPieceName.GoldenGeneral),
|
||||
"K" => new FSharpOption<ShogiApi.WhichPieceName>(ShogiApi.WhichPieceName.King),
|
||||
"k" => new FSharpOption<ShogiApi.WhichPieceName>(ShogiApi.WhichPieceName.Knight),
|
||||
"L" => new FSharpOption<ShogiApi.WhichPieceName>(ShogiApi.WhichPieceName.Lance),
|
||||
"P" => new FSharpOption<ShogiApi.WhichPieceName>(ShogiApi.WhichPieceName.Pawn),
|
||||
"R" => new FSharpOption<ShogiApi.WhichPieceName>(ShogiApi.WhichPieceName.Rook),
|
||||
"S" => new FSharpOption<ShogiApi.WhichPieceName>(ShogiApi.WhichPieceName.SilverGeneral),
|
||||
_ => null
|
||||
};
|
||||
var target = new ShogiApi.Move
|
||||
{
|
||||
Origin = new ShogiApi.BoardLocation { X = From.X, Y = From.Y },
|
||||
Destination = new ShogiApi.BoardLocation { X = To.X, Y = To.Y },
|
||||
IsPromotion = IsPromotion,
|
||||
PieceFromCaptured = pieceFromCaptured
|
||||
};
|
||||
return target;
|
||||
}
|
||||
public BoardStateMove ToBoardModel()
|
||||
{
|
||||
return new BoardStateMove
|
||||
{
|
||||
From = new Vector2(From.X, From.Y),
|
||||
IsPromotion = IsPromotion,
|
||||
PieceFromCaptured = Enum.TryParse<WhichPiece>(PieceFromCaptured, out var whichPiece) ? whichPiece : null,
|
||||
To = new Vector2(To.X, To.Y)
|
||||
};
|
||||
return PieceFromHand != null
|
||||
? new Rules.Move((Rules.WhichPiece)PieceFromHand, new Vector2(To.X, To.Y))
|
||||
: new Rules.Move(new Vector2(From!.X, From.Y), new Vector2(To.X, To.Y), IsPromotion);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,18 +1,25 @@
|
||||
using Gameboard.ShogiUI.Sockets.ServiceModels.Socket.Types;
|
||||
using BoardStatePiece = Gameboard.ShogiUI.Rules.Pieces.Piece;
|
||||
|
||||
namespace Gameboard.ShogiUI.Sockets.Models
|
||||
{
|
||||
public class Piece
|
||||
{
|
||||
public WhichPiece WhichPiece { get; set; }
|
||||
public bool IsPromoted { get; }
|
||||
public WhichPlayer Owner { get; }
|
||||
public WhichPiece WhichPiece { get; }
|
||||
|
||||
public bool IsPromoted { get; set; }
|
||||
|
||||
public Piece(BoardStatePiece piece)
|
||||
public Piece(bool isPromoted, WhichPlayer owner, WhichPiece whichPiece)
|
||||
{
|
||||
IsPromoted = isPromoted;
|
||||
Owner = owner;
|
||||
WhichPiece = whichPiece;
|
||||
}
|
||||
|
||||
public Piece(Rules.Pieces.Piece piece)
|
||||
{
|
||||
WhichPiece = (WhichPiece)piece.WhichPiece;
|
||||
IsPromoted = piece.IsPromoted;
|
||||
Owner = (WhichPlayer)piece.Owner;
|
||||
WhichPiece = (WhichPiece)piece.WhichPiece;
|
||||
}
|
||||
|
||||
public ServiceModels.Socket.Types.Piece ToServiceModel()
|
||||
@@ -20,6 +27,7 @@ namespace Gameboard.ShogiUI.Sockets.Models
|
||||
return new ServiceModels.Socket.Types.Piece
|
||||
{
|
||||
IsPromoted = IsPromoted,
|
||||
Owner = Owner,
|
||||
WhichPiece = WhichPiece
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using Gameboard.ShogiUI.Sockets.Extensions;
|
||||
using Gameboard.ShogiUI.Sockets.ServiceModels.Socket.Types;
|
||||
using Newtonsoft.Json;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Net.WebSockets;
|
||||
@@ -9,18 +10,20 @@ namespace Gameboard.ShogiUI.Sockets.Models
|
||||
{
|
||||
public class Session
|
||||
{
|
||||
[JsonIgnore] public ConcurrentDictionary<string, WebSocket> Subscriptions { get; }
|
||||
public string Name { get; }
|
||||
public string Player1 { get; }
|
||||
public string Player2 { get; }
|
||||
public string? Player2 { get; }
|
||||
public bool IsPrivate { get; }
|
||||
|
||||
public ConcurrentDictionary<string, WebSocket> Subscriptions { get; }
|
||||
|
||||
public Session(Shogi.Api.ServiceModels.Types.Session session)
|
||||
public Session(string name, bool isPrivate, string player1, string? player2 = null)
|
||||
{
|
||||
Name = session.Name;
|
||||
Player1 = session.Player1;
|
||||
Player2 = session.Player2;
|
||||
Subscriptions = new ConcurrentDictionary<string, WebSocket>();
|
||||
|
||||
Name = name;
|
||||
Player1 = player1;
|
||||
Player2 = player2;
|
||||
IsPrivate = isPrivate;
|
||||
}
|
||||
|
||||
public bool Subscribe(string playerName, WebSocket socket) => Subscriptions.TryAdd(playerName, socket);
|
||||
@@ -47,7 +50,7 @@ namespace Gameboard.ShogiUI.Sockets.Models
|
||||
|
||||
public Task SendToPlayer2(string message)
|
||||
{
|
||||
if (Subscriptions.TryGetValue(Player2, out var socket))
|
||||
if (Player2 != null && Subscriptions.TryGetValue(Player2, out var socket))
|
||||
{
|
||||
return socket.SendTextAsync(message);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
|
||||
namespace Gameboard.ShogiUI.Sockets.Repositories.CouchModels
|
||||
{
|
||||
public class BoardState : CouchDocument
|
||||
{
|
||||
public string Name { get; set; }
|
||||
public Piece?[,] Board { get; set; }
|
||||
public Piece[] Player1Hand { get; set; }
|
||||
public Piece[] Player2Hand { get; set; }
|
||||
/// <summary>
|
||||
/// Move is null for first BoardState of a session - before anybody has made moves.
|
||||
/// </summary>
|
||||
public Move? Move { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Default constructor and setters are for deserialization.
|
||||
/// </summary>
|
||||
public BoardState() : base()
|
||||
{
|
||||
Name = string.Empty;
|
||||
Board = new Piece[9, 9];
|
||||
Player1Hand = Array.Empty<Piece>();
|
||||
Player2Hand = Array.Empty<Piece>();
|
||||
}
|
||||
|
||||
public BoardState(string sessionName, Models.BoardState boardState) : base($"{sessionName}-{DateTime.Now:O}", nameof(BoardState))
|
||||
{
|
||||
Name = sessionName;
|
||||
Board = new Piece[9, 9];
|
||||
|
||||
for (var x = 0; x < 9; x++)
|
||||
for (var y = 0; y < 9; y++)
|
||||
{
|
||||
var piece = boardState.Board[x, y];
|
||||
if (piece != null)
|
||||
{
|
||||
Board[x, y] = new Piece(piece);
|
||||
}
|
||||
}
|
||||
|
||||
Player1Hand = boardState.Player1Hand.Select(model => new Piece(model)).ToArray();
|
||||
Player2Hand = boardState.Player2Hand.Select(model => new Piece(model)).ToArray();
|
||||
if (boardState.Move != null)
|
||||
{
|
||||
Move = new Move(boardState.Move);
|
||||
}
|
||||
}
|
||||
|
||||
public Models.BoardState ToDomainModel()
|
||||
{
|
||||
/*
|
||||
* Board = new Piece[9, 9];
|
||||
for (var x = 0; x < 9; x++)
|
||||
for (var y = 0; y < 9; y++)
|
||||
{
|
||||
var piece = boardState.Board[x, y];
|
||||
if (piece != null)
|
||||
{
|
||||
Board[x, y] = new Piece(piece);
|
||||
}
|
||||
}
|
||||
|
||||
Player1Hand = boardState.Player1Hand.Select(_ => new Piece(_)).ToList();
|
||||
Player2Hand = boardState.Player2Hand.Select(_ => new Piece(_)).ToList();
|
||||
if (boardState.Move != null)
|
||||
{
|
||||
Move = new Move(boardState.Move);
|
||||
}
|
||||
*/
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
namespace Gameboard.ShogiUI.Sockets.Repositories.CouchModels
|
||||
{
|
||||
public class CouchCreateResult
|
||||
{
|
||||
public string Id { get; set; }
|
||||
public bool Ok { get; set; }
|
||||
public string Rev { get; set; }
|
||||
|
||||
public CouchCreateResult()
|
||||
{
|
||||
Id = string.Empty;
|
||||
Rev = string.Empty;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
using Newtonsoft.Json;
|
||||
using System;
|
||||
|
||||
namespace Gameboard.ShogiUI.Sockets.Repositories.CouchModels
|
||||
{
|
||||
public abstract class CouchDocument
|
||||
{
|
||||
[JsonProperty("_id")]
|
||||
public string Id { get; set; }
|
||||
public string Type { get; set; }
|
||||
public DateTimeOffset CreatedDate { get; set; }
|
||||
|
||||
public CouchDocument()
|
||||
{
|
||||
Id = string.Empty;
|
||||
Type = string.Empty;
|
||||
CreatedDate = DateTimeOffset.UtcNow;
|
||||
}
|
||||
public CouchDocument(string id, string type)
|
||||
{
|
||||
Id = id;
|
||||
Type = type;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using System;
|
||||
|
||||
namespace Gameboard.ShogiUI.Sockets.Repositories.CouchModels
|
||||
{
|
||||
internal class CouchFindResult<T>
|
||||
{
|
||||
public T[] docs;
|
||||
|
||||
public CouchFindResult()
|
||||
{
|
||||
docs = Array.Empty<T>();
|
||||
}
|
||||
}
|
||||
}
|
||||
45
Gameboard.ShogiUI.Sockets/Repositories/CouchModels/Move.cs
Normal file
45
Gameboard.ShogiUI.Sockets/Repositories/CouchModels/Move.cs
Normal file
@@ -0,0 +1,45 @@
|
||||
using Gameboard.ShogiUI.Sockets.Models;
|
||||
using Gameboard.ShogiUI.Sockets.ServiceModels.Socket.Types;
|
||||
|
||||
namespace Gameboard.ShogiUI.Sockets.Repositories.CouchModels
|
||||
{
|
||||
public class Move
|
||||
{
|
||||
/// <summary>
|
||||
/// A board coordinate, like A3 or G6. When null, look for PieceFromHand to exist.
|
||||
/// </summary>
|
||||
public string? From { get; set; }
|
||||
|
||||
public bool IsPromotion { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The piece placed from the player's hand.
|
||||
/// </summary>
|
||||
public WhichPiece? PieceFromHand { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// A board coordinate, like A3 or G6.
|
||||
/// </summary>
|
||||
public string To { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Default constructor and setters are for deserialization.
|
||||
/// </summary>
|
||||
public Move()
|
||||
{
|
||||
To = string.Empty;
|
||||
}
|
||||
|
||||
public Move(Models.Move move)
|
||||
{
|
||||
From = move.From?.ToBoardNotation();
|
||||
IsPromotion = move.IsPromotion;
|
||||
To = move.To.ToBoardNotation();
|
||||
PieceFromHand = move.PieceFromHand;
|
||||
}
|
||||
|
||||
public Models.Move ToDomainModel() => PieceFromHand.HasValue
|
||||
? new((ServiceModels.Socket.Types.WhichPiece)PieceFromHand, Coords.FromBoardNotation(To))
|
||||
: new(Coords.FromBoardNotation(From!), Coords.FromBoardNotation(To), IsPromotion);
|
||||
}
|
||||
}
|
||||
27
Gameboard.ShogiUI.Sockets/Repositories/CouchModels/Piece.cs
Normal file
27
Gameboard.ShogiUI.Sockets/Repositories/CouchModels/Piece.cs
Normal file
@@ -0,0 +1,27 @@
|
||||
using Gameboard.ShogiUI.Sockets.ServiceModels.Socket.Types;
|
||||
|
||||
namespace Gameboard.ShogiUI.Sockets.Repositories.CouchModels
|
||||
{
|
||||
public class Piece
|
||||
{
|
||||
public bool IsPromoted { get; set; }
|
||||
public WhichPlayer Owner { get; set; }
|
||||
public WhichPiece WhichPiece { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Default constructor and setters are for deserialization.
|
||||
/// </summary>
|
||||
public Piece()
|
||||
{
|
||||
}
|
||||
|
||||
public Piece(Models.Piece piece)
|
||||
{
|
||||
IsPromoted = piece.IsPromoted;
|
||||
Owner = piece.Owner;
|
||||
WhichPiece = piece.WhichPiece;
|
||||
}
|
||||
|
||||
public Models.Piece ToDomainModel() => new(IsPromoted, Owner, WhichPiece);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
### Couch Models
|
||||
|
||||
Couch models should accept domain models during construction and offer a ToDomainModel method which constructs a domain model.
|
||||
In this way, domain models have the freedom to define their valid states.
|
||||
@@ -0,0 +1,30 @@
|
||||
namespace Gameboard.ShogiUI.Sockets.Repositories.CouchModels
|
||||
{
|
||||
public class Session : CouchDocument
|
||||
{
|
||||
public string Name { get; set; }
|
||||
public string Player1 { get; set; }
|
||||
public string? Player2 { get; set; }
|
||||
public bool IsPrivate { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Default constructor and setters are for deserialization.
|
||||
/// </summary>
|
||||
public Session() : base()
|
||||
{
|
||||
Name = string.Empty;
|
||||
Player1 = string.Empty;
|
||||
Player2 = string.Empty;
|
||||
}
|
||||
|
||||
public Session(string id, Models.Session session) : base(id, nameof(Session))
|
||||
{
|
||||
Name = session.Name;
|
||||
Player1 = session.Player1;
|
||||
Player2 = session.Player2;
|
||||
IsPrivate = session.IsPrivate;
|
||||
}
|
||||
|
||||
public Models.Session ToDomainModel() => new(Name, IsPrivate, Player1, Player2);
|
||||
}
|
||||
}
|
||||
23
Gameboard.ShogiUI.Sockets/Repositories/CouchModels/User.cs
Normal file
23
Gameboard.ShogiUI.Sockets/Repositories/CouchModels/User.cs
Normal file
@@ -0,0 +1,23 @@
|
||||
using System;
|
||||
|
||||
namespace Gameboard.ShogiUI.Sockets.Repositories.CouchModels
|
||||
{
|
||||
public class User : CouchDocument
|
||||
{
|
||||
public static string GetDocumentId(string userName) => $"org.couchdb.user:{userName}";
|
||||
|
||||
public enum LoginPlatform
|
||||
{
|
||||
Microsoft,
|
||||
Guest
|
||||
}
|
||||
|
||||
public string Name { get; set; }
|
||||
public LoginPlatform Platform { get; set; }
|
||||
public User(string name, LoginPlatform platform) : base($"org.couchdb.user:{name}", nameof(User))
|
||||
{
|
||||
Name = name;
|
||||
Platform = platform;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
using Gameboard.Shogi.Api.ServiceModels.Messages;
|
||||
using Gameboard.ShogiUI.Sockets.Models;
|
||||
using Gameboard.ShogiUI.Sockets.Repositories.Utility;
|
||||
using Gameboard.ShogiUI.Sockets.Repositories.CouchModels;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Newtonsoft.Json;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
@@ -13,141 +12,173 @@ namespace Gameboard.ShogiUI.Sockets.Repositories
|
||||
{
|
||||
public interface IGameboardRepository
|
||||
{
|
||||
Task DeleteGame(string gameName);
|
||||
Task<Session> GetGame(string gameName);
|
||||
Task<GetSessionsResponse> GetGames();
|
||||
Task<GetSessionsResponse> GetGames(string playerName);
|
||||
Task<List<Move>> GetMoves(string gameName);
|
||||
Task<string> PostSession(PostSession request);
|
||||
Task<string> PostJoinPrivateSession(PostJoinPrivateSession request);
|
||||
Task<bool> PutJoinPublicSession(PutJoinPublicSession request);
|
||||
Task PostMove(string gameName, PostMove request);
|
||||
Task<bool> CreateBoardState(string sessionName, Models.BoardState boardState, Models.Move? move);
|
||||
Task<bool> CreateGuestUser(string userName);
|
||||
Task<bool> CreateSession(Models.Session session);
|
||||
Task<IList<Models.Session>> ReadSessions();
|
||||
Task<bool> IsGuestUser(string userName);
|
||||
Task<string> PostJoinCode(string gameName, string userName);
|
||||
Task<Player> GetPlayer(string userName);
|
||||
Task<bool> PostPlayer(PostPlayer request);
|
||||
Task<Models.Session?> ReadSession(string name);
|
||||
Task<IList<Models.BoardState>> ReadBoardStates(string name);
|
||||
}
|
||||
|
||||
public class GameboardRepository : IGameboardRepository
|
||||
{
|
||||
private const string GetSessionsRoute = "Sessions";
|
||||
private const string PostSessionRoute = "Session";
|
||||
private const string JoinSessionRoute = "Session/Join";
|
||||
private const string PlayerRoute = "Player";
|
||||
private const string MediaType = "application/json";
|
||||
private readonly IAuthenticatedHttpClient client;
|
||||
public GameboardRepository(IAuthenticatedHttpClient client)
|
||||
private const string ApplicationJson = "application/json";
|
||||
private readonly HttpClient client;
|
||||
private readonly ILogger<GameboardRepository> logger;
|
||||
|
||||
public GameboardRepository(IHttpClientFactory clientFactory, ILogger<GameboardRepository> logger)
|
||||
{
|
||||
this.client = client;
|
||||
client = clientFactory.CreateClient("couchdb");
|
||||
this.logger = logger;
|
||||
}
|
||||
|
||||
public async Task<GetSessionsResponse> GetGames()
|
||||
public async Task<IList<Models.Session>> ReadSessions()
|
||||
{
|
||||
var response = await client.GetAsync(GetSessionsRoute);
|
||||
var json = await response.Content.ReadAsStringAsync();
|
||||
return JsonConvert.DeserializeObject<GetSessionsResponse>(json);
|
||||
}
|
||||
var selector = $@"{{ ""{nameof(Session.Type)}"": ""{nameof(Session)}"" }}";
|
||||
var query = $@"{{ ""selector"": {selector} }}";
|
||||
var content = new StringContent(query, Encoding.UTF8, ApplicationJson);
|
||||
var response = await client.PostAsync("_find", content);
|
||||
var responseContent = await response.Content.ReadAsStringAsync();
|
||||
var result = JsonConvert.DeserializeObject<CouchFindResult<Session>>(responseContent);
|
||||
|
||||
public async Task<GetSessionsResponse> GetGames(string playerName)
|
||||
{
|
||||
var uri = $"Sessions/{playerName}";
|
||||
var response = await client.GetAsync(Uri.EscapeUriString(uri));
|
||||
var json = await response.Content.ReadAsStringAsync();
|
||||
return JsonConvert.DeserializeObject<GetSessionsResponse>(json);
|
||||
}
|
||||
|
||||
public async Task<Session> GetGame(string gameName)
|
||||
{
|
||||
var uri = $"Session/{gameName}";
|
||||
var response = await client.GetAsync(Uri.EscapeUriString(uri));
|
||||
var json = await response.Content.ReadAsStringAsync();
|
||||
if (string.IsNullOrWhiteSpace(json))
|
||||
if (result == null)
|
||||
{
|
||||
return null;
|
||||
logger.LogError("Unable to deserialize couchdb result during {0}.", nameof(this.ReadSessions));
|
||||
return Array.Empty<Models.Session>();
|
||||
}
|
||||
return new Session(JsonConvert.DeserializeObject<GetSessionResponse>(json).Session);
|
||||
return result.docs
|
||||
.Select(_ => _.ToDomainModel())
|
||||
.ToList();
|
||||
}
|
||||
|
||||
public async Task DeleteGame(string gameName)
|
||||
public async Task<Models.Session?> ReadSession(string name)
|
||||
{
|
||||
var uri = $"Session/{gameName}";
|
||||
await client.DeleteAsync(Uri.EscapeUriString(uri));
|
||||
var response = await client.GetAsync(name);
|
||||
var responseContent = await response.Content.ReadAsStringAsync();
|
||||
var couchModel = JsonConvert.DeserializeObject<Session>(responseContent);
|
||||
return couchModel.ToDomainModel();
|
||||
}
|
||||
|
||||
public async Task<string> PostSession(PostSession request)
|
||||
public async Task<IList<Models.BoardState>> ReadBoardStates(string name)
|
||||
{
|
||||
var content = new StringContent(JsonConvert.SerializeObject(request), Encoding.UTF8, MediaType);
|
||||
var response = await client.PostAsync(PostSessionRoute, content);
|
||||
var json = await response.Content.ReadAsStringAsync();
|
||||
return JsonConvert.DeserializeObject<PostSessionResponse>(json).SessionName;
|
||||
}
|
||||
var selector = $@"{{ ""{nameof(BoardState.Type)}"": ""{nameof(BoardState)}"", ""{nameof(BoardState.Name)}"": ""{name}"" }}";
|
||||
var sort = $@"{{ ""{nameof(BoardState.CreatedDate)}"" : ""desc"" }}";
|
||||
var query = $@"{{ ""selector"": {selector}, ""sort"": {sort} }}";
|
||||
var content = new StringContent(query, Encoding.UTF8, ApplicationJson);
|
||||
var response = await client.PostAsync("_find", content);
|
||||
var responseContent = await response.Content.ReadAsStringAsync();
|
||||
var result = JsonConvert.DeserializeObject<CouchFindResult<BoardState>>(responseContent);
|
||||
|
||||
public async Task<bool> PutJoinPublicSession(PutJoinPublicSession request)
|
||||
{
|
||||
var content = new StringContent(JsonConvert.SerializeObject(request), Encoding.UTF8, MediaType);
|
||||
var response = await client.PutAsync(JoinSessionRoute, content);
|
||||
var json = await response.Content.ReadAsStringAsync();
|
||||
return JsonConvert.DeserializeObject<PutJoinPublicSessionResponse>(json).JoinSucceeded;
|
||||
}
|
||||
|
||||
public async Task<string> PostJoinPrivateSession(PostJoinPrivateSession request)
|
||||
{
|
||||
var content = new StringContent(JsonConvert.SerializeObject(request), Encoding.UTF8, MediaType);
|
||||
var response = await client.PostAsync(JoinSessionRoute, content);
|
||||
var json = await response.Content.ReadAsStringAsync();
|
||||
var deserialized = JsonConvert.DeserializeObject<PostJoinPrivateSessionResponse>(json);
|
||||
if (deserialized.JoinSucceeded)
|
||||
if (result == null)
|
||||
{
|
||||
return deserialized.SessionName;
|
||||
logger.LogError("Unable to deserialize couchdb result during {0}.", nameof(this.ReadSessions));
|
||||
return Array.Empty<Models.BoardState>();
|
||||
}
|
||||
return null;
|
||||
return result.docs
|
||||
.Select(_ => new Models.BoardState(_))
|
||||
.ToList();
|
||||
}
|
||||
|
||||
public async Task<List<Move>> GetMoves(string gameName)
|
||||
//public async Task DeleteGame(string gameName)
|
||||
//{
|
||||
// //var uri = $"Session/{gameName}";
|
||||
// //await client.DeleteAsync(Uri.EscapeUriString(uri));
|
||||
//}
|
||||
|
||||
public async Task<bool> CreateSession(Models.Session session)
|
||||
{
|
||||
var uri = $"Session/{gameName}/Moves";
|
||||
var get = await client.GetAsync(Uri.EscapeUriString(uri));
|
||||
var json = await get.Content.ReadAsStringAsync();
|
||||
if (string.IsNullOrWhiteSpace(json))
|
||||
{
|
||||
return new List<Move>();
|
||||
}
|
||||
var response = JsonConvert.DeserializeObject<GetMovesResponse>(json);
|
||||
return response.Moves.Select(m => new Move(m)).ToList();
|
||||
var couchModel = new Session(session.Name, session);
|
||||
var content = new StringContent(JsonConvert.SerializeObject(couchModel), Encoding.UTF8, ApplicationJson);
|
||||
var response = await client.PostAsync(string.Empty, content);
|
||||
return response.IsSuccessStatusCode;
|
||||
}
|
||||
|
||||
public async Task PostMove(string gameName, PostMove request)
|
||||
public async Task<bool> CreateBoardState(string sessionName, Models.BoardState boardState, Models.Move? move)
|
||||
{
|
||||
var uri = $"Session/{gameName}/Move";
|
||||
var content = new StringContent(JsonConvert.SerializeObject(request), Encoding.UTF8, MediaType);
|
||||
await client.PostAsync(Uri.EscapeUriString(uri), content);
|
||||
var couchModel = new BoardState(sessionName, boardState, move);
|
||||
var content = new StringContent(JsonConvert.SerializeObject(couchModel), Encoding.UTF8, ApplicationJson);
|
||||
var response = await client.PostAsync(string.Empty, content);
|
||||
return response.IsSuccessStatusCode;
|
||||
}
|
||||
|
||||
//public async Task<bool> PutJoinPublicSession(PutJoinPublicSession request)
|
||||
//{
|
||||
// var content = new StringContent(JsonConvert.SerializeObject(request), Encoding.UTF8, MediaType);
|
||||
// var response = await client.PutAsync(JoinSessionRoute, content);
|
||||
// var json = await response.Content.ReadAsStringAsync();
|
||||
// return JsonConvert.DeserializeObject<PutJoinPublicSessionResponse>(json).JoinSucceeded;
|
||||
//}
|
||||
|
||||
//public async Task<string> PostJoinPrivateSession(PostJoinPrivateSession request)
|
||||
//{
|
||||
// var content = new StringContent(JsonConvert.SerializeObject(request), Encoding.UTF8, MediaType);
|
||||
// var response = await client.PostAsync(JoinSessionRoute, content);
|
||||
// var json = await response.Content.ReadAsStringAsync();
|
||||
// var deserialized = JsonConvert.DeserializeObject<PostJoinPrivateSessionResponse>(json);
|
||||
// if (deserialized.JoinSucceeded)
|
||||
// {
|
||||
// return deserialized.SessionName;
|
||||
// }
|
||||
// return null;
|
||||
//}
|
||||
|
||||
//public async Task<List<Move>> GetMoves(string gameName)
|
||||
//{
|
||||
// var uri = $"Session/{gameName}/Moves";
|
||||
// var get = await client.GetAsync(Uri.EscapeUriString(uri));
|
||||
// var json = await get.Content.ReadAsStringAsync();
|
||||
// if (string.IsNullOrWhiteSpace(json))
|
||||
// {
|
||||
// return new List<Move>();
|
||||
// }
|
||||
// var response = JsonConvert.DeserializeObject<GetMovesResponse>(json);
|
||||
// return response.Moves.Select(m => new Move(m)).ToList();
|
||||
//}
|
||||
|
||||
//public async Task PostMove(string gameName, PostMove request)
|
||||
//{
|
||||
// var uri = $"Session/{gameName}/Move";
|
||||
// var content = new StringContent(JsonConvert.SerializeObject(request), Encoding.UTF8, MediaType);
|
||||
// await client.PostAsync(Uri.EscapeUriString(uri), content);
|
||||
//}
|
||||
|
||||
public async Task<string> PostJoinCode(string gameName, string userName)
|
||||
{
|
||||
var uri = $"JoinCode/{gameName}";
|
||||
var serialized = JsonConvert.SerializeObject(new PostJoinCode { PlayerName = userName });
|
||||
var content = new StringContent(serialized, Encoding.UTF8, MediaType);
|
||||
var json = await (await client.PostAsync(Uri.EscapeUriString(uri), content)).Content.ReadAsStringAsync();
|
||||
return JsonConvert.DeserializeObject<PostJoinCodeResponse>(json).JoinCode;
|
||||
// var uri = $"JoinCode/{gameName}";
|
||||
// var serialized = JsonConvert.SerializeObject(new PostJoinCode { PlayerName = userName });
|
||||
// var content = new StringContent(serialized, Encoding.UTF8, MediaType);
|
||||
// var json = await (await client.PostAsync(Uri.EscapeUriString(uri), content)).Content.ReadAsStringAsync();
|
||||
// return JsonConvert.DeserializeObject<PostJoinCodeResponse>(json).JoinCode;
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
public async Task<Player> GetPlayer(string playerName)
|
||||
//public async Task<Player> GetPlayer(string playerName)
|
||||
//{
|
||||
// var uri = $"Player/{playerName}";
|
||||
// var get = await client.GetAsync(Uri.EscapeUriString(uri));
|
||||
// var content = await get.Content.ReadAsStringAsync();
|
||||
// if (!string.IsNullOrWhiteSpace(content))
|
||||
// {
|
||||
// var response = JsonConvert.DeserializeObject<GetPlayerResponse>(content);
|
||||
// return new Player(response.Player.Name);
|
||||
// }
|
||||
// return null;
|
||||
//}
|
||||
|
||||
public async Task<bool> CreateGuestUser(string userName)
|
||||
{
|
||||
var uri = $"Player/{playerName}";
|
||||
var get = await client.GetAsync(Uri.EscapeUriString(uri));
|
||||
var content = await get.Content.ReadAsStringAsync();
|
||||
if (!string.IsNullOrWhiteSpace(content))
|
||||
{
|
||||
var response = JsonConvert.DeserializeObject<GetPlayerResponse>(content);
|
||||
return new Player(response.Player.Name);
|
||||
}
|
||||
return null;
|
||||
var couchModel = new User(userName, User.LoginPlatform.Guest);
|
||||
var content = new StringContent(JsonConvert.SerializeObject(couchModel), Encoding.UTF8, ApplicationJson);
|
||||
var response = await client.PostAsync(string.Empty, content);
|
||||
return response.IsSuccessStatusCode;
|
||||
}
|
||||
|
||||
public async Task<bool> PostPlayer(PostPlayer request)
|
||||
public async Task<bool> IsGuestUser(string userName)
|
||||
{
|
||||
var content = new StringContent(JsonConvert.SerializeObject(request), Encoding.UTF8, MediaType);
|
||||
var response = await client.PostAsync(PlayerRoute, content);
|
||||
var req = new HttpRequestMessage(HttpMethod.Head, new Uri($"{client.BaseAddress}/{User.GetDocumentId(userName)}"));
|
||||
var response = await client.SendAsync(req);
|
||||
return response.IsSuccessStatusCode;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using Gameboard.Shogi.Api.ServiceModels.Messages;
|
||||
using Gameboard.ShogiUI.Sockets.Models;
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
@@ -9,7 +9,7 @@ namespace Gameboard.ShogiUI.Sockets.Repositories.RepositoryManagers
|
||||
Task<string> CreateGuestUser();
|
||||
Task<bool> IsPlayer1(string sessionName, string playerName);
|
||||
bool IsGuest(string playerName);
|
||||
Task<bool> PlayerExists(string playerName);
|
||||
Task<bool> CreateSession(Session session);
|
||||
}
|
||||
|
||||
public class GameboardRepositoryManager : IGameboardRepositoryManager
|
||||
@@ -30,11 +30,7 @@ namespace Gameboard.ShogiUI.Sockets.Repositories.RepositoryManagers
|
||||
{
|
||||
count++;
|
||||
var clientId = $"Guest-{Guid.NewGuid()}";
|
||||
var request = new PostPlayer
|
||||
{
|
||||
PlayerName = clientId
|
||||
};
|
||||
var isCreated = await repository.PostPlayer(request);
|
||||
var isCreated = await repository.CreateGuestUser(clientId);
|
||||
if (isCreated)
|
||||
{
|
||||
return clientId;
|
||||
@@ -45,22 +41,31 @@ namespace Gameboard.ShogiUI.Sockets.Repositories.RepositoryManagers
|
||||
|
||||
public async Task<bool> IsPlayer1(string sessionName, string playerName)
|
||||
{
|
||||
var session = await repository.GetGame(sessionName);
|
||||
return session?.Player1 == playerName;
|
||||
//var session = await repository.GetGame(sessionName);
|
||||
//return session?.Player1 == playerName;
|
||||
return true;
|
||||
}
|
||||
|
||||
public async Task<string> CreateJoinCode(string sessionName, string playerName)
|
||||
{
|
||||
var session = await repository.GetGame(sessionName);
|
||||
if (playerName == session?.Player1)
|
||||
{
|
||||
return await repository.PostJoinCode(sessionName, playerName);
|
||||
}
|
||||
//var session = await repository.GetGame(sessionName);
|
||||
//if (playerName == session?.Player1)
|
||||
//{
|
||||
// return await repository.PostJoinCode(sessionName, playerName);
|
||||
//}
|
||||
return null;
|
||||
}
|
||||
|
||||
public bool IsGuest(string playerName) => playerName.StartsWith(GuestPrefix);
|
||||
public async Task<bool> CreateSession(Session session)
|
||||
{
|
||||
var success = await repository.CreateSession(session);
|
||||
if (success)
|
||||
{
|
||||
return await repository.CreateBoardState(session.Name, new BoardState(), null);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public async Task<bool> PlayerExists(string playerName) => await repository.GetPlayer(playerName) != null;
|
||||
public bool IsGuest(string playerName) => playerName.StartsWith(GuestPrefix);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,122 +0,0 @@
|
||||
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 Gameboard.ShogiUI.Sockets.Repositories.Utility
|
||||
{
|
||||
public interface IAuthenticatedHttpClient
|
||||
{
|
||||
Task<HttpResponseMessage> DeleteAsync(string requestUri);
|
||||
Task<HttpResponseMessage> GetAsync(string requestUri);
|
||||
Task<HttpResponseMessage> PostAsync(string requestUri, HttpContent content);
|
||||
Task<HttpResponseMessage> PutAsync(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 new async 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 new async 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} \n\tRespCode: {RespCode} \n\tRequest: {Request}\n\tResponse: {Response}\n",
|
||||
BaseAddress,
|
||||
requestUri,
|
||||
response.StatusCode,
|
||||
await content.ReadAsStringAsync(),
|
||||
await response.Content.ReadAsStringAsync());
|
||||
return response;
|
||||
}
|
||||
public new async Task<HttpResponseMessage> PutAsync(string requestUri, HttpContent content)
|
||||
{
|
||||
var response = await base.PutAsync(requestUri, content);
|
||||
if (response.StatusCode == HttpStatusCode.Unauthorized)
|
||||
{
|
||||
await RefreshBearerToken();
|
||||
response = await base.PutAsync(requestUri, content);
|
||||
}
|
||||
logger.LogInformation(
|
||||
"Repository PUT to {BaseUrl}{RequestUrl} \n\tRespCode: {RespCode} \n\tRequest: {Request}\n\tResponse: {Response}\n",
|
||||
BaseAddress,
|
||||
requestUri,
|
||||
response.StatusCode,
|
||||
await content.ReadAsStringAsync(),
|
||||
await response.Content.ReadAsStringAsync());
|
||||
return response;
|
||||
}
|
||||
public new async 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,8 +3,6 @@ using Gameboard.ShogiUI.Sockets.Managers;
|
||||
using Gameboard.ShogiUI.Sockets.Managers.ClientActionHandlers;
|
||||
using Gameboard.ShogiUI.Sockets.Repositories;
|
||||
using Gameboard.ShogiUI.Sockets.Repositories.RepositoryManagers;
|
||||
using Gameboard.ShogiUI.Sockets.Repositories.Utility;
|
||||
using Gameboard.ShogiUI.Sockets.ServiceModels.Socket.Types;
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
@@ -15,8 +13,8 @@ using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Converters;
|
||||
using Newtonsoft.Json.Serialization;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Gameboard.ShogiUI.Sockets
|
||||
{
|
||||
@@ -33,36 +31,33 @@ namespace Gameboard.ShogiUI.Sockets
|
||||
public void ConfigureServices(IServiceCollection services)
|
||||
{
|
||||
// Socket ActionHandlers
|
||||
services.AddSingleton<CreateGameHandler>();
|
||||
services.AddSingleton<JoinByCodeHandler>();
|
||||
services.AddSingleton<JoinGameHandler>();
|
||||
services.AddSingleton<ListGamesHandler>();
|
||||
services.AddSingleton<LoadGameHandler>();
|
||||
services.AddSingleton<MoveHandler>();
|
||||
services.AddSingleton<ICreateGameHandler, CreateGameHandler>();
|
||||
services.AddSingleton<IJoinByCodeHandler, JoinByCodeHandler>();
|
||||
services.AddSingleton<IJoinGameHandler, JoinGameHandler>();
|
||||
services.AddSingleton<IListGamesHandler, ListGamesHandler>();
|
||||
services.AddSingleton<ILoadGameHandler, LoadGameHandler>();
|
||||
services.AddSingleton<IMoveHandler, MoveHandler>();
|
||||
|
||||
// Managers
|
||||
services.AddSingleton<ISocketCommunicationManager, SocketCommunicationManager>();
|
||||
services.AddSingleton<ISocketTokenManager, SocketTokenManager>();
|
||||
services.AddSingleton<ISocketConnectionManager, SocketConnectionManager>();
|
||||
services.AddScoped<IGameboardRepositoryManager, GameboardRepositoryManager>();
|
||||
services.AddSingleton<IGameboardRepositoryManager, GameboardRepositoryManager>();
|
||||
services.AddSingleton<IBoardManager, BoardManager>();
|
||||
services.AddSingleton<ActionHandlerResolver>(sp => action =>
|
||||
{
|
||||
return action switch
|
||||
{
|
||||
ClientAction.ListGames => sp.GetService<ListGamesHandler>(),
|
||||
ClientAction.CreateGame => sp.GetService<CreateGameHandler>(),
|
||||
ClientAction.JoinGame => sp.GetService<JoinGameHandler>(),
|
||||
ClientAction.JoinByCode => sp.GetService<JoinByCodeHandler>(),
|
||||
ClientAction.LoadGame => sp.GetService<LoadGameHandler>(),
|
||||
ClientAction.Move => sp.GetService<MoveHandler>(),
|
||||
_ => throw new KeyNotFoundException($"Unable to resolve {nameof(IActionHandler)} for {nameof(ClientAction)} {action}"),
|
||||
};
|
||||
});
|
||||
|
||||
// Repositories
|
||||
services.AddHttpClient("couchdb", c =>
|
||||
{
|
||||
var base64 = Convert.ToBase64String(Encoding.UTF8.GetBytes("admin:admin"));
|
||||
c.DefaultRequestHeaders.Add("Accept", "application/json");
|
||||
c.DefaultRequestHeaders.Add("Authorization", $"Basic {base64}");
|
||||
|
||||
var baseUrl = $"{Configuration["AppSettings:CouchDB:Url"]}/{Configuration["AppSettings:CouchDB:Database"]}/";
|
||||
c.BaseAddress = new Uri(baseUrl);
|
||||
});
|
||||
services.AddTransient<IGameboardRepository, GameboardRepository>();
|
||||
services.AddSingleton<IAuthenticatedHttpClient, AuthenticatedHttpClient>();
|
||||
//services.AddSingleton<IAuthenticatedHttpClient, AuthenticatedHttpClient>();
|
||||
//services.AddSingleton<ICouchClient>(provider => new CouchClient(databaseName, couchUrl));
|
||||
|
||||
services.AddControllers();
|
||||
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
{
|
||||
"AppSettings": {
|
||||
"IdentityServer": "https://identity.lucaserver.space/",
|
||||
"GameboardShogiApi": "https://dev.lucaserver.space/Gameboard.Shogi.Api/",
|
||||
"ClientId": "DevClientId",
|
||||
"ClientSecret": "DevSecret",
|
||||
"Scope": "DevEnvironment"
|
||||
"CouchDB": {
|
||||
"Database": "shogi-dev",
|
||||
"Url": "http://192.168.1.15:5984"
|
||||
}
|
||||
},
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
|
||||
Reference in New Issue
Block a user