Add chat service, collection clone/tier rules, social graph
SOR.Chat (new project):
- 10 WebSocket message handlers: send, get_channels, get_messages,
dm_open, friend_request, friend_respond, friend_remove, block,
unblock, get_social
- Cursor-based pagination for message history
- Block checks on DM send and dm_open
- Social graph: friends / pending requests (in+out) / blocked list
- Batch identity DB lookups for display names
Collection updates:
- clone_deck handler (copy deck + re-validate)
- Tier-chain validation: deck ArchSpirit must be Tier 1 (hard rule);
warn on Tier 2+ card without previous tier present (soft warning)
- Tier 2+ ArchSpirits now allowed in card list as ascension targets
- ValidationWarnings field added to DeckSummaryDto + DeckDetailDto
Database:
- CardDefinition.PreviousTierId self-reference FK for ascension chains
- FriendRequest + BlockedUser entities in chat schema
- ChatChannelType.System + FriendRequestStatus enum values
- Migrations: AddArchSpiritTierChain (catalog), AddSocialGraph (chat)
Admin portal:
- ChatOverview (/chat) — stats + channel list with type filter
- ChatChannelViewer (/chat/channel/{id}) — message history + system
message compose for admins
- SocialModerationPage (/chat/social) — friend/block lookup + actions
- NavMenu: Chat section with Social Graph sub-item
Generated with [Claude Code](https://claude.ai/code)
via [Happy](https://happy.engineering)
Co-Authored-By: Claude <noreply@anthropic.com>
Co-Authored-By: Happy <yesreply@happy.engineering>
This commit is contained in:
@@ -0,0 +1,11 @@
|
||||
namespace SOR.Chat;
|
||||
|
||||
public static class ChatLimits
|
||||
{
|
||||
/// <summary>Maximum characters in a single chat message.</summary>
|
||||
public const int MaxMessageLength = 500;
|
||||
|
||||
/// <summary>Default and maximum messages returned per page.</summary>
|
||||
public const int DefaultPageSize = 50;
|
||||
public const int MaxPageSize = 100;
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
namespace SOR.Chat;
|
||||
|
||||
// ── Request types (client → server) ──────────────────────────────────────────
|
||||
|
||||
/// <summary>Send a message to a channel the caller is a member of.</summary>
|
||||
public sealed record SendMessageRequest(Guid ChannelId, string Content);
|
||||
|
||||
/// <summary>List all channels the caller is currently a member of.</summary>
|
||||
public sealed record GetChannelsRequest; // identity from connection
|
||||
|
||||
/// <summary>
|
||||
/// Fetch message history for a channel.
|
||||
/// BeforeMessageId enables cursor-based pagination: pass the oldest
|
||||
/// message Id from the previous page to load earlier messages.
|
||||
/// Null = start from the most recent messages.
|
||||
/// </summary>
|
||||
public sealed record GetMessagesRequest(
|
||||
Guid ChannelId,
|
||||
Guid? BeforeMessageId = null,
|
||||
int PageSize = ChatLimits.DefaultPageSize);
|
||||
|
||||
/// <summary>
|
||||
/// Open (or retrieve) the DM channel with another player.
|
||||
/// Creates the channel and adds both members if it does not already exist.
|
||||
/// Fails if the recipient has blocked the caller or vice-versa.
|
||||
/// </summary>
|
||||
public sealed record DmOpenRequest(Guid RecipientAccountId);
|
||||
|
||||
/// <summary>Send a friend request to another player.</summary>
|
||||
public sealed record FriendRequestRequest(Guid RecipientAccountId);
|
||||
|
||||
/// <summary>Accept or decline an incoming friend request.</summary>
|
||||
public sealed record FriendRespondRequest(Guid RequestId, bool Accept);
|
||||
|
||||
/// <summary>Remove an existing friendship.</summary>
|
||||
public sealed record FriendRemoveRequest(Guid FriendAccountId);
|
||||
|
||||
/// <summary>Block a player (dissolves friendship and any pending friend request).</summary>
|
||||
public sealed record BlockRequest(Guid TargetAccountId);
|
||||
|
||||
/// <summary>Remove a block previously placed on a player.</summary>
|
||||
public sealed record UnblockRequest(Guid TargetAccountId);
|
||||
|
||||
/// <summary>Returns friends, pending requests, and blocked users for the caller.</summary>
|
||||
public sealed record GetSocialRequest; // identity from connection
|
||||
|
||||
// ── Response / DTO types (server → client) ────────────────────────────────────
|
||||
|
||||
public sealed record SendMessageResponse(ChatMessageDto Message);
|
||||
|
||||
public sealed record GetChannelsResponse(IEnumerable<ChatChannelDto> Channels);
|
||||
|
||||
public sealed record GetMessagesResponse(
|
||||
IEnumerable<ChatMessageDto> Messages,
|
||||
bool HasMore);
|
||||
|
||||
public sealed record DmOpenResponse(Guid ChannelId);
|
||||
|
||||
public sealed record GetSocialResponse(
|
||||
IEnumerable<FriendDto> Friends,
|
||||
IEnumerable<FriendRequestDto> IncomingRequests,
|
||||
IEnumerable<FriendRequestDto> OutgoingRequests,
|
||||
IEnumerable<BlockedUserDto> Blocked);
|
||||
|
||||
// ── DTOs ────────────────────────────────────────────────────────────────────
|
||||
|
||||
public sealed record ChatChannelDto(
|
||||
Guid Id,
|
||||
string Name,
|
||||
string ChannelType,
|
||||
DateTimeOffset CreatedAt);
|
||||
|
||||
public sealed record ChatMessageDto(
|
||||
Guid Id,
|
||||
Guid ChannelId,
|
||||
Guid SenderAccountId,
|
||||
string SenderDisplayName,
|
||||
string Content,
|
||||
DateTimeOffset SentAt,
|
||||
DateTimeOffset? EditedAt,
|
||||
bool IsDeleted);
|
||||
|
||||
public sealed record FriendDto(
|
||||
Guid AccountId,
|
||||
string DisplayName,
|
||||
DateTimeOffset FriendsSince);
|
||||
|
||||
public sealed record FriendRequestDto(
|
||||
Guid RequestId,
|
||||
Guid OtherAccountId,
|
||||
string OtherDisplayName,
|
||||
DateTimeOffset CreatedAt);
|
||||
|
||||
public sealed record BlockedUserDto(
|
||||
Guid AccountId,
|
||||
string DisplayName,
|
||||
DateTimeOffset BlockedAt);
|
||||
@@ -0,0 +1,73 @@
|
||||
namespace SOR.Chat.Handlers;
|
||||
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using SOR.Database.Contexts;
|
||||
using SOR.Database.Entities.Chat;
|
||||
using SOR.Database.Enums;
|
||||
using SOR.Networking.Abstractions.Messaging;
|
||||
using SOR.Networking.Abstractions.Transport;
|
||||
using SOR.Shared.Networking;
|
||||
|
||||
/// <summary>
|
||||
/// chat.block — blocks another player.
|
||||
///
|
||||
/// Effects:
|
||||
/// - Creates a BlockedUser row (idempotent if already blocked).
|
||||
/// - Dissolves any existing friendship between the two players.
|
||||
/// - Removes any pending friend request between them.
|
||||
/// </summary>
|
||||
internal sealed class ChatBlockHandler : ChatHandlerBase, IMessageHandler
|
||||
{
|
||||
private readonly IMessageSerializer _serializer;
|
||||
private readonly ChatDbContext _chatDb;
|
||||
|
||||
public ChatBlockHandler(
|
||||
IMessageSerializer serializer,
|
||||
ChatDbContext chatDb)
|
||||
{
|
||||
_serializer = serializer;
|
||||
_chatDb = chatDb;
|
||||
}
|
||||
|
||||
public string MessageType => "chat.block";
|
||||
|
||||
public async Task<IServerMessage?> HandleAsync(
|
||||
IClientMessage message,
|
||||
AuthenticatedConnection connection,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var req = _serializer.DeserializePayload<BlockRequest>(message.Payload);
|
||||
var accountId = Guid.Parse(connection.UserId);
|
||||
|
||||
if (req.TargetAccountId == accountId)
|
||||
return ServerMessage.Error(message.Seq, "INVALID_TARGET", "Cannot block yourself.");
|
||||
|
||||
// ── Idempotent block ──────────────────────────────────────────────────
|
||||
var alreadyBlocked = await _chatDb.BlockedUsers.AnyAsync(
|
||||
b => b.BlockerAccountId == accountId && b.BlockedAccountId == req.TargetAccountId,
|
||||
cancellationToken);
|
||||
|
||||
if (!alreadyBlocked)
|
||||
{
|
||||
_chatDb.BlockedUsers.Add(new BlockedUser
|
||||
{
|
||||
BlockerAccountId = accountId,
|
||||
BlockedAccountId = req.TargetAccountId,
|
||||
BlockedAt = DateTimeOffset.UtcNow,
|
||||
});
|
||||
}
|
||||
|
||||
// ── Dissolve friendship or pending requests ────────────────────────────
|
||||
var socialRow = await _chatDb.FriendRequests.FirstOrDefaultAsync(
|
||||
f => (f.RequesterAccountId == accountId && f.RecipientAccountId == req.TargetAccountId)
|
||||
|| (f.RequesterAccountId == req.TargetAccountId && f.RecipientAccountId == accountId),
|
||||
cancellationToken);
|
||||
|
||||
if (socialRow != null)
|
||||
_chatDb.FriendRequests.Remove(socialRow);
|
||||
|
||||
await _chatDb.SaveChangesAsync(cancellationToken);
|
||||
|
||||
return ServerMessage.Reply("chat.block.ack", message.Seq, new { });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
namespace SOR.Chat.Handlers;
|
||||
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using SOR.Database.Contexts;
|
||||
using SOR.Database.Entities.Chat;
|
||||
using SOR.Database.Enums;
|
||||
using SOR.Networking.Abstractions.Messaging;
|
||||
using SOR.Networking.Abstractions.Transport;
|
||||
using SOR.Shared.Networking;
|
||||
|
||||
/// <summary>
|
||||
/// chat.dm_open — opens (or retrieves) a DM channel between the caller and a recipient.
|
||||
///
|
||||
/// If the channel already exists it is returned immediately.
|
||||
/// Fails if either player has blocked the other.
|
||||
/// </summary>
|
||||
internal sealed class ChatDmOpenHandler : ChatHandlerBase, IMessageHandler
|
||||
{
|
||||
private readonly IMessageSerializer _serializer;
|
||||
private readonly ChatDbContext _chatDb;
|
||||
|
||||
public ChatDmOpenHandler(
|
||||
IMessageSerializer serializer,
|
||||
ChatDbContext chatDb)
|
||||
{
|
||||
_serializer = serializer;
|
||||
_chatDb = chatDb;
|
||||
}
|
||||
|
||||
public string MessageType => "chat.dm_open";
|
||||
|
||||
public async Task<IServerMessage?> HandleAsync(
|
||||
IClientMessage message,
|
||||
AuthenticatedConnection connection,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var req = _serializer.DeserializePayload<DmOpenRequest>(message.Payload);
|
||||
var accountId = Guid.Parse(connection.UserId);
|
||||
|
||||
if (req.RecipientAccountId == accountId)
|
||||
return ServerMessage.Error(message.Seq, "INVALID_RECIPIENT", "Cannot open a DM with yourself.");
|
||||
|
||||
// ── Block check ───────────────────────────────────────────────────────
|
||||
var blocked = await IsBlockedEitherWayAsync(_chatDb, accountId, req.RecipientAccountId, cancellationToken);
|
||||
if (blocked)
|
||||
return ServerMessage.Error(message.Seq, "BLOCKED", "Cannot open a DM with this user.");
|
||||
|
||||
// ── Find existing DM channel ──────────────────────────────────────────
|
||||
// A DM channel exists if both accounts are active members of the same Direct channel.
|
||||
var existingChannelId = await _chatDb.Members
|
||||
.Where(m => m.AccountId == accountId && m.LeftAt == null)
|
||||
.Select(m => m.ChannelId)
|
||||
.Intersect(
|
||||
_chatDb.Members
|
||||
.Where(m => m.AccountId == req.RecipientAccountId && m.LeftAt == null)
|
||||
.Select(m => m.ChannelId))
|
||||
.Join(
|
||||
_chatDb.Channels.Where(c => c.ChannelType == ChatChannelType.Direct),
|
||||
id => id,
|
||||
c => c.Id,
|
||||
(id, c) => c.Id)
|
||||
.FirstOrDefaultAsync(cancellationToken);
|
||||
|
||||
if (existingChannelId != Guid.Empty)
|
||||
return ServerMessage.Reply("chat.dm_open.ack", message.Seq,
|
||||
new DmOpenResponse(existingChannelId));
|
||||
|
||||
// ── Create new DM channel ─────────────────────────────────────────────
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
var channel = new ChatChannel
|
||||
{
|
||||
Name = "dm",
|
||||
ChannelType = ChatChannelType.Direct,
|
||||
CreatedAt = now,
|
||||
};
|
||||
_chatDb.Channels.Add(channel);
|
||||
await _chatDb.SaveChangesAsync(cancellationToken);
|
||||
|
||||
_chatDb.Members.Add(new ChatMember { ChannelId = channel.Id, AccountId = accountId, JoinedAt = now });
|
||||
_chatDb.Members.Add(new ChatMember { ChannelId = channel.Id, AccountId = req.RecipientAccountId, JoinedAt = now });
|
||||
await _chatDb.SaveChangesAsync(cancellationToken);
|
||||
|
||||
return ServerMessage.Reply("chat.dm_open.ack", message.Seq,
|
||||
new DmOpenResponse(channel.Id));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
namespace SOR.Chat.Handlers;
|
||||
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using SOR.Database.Contexts;
|
||||
using SOR.Database.Enums;
|
||||
using SOR.Networking.Abstractions.Messaging;
|
||||
using SOR.Networking.Abstractions.Transport;
|
||||
using SOR.Shared.Networking;
|
||||
|
||||
/// <summary>
|
||||
/// chat.friend_remove — removes an existing friendship.
|
||||
///
|
||||
/// Hard-deletes the FriendRequest row so both players can re-friend later.
|
||||
/// </summary>
|
||||
internal sealed class ChatFriendRemoveHandler : ChatHandlerBase, IMessageHandler
|
||||
{
|
||||
private readonly IMessageSerializer _serializer;
|
||||
private readonly ChatDbContext _chatDb;
|
||||
|
||||
public ChatFriendRemoveHandler(
|
||||
IMessageSerializer serializer,
|
||||
ChatDbContext chatDb)
|
||||
{
|
||||
_serializer = serializer;
|
||||
_chatDb = chatDb;
|
||||
}
|
||||
|
||||
public string MessageType => "chat.friend_remove";
|
||||
|
||||
public async Task<IServerMessage?> HandleAsync(
|
||||
IClientMessage message,
|
||||
AuthenticatedConnection connection,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var req = _serializer.DeserializePayload<FriendRemoveRequest>(message.Payload);
|
||||
var accountId = Guid.Parse(connection.UserId);
|
||||
|
||||
var friendship = await _chatDb.FriendRequests.FirstOrDefaultAsync(
|
||||
f => f.Status == FriendRequestStatus.Accepted
|
||||
&& ((f.RequesterAccountId == accountId && f.RecipientAccountId == req.FriendAccountId)
|
||||
|| (f.RequesterAccountId == req.FriendAccountId && f.RecipientAccountId == accountId)),
|
||||
cancellationToken);
|
||||
|
||||
if (friendship == null)
|
||||
return ServerMessage.Error(message.Seq, "NOT_FRIENDS", "You are not friends with this player.");
|
||||
|
||||
_chatDb.FriendRequests.Remove(friendship);
|
||||
await _chatDb.SaveChangesAsync(cancellationToken);
|
||||
|
||||
return ServerMessage.Reply("chat.friend_remove.ack", message.Seq, new { });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
namespace SOR.Chat.Handlers;
|
||||
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using SOR.Database.Contexts;
|
||||
using SOR.Database.Entities.Chat;
|
||||
using SOR.Database.Enums;
|
||||
using SOR.Networking.Abstractions.Messaging;
|
||||
using SOR.Networking.Abstractions.Transport;
|
||||
using SOR.Shared.Networking;
|
||||
|
||||
/// <summary>
|
||||
/// chat.friend_request — sends a friend request to another player.
|
||||
///
|
||||
/// Fails if: already friends, already have a pending request, or either player has blocked the other.
|
||||
/// </summary>
|
||||
internal sealed class ChatFriendRequestHandler : ChatHandlerBase, IMessageHandler
|
||||
{
|
||||
private readonly IMessageSerializer _serializer;
|
||||
private readonly ChatDbContext _chatDb;
|
||||
|
||||
public ChatFriendRequestHandler(
|
||||
IMessageSerializer serializer,
|
||||
ChatDbContext chatDb)
|
||||
{
|
||||
_serializer = serializer;
|
||||
_chatDb = chatDb;
|
||||
}
|
||||
|
||||
public string MessageType => "chat.friend_request";
|
||||
|
||||
public async Task<IServerMessage?> HandleAsync(
|
||||
IClientMessage message,
|
||||
AuthenticatedConnection connection,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var req = _serializer.DeserializePayload<FriendRequestRequest>(message.Payload);
|
||||
var accountId = Guid.Parse(connection.UserId);
|
||||
|
||||
if (req.RecipientAccountId == accountId)
|
||||
return ServerMessage.Error(message.Seq, "INVALID_RECIPIENT", "Cannot send a friend request to yourself.");
|
||||
|
||||
// ── Block check ───────────────────────────────────────────────────────
|
||||
var blocked = await IsBlockedEitherWayAsync(_chatDb, accountId, req.RecipientAccountId, cancellationToken);
|
||||
if (blocked)
|
||||
return ServerMessage.Error(message.Seq, "BLOCKED", "Cannot send a friend request to this user.");
|
||||
|
||||
// ── Existing relationship check ────────────────────────────────────────
|
||||
var existing = await _chatDb.FriendRequests.FirstOrDefaultAsync(
|
||||
f => (f.RequesterAccountId == accountId && f.RecipientAccountId == req.RecipientAccountId)
|
||||
|| (f.RequesterAccountId == req.RecipientAccountId && f.RecipientAccountId == accountId),
|
||||
cancellationToken);
|
||||
|
||||
if (existing != null)
|
||||
{
|
||||
if (existing.Status == FriendRequestStatus.Accepted)
|
||||
return ServerMessage.Error(message.Seq, "ALREADY_FRIENDS", "You are already friends.");
|
||||
if (existing.Status == FriendRequestStatus.Pending)
|
||||
return ServerMessage.Error(message.Seq, "REQUEST_EXISTS", "A friend request already exists between you and this player.");
|
||||
// Declined: allow a new request by updating the row back to Pending.
|
||||
existing.Status = FriendRequestStatus.Pending;
|
||||
existing.RequesterAccountId = accountId;
|
||||
existing.RecipientAccountId = req.RecipientAccountId;
|
||||
existing.UpdatedAt = DateTimeOffset.UtcNow;
|
||||
await _chatDb.SaveChangesAsync(cancellationToken);
|
||||
return ServerMessage.Reply("chat.friend_request.ack", message.Seq, new { });
|
||||
}
|
||||
|
||||
// ── Create new request ────────────────────────────────────────────────
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
_chatDb.FriendRequests.Add(new FriendRequest
|
||||
{
|
||||
RequesterAccountId = accountId,
|
||||
RecipientAccountId = req.RecipientAccountId,
|
||||
Status = FriendRequestStatus.Pending,
|
||||
CreatedAt = now,
|
||||
UpdatedAt = now,
|
||||
});
|
||||
await _chatDb.SaveChangesAsync(cancellationToken);
|
||||
|
||||
return ServerMessage.Reply("chat.friend_request.ack", message.Seq, new { });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
namespace SOR.Chat.Handlers;
|
||||
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using SOR.Database.Contexts;
|
||||
using SOR.Database.Enums;
|
||||
using SOR.Networking.Abstractions.Messaging;
|
||||
using SOR.Networking.Abstractions.Transport;
|
||||
using SOR.Shared.Networking;
|
||||
|
||||
/// <summary>
|
||||
/// chat.friend_respond — accept or decline an incoming friend request.
|
||||
///
|
||||
/// Only the recipient of the request may respond to it.
|
||||
/// </summary>
|
||||
internal sealed class ChatFriendRespondHandler : ChatHandlerBase, IMessageHandler
|
||||
{
|
||||
private readonly IMessageSerializer _serializer;
|
||||
private readonly ChatDbContext _chatDb;
|
||||
|
||||
public ChatFriendRespondHandler(
|
||||
IMessageSerializer serializer,
|
||||
ChatDbContext chatDb)
|
||||
{
|
||||
_serializer = serializer;
|
||||
_chatDb = chatDb;
|
||||
}
|
||||
|
||||
public string MessageType => "chat.friend_respond";
|
||||
|
||||
public async Task<IServerMessage?> HandleAsync(
|
||||
IClientMessage message,
|
||||
AuthenticatedConnection connection,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var req = _serializer.DeserializePayload<FriendRespondRequest>(message.Payload);
|
||||
var accountId = Guid.Parse(connection.UserId);
|
||||
|
||||
var request = await _chatDb.FriendRequests
|
||||
.FirstOrDefaultAsync(f => f.Id == req.RequestId, cancellationToken);
|
||||
|
||||
if (request == null)
|
||||
return ServerMessage.Error(message.Seq, "REQUEST_NOT_FOUND", "Friend request not found.");
|
||||
|
||||
if (request.RecipientAccountId != accountId)
|
||||
return ServerMessage.Error(message.Seq, "NOT_RECIPIENT", "You are not the recipient of this request.");
|
||||
|
||||
if (request.Status != FriendRequestStatus.Pending)
|
||||
return ServerMessage.Error(message.Seq, "REQUEST_NOT_PENDING", "This request has already been responded to.");
|
||||
|
||||
request.Status = req.Accept ? FriendRequestStatus.Accepted : FriendRequestStatus.Declined;
|
||||
request.UpdatedAt = DateTimeOffset.UtcNow;
|
||||
await _chatDb.SaveChangesAsync(cancellationToken);
|
||||
|
||||
return ServerMessage.Reply("chat.friend_respond.ack", message.Seq, new { Accepted = req.Accept });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
namespace SOR.Chat.Handlers;
|
||||
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using SOR.Database.Contexts;
|
||||
using SOR.Networking.Abstractions.Messaging;
|
||||
using SOR.Networking.Abstractions.Transport;
|
||||
using SOR.Shared.Networking;
|
||||
|
||||
/// <summary>
|
||||
/// chat.get_channels — returns all channels the caller is currently a member of.
|
||||
/// </summary>
|
||||
internal sealed class ChatGetChannelsHandler : ChatHandlerBase, IMessageHandler
|
||||
{
|
||||
private readonly ChatDbContext _chatDb;
|
||||
|
||||
public ChatGetChannelsHandler(ChatDbContext chatDb)
|
||||
=> _chatDb = chatDb;
|
||||
|
||||
public string MessageType => "chat.get_channels";
|
||||
|
||||
public async Task<IServerMessage?> HandleAsync(
|
||||
IClientMessage message,
|
||||
AuthenticatedConnection connection,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var accountId = Guid.Parse(connection.UserId);
|
||||
|
||||
var channels = await _chatDb.Members
|
||||
.Where(m => m.AccountId == accountId && m.LeftAt == null)
|
||||
.Select(m => m.Channel)
|
||||
.OrderBy(c => c.CreatedAt)
|
||||
.Select(c => new ChatChannelDto(
|
||||
c.Id,
|
||||
c.Name,
|
||||
c.ChannelType.ToString(),
|
||||
c.CreatedAt))
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
return ServerMessage.Reply("chat.get_channels.ack", message.Seq,
|
||||
new GetChannelsResponse(channels));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
namespace SOR.Chat.Handlers;
|
||||
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using SOR.Database.Contexts;
|
||||
using SOR.Networking.Abstractions.Messaging;
|
||||
using SOR.Networking.Abstractions.Transport;
|
||||
using SOR.Shared.Networking;
|
||||
|
||||
/// <summary>
|
||||
/// chat.get_messages — cursor-based message history for a channel.
|
||||
///
|
||||
/// Pages are returned newest-first. Pass the oldest SentAt/Id from the previous
|
||||
/// page as BeforeMessageId to load earlier messages.
|
||||
/// </summary>
|
||||
internal sealed class ChatGetMessagesHandler : ChatHandlerBase, IMessageHandler
|
||||
{
|
||||
private readonly IMessageSerializer _serializer;
|
||||
private readonly ChatDbContext _chatDb;
|
||||
private readonly SorIdentityDbContext _identityDb;
|
||||
|
||||
public ChatGetMessagesHandler(
|
||||
IMessageSerializer serializer,
|
||||
ChatDbContext chatDb,
|
||||
SorIdentityDbContext identityDb)
|
||||
{
|
||||
_serializer = serializer;
|
||||
_chatDb = chatDb;
|
||||
_identityDb = identityDb;
|
||||
}
|
||||
|
||||
public string MessageType => "chat.get_messages";
|
||||
|
||||
public async Task<IServerMessage?> HandleAsync(
|
||||
IClientMessage message,
|
||||
AuthenticatedConnection connection,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var req = _serializer.DeserializePayload<GetMessagesRequest>(message.Payload);
|
||||
var accountId = Guid.Parse(connection.UserId);
|
||||
|
||||
// Verify membership.
|
||||
var isMember = await _chatDb.Members
|
||||
.AnyAsync(m => m.ChannelId == req.ChannelId
|
||||
&& m.AccountId == accountId
|
||||
&& m.LeftAt == null, cancellationToken);
|
||||
if (!isMember)
|
||||
return ServerMessage.Error(message.Seq, "NOT_A_MEMBER", "You are not a member of this channel.");
|
||||
|
||||
var pageSize = Math.Clamp(req.PageSize, 1, ChatLimits.MaxPageSize);
|
||||
|
||||
IQueryable<SOR.Database.Entities.Chat.ChatMessage> query =
|
||||
_chatDb.Messages.Where(m => m.ChannelId == req.ChannelId);
|
||||
|
||||
if (req.BeforeMessageId.HasValue)
|
||||
{
|
||||
// Find the SentAt of the cursor message for efficient index use.
|
||||
var cursorSentAt = await _chatDb.Messages
|
||||
.Where(m => m.Id == req.BeforeMessageId.Value)
|
||||
.Select(m => (DateTimeOffset?)m.SentAt)
|
||||
.FirstOrDefaultAsync(cancellationToken);
|
||||
|
||||
if (cursorSentAt.HasValue)
|
||||
query = query.Where(m => m.SentAt < cursorSentAt.Value);
|
||||
}
|
||||
|
||||
// Fetch one extra to determine whether there are more pages.
|
||||
var rows = await query
|
||||
.OrderByDescending(m => m.SentAt)
|
||||
.Take(pageSize + 1)
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
var hasMore = rows.Count > pageSize;
|
||||
if (hasMore)
|
||||
rows.RemoveAt(rows.Count - 1);
|
||||
|
||||
// Batch-fetch display names.
|
||||
var senderIds = rows.Select(m => m.SenderAccountId).Distinct().ToList();
|
||||
var names = await GetDisplayNamesAsync(_identityDb, senderIds, cancellationToken);
|
||||
|
||||
var dtos = rows.Select(m =>
|
||||
ChatSendHandler.ToDto(m, names.GetValueOrDefault(m.SenderAccountId, m.SenderAccountId.ToString())));
|
||||
|
||||
return ServerMessage.Reply("chat.get_messages.ack", message.Seq,
|
||||
new GetMessagesResponse(dtos, hasMore));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
namespace SOR.Chat.Handlers;
|
||||
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using SOR.Database.Contexts;
|
||||
using SOR.Database.Enums;
|
||||
using SOR.Networking.Abstractions.Messaging;
|
||||
using SOR.Networking.Abstractions.Transport;
|
||||
using SOR.Shared.Networking;
|
||||
|
||||
/// <summary>
|
||||
/// chat.get_social — returns the caller's full social graph:
|
||||
/// • accepted friends
|
||||
/// • pending incoming friend requests
|
||||
/// • pending outgoing friend requests
|
||||
/// • blocked players
|
||||
/// </summary>
|
||||
internal sealed class ChatGetSocialHandler : ChatHandlerBase, IMessageHandler
|
||||
{
|
||||
private readonly ChatDbContext _chatDb;
|
||||
private readonly SorIdentityDbContext _identityDb;
|
||||
|
||||
public ChatGetSocialHandler(
|
||||
ChatDbContext chatDb,
|
||||
SorIdentityDbContext identityDb)
|
||||
{
|
||||
_chatDb = chatDb;
|
||||
_identityDb = identityDb;
|
||||
}
|
||||
|
||||
public string MessageType => "chat.get_social";
|
||||
|
||||
public async Task<IServerMessage?> HandleAsync(
|
||||
IClientMessage message,
|
||||
AuthenticatedConnection connection,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var accountId = Guid.Parse(connection.UserId);
|
||||
|
||||
// ── Load all social rows ──────────────────────────────────────────────
|
||||
var friendRows = await _chatDb.FriendRequests
|
||||
.Where(f => f.RequesterAccountId == accountId || f.RecipientAccountId == accountId)
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
var blockedRows = await _chatDb.BlockedUsers
|
||||
.Where(b => b.BlockerAccountId == accountId)
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
// ── Collect all account IDs that need display names ───────────────────
|
||||
var otherIds = new HashSet<Guid>();
|
||||
foreach (var f in friendRows)
|
||||
{
|
||||
otherIds.Add(f.RequesterAccountId);
|
||||
otherIds.Add(f.RecipientAccountId);
|
||||
}
|
||||
foreach (var b in blockedRows)
|
||||
otherIds.Add(b.BlockedAccountId);
|
||||
otherIds.Remove(accountId);
|
||||
|
||||
var names = await GetDisplayNamesAsync(_identityDb, otherIds, cancellationToken);
|
||||
|
||||
// ── Project ───────────────────────────────────────────────────────────
|
||||
var friends = friendRows
|
||||
.Where(f => f.Status == FriendRequestStatus.Accepted)
|
||||
.Select(f =>
|
||||
{
|
||||
var otherId = f.RequesterAccountId == accountId ? f.RecipientAccountId : f.RequesterAccountId;
|
||||
return new FriendDto(otherId, names.GetValueOrDefault(otherId, otherId.ToString()), f.UpdatedAt);
|
||||
})
|
||||
.ToList();
|
||||
|
||||
var incoming = friendRows
|
||||
.Where(f => f.Status == FriendRequestStatus.Pending && f.RecipientAccountId == accountId)
|
||||
.Select(f => new FriendRequestDto(
|
||||
f.Id,
|
||||
f.RequesterAccountId,
|
||||
names.GetValueOrDefault(f.RequesterAccountId, f.RequesterAccountId.ToString()),
|
||||
f.CreatedAt))
|
||||
.ToList();
|
||||
|
||||
var outgoing = friendRows
|
||||
.Where(f => f.Status == FriendRequestStatus.Pending && f.RequesterAccountId == accountId)
|
||||
.Select(f => new FriendRequestDto(
|
||||
f.Id,
|
||||
f.RecipientAccountId,
|
||||
names.GetValueOrDefault(f.RecipientAccountId, f.RecipientAccountId.ToString()),
|
||||
f.CreatedAt))
|
||||
.ToList();
|
||||
|
||||
var blocked = blockedRows
|
||||
.Select(b => new BlockedUserDto(
|
||||
b.BlockedAccountId,
|
||||
names.GetValueOrDefault(b.BlockedAccountId, b.BlockedAccountId.ToString()),
|
||||
b.BlockedAt))
|
||||
.ToList();
|
||||
|
||||
return ServerMessage.Reply("chat.get_social.ack", message.Seq,
|
||||
new GetSocialResponse(friends, incoming, outgoing, blocked));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
namespace SOR.Chat.Handlers;
|
||||
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using SOR.Database.Contexts;
|
||||
using SOR.Database.Entities.Identity;
|
||||
|
||||
/// <summary>
|
||||
/// Shared helpers for all chat message handlers.
|
||||
/// </summary>
|
||||
internal abstract class ChatHandlerBase
|
||||
{
|
||||
/// <summary>
|
||||
/// Batch-fetches display names for a set of account IDs from the identity DB.
|
||||
/// Returns a dictionary keyed by AccountId → DisplayName (or email fallback).
|
||||
/// </summary>
|
||||
protected static async Task<Dictionary<Guid, string>> GetDisplayNamesAsync(
|
||||
SorIdentityDbContext identityDb,
|
||||
IEnumerable<Guid> accountIds,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var ids = accountIds.Distinct().ToList();
|
||||
if (ids.Count == 0)
|
||||
return new Dictionary<Guid, string>();
|
||||
|
||||
return await identityDb.Set<Account>()
|
||||
.Where(a => ids.Contains(a.Id))
|
||||
.ToDictionaryAsync(
|
||||
a => a.Id,
|
||||
a => a.DisplayName ?? a.Email ?? a.Id.ToString(),
|
||||
ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns true if either player has blocked the other.
|
||||
/// </summary>
|
||||
protected static async Task<bool> IsBlockedEitherWayAsync(
|
||||
ChatDbContext chatDb,
|
||||
Guid playerA,
|
||||
Guid playerB,
|
||||
CancellationToken ct)
|
||||
=> await chatDb.BlockedUsers.AnyAsync(
|
||||
b => (b.BlockerAccountId == playerA && b.BlockedAccountId == playerB)
|
||||
|| (b.BlockerAccountId == playerB && b.BlockedAccountId == playerA),
|
||||
ct);
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
namespace SOR.Chat.Handlers;
|
||||
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using SOR.Database.Contexts;
|
||||
using SOR.Database.Entities.Chat;
|
||||
using SOR.Database.Enums;
|
||||
using SOR.Networking.Abstractions.Messaging;
|
||||
using SOR.Networking.Abstractions.Transport;
|
||||
using SOR.Shared.Networking;
|
||||
|
||||
/// <summary>
|
||||
/// chat.send — sends a message to a channel the caller is a member of.
|
||||
///
|
||||
/// For DM channels: rejects the send if either participant has blocked the other.
|
||||
/// </summary>
|
||||
internal sealed class ChatSendHandler : ChatHandlerBase, IMessageHandler
|
||||
{
|
||||
private readonly IMessageSerializer _serializer;
|
||||
private readonly ChatDbContext _chatDb;
|
||||
private readonly SorIdentityDbContext _identityDb;
|
||||
|
||||
public ChatSendHandler(
|
||||
IMessageSerializer serializer,
|
||||
ChatDbContext chatDb,
|
||||
SorIdentityDbContext identityDb)
|
||||
{
|
||||
_serializer = serializer;
|
||||
_chatDb = chatDb;
|
||||
_identityDb = identityDb;
|
||||
}
|
||||
|
||||
public string MessageType => "chat.send";
|
||||
|
||||
public async Task<IServerMessage?> HandleAsync(
|
||||
IClientMessage message,
|
||||
AuthenticatedConnection connection,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var req = _serializer.DeserializePayload<SendMessageRequest>(message.Payload);
|
||||
var accountId = Guid.Parse(connection.UserId);
|
||||
|
||||
if (string.IsNullOrWhiteSpace(req.Content))
|
||||
return ServerMessage.Error(message.Seq, "EMPTY_MESSAGE", "Message content cannot be empty.");
|
||||
|
||||
if (req.Content.Length > ChatLimits.MaxMessageLength)
|
||||
return ServerMessage.Error(message.Seq, "MESSAGE_TOO_LONG",
|
||||
$"Message must be {ChatLimits.MaxMessageLength} characters or fewer.");
|
||||
|
||||
// ── Verify membership ──────────────────────────────────────────────────
|
||||
var channel = await _chatDb.Channels
|
||||
.Include(c => c.Members)
|
||||
.FirstOrDefaultAsync(c => c.Id == req.ChannelId, cancellationToken);
|
||||
|
||||
if (channel == null)
|
||||
return ServerMessage.Error(message.Seq, "CHANNEL_NOT_FOUND", "Channel not found.");
|
||||
|
||||
var member = channel.Members.FirstOrDefault(m => m.AccountId == accountId && m.LeftAt == null);
|
||||
if (member == null)
|
||||
return ServerMessage.Error(message.Seq, "NOT_A_MEMBER", "You are not a member of this channel.");
|
||||
|
||||
// ── DM block check ─────────────────────────────────────────────────────
|
||||
if (channel.ChannelType == ChatChannelType.Direct)
|
||||
{
|
||||
var otherMember = channel.Members.FirstOrDefault(m => m.AccountId != accountId && m.LeftAt == null);
|
||||
if (otherMember != null)
|
||||
{
|
||||
var blocked = await IsBlockedEitherWayAsync(_chatDb, accountId, otherMember.AccountId, cancellationToken);
|
||||
if (blocked)
|
||||
return ServerMessage.Error(message.Seq, "BLOCKED", "Cannot send messages to this user.");
|
||||
}
|
||||
}
|
||||
|
||||
// ── Persist ────────────────────────────────────────────────────────────
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
var chatMessage = new ChatMessage
|
||||
{
|
||||
ChannelId = req.ChannelId,
|
||||
SenderAccountId = accountId,
|
||||
Content = req.Content.Trim(),
|
||||
SentAt = now,
|
||||
};
|
||||
_chatDb.Messages.Add(chatMessage);
|
||||
await _chatDb.SaveChangesAsync(cancellationToken);
|
||||
|
||||
// ── Resolve sender display name ────────────────────────────────────────
|
||||
var names = await GetDisplayNamesAsync(_identityDb, new[] { accountId }, cancellationToken);
|
||||
var senderName = names.GetValueOrDefault(accountId, connection.DisplayName);
|
||||
|
||||
var dto = ToDto(chatMessage, senderName);
|
||||
|
||||
return ServerMessage.Reply("chat.send.ack", message.Seq, new SendMessageResponse(dto));
|
||||
}
|
||||
|
||||
internal static ChatMessageDto ToDto(ChatMessage m, string senderDisplayName)
|
||||
=> new(
|
||||
Id: m.Id,
|
||||
ChannelId: m.ChannelId,
|
||||
SenderAccountId: m.SenderAccountId,
|
||||
SenderDisplayName: senderDisplayName,
|
||||
Content: m.IsDeleted ? string.Empty : m.Content,
|
||||
SentAt: m.SentAt,
|
||||
EditedAt: m.EditedAt,
|
||||
IsDeleted: m.IsDeleted);
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
namespace SOR.Chat.Handlers;
|
||||
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using SOR.Database.Contexts;
|
||||
using SOR.Networking.Abstractions.Messaging;
|
||||
using SOR.Networking.Abstractions.Transport;
|
||||
using SOR.Shared.Networking;
|
||||
|
||||
/// <summary>
|
||||
/// chat.unblock — removes a block the caller placed on another player.
|
||||
/// </summary>
|
||||
internal sealed class ChatUnblockHandler : ChatHandlerBase, IMessageHandler
|
||||
{
|
||||
private readonly IMessageSerializer _serializer;
|
||||
private readonly ChatDbContext _chatDb;
|
||||
|
||||
public ChatUnblockHandler(
|
||||
IMessageSerializer serializer,
|
||||
ChatDbContext chatDb)
|
||||
{
|
||||
_serializer = serializer;
|
||||
_chatDb = chatDb;
|
||||
}
|
||||
|
||||
public string MessageType => "chat.unblock";
|
||||
|
||||
public async Task<IServerMessage?> HandleAsync(
|
||||
IClientMessage message,
|
||||
AuthenticatedConnection connection,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var req = _serializer.DeserializePayload<UnblockRequest>(message.Payload);
|
||||
var accountId = Guid.Parse(connection.UserId);
|
||||
|
||||
var block = await _chatDb.BlockedUsers.FirstOrDefaultAsync(
|
||||
b => b.BlockerAccountId == accountId && b.BlockedAccountId == req.TargetAccountId,
|
||||
cancellationToken);
|
||||
|
||||
if (block == null)
|
||||
return ServerMessage.Error(message.Seq, "NOT_BLOCKED", "This player is not in your block list.");
|
||||
|
||||
_chatDb.BlockedUsers.Remove(block);
|
||||
await _chatDb.SaveChangesAsync(cancellationToken);
|
||||
|
||||
return ServerMessage.Reply("chat.unblock.ack", message.Seq, new { });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<AssemblyName>SOR.Chat</AssemblyName>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<FrameworkReference Include="Microsoft.AspNetCore.App" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\SOR.Database\SOR.Database.csproj" />
|
||||
<ProjectReference Include="..\SOR.Networking.Abstractions\SOR.Networking.Abstractions.csproj" />
|
||||
<ProjectReference Include="..\SOR.Shared\SOR.Shared.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,37 @@
|
||||
namespace SOR.Chat;
|
||||
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using SOR.Chat.Handlers;
|
||||
using SOR.Database;
|
||||
using SOR.Networking.Abstractions.Messaging;
|
||||
|
||||
/// <summary>
|
||||
/// Registers all chat service components into the DI container.
|
||||
/// Called from SOR.Host/Program.cs when ENABLED_SERVICES includes "chat".
|
||||
/// </summary>
|
||||
public static class ServiceRegistration
|
||||
{
|
||||
public static IServiceCollection AddChatService(
|
||||
this IServiceCollection services,
|
||||
IConfiguration configuration)
|
||||
{
|
||||
// Database contexts the chat service needs.
|
||||
services.AddChatDatabase(configuration);
|
||||
services.AddIdentityDatabase(configuration);
|
||||
|
||||
// Message handlers — one per message type, Transient lifetime.
|
||||
services.AddTransient<IMessageHandler, ChatSendHandler>();
|
||||
services.AddTransient<IMessageHandler, ChatGetChannelsHandler>();
|
||||
services.AddTransient<IMessageHandler, ChatGetMessagesHandler>();
|
||||
services.AddTransient<IMessageHandler, ChatDmOpenHandler>();
|
||||
services.AddTransient<IMessageHandler, ChatFriendRequestHandler>();
|
||||
services.AddTransient<IMessageHandler, ChatFriendRespondHandler>();
|
||||
services.AddTransient<IMessageHandler, ChatFriendRemoveHandler>();
|
||||
services.AddTransient<IMessageHandler, ChatBlockHandler>();
|
||||
services.AddTransient<IMessageHandler, ChatUnblockHandler>();
|
||||
services.AddTransient<IMessageHandler, ChatGetSocialHandler>();
|
||||
|
||||
return services;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user