Files
Shogi/Gameboard.ShogiUI.Sockets/Managers/ClientActionHandlers/JoinByCodeHandler.cs

76 lines
2.6 KiB
C#

using Gameboard.Shogi.Api.ServiceModels.Messages;
using Gameboard.ShogiUI.Sockets.Extensions;
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.Net.WebSockets;
using System.Threading.Tasks;
namespace Gameboard.ShogiUI.Sockets.Managers.ClientActionHandlers
{
public class JoinByCodeHandler : IActionHandler
{
private readonly ILogger<JoinByCodeHandler> logger;
private readonly IGameboardRepository repository;
private readonly ISocketCommunicationManager communicationManager;
public JoinByCodeHandler(
ILogger<JoinByCodeHandler> logger,
ISocketCommunicationManager communicationManager,
IGameboardRepository repository)
{
this.logger = logger;
this.repository = repository;
this.communicationManager = communicationManager;
}
public async Task Handle(WebSocket socket, string json, string userName)
{
logger.LogInformation("Socket Request \n{0}\n", new[] { json });
var request = JsonConvert.DeserializeObject<JoinByCode>(json);
var joinGameResponse = await repository.PostJoinPrivateSession(new PostJoinPrivateSession
{
PlayerName = userName,
JoinCode = request.JoinCode
});
if (joinGameResponse.JoinSucceeded)
{
var gameName = (await repository.GetGame(joinGameResponse.SessionName)).Session.Name;
// Other members of the game see a regular JoinGame occur.
var response = new JoinGameResponse(ClientAction.JoinGame)
{
PlayerName = userName,
GameName = gameName
};
var serialized = JsonConvert.SerializeObject(response);
await communicationManager.BroadcastToGame(gameName, serialized);
communicationManager.SubscribeToGame(socket, gameName, userName);
// But the player joining sees the JoinByCode occur.
response = new JoinGameResponse(ClientAction.JoinByCode)
{
PlayerName = userName,
GameName = gameName
};
serialized = JsonConvert.SerializeObject(response);
await socket.SendTextAsync(serialized);
}
else
{
var response = new JoinGameResponse(ClientAction.JoinByCode)
{
PlayerName = userName,
Error = "Error joining game."
};
var serialized = JsonConvert.SerializeObject(response);
logger.LogInformation("Socket Response \n{0}\n", new[] { serialized });
await socket.SendTextAsync(serialized);
}
}
}
}