Add chat message handling and WebSocket integration

Introduce new `ChatService` for managing chat messages, including marking messages as read and checking read status. Add `WebSocketPacket` class for handling WebSocket communication and integrate it with `WebSocketService` to process chat-related packets. Enhance `ChatRoom` and `ChatMember` models with additional fields and relationships. Update `AppDatabase` to include new chat-related entities and adjust permissions for chat creation.
This commit is contained in:
2025-05-02 19:51:32 +08:00
parent da6a891b5f
commit 17de9a0f23
18 changed files with 483 additions and 1819 deletions

View File

@ -2,6 +2,7 @@ using System.Collections.Concurrent;
using System.Net.WebSockets;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Swashbuckle.AspNetCore.Annotations;
namespace DysonNetwork.Sphere.Connection;
@ -52,7 +53,7 @@ public class WebSocketController(WebSocketService ws, ILogger<WebSocketContext>
try
{
await _ConnectionEventLoop(connectionKey, webSocket, cts.Token);
await _ConnectionEventLoop(deviceId, currentUser, webSocket, cts.Token);
}
catch (Exception ex)
{
@ -67,11 +68,14 @@ public class WebSocketController(WebSocketService ws, ILogger<WebSocketContext>
}
private async Task _ConnectionEventLoop(
(long AccountId, string DeviceId) connectionKey,
string deviceId,
Account.Account currentUser,
WebSocket webSocket,
CancellationToken cancellationToken
)
{
var connectionKey = (AccountId: currentUser.Id, DeviceId: deviceId);
var buffer = new byte[1024 * 4];
try
{
@ -85,9 +89,11 @@ public class WebSocketController(WebSocketService ws, ILogger<WebSocketContext>
new ArraySegment<byte>(buffer),
cancellationToken
);
}
// TODO handle values
var packet = WebSocketPacket.FromBytes(buffer[..receiveResult.Count]);
if (packet is null) continue;
ws.HandlePacket(currentUser, connectionKey.DeviceId, packet, webSocket);
}
}
catch (OperationCanceledException)
{

View File

@ -0,0 +1,62 @@
using System.Text.Json;
public class WebSocketPacketType
{
public const string Error = "error";
}
public class WebSocketPacket
{
public string Type { get; set; } = null!;
public object Data { get; set; }
public string? ErrorMessage { get; set; }
/// <summary>
/// Creates a WebSocketPacket from raw WebSocket message bytes
/// </summary>
/// <param name="bytes">Raw WebSocket message bytes</param>
/// <returns>Deserialized WebSocketPacket</returns>
public static WebSocketPacket FromBytes(byte[] bytes)
{
var json = System.Text.Encoding.UTF8.GetString(bytes);
var jsonOpts = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower,
DictionaryKeyPolicy = JsonNamingPolicy.SnakeCaseLower,
};
return JsonSerializer.Deserialize<WebSocketPacket>(json, jsonOpts) ??
throw new JsonException("Failed to deserialize WebSocketPacket");
}
/// <summary>
/// Deserializes the Data property to the specified type T
/// </summary>
/// <typeparam name="T">Target type to deserialize to</typeparam>
/// <returns>Deserialized data of type T</returns>
public T? GetData<T>()
{
if (Data == null)
return default;
if (Data is T typedData)
return typedData;
return JsonSerializer.Deserialize<T>(
JsonSerializer.Serialize(Data)
);
}
/// <summary>
/// Serializes this WebSocketPacket to a byte array for sending over WebSocket
/// </summary>
/// <returns>Byte array representation of the packet</returns>
public byte[] ToBytes()
{
var jsonOpts = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower,
DictionaryKeyPolicy = JsonNamingPolicy.SnakeCaseLower,
};
var json = JsonSerializer.Serialize(this, jsonOpts);
return System.Text.Encoding.UTF8.GetBytes(json);
}
}

View File

@ -3,7 +3,7 @@ using System.Net.WebSockets;
namespace DysonNetwork.Sphere.Connection;
public class WebSocketService
public class WebSocketService(ChatService cs)
{
public static readonly ConcurrentDictionary<
(long AccountId, string DeviceId),
@ -32,4 +32,41 @@ public class WebSocketService
data.Cts.Cancel();
ActiveConnections.TryRemove(key, out _);
}
public void HandlePacket(Account.Account currentUser, string deviceId, WebSocketPacket packet, WebSocket socket)
{
switch (packet.Type)
{
case "message.read":
var request = packet.GetData<ChatController.MarkMessageReadRequest>();
if (request is null)
{
socket.SendAsync(
new ArraySegment<byte>(new WebSocketPacket
{
Type = WebSocketPacketType.Error,
ErrorMessage = "Mark message as read requires you provide the ChatRoomId and MessageId"
}.ToBytes()),
WebSocketMessageType.Binary,
true,
CancellationToken.None
);
break;
}
_ = cs.MarkMessageAsReadAsync(request.MessageId, currentUser.Id, currentUser.Id).ConfigureAwait(false);
break;
default:
socket.SendAsync(
new ArraySegment<byte>(new WebSocketPacket
{
Type = WebSocketPacketType.Error,
ErrorMessage = $"Unprocessable packet: {packet.Type}"
}.ToBytes()),
WebSocketMessageType.Binary,
true,
CancellationToken.None
);
break;
}
}
}