100 lines
3.0 KiB
C#
100 lines
3.0 KiB
C#
using System.Net.WebSockets;
|
|
using System.Text.Json;
|
|
using System.Text.RegularExpressions;
|
|
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;
|
|
private readonly Chat.Chat _chat;
|
|
public RoomType _roomType;
|
|
|
|
public Room(IRoomManager roomManager, string roomId)
|
|
{
|
|
_roomManager = roomManager;
|
|
_chat = new Chat.Chat(this);
|
|
_roomType = new Lobby(this);
|
|
_roomId = roomId;
|
|
}
|
|
|
|
public async Task InstantiateConnection(WebSocket socket, string name)
|
|
{
|
|
var connection = AddConnection(socket, name);
|
|
_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<MessageDTO>(webSocketResponse.SlicedBuffer);
|
|
if (message.Type == "CHAT")
|
|
{
|
|
var cleanedMessage = StripHTML(message.Payload);
|
|
if (string.IsNullOrWhiteSpace(cleanedMessage)) cleanedMessage = "Mau!";
|
|
_chat.SendChatMessage(connection, cleanedMessage);
|
|
}
|
|
else
|
|
{
|
|
_roomType.OnMessage(connection, message.Payload);
|
|
}
|
|
|
|
webSocketResponse = await WebsocketManager.ReceiveAsync(connection.Socket);
|
|
}
|
|
WebsocketManager.CloseAsync(connection.Socket, webSocketResponse.Result);
|
|
HandleDisconnect(connection);
|
|
}
|
|
|
|
private ConnectionInstance AddConnection(WebSocket socket, string name)
|
|
{
|
|
var connectionId = Guid.NewGuid().ToString();
|
|
var connection = new ConnectionInstance(name, connectionId, socket);
|
|
if (IsEmpty()) _host = connection;
|
|
Connections.Add(connection);
|
|
return connection;
|
|
}
|
|
|
|
private void HandleDisconnect(ConnectionInstance connection)
|
|
{
|
|
Connections.Remove(connection);
|
|
_roomType.OnDisconnect(connection);
|
|
if (IsEmpty())
|
|
{
|
|
_roomManager.RemoveRoom(_roomId);
|
|
}
|
|
else if (connection == _host)
|
|
{
|
|
_host = Connections.First();
|
|
}
|
|
}
|
|
|
|
public void BroadCast(RoomMessage message)
|
|
{
|
|
foreach (var connection in Connections)
|
|
{
|
|
connection.SendMessageAsync(JsonSerializer.Serialize(message));
|
|
}
|
|
}
|
|
|
|
public List<WebSocket> GetWebsockets()
|
|
{
|
|
return Connections.Select(connection => connection.Socket).ToList();
|
|
}
|
|
|
|
public bool IsEmpty()
|
|
{
|
|
return Connections.Count == 0;
|
|
}
|
|
|
|
private static string StripHTML(string input)
|
|
{
|
|
return Regex.Replace(input, "<.*?>", string.Empty);
|
|
}
|
|
} |