Working on "Join Game" feature.
This commit is contained in:
@@ -15,141 +15,144 @@ namespace Shogi.Api.Controllers;
|
||||
[Authorize]
|
||||
public class SessionsController : ControllerBase
|
||||
{
|
||||
private readonly ISocketConnectionManager communicationManager;
|
||||
private readonly IModelMapper mapper;
|
||||
private readonly ISessionRepository sessionRepository;
|
||||
private readonly IQueryRespository queryRespository;
|
||||
private readonly ILogger<SessionsController> logger;
|
||||
private readonly ISocketConnectionManager communicationManager;
|
||||
private readonly IModelMapper mapper;
|
||||
private readonly ISessionRepository sessionRepository;
|
||||
private readonly IQueryRespository queryRespository;
|
||||
private readonly ILogger<SessionsController> logger;
|
||||
|
||||
public SessionsController(
|
||||
ISocketConnectionManager communicationManager,
|
||||
IModelMapper mapper,
|
||||
ISessionRepository sessionRepository,
|
||||
IQueryRespository queryRespository,
|
||||
ILogger<SessionsController> logger)
|
||||
{
|
||||
this.communicationManager = communicationManager;
|
||||
this.mapper = mapper;
|
||||
this.sessionRepository = sessionRepository;
|
||||
this.queryRespository = queryRespository;
|
||||
this.logger = logger;
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
public async Task<IActionResult> CreateSession([FromBody] CreateSessionCommand request)
|
||||
{
|
||||
var userId = User.GetShogiUserId();
|
||||
var session = new Domain.Session(request.Name, userId);
|
||||
try
|
||||
public SessionsController(
|
||||
ISocketConnectionManager communicationManager,
|
||||
IModelMapper mapper,
|
||||
ISessionRepository sessionRepository,
|
||||
IQueryRespository queryRespository,
|
||||
ILogger<SessionsController> logger)
|
||||
{
|
||||
await sessionRepository.CreateSession(session);
|
||||
}
|
||||
catch (SqlException e)
|
||||
{
|
||||
logger.LogError(exception: e, message: "Uh oh");
|
||||
return this.Conflict();
|
||||
this.communicationManager = communicationManager;
|
||||
this.mapper = mapper;
|
||||
this.sessionRepository = sessionRepository;
|
||||
this.queryRespository = queryRespository;
|
||||
this.logger = logger;
|
||||
}
|
||||
|
||||
await communicationManager.BroadcastToAll(new SessionCreatedSocketMessage());
|
||||
return CreatedAtAction(nameof(CreateSession), new { sessionName = request.Name }, null);
|
||||
}
|
||||
|
||||
[HttpDelete("{name}")]
|
||||
public async Task<IActionResult> DeleteSession(string name)
|
||||
{
|
||||
var userId = User.GetShogiUserId();
|
||||
var session = await sessionRepository.ReadSession(name);
|
||||
|
||||
if (session == null) return this.NoContent();
|
||||
|
||||
if (session.Player1 == userId)
|
||||
[HttpPost]
|
||||
public async Task<IActionResult> CreateSession([FromBody] CreateSessionCommand request)
|
||||
{
|
||||
await sessionRepository.DeleteSession(name);
|
||||
return this.NoContent();
|
||||
}
|
||||
|
||||
return this.StatusCode(StatusCodes.Status403Forbidden, "Cannot delete sessions created by others.");
|
||||
}
|
||||
|
||||
[HttpGet("PlayerCount")]
|
||||
public async Task<ActionResult<ReadSessionsPlayerCountResponse>> GetSessionsPlayerCount()
|
||||
{
|
||||
return Ok(await this.queryRespository.ReadSessionPlayerCount(this.User.GetShogiUserId()));
|
||||
}
|
||||
|
||||
[HttpGet("{name}")]
|
||||
public async Task<ActionResult<ReadSessionResponse>> GetSession(string name)
|
||||
{
|
||||
var session = await sessionRepository.ReadSession(name);
|
||||
if (session == null) return this.NotFound();
|
||||
|
||||
return new ReadSessionResponse
|
||||
{
|
||||
Session = new Session
|
||||
{
|
||||
BoardState = new BoardState
|
||||
var userId = User.GetShogiUserId();
|
||||
var session = new Domain.Session(request.Name, userId);
|
||||
try
|
||||
{
|
||||
Board = session.Board.BoardState.State.ToContract(),
|
||||
Player1Hand = session.Board.BoardState.Player1Hand.ToContract(),
|
||||
Player2Hand = session.Board.BoardState.Player2Hand.ToContract(),
|
||||
PlayerInCheck = session.Board.BoardState.InCheck?.ToContract(),
|
||||
WhoseTurn = session.Board.BoardState.WhoseTurn.ToContract()
|
||||
},
|
||||
Player1 = session.Player1,
|
||||
Player2 = session.Player2,
|
||||
SessionName = session.Name
|
||||
}
|
||||
};
|
||||
}
|
||||
await sessionRepository.CreateSession(session);
|
||||
}
|
||||
catch (SqlException e)
|
||||
{
|
||||
logger.LogError(exception: e, message: "Uh oh");
|
||||
return this.Conflict();
|
||||
}
|
||||
|
||||
[HttpPut("{name}/Join")]
|
||||
public async Task<IActionResult> JoinSession(string name)
|
||||
{
|
||||
var session = await sessionRepository.ReadSession(name);
|
||||
if (session == null) return this.NotFound();
|
||||
|
||||
if (string.IsNullOrEmpty(session.Player2))
|
||||
{
|
||||
session.AddPlayer2(User.GetShogiUserId());
|
||||
await communicationManager.BroadcastToAll(new SessionCreatedSocketMessage());
|
||||
return CreatedAtAction(nameof(CreateSession), new { sessionName = request.Name }, null);
|
||||
}
|
||||
return this.Ok();
|
||||
}
|
||||
|
||||
[HttpPatch("{sessionName}/Move")]
|
||||
public async Task<IActionResult> Move([FromRoute] string sessionName, [FromBody] MovePieceCommand command)
|
||||
{
|
||||
var userId = User.GetShogiUserId();
|
||||
var session = await sessionRepository.ReadSession(sessionName);
|
||||
|
||||
if (session == null) return this.NotFound("Shogi session does not exist.");
|
||||
|
||||
if (!session.IsSeated(userId)) return this.StatusCode(StatusCodes.Status403Forbidden, "Player is not a member of the Shogi session.");
|
||||
|
||||
try
|
||||
[HttpDelete("{name}")]
|
||||
public async Task<IActionResult> DeleteSession(string name)
|
||||
{
|
||||
if (command.PieceFromHand.HasValue)
|
||||
{
|
||||
session.Board.Move(command.PieceFromHand.Value.ToDomain(), command.To);
|
||||
}
|
||||
else
|
||||
{
|
||||
session.Board.Move(command.From!, command.To, command.IsPromotion ?? false);
|
||||
}
|
||||
}
|
||||
catch (InvalidOperationException e)
|
||||
{
|
||||
return this.Conflict(e.Message);
|
||||
}
|
||||
await sessionRepository.CreateMove(sessionName, command);
|
||||
await communicationManager.BroadcastToPlayers(
|
||||
new PlayerHasMovedMessage
|
||||
{
|
||||
PlayerName = userId,
|
||||
SessionName = session.Name,
|
||||
},
|
||||
session.Player1,
|
||||
session.Player2);
|
||||
var userId = User.GetShogiUserId();
|
||||
var session = await sessionRepository.ReadSession(name);
|
||||
|
||||
return this.NoContent();
|
||||
}
|
||||
if (session == null) return this.NoContent();
|
||||
|
||||
if (session.Player1 == userId)
|
||||
{
|
||||
await sessionRepository.DeleteSession(name);
|
||||
return this.NoContent();
|
||||
}
|
||||
|
||||
return this.StatusCode(StatusCodes.Status403Forbidden, "Cannot delete sessions created by others.");
|
||||
}
|
||||
|
||||
[HttpGet("PlayerCount")]
|
||||
public async Task<ActionResult<ReadSessionsPlayerCountResponse>> GetSessionsPlayerCount()
|
||||
{
|
||||
return Ok(await this.queryRespository.ReadSessionPlayerCount(this.User.GetShogiUserId()));
|
||||
}
|
||||
|
||||
[HttpGet("{name}")]
|
||||
public async Task<ActionResult<ReadSessionResponse>> GetSession(string name)
|
||||
{
|
||||
var session = await sessionRepository.ReadSession(name);
|
||||
if (session == null) return this.NotFound();
|
||||
|
||||
return new ReadSessionResponse
|
||||
{
|
||||
Session = new Session
|
||||
{
|
||||
BoardState = new BoardState
|
||||
{
|
||||
Board = session.Board.BoardState.State.ToContract(),
|
||||
Player1Hand = session.Board.BoardState.Player1Hand.ToContract(),
|
||||
Player2Hand = session.Board.BoardState.Player2Hand.ToContract(),
|
||||
PlayerInCheck = session.Board.BoardState.InCheck?.ToContract(),
|
||||
WhoseTurn = session.Board.BoardState.WhoseTurn.ToContract()
|
||||
},
|
||||
Player1 = session.Player1,
|
||||
Player2 = session.Player2,
|
||||
SessionName = session.Name
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
[HttpPatch("{name}/Join")]
|
||||
public async Task<IActionResult> JoinSession(string name)
|
||||
{
|
||||
var session = await sessionRepository.ReadSession(name);
|
||||
if (session == null) return this.NotFound();
|
||||
|
||||
if (string.IsNullOrEmpty(session.Player2))
|
||||
{
|
||||
session.AddPlayer2(User.GetShogiUserId());
|
||||
|
||||
await sessionRepository.SetPlayer2(name, User.GetShogiUserId());
|
||||
return this.Ok();
|
||||
}
|
||||
return this.Conflict("This game already has two players.");
|
||||
}
|
||||
|
||||
[HttpPatch("{sessionName}/Move")]
|
||||
public async Task<IActionResult> Move([FromRoute] string sessionName, [FromBody] MovePieceCommand command)
|
||||
{
|
||||
var userId = User.GetShogiUserId();
|
||||
var session = await sessionRepository.ReadSession(sessionName);
|
||||
|
||||
if (session == null) return this.NotFound("Shogi session does not exist.");
|
||||
|
||||
if (!session.IsSeated(userId)) return this.StatusCode(StatusCodes.Status403Forbidden, "Player is not a member of the Shogi session.");
|
||||
|
||||
try
|
||||
{
|
||||
if (command.PieceFromHand.HasValue)
|
||||
{
|
||||
session.Board.Move(command.PieceFromHand.Value.ToDomain(), command.To);
|
||||
}
|
||||
else
|
||||
{
|
||||
session.Board.Move(command.From!, command.To, command.IsPromotion ?? false);
|
||||
}
|
||||
}
|
||||
catch (InvalidOperationException e)
|
||||
{
|
||||
return this.Conflict(e.Message);
|
||||
}
|
||||
await sessionRepository.CreateMove(sessionName, command);
|
||||
await communicationManager.BroadcastToPlayers(
|
||||
new PlayerHasMovedMessage
|
||||
{
|
||||
PlayerName = userId,
|
||||
SessionName = session.Name,
|
||||
},
|
||||
session.Player1,
|
||||
session.Player2);
|
||||
|
||||
return this.NoContent();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,7 +33,6 @@ namespace Shogi.Api
|
||||
.AllowCredentials();
|
||||
});
|
||||
});
|
||||
|
||||
ConfigureAuthentication(builder);
|
||||
ConfigureControllers(builder);
|
||||
ConfigureSwagger(builder);
|
||||
|
||||
@@ -11,7 +11,8 @@ public class QueryRepository : IQueryRespository
|
||||
|
||||
public QueryRepository(IConfiguration configuration)
|
||||
{
|
||||
connectionString = configuration.GetConnectionString("ShogiDatabase");
|
||||
var connectionString = configuration.GetConnectionString("ShogiDatabase") ?? throw new InvalidOperationException("No database configured for QueryRepository.");
|
||||
this.connectionString = connectionString;
|
||||
}
|
||||
|
||||
public async Task<ReadSessionsPlayerCountResponse> ReadSessionPlayerCount(string playerName)
|
||||
|
||||
@@ -9,89 +9,103 @@ namespace Shogi.Api.Repositories;
|
||||
|
||||
public class SessionRepository : ISessionRepository
|
||||
{
|
||||
private readonly string connectionString;
|
||||
private readonly string connectionString;
|
||||
|
||||
public SessionRepository(IConfiguration configuration)
|
||||
{
|
||||
connectionString = configuration.GetConnectionString("ShogiDatabase");
|
||||
}
|
||||
|
||||
public async Task CreateSession(Session session)
|
||||
{
|
||||
using var connection = new SqlConnection(connectionString);
|
||||
await connection.ExecuteAsync(
|
||||
"session.CreateSession",
|
||||
new
|
||||
{
|
||||
session.Name,
|
||||
Player1Name = session.Player1,
|
||||
},
|
||||
commandType: CommandType.StoredProcedure);
|
||||
}
|
||||
|
||||
public async Task DeleteSession(string name)
|
||||
{
|
||||
using var connection = new SqlConnection(connectionString);
|
||||
await connection.ExecuteAsync(
|
||||
"session.DeleteSession",
|
||||
new { Name = name },
|
||||
commandType: CommandType.StoredProcedure);
|
||||
}
|
||||
|
||||
public async Task<Session?> ReadSession(string name)
|
||||
{
|
||||
using var connection = new SqlConnection(connectionString);
|
||||
var results = await connection.QueryMultipleAsync(
|
||||
"session.ReadSession",
|
||||
new { Name = name },
|
||||
commandType: CommandType.StoredProcedure);
|
||||
|
||||
var sessionDtos = await results.ReadAsync<SessionDto>();
|
||||
if (!sessionDtos.Any()) return null;
|
||||
var dto = sessionDtos.First();
|
||||
var session = new Session(dto.Name, dto.Player1);
|
||||
if (!string.IsNullOrWhiteSpace(dto.Player2)) session.AddPlayer2(dto.Player2);
|
||||
|
||||
var moveDtos = await results.ReadAsync<MoveDto>();
|
||||
foreach (var move in moveDtos)
|
||||
public SessionRepository(IConfiguration configuration)
|
||||
{
|
||||
if (move.PieceFromHand.HasValue)
|
||||
{
|
||||
session.Board.Move(move.PieceFromHand.Value, move.To);
|
||||
}
|
||||
else if (move.From != null)
|
||||
{
|
||||
session.Board.Move(move.From, move.To, false);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new InvalidOperationException($"Corrupt data during {nameof(ReadSession)}");
|
||||
}
|
||||
connectionString = configuration.GetConnectionString("ShogiDatabase") ?? throw new InvalidOperationException("Database connection string not configured.");
|
||||
}
|
||||
return session;
|
||||
}
|
||||
|
||||
public async Task CreateMove(string sessionName, Contracts.Api.MovePieceCommand command)
|
||||
{
|
||||
using var connection = new SqlConnection(connectionString);
|
||||
await connection.ExecuteAsync(
|
||||
"session.CreateMove",
|
||||
new
|
||||
{
|
||||
command.To,
|
||||
command.From,
|
||||
command.IsPromotion,
|
||||
command.PieceFromHand,
|
||||
SessionName = sessionName
|
||||
},
|
||||
commandType: CommandType.StoredProcedure);
|
||||
}
|
||||
public async Task CreateSession(Session session)
|
||||
{
|
||||
using var connection = new SqlConnection(connectionString);
|
||||
await connection.ExecuteAsync(
|
||||
"session.CreateSession",
|
||||
new
|
||||
{
|
||||
session.Name,
|
||||
Player1Name = session.Player1,
|
||||
},
|
||||
commandType: CommandType.StoredProcedure);
|
||||
}
|
||||
|
||||
public async Task DeleteSession(string name)
|
||||
{
|
||||
using var connection = new SqlConnection(connectionString);
|
||||
await connection.ExecuteAsync(
|
||||
"session.DeleteSession",
|
||||
new { Name = name },
|
||||
commandType: CommandType.StoredProcedure);
|
||||
}
|
||||
|
||||
public async Task<Session?> ReadSession(string name)
|
||||
{
|
||||
using var connection = new SqlConnection(connectionString);
|
||||
var results = await connection.QueryMultipleAsync(
|
||||
"session.ReadSession",
|
||||
new { Name = name },
|
||||
commandType: CommandType.StoredProcedure);
|
||||
|
||||
var sessionDtos = await results.ReadAsync<SessionDto>();
|
||||
if (!sessionDtos.Any()) return null;
|
||||
var dto = sessionDtos.First();
|
||||
var session = new Session(dto.Name, dto.Player1);
|
||||
if (!string.IsNullOrWhiteSpace(dto.Player2)) session.AddPlayer2(dto.Player2);
|
||||
|
||||
var moveDtos = await results.ReadAsync<MoveDto>();
|
||||
foreach (var move in moveDtos)
|
||||
{
|
||||
if (move.PieceFromHand.HasValue)
|
||||
{
|
||||
session.Board.Move(move.PieceFromHand.Value, move.To);
|
||||
}
|
||||
else if (move.From != null)
|
||||
{
|
||||
session.Board.Move(move.From, move.To, false);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new InvalidOperationException($"Corrupt data during {nameof(ReadSession)}");
|
||||
}
|
||||
}
|
||||
return session;
|
||||
}
|
||||
|
||||
public async Task CreateMove(string sessionName, MovePieceCommand command)
|
||||
{
|
||||
using var connection = new SqlConnection(connectionString);
|
||||
await connection.ExecuteAsync(
|
||||
"session.CreateMove",
|
||||
new
|
||||
{
|
||||
command.To,
|
||||
command.From,
|
||||
command.IsPromotion,
|
||||
command.PieceFromHand,
|
||||
SessionName = sessionName
|
||||
},
|
||||
commandType: CommandType.StoredProcedure);
|
||||
}
|
||||
|
||||
public async Task SetPlayer2(string sessionName, string player2Name)
|
||||
{
|
||||
using var connection = new SqlConnection(connectionString);
|
||||
await connection.ExecuteAsync(
|
||||
"session.SetPlayer2",
|
||||
new
|
||||
{
|
||||
SessionName = sessionName,
|
||||
Player2Name = player2Name
|
||||
},
|
||||
commandType: CommandType.StoredProcedure);
|
||||
}
|
||||
}
|
||||
|
||||
public interface ISessionRepository
|
||||
{
|
||||
Task CreateMove(string sessionName, MovePieceCommand command);
|
||||
Task CreateSession(Session session);
|
||||
Task DeleteSession(string name);
|
||||
Task<Session?> ReadSession(string name);
|
||||
Task CreateMove(string sessionName, MovePieceCommand command);
|
||||
Task CreateSession(Session session);
|
||||
Task DeleteSession(string name);
|
||||
Task<Session?> ReadSession(string name);
|
||||
Task SetPlayer2(string sessionName, string player2Name);
|
||||
}
|
||||
Reference in New Issue
Block a user