92 lines
2.8 KiB
C#
92 lines
2.8 KiB
C#
using System.Net.WebSockets;
|
|
using System.Text.Json;
|
|
using System.Text.RegularExpressions;
|
|
using MauMau_Server.Room.Messages;
|
|
using MauMau_Server.Websockets;
|
|
|
|
namespace MauMau_Server.Room;
|
|
|
|
public class Room
|
|
{
|
|
private readonly IRoomManager _roomManager;
|
|
private readonly string _roomId;
|
|
public readonly List<ConnectionInstance> Connections = new();
|
|
public ConnectionInstance? Host;
|
|
public RoomType RoomType;
|
|
|
|
public Room(IRoomManager roomManager, string roomId)
|
|
{
|
|
_roomManager = roomManager;
|
|
RoomType = new Lobby(this);
|
|
_roomId = roomId;
|
|
}
|
|
|
|
public async Task InstantiateConnection(WebSocket socket, string name)
|
|
{
|
|
var connectionId = Guid.NewGuid();
|
|
var connection = new ConnectionInstance(name, connectionId, socket);
|
|
if (IsEmpty()) Host = connection;
|
|
Connections.Add(connection);
|
|
|
|
RoomType.OnConnect(connection);
|
|
await HandleConnection(connection);
|
|
}
|
|
|
|
private async Task HandleConnection(ConnectionInstance connection)
|
|
{
|
|
var webSocketResponse = await WebsocketManager.ReceiveAsync(connection.Socket);
|
|
while (!webSocketResponse.Result!.CloseStatus.HasValue)
|
|
{
|
|
var message = JsonSerializer.Deserialize<RoomMessage<string>>(webSocketResponse.SlicedBuffer);
|
|
if (message.Type == "CHAT")
|
|
{
|
|
var cleanedMessage = StripHTML(message.Data);
|
|
if (string.IsNullOrWhiteSpace(cleanedMessage)) cleanedMessage = "Mau!";
|
|
var chatMessage = new ChatMessage(connection.Name, cleanedMessage);
|
|
BroadCast(new RoomMessage<ChatMessage>("CHAT", chatMessage));
|
|
}
|
|
else
|
|
{
|
|
RoomType.OnMessage(connection, message);
|
|
}
|
|
|
|
webSocketResponse = await WebsocketManager.ReceiveAsync(connection.Socket);
|
|
}
|
|
WebsocketManager.CloseAsync(connection.Socket, webSocketResponse.Result);
|
|
HandleDisconnect(connection);
|
|
}
|
|
|
|
private void HandleDisconnect(ConnectionInstance connection)
|
|
{
|
|
Connections.Remove(connection);
|
|
RoomType.OnDisconnect(connection);
|
|
if (IsEmpty())
|
|
{
|
|
_roomManager.RemoveRoom(_roomId);
|
|
return;
|
|
}
|
|
|
|
if (connection == Host)
|
|
{
|
|
Host = Connections.First();
|
|
}
|
|
}
|
|
|
|
public void BroadCast<T>(RoomMessage<T> message)
|
|
{
|
|
foreach (var connection in Connections)
|
|
{
|
|
connection.SendMessageAsync(JsonSerializer.Serialize(message));
|
|
}
|
|
}
|
|
|
|
public bool IsEmpty()
|
|
{
|
|
return Connections.Count == 0;
|
|
}
|
|
|
|
private static string StripHTML(string input)
|
|
{
|
|
return Regex.Replace(input, "<.*?>", string.Empty);
|
|
}
|
|
} |