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:
dingo
2026-02-25 13:16:43 -05:00
co-authored by Claude Happy
parent 0198aec9e5
commit c6dc56a350
40 changed files with 2709 additions and 39 deletions
+1
View File
@@ -3,6 +3,7 @@
<Project Path="src/SOR.Admin/SOR.Admin.csproj" />
<Project Path="src/SOR.Auth/SOR.Auth.csproj" />
<Project Path="src/SOR.Cdn/SOR.Cdn.csproj" />
<Project Path="src/SOR.Chat/SOR.Chat.csproj" />
<Project Path="src/SOR.Collection/SOR.Collection.csproj" />
<Project Path="src/SOR.Database/SOR.Database.csproj" />
<Project Path="src/SOR.Gateway/SOR.Gateway.csproj" />
@@ -41,6 +41,18 @@
</li>
</ul>
</li>
<li class="nav-item">
<NavLink class="nav-link text-white" href="/chat" Match="NavLinkMatch.All">
<i class="bi bi-chat-dots me-2"></i>Chat
</NavLink>
<ul class="nav nav-pills flex-column gap-1 ps-3 mt-1">
<li class="nav-item">
<NavLink class="nav-link text-white-50 py-1" href="/chat/social">
<i class="bi bi-people me-2"></i>Social Graph
</NavLink>
</li>
</ul>
</li>
<li class="nav-item">
<NavLink class="nav-link text-white" href="/feature-flags">
<i class="bi bi-toggles me-2"></i>Feature Flags
@@ -0,0 +1,250 @@
@page "/chat/channel/{ChannelId:guid}"
@using Microsoft.EntityFrameworkCore
@using SOR.Database.Contexts
@using SOR.Database.Entities.Chat
@using SOR.Database.Entities.Identity
@inject ChatDbContext ChatDb
@inject SorIdentityDbContext IdentityDb
<PageTitle>Channel Viewer — SOR Admin</PageTitle>
<nav aria-label="breadcrumb" class="mb-3">
<ol class="breadcrumb">
<li class="breadcrumb-item"><a href="/chat" class="text-decoration-none">Chat</a></li>
<li class="breadcrumb-item active">Channel</li>
</ol>
</nav>
@if (_loading)
{
<div class="text-muted">Loading...</div>
}
else if (_channel == null)
{
<div class="alert alert-danger">Channel not found.</div>
}
else
{
<div class="d-flex justify-content-between align-items-center mb-3">
<div>
<h4 class="fw-bold mb-0">
<span class="badge @TypeBadge(_channel.ChannelType) me-2">@_channel.ChannelType</span>
@_channel.Name
</h4>
<div class="text-muted small font-monospace">@_channel.Id</div>
</div>
<div class="text-muted small">Created @_channel.CreatedAt.ToString("yyyy-MM-dd HH:mm")</div>
</div>
<!-- System message compose (admins only) -->
@if (_channel.ChannelType != SOR.Database.Enums.ChatChannelType.Match)
{
<div class="card bg-dark text-white border-secondary mb-4">
<div class="card-header fw-semibold text-danger">
<i class="bi bi-megaphone me-1"></i>Post System Message
</div>
<div class="card-body">
<textarea class="form-control bg-dark text-white border-secondary mb-2"
rows="2" placeholder="System message content..."
@bind="_systemMessageText" maxlength="500"></textarea>
@if (!string.IsNullOrEmpty(_systemError))
{
<div class="text-danger small mb-2">@_systemError</div>
}
@if (_systemSuccess)
{
<div class="text-success small mb-2">Message posted.</div>
}
<button class="btn btn-sm btn-danger" @onclick="PostSystemMessageAsync"
disabled="@_posting">
@(_posting ? "Posting..." : "Post")
</button>
</div>
</div>
}
<!-- Message history -->
<div class="card bg-dark text-white border-secondary">
<div class="card-header d-flex justify-content-between align-items-center">
<span class="fw-semibold">Messages (newest first)</span>
<span class="text-muted small">@_messages.Count shown</span>
</div>
<div class="card-body p-0">
<table class="table table-dark table-hover mb-0 small">
<thead>
<tr>
<th style="width:160px">Sent</th>
<th style="width:180px">Sender</th>
<th>Content</th>
<th style="width:80px">Deleted</th>
</tr>
</thead>
<tbody>
@foreach (var m in _messages)
{
<tr class="@(m.IsDeleted ? "text-muted" : "")">
<td class="font-monospace">@m.SentAt.ToString("MM-dd HH:mm:ss")</td>
<td>
<span class="font-monospace">@(_senderNames.GetValueOrDefault(m.SenderAccountId, m.SenderAccountId.ToString()[..8]))</span>
</td>
<td>@(m.IsDeleted ? "[deleted]" : m.Content)</td>
<td>
@if (m.IsDeleted)
{
<span class="badge bg-secondary">yes</span>
}
</td>
</tr>
}
@if (!_messages.Any())
{
<tr>
<td colspan="4" class="text-center text-muted py-3">No messages.</td>
</tr>
}
</tbody>
</table>
</div>
@if (_hasMore)
{
<div class="card-footer text-center">
<button class="btn btn-sm btn-outline-secondary" @onclick="LoadMoreAsync"
disabled="@_loadingMore">
@(_loadingMore ? "Loading..." : "Load more")
</button>
</div>
}
</div>
}
@code {
[Parameter] public Guid ChannelId { get; set; }
private bool _loading = true;
private bool _loadingMore = false;
private bool _posting = false;
private bool _systemSuccess = false;
private string _systemError = "";
private string _systemMessageText = "";
private ChatChannel? _channel;
private List<ChatMessage> _messages = new();
private Dictionary<Guid, string> _senderNames = new();
private bool _hasMore = false;
private const int PageSize = 50;
// Sentinel: a fixed Guid used as the "system" sender for admin-injected messages.
// All-zeros so it's obvious in the DB this was a server-posted message.
private static readonly Guid SystemSenderId = Guid.Empty;
protected override async Task OnInitializedAsync()
{
_channel = await ChatDb.Channels
.Include(c => c.Members)
.FirstOrDefaultAsync(c => c.Id == ChannelId);
if (_channel == null)
{
_loading = false;
return;
}
await LoadPageAsync(null);
_loading = false;
}
private async Task LoadPageAsync(DateTimeOffset? before)
{
IQueryable<ChatMessage> q = ChatDb.Messages.Where(m => m.ChannelId == ChannelId);
if (before.HasValue)
q = q.Where(m => m.SentAt < before.Value);
var page = await q
.OrderByDescending(m => m.SentAt)
.Take(PageSize + 1)
.ToListAsync();
_hasMore = page.Count > PageSize;
if (_hasMore) page.RemoveAt(page.Count - 1);
_messages.AddRange(page);
await ResolveNamesAsync();
}
private async Task LoadMoreAsync()
{
_loadingMore = true;
var oldest = _messages.LastOrDefault()?.SentAt;
await LoadPageAsync(oldest);
_loadingMore = false;
}
private async Task ResolveNamesAsync()
{
var missing = _messages
.Select(m => m.SenderAccountId)
.Where(id => id != SystemSenderId && !_senderNames.ContainsKey(id))
.Distinct()
.ToList();
if (missing.Count == 0) return;
var found = await IdentityDb.Set<Account>()
.Where(a => missing.Contains(a.Id))
.ToDictionaryAsync(a => a.Id, a => a.DisplayName ?? a.Email ?? a.Id.ToString());
foreach (var kv in found)
_senderNames[kv.Key] = kv.Value;
// Mark system messages
if (!_senderNames.ContainsKey(SystemSenderId))
_senderNames[SystemSenderId] = "[System]";
}
private async Task PostSystemMessageAsync()
{
_systemError = "";
_systemSuccess = false;
if (string.IsNullOrWhiteSpace(_systemMessageText))
{
_systemError = "Message cannot be empty.";
return;
}
if (_systemMessageText.Length > 500)
{
_systemError = "Message must be 500 characters or fewer.";
return;
}
_posting = true;
var msg = new ChatMessage
{
ChannelId = ChannelId,
SenderAccountId = SystemSenderId,
Content = _systemMessageText.Trim(),
SentAt = DateTimeOffset.UtcNow,
};
ChatDb.Messages.Add(msg);
await ChatDb.SaveChangesAsync();
// Prepend to the visible list.
_messages.Insert(0, msg);
_senderNames[SystemSenderId] = "[System]";
_systemMessageText = "";
_systemSuccess = true;
_posting = false;
}
private static string TypeBadge(SOR.Database.Enums.ChatChannelType t) => t switch
{
SOR.Database.Enums.ChatChannelType.Global => "bg-primary",
SOR.Database.Enums.ChatChannelType.Direct => "bg-info text-dark",
SOR.Database.Enums.ChatChannelType.Match => "bg-success",
SOR.Database.Enums.ChatChannelType.Guild => "bg-warning text-dark",
SOR.Database.Enums.ChatChannelType.System => "bg-danger",
_ => "bg-secondary",
};
}
@@ -0,0 +1,163 @@
@page "/chat"
@using Microsoft.EntityFrameworkCore
@using SOR.Database.Contexts
@using SOR.Database.Enums
@inject ChatDbContext Db
<PageTitle>Chat — SOR Admin</PageTitle>
<div class="d-flex justify-content-between align-items-center mb-4">
<h2 class="fw-bold mb-0">Chat</h2>
</div>
@if (_loading)
{
<div class="text-muted">Loading...</div>
}
else
{
<!-- Stats row -->
<div class="row g-3 mb-4">
<div class="col-md-3">
<div class="card bg-dark text-white border-secondary h-100">
<div class="card-body">
<div class="text-muted small">Total Channels</div>
<div class="fs-3 fw-bold">@_totalChannels</div>
</div>
</div>
</div>
<div class="col-md-3">
<div class="card bg-dark text-white border-secondary h-100">
<div class="card-body">
<div class="text-muted small">Total Messages</div>
<div class="fs-3 fw-bold">@_totalMessages</div>
</div>
</div>
</div>
<div class="col-md-3">
<div class="card bg-dark text-white border-secondary h-100">
<div class="card-body">
<div class="text-muted small">Friendships</div>
<div class="fs-3 fw-bold">@_friendships</div>
</div>
</div>
</div>
<div class="col-md-3">
<div class="card bg-dark text-white border-secondary h-100">
<div class="card-body">
<div class="text-muted small">Blocked Pairs</div>
<div class="fs-3 fw-bold">@_blockedPairs</div>
</div>
</div>
</div>
</div>
<!-- Channel list with type filter -->
<div class="card bg-dark text-white border-secondary">
<div class="card-header d-flex justify-content-between align-items-center">
<span class="fw-semibold">Channels</span>
<select class="form-select form-select-sm bg-dark text-white border-secondary w-auto"
@bind="_typeFilter">
<option value="">All Types</option>
<option value="Global">Global</option>
<option value="Match">Match</option>
<option value="Direct">Direct</option>
<option value="Guild">Guild</option>
<option value="System">System</option>
</select>
</div>
<div class="card-body p-0">
<table class="table table-dark table-hover mb-0">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th>Members</th>
<th>Messages</th>
<th>Created</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var ch in FilteredChannels)
{
<tr>
<td class="font-monospace small">@ch.Name</td>
<td>
<span class="badge @TypeBadge(ch.ChannelType)">@ch.ChannelType</span>
</td>
<td>@ch.MemberCount</td>
<td>@ch.MessageCount</td>
<td class="text-muted small">@ch.CreatedAt.ToString("yyyy-MM-dd HH:mm")</td>
<td>
<a href="/chat/channel/@ch.Id" class="btn btn-sm btn-outline-secondary">View</a>
</td>
</tr>
}
@if (!FilteredChannels.Any())
{
<tr>
<td colspan="6" class="text-center text-muted py-3">No channels found.</td>
</tr>
}
</tbody>
</table>
</div>
</div>
}
@code {
private bool _loading = true;
private int _totalChannels;
private int _totalMessages;
private int _friendships;
private int _blockedPairs;
private string _typeFilter = "";
private record ChannelRow(
Guid Id,
string Name,
ChatChannelType ChannelType,
int MemberCount,
int MessageCount,
DateTimeOffset CreatedAt);
private List<ChannelRow> _channels = new();
private IEnumerable<ChannelRow> FilteredChannels => string.IsNullOrEmpty(_typeFilter)
? _channels
: _channels.Where(c => c.ChannelType.ToString() == _typeFilter);
protected override async Task OnInitializedAsync()
{
_totalChannels = await Db.Channels.CountAsync();
_totalMessages = await Db.Messages.CountAsync();
_friendships = await Db.FriendRequests
.CountAsync(f => f.Status == FriendRequestStatus.Accepted);
_blockedPairs = await Db.BlockedUsers.CountAsync();
_channels = await Db.Channels
.OrderByDescending(c => c.CreatedAt)
.Take(200)
.Select(c => new ChannelRow(
c.Id,
c.Name,
c.ChannelType,
c.Members.Count(m => m.LeftAt == null),
c.Messages.Count,
c.CreatedAt))
.ToListAsync();
_loading = false;
}
private static string TypeBadge(ChatChannelType t) => t switch
{
ChatChannelType.Global => "bg-primary",
ChatChannelType.Direct => "bg-info text-dark",
ChatChannelType.Match => "bg-success",
ChatChannelType.Guild => "bg-warning text-dark",
ChatChannelType.System => "bg-danger",
_ => "bg-secondary",
};
}
@@ -0,0 +1,282 @@
@page "/chat/social"
@using Microsoft.EntityFrameworkCore
@using SOR.Database.Contexts
@using SOR.Database.Entities.Identity
@using SOR.Database.Enums
@inject ChatDbContext ChatDb
@inject SorIdentityDbContext IdentityDb
<PageTitle>Social Graph — SOR Admin</PageTitle>
<nav aria-label="breadcrumb" class="mb-3">
<ol class="breadcrumb">
<li class="breadcrumb-item"><a href="/chat" class="text-decoration-none">Chat</a></li>
<li class="breadcrumb-item active">Social Graph</li>
</ol>
</nav>
<h4 class="fw-bold mb-4">Social Graph</h4>
<!-- Player lookup -->
<div class="card bg-dark text-white border-secondary mb-4">
<div class="card-header fw-semibold">Player Lookup</div>
<div class="card-body">
<div class="input-group" style="max-width:420px">
<input type="text" class="form-control bg-dark text-white border-secondary"
placeholder="Account ID (GUID)..."
@bind="_lookupInput" @bind:event="oninput" @onkeydown="OnLookupKeyDown" />
<button class="btn btn-outline-secondary" @onclick="LookupAsync">Search</button>
</div>
@if (!string.IsNullOrEmpty(_lookupError))
{
<div class="text-danger small mt-1">@_lookupError</div>
}
</div>
</div>
@if (_loading)
{
<div class="text-muted">Loading...</div>
}
else if (_accountId.HasValue)
{
<div class="mb-3 text-muted small">
Showing social graph for <span class="font-monospace text-white">@_accountId</span>
@if (!string.IsNullOrEmpty(_accountName))
{
<span> — <strong class="text-white">@_accountName</strong></span>
}
</div>
<!-- Friends -->
<div class="card bg-dark text-white border-secondary mb-3">
<div class="card-header fw-semibold">
Friends <span class="badge bg-secondary ms-1">@_friends.Count</span>
</div>
<div class="card-body p-0">
<table class="table table-dark table-hover mb-0 small">
<thead><tr><th>Account ID</th><th>Name</th><th>Since</th><th></th></tr></thead>
<tbody>
@foreach (var f in _friends)
{
<tr>
<td class="font-monospace">@f.AccountId</td>
<td>@f.DisplayName</td>
<td class="text-muted">@f.Since.ToString("yyyy-MM-dd")</td>
<td>
<button class="btn btn-sm btn-outline-danger"
@onclick="() => RemoveFriendAsync(f.RowId)">
Remove
</button>
</td>
</tr>
}
@if (!_friends.Any())
{
<tr><td colspan="4" class="text-center text-muted py-2">No friends.</td></tr>
}
</tbody>
</table>
</div>
</div>
<!-- Pending requests -->
<div class="card bg-dark text-white border-secondary mb-3">
<div class="card-header fw-semibold">
Pending Friend Requests <span class="badge bg-secondary ms-1">@_pending.Count</span>
</div>
<div class="card-body p-0">
<table class="table table-dark table-hover mb-0 small">
<thead><tr><th>Direction</th><th>Other Account</th><th>Name</th><th>Since</th><th></th></tr></thead>
<tbody>
@foreach (var r in _pending)
{
<tr>
<td>
<span class="badge @(r.IsIncoming ? "bg-info text-dark" : "bg-secondary")">
@(r.IsIncoming ? "Incoming" : "Outgoing")
</span>
</td>
<td class="font-monospace">@r.AccountId</td>
<td>@r.DisplayName</td>
<td class="text-muted">@r.CreatedAt.ToString("yyyy-MM-dd")</td>
<td>
<button class="btn btn-sm btn-outline-danger"
@onclick="() => CancelRequestAsync(r.RowId)">
Cancel
</button>
</td>
</tr>
}
@if (!_pending.Any())
{
<tr><td colspan="5" class="text-center text-muted py-2">No pending requests.</td></tr>
}
</tbody>
</table>
</div>
</div>
<!-- Blocked -->
<div class="card bg-dark text-white border-secondary">
<div class="card-header fw-semibold">
Blocked Players <span class="badge bg-secondary ms-1">@_blocked.Count</span>
</div>
<div class="card-body p-0">
<table class="table table-dark table-hover mb-0 small">
<thead><tr><th>Account ID</th><th>Name</th><th>Blocked At</th><th></th></tr></thead>
<tbody>
@foreach (var b in _blocked)
{
<tr>
<td class="font-monospace">@b.AccountId</td>
<td>@b.DisplayName</td>
<td class="text-muted">@b.BlockedAt.ToString("yyyy-MM-dd")</td>
<td>
<button class="btn btn-sm btn-outline-secondary"
@onclick="() => UnblockAsync(b.RowId)">
Unblock
</button>
</td>
</tr>
}
@if (!_blocked.Any())
{
<tr><td colspan="4" class="text-center text-muted py-2">Not blocking anyone.</td></tr>
}
</tbody>
</table>
</div>
</div>
}
@code {
private bool _loading = false;
private string _lookupInput = "";
private string _lookupError = "";
private Guid? _accountId;
private string _accountName = "";
private record FriendRow(Guid RowId, Guid AccountId, string DisplayName, DateTimeOffset Since);
private record PendingRow(Guid RowId, Guid AccountId, string DisplayName, bool IsIncoming, DateTimeOffset CreatedAt);
private record BlockedRow(Guid RowId, Guid AccountId, string DisplayName, DateTimeOffset BlockedAt);
private List<FriendRow> _friends = new();
private List<PendingRow> _pending = new();
private List<BlockedRow> _blocked = new();
private async Task OnLookupKeyDown(KeyboardEventArgs e)
{
if (e.Key == "Enter") await LookupAsync();
}
private async Task LookupAsync()
{
_lookupError = "";
if (!Guid.TryParse(_lookupInput.Trim(), out var id))
{
_lookupError = "Invalid GUID.";
return;
}
_loading = true;
_accountId = id;
// Resolve display name
var account = await IdentityDb.Set<Account>()
.Where(a => a.Id == id)
.Select(a => new { a.DisplayName, a.Email })
.FirstOrDefaultAsync();
_accountName = account?.DisplayName ?? account?.Email ?? "";
// Load all social rows
var friendRows = await ChatDb.FriendRequests
.Where(f => f.RequesterAccountId == id || f.RecipientAccountId == id)
.ToListAsync();
var blockedRows = await ChatDb.BlockedUsers
.Where(b => b.BlockerAccountId == id)
.ToListAsync();
// Collect other account IDs for name resolution
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(id);
var names = new Dictionary<Guid, string>();
if (otherIds.Any())
{
names = await IdentityDb.Set<Account>()
.Where(a => otherIds.Contains(a.Id))
.ToDictionaryAsync(a => a.Id, a => a.DisplayName ?? a.Email ?? a.Id.ToString());
}
_friends = friendRows
.Where(f => f.Status == FriendRequestStatus.Accepted)
.Select(f =>
{
var other = f.RequesterAccountId == id ? f.RecipientAccountId : f.RequesterAccountId;
return new FriendRow(f.Id, other, names.GetValueOrDefault(other, other.ToString()), f.UpdatedAt);
})
.ToList();
_pending = friendRows
.Where(f => f.Status == FriendRequestStatus.Pending)
.Select(f =>
{
var isIncoming = f.RecipientAccountId == id;
var other = isIncoming ? f.RequesterAccountId : f.RecipientAccountId;
return new PendingRow(f.Id, other, names.GetValueOrDefault(other, other.ToString()), isIncoming, f.CreatedAt);
})
.ToList();
_blocked = blockedRows
.Select(b => new BlockedRow(
b.Id,
b.BlockedAccountId,
names.GetValueOrDefault(b.BlockedAccountId, b.BlockedAccountId.ToString()),
b.BlockedAt))
.ToList();
_loading = false;
}
private async Task RemoveFriendAsync(Guid rowId)
{
var row = await ChatDb.FriendRequests.FindAsync(rowId);
if (row != null)
{
ChatDb.FriendRequests.Remove(row);
await ChatDb.SaveChangesAsync();
}
_friends.RemoveAll(f => f.RowId == rowId);
}
private async Task CancelRequestAsync(Guid rowId)
{
var row = await ChatDb.FriendRequests.FindAsync(rowId);
if (row != null)
{
ChatDb.FriendRequests.Remove(row);
await ChatDb.SaveChangesAsync();
}
_pending.RemoveAll(r => r.RowId == rowId);
}
private async Task UnblockAsync(Guid rowId)
{
var row = await ChatDb.BlockedUsers.FindAsync(rowId);
if (row != null)
{
ChatDb.BlockedUsers.Remove(row);
await ChatDb.SaveChangesAsync();
}
_blocked.RemoveAll(b => b.RowId == rowId);
}
}
+11
View File
@@ -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;
}
+97
View File
@@ -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 { });
}
}
+15
View File
@@ -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;
}
}
@@ -45,6 +45,12 @@ public sealed record AddCardRequest(Guid DeckId, Guid CardDefinitionId, int Quan
/// </summary>
public sealed record RemoveCardRequest(Guid DeckId, Guid CardDefinitionId, int? Quantity = null);
/// <summary>
/// Creates a copy of an existing deck with a new name.
/// Name defaults to "Copy of [original name]" if not provided.
/// </summary>
public sealed record CloneDeckRequest(Guid DeckId, string? Name = null);
// ── Response / DTO types (server → client) ────────────────────────────────────
public sealed record GetCardsResponse(
@@ -75,7 +81,9 @@ public sealed record DeckSummaryDto(
int CardCount,
bool IsValid,
DateTimeOffset CreatedAt,
DateTimeOffset UpdatedAt);
DateTimeOffset UpdatedAt,
/// <summary>Non-blocking warnings about the deck composition (e.g. missing tier prerequisites).</summary>
string[]? ValidationWarnings = null);
public sealed record GetDeckResponse(DeckDetailDto? Deck);
@@ -87,7 +95,8 @@ public sealed record DeckDetailDto(
bool IsValid,
DateTimeOffset CreatedAt,
DateTimeOffset UpdatedAt,
IEnumerable<DeckCardDto> Cards);
IEnumerable<DeckCardDto> Cards,
string[]? ValidationWarnings = null);
public sealed record DeckCardDto(
Guid CardDefinitionId,
@@ -13,7 +13,8 @@ using SOR.Shared.Networking;
///
/// Validation:
/// - Deck exists and belongs to the player.
/// - CardDefinitionId must not be an ArchSpirit (those live at the deck level).
/// - Tier 1 ArchSpirits are not allowed in the card list (they're the deck commander).
/// - Tier 2+ ArchSpirits ARE allowed — they're ascension targets played during the match.
/// - Player owns enough physical copies (existing + delta ≤ owned).
/// - Adding would not push the definition over MaxCopiesPerCard.
/// - Adding would not push the deck over MaxDeckSize.
@@ -56,16 +57,21 @@ internal sealed class CollectionAddCardHandler : CollectionHandlerBase, IMessage
if (deck == null)
return ServerMessage.Error(message.Seq, "DECK_NOT_FOUND", "Deck not found.");
// ── Validate card type (ArchSpirits cannot be added to the card list) ──
var cardType = await _catalogDb.CardDefinitions
// ── Validate card type ─────────────────────────────────────────────────
// Tier 1 ArchSpirits: deck commander, not added to card list.
// Tier 2+ ArchSpirits: ascension targets, allowed in card list.
var cardMeta = await _catalogDb.CardDefinitions
.Where(cd => cd.Id == req.CardDefinitionId)
.Select(cd => (CardType?)cd.CardType)
.Select(cd => new { cd.CardType, cd.Tier })
.FirstOrDefaultAsync(cancellationToken);
if (cardType == null)
if (cardMeta == null)
return ServerMessage.Error(message.Seq, "CARD_NOT_FOUND", "Card definition not found.");
if (cardType == CardType.ArchSpirit)
if (cardMeta.CardType == CardType.ArchSpirit && (cardMeta.Tier ?? 1) == 1)
return ServerMessage.Error(message.Seq, "ARCH_SPIRIT_NOT_ALLOWED",
"ArchSpirit cards are set at the deck level, not in the card list.");
"Tier 1 ArchSpirits are your deck commander — set them at the deck level. " +
"Add a higher-tier version to the card list if you want to ascend during a match.");
// ── Copy-count checks ──────────────────────────────────────────────────
var existingEntry = deck.Cards.FirstOrDefault(c => c.CardDefinitionId == req.CardDefinitionId);
@@ -109,9 +115,8 @@ internal sealed class CollectionAddCardHandler : CollectionHandlerBase, IMessage
deck.Cards.Add(entry);
}
await RefreshValidityAsync(_collectionDb, deck, cancellationToken);
var warnings = await RefreshValidityAsync(_collectionDb, _catalogDb, deck, cancellationToken);
// Return the updated deck summary.
var archName = await _catalogDb.CardDefinitions
.Where(cd => cd.Id == deck.ArchSpiritCardDefinitionId)
.Select(cd => cd.Name)
@@ -125,7 +130,8 @@ internal sealed class CollectionAddCardHandler : CollectionHandlerBase, IMessage
CardCount: deck.Cards.Sum(c => c.Quantity),
IsValid: deck.IsValid,
CreatedAt: deck.CreatedAt,
UpdatedAt: deck.UpdatedAt);
UpdatedAt: deck.UpdatedAt,
ValidationWarnings: warnings.Length > 0 ? warnings : null);
return ServerMessage.Reply("collection.add_card.ack", message.Seq,
new DeckMutationResponse(summary));
@@ -0,0 +1,115 @@
namespace SOR.Collection.Handlers;
using Microsoft.EntityFrameworkCore;
using SOR.Database.Contexts;
using SOR.Database.Entities.Collection;
using SOR.Networking.Abstractions.Messaging;
using SOR.Networking.Abstractions.Transport;
using SOR.Shared.Networking;
/// <summary>
/// collection.clone_deck — creates an exact copy of an existing deck.
///
/// Useful for experimenting with small changes without losing the original.
/// The clone's name defaults to "Copy of [original name]" if not specified.
/// </summary>
internal sealed class CollectionCloneDeckHandler : CollectionHandlerBase, IMessageHandler
{
private readonly IMessageSerializer _serializer;
private readonly CollectionDbContext _collectionDb;
private readonly CatalogDbContext _catalogDb;
public CollectionCloneDeckHandler(
IMessageSerializer serializer,
CollectionDbContext collectionDb,
CatalogDbContext catalogDb)
{
_serializer = serializer;
_collectionDb = collectionDb;
_catalogDb = catalogDb;
}
public string MessageType => "collection.clone_deck";
public async Task<IServerMessage?> HandleAsync(
IClientMessage message,
AuthenticatedConnection connection,
CancellationToken cancellationToken)
{
var req = _serializer.DeserializePayload<CloneDeckRequest>(message.Payload);
var accountId = Guid.Parse(connection.UserId);
// ── Load original ──────────────────────────────────────────────────────
var original = await _collectionDb.Decks
.Include(d => d.Cards)
.FirstOrDefaultAsync(
d => d.Id == req.DeckId && d.AccountId == accountId,
cancellationToken);
if (original == null)
return ServerMessage.Error(message.Seq, "DECK_NOT_FOUND", "Deck not found.");
// ── Enforce deck limit ─────────────────────────────────────────────────
var deckCount = await _collectionDb.Decks
.CountAsync(d => d.AccountId == accountId, cancellationToken);
if (deckCount >= DeckRules.MaxDecksPerPlayer)
return ServerMessage.Error(message.Seq, "DECK_LIMIT_REACHED",
$"Maximum of {DeckRules.MaxDecksPerPlayer} decks reached.");
// ── Resolve name ───────────────────────────────────────────────────────
string newName = string.IsNullOrWhiteSpace(req.Name)
? $"Copy of {original.Name}"
: req.Name.Trim();
if (newName.Length > 50)
return ServerMessage.Error(message.Seq, "INVALID_NAME",
"Deck name must be 1-50 characters.");
// ── Create clone ───────────────────────────────────────────────────────
var now = DateTimeOffset.UtcNow;
var clone = new Deck
{
AccountId = accountId,
Name = newName,
ArchSpiritCardDefinitionId = original.ArchSpiritCardDefinitionId,
IsValid = original.IsValid,
CreatedAt = now,
UpdatedAt = now,
};
_collectionDb.Decks.Add(clone);
await _collectionDb.SaveChangesAsync(cancellationToken);
// Copy all DeckCard rows.
foreach (var card in original.Cards)
{
_collectionDb.DeckCards.Add(new DeckCard
{
DeckId = clone.Id,
CardDefinitionId = card.CardDefinitionId,
Quantity = card.Quantity,
});
}
await _collectionDb.SaveChangesAsync(cancellationToken);
// Revalidate the clone (ownership/validity may have changed since original was built).
var warnings = await RefreshValidityAsync(_collectionDb, _catalogDb, clone, cancellationToken);
var archName = await _catalogDb.CardDefinitions
.Where(cd => cd.Id == clone.ArchSpiritCardDefinitionId)
.Select(cd => cd.Name)
.FirstOrDefaultAsync(cancellationToken);
var summary = new DeckSummaryDto(
Id: clone.Id,
Name: clone.Name,
ArchSpiritCardDefinitionId: clone.ArchSpiritCardDefinitionId,
ArchSpiritName: archName,
CardCount: original.Cards.Sum(c => c.Quantity),
IsValid: clone.IsValid,
CreatedAt: clone.CreatedAt,
UpdatedAt: clone.UpdatedAt,
ValidationWarnings: warnings.Length > 0 ? warnings : null);
return ServerMessage.Reply("collection.clone_deck.ack", message.Seq,
new DeckMutationResponse(summary));
}
}
@@ -7,14 +7,9 @@ using SOR.Database.Enums;
/// <summary>
/// Shared helpers for all collection message handlers.
/// Each handler subclass inherits these utilities for cross-context lookups.
/// </summary>
internal abstract class CollectionHandlerBase
{
/// <summary>
/// Batch-loads CardDefinitions from the catalog context for a set of definition IDs.
/// Used to enrich PlayerCard and DeckCard results with name/type/art data.
/// </summary>
protected static async Task<Dictionary<Guid, CardDefinition>> LoadDefinitionsAsync(
CatalogDbContext catalogDb,
IEnumerable<Guid> ids,
@@ -29,18 +24,11 @@ internal abstract class CollectionHandlerBase
.ToDictionaryAsync(cd => cd.Id, ct);
}
/// <summary>
/// Returns the first Art2D CDN URL for a card definition, or null if none.
/// </summary>
protected static string? GetArtUrl(CardDefinition? def)
=> def?.Assets
.FirstOrDefault(a => a.AssetType == CardAssetType.Art2D)
?.CdnUrl;
/// <summary>
/// Counts how many copies of each CardDefinitionId the player currently owns.
/// Returns a dictionary: CardDefinitionId → owned count.
/// </summary>
protected static async Task<Dictionary<Guid, int>> GetOwnedCountsAsync(
CollectionDbContext collectionDb,
Guid accountId,
@@ -58,11 +46,21 @@ internal abstract class CollectionHandlerBase
}
/// <summary>
/// Recomputes and saves Deck.IsValid based on current cards and ownership.
/// Should be called after any add/remove card mutation.
/// Recomputes Deck.IsValid and returns any non-blocking validation warnings.
///
/// Hard rules (affect IsValid = false):
/// - Non-ArchSpirit card count must be MinDeckSize..MaxDeckSize
/// - No definition may appear more than MaxCopiesPerCard times
/// - Player must own enough copies of every card in the list
/// - The deck's primary ArchSpirit must be Tier 1
///
/// Soft warnings (returned but do NOT affect IsValid):
/// - A Tier 2+ ArchSpirit in the card list is missing its previous-tier prerequisite.
/// Common when players are testing with small changes. Deck is still legal.
/// </summary>
protected static async Task RefreshValidityAsync(
protected static async Task<string[]> RefreshValidityAsync(
CollectionDbContext collectionDb,
CatalogDbContext catalogDb,
Database.Entities.Collection.Deck deck,
CancellationToken ct)
{
@@ -76,16 +74,67 @@ internal abstract class CollectionHandlerBase
cards.Select(c => c.CardDefinitionId),
ct);
int total = cards.Sum(c => c.Quantity);
bool valid =
total >= DeckRules.MinDeckSize &&
total <= DeckRules.MaxDeckSize &&
cards.All(c =>
c.Quantity <= DeckRules.MaxCopiesPerCard &&
ownedCounts.GetValueOrDefault(c.CardDefinitionId) >= c.Quantity);
int total = cards.Sum(c => c.Quantity);
bool sizeValid = total >= DeckRules.MinDeckSize && total <= DeckRules.MaxDeckSize;
bool copiesValid = cards.All(c =>
c.Quantity <= DeckRules.MaxCopiesPerCard &&
ownedCounts.GetValueOrDefault(c.CardDefinitionId) >= c.Quantity);
deck.IsValid = valid;
deck.UpdatedAt = DateTimeOffset.UtcNow;
// Hard rule: primary ArchSpirit must be Tier 1.
var primaryTier = await catalogDb.CardDefinitions
.Where(cd => cd.Id == deck.ArchSpiritCardDefinitionId)
.Select(cd => cd.Tier)
.FirstOrDefaultAsync(ct);
bool primaryIsT1 = primaryTier == 1;
// Soft warning: check tier-chain gaps for higher-tier ArchSpirits in the card list.
var warnings = new List<string>();
if (cards.Count > 0)
{
var defIds = cards.Select(c => c.CardDefinitionId).Distinct().ToList();
var archCardsInDeck = await catalogDb.CardDefinitions
.Where(cd => defIds.Contains(cd.Id) && cd.CardType == CardType.ArchSpirit)
.Select(cd => new { cd.Id, cd.Name, cd.Tier, cd.PreviousTierId })
.ToListAsync(ct);
if (archCardsInDeck.Count > 0)
{
var presentArchIds = new HashSet<Guid>(archCardsInDeck.Select(a => a.Id))
{
deck.ArchSpiritCardDefinitionId
};
var gapped = archCardsInDeck
.Where(a => a.Tier > 1 && a.PreviousTierId.HasValue
&& !presentArchIds.Contains(a.PreviousTierId.Value))
.ToList();
if (gapped.Count > 0)
{
var prevIds = gapped.Select(g => g.PreviousTierId!.Value).Distinct().ToList();
var prevNames = await catalogDb.CardDefinitions
.Where(cd => prevIds.Contains(cd.Id))
.ToDictionaryAsync(cd => cd.Id, cd => cd.Name, ct);
foreach (var g in gapped)
{
var prevName = g.PreviousTierId.HasValue
? prevNames.GetValueOrDefault(g.PreviousTierId.Value,
$"Tier {g.Tier - 1} prerequisite")
: $"Tier {g.Tier - 1} prerequisite";
warnings.Add(
$"{g.Name} (Tier {g.Tier}) is in the deck but {prevName} is missing. " +
"It cannot ascend in-game without its previous tier.");
}
}
}
}
deck.IsValid = sizeValid && copiesValid && primaryIsT1;
deck.UpdatedAt = DateTimeOffset.UtcNow;
await collectionDb.SaveChangesAsync(ct);
return warnings.ToArray();
}
}
@@ -64,7 +64,7 @@ internal sealed class CollectionRemoveCardHandler : CollectionHandlerBase, IMess
entry.Quantity -= toRemove;
}
await RefreshValidityAsync(_collectionDb, deck, cancellationToken);
var warnings = await RefreshValidityAsync(_collectionDb, _catalogDb, deck, cancellationToken);
var archName = await _catalogDb.CardDefinitions
.Where(cd => cd.Id == deck.ArchSpiritCardDefinitionId)
@@ -79,7 +79,8 @@ internal sealed class CollectionRemoveCardHandler : CollectionHandlerBase, IMess
CardCount: deck.Cards.Sum(c => c.Quantity),
IsValid: deck.IsValid,
CreatedAt: deck.CreatedAt,
UpdatedAt: deck.UpdatedAt);
UpdatedAt: deck.UpdatedAt,
ValidationWarnings: warnings.Length > 0 ? warnings : null);
return ServerMessage.Reply("collection.remove_card.ack", message.Seq,
new DeckMutationResponse(summary));
@@ -30,6 +30,7 @@ public static class ServiceRegistration
services.AddTransient<IMessageHandler, CollectionDeleteDeckHandler>();
services.AddTransient<IMessageHandler, CollectionAddCardHandler>();
services.AddTransient<IMessageHandler, CollectionRemoveCardHandler>();
services.AddTransient<IMessageHandler, CollectionCloneDeckHandler>();
return services;
}
@@ -75,6 +75,13 @@ public sealed class CatalogDbContext : DbContext
e.HasIndex(c => c.Rarity);
e.HasIndex(c => new { c.IsPublished, c.SetId });
// Self-reference: Tier N ArchSpirit → Tier (N-1) ArchSpirit.
e.HasOne(c => c.PreviousTier)
.WithMany()
.HasForeignKey(c => c.PreviousTierId)
.IsRequired(false)
.OnDelete(DeleteBehavior.SetNull);
e.HasMany(c => c.Assets)
.WithOne(a => a.CardDefinition)
.HasForeignKey(a => a.CardDefinitionId)
@@ -24,6 +24,8 @@ public sealed class ChatDbContext : DbContext
public DbSet<ChatChannel> Channels => Set<ChatChannel>();
public DbSet<ChatMember> Members => Set<ChatMember>();
public DbSet<ChatMessage> Messages => Set<ChatMessage>();
public DbSet<FriendRequest> FriendRequests => Set<FriendRequest>();
public DbSet<BlockedUser> BlockedUsers => Set<BlockedUser>();
protected override void OnModelCreating(ModelBuilder builder)
{
@@ -61,5 +63,25 @@ public sealed class ChatDbContext : DbContext
e.HasIndex(m => new { m.ChannelId, m.SentAt });
e.HasIndex(m => m.SenderAccountId);
});
builder.Entity<FriendRequest>(e =>
{
e.ToTable("friend_requests");
e.HasKey(f => f.Id);
e.Property(f => f.Status).HasConversion<string>();
// Unique pair regardless of who initiated: enforced at service layer
// (two players can't have duplicate relationships).
e.HasIndex(f => new { f.RequesterAccountId, f.RecipientAccountId }).IsUnique();
e.HasIndex(f => f.RecipientAccountId);
e.HasIndex(f => f.Status);
});
builder.Entity<BlockedUser>(e =>
{
e.ToTable("blocked_users");
e.HasKey(b => b.Id);
e.HasIndex(b => new { b.BlockerAccountId, b.BlockedAccountId }).IsUnique();
e.HasIndex(b => b.BlockerAccountId);
});
}
}
@@ -61,6 +61,16 @@ public sealed class CardDefinition
/// <summary>Tier 1 = base form; higher tiers reached via Ascend/Transition.</summary>
public int? Tier { get; set; }
/// <summary>
/// For Tier 2+ ArchSpirits: the Tier (N-1) card this ascends from.
/// Null for Tier 1 and all non-ArchSpirit cards.
/// Used to validate ascension chains in deck construction.
/// </summary>
public Guid? PreviousTierId { get; set; }
/// <summary>Navigation for the ascension chain (self-reference within catalog).</summary>
public CardDefinition? PreviousTier { get; set; }
// ── Terramorpha-only ────────────────────────────────────────────────────
public TerramorphaMode? TerramorphaMode { get; set; }
@@ -0,0 +1,25 @@
namespace SOR.Database.Entities.Chat;
/// <summary>
/// Records that one player has blocked another.
///
/// Effects of blocking:
/// - Blocker cannot receive DMs from the blocked player.
/// - Blocked player cannot send DMs to the blocker.
/// - Existing friendship (if any) is dissolved when a block is created.
/// - Blocked player cannot send friend requests to the blocker.
///
/// Cross-schema: both Guids have no EF FK to identity.accounts.
/// </summary>
public sealed class BlockedUser
{
public Guid Id { get; set; } = Guid.NewGuid();
/// <summary>The player who performed the block.</summary>
public Guid BlockerAccountId { get; set; }
/// <summary>The player who was blocked.</summary>
public Guid BlockedAccountId { get; set; }
public DateTimeOffset BlockedAt { get; set; }
}
@@ -0,0 +1,30 @@
namespace SOR.Database.Entities.Chat;
using SOR.Database.Enums;
/// <summary>
/// A friend request from one player to another.
///
/// Once accepted, the row stays with Status = Accepted — this is the
/// canonical record of friendship. To check if two players are friends:
/// SELECT 1 FROM chat.friend_requests
/// WHERE ((requester = A AND recipient = B) OR (requester = B AND recipient = A))
/// AND status = 'Accepted'
///
/// Declined requests are kept for spam-prevention (prevents immediate re-request).
/// A player can re-request after the existing declined row is cleared by TTL/admin.
///
/// Cross-schema: both Guids have no EF FK to identity.accounts.
/// </summary>
public sealed class FriendRequest
{
public Guid Id { get; set; } = Guid.NewGuid();
public Guid RequesterAccountId { get; set; }
public Guid RecipientAccountId { get; set; }
public FriendRequestStatus Status { get; set; } = FriendRequestStatus.Pending;
public DateTimeOffset CreatedAt { get; set; }
public DateTimeOffset UpdatedAt { get; set; }
}
@@ -10,4 +10,13 @@ public enum ChatChannelType
Direct,
/// <summary>Guild/clan channel.</summary>
Guild,
/// <summary>Admin-only broadcast channel for system announcements.</summary>
System,
}
public enum FriendRequestStatus
{
Pending,
Accepted,
Declined,
}
@@ -0,0 +1,315 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using SOR.Database.Contexts;
#nullable disable
namespace SOR.Database.Migrations.Catalog
{
[DbContext(typeof(CatalogDbContext))]
[Migration("20260225174746_AddArchSpiritTierChain")]
partial class AddArchSpiritTierChain
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasDefaultSchema("catalog")
.HasAnnotation("ProductVersion", "8.0.0")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("SOR.Database.Entities.Catalog.CardAnimationBinding", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("ActionName")
.IsRequired()
.HasColumnType("text");
b.Property<string>("AnimationCdnUrl")
.IsRequired()
.HasColumnType("text");
b.Property<Guid>("CardDefinitionId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("CardDefinitionId", "ActionName")
.IsUnique();
b.ToTable("card_animation_bindings", "catalog");
});
modelBuilder.Entity("SOR.Database.Entities.Catalog.CardAsset", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("AssetType")
.IsRequired()
.HasColumnType("text");
b.Property<Guid>("CardDefinitionId")
.HasColumnType("uuid");
b.Property<string>("CdnUrl")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("MimeType")
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("CardDefinitionId", "AssetType");
b.ToTable("card_assets", "catalog");
});
modelBuilder.Entity("SOR.Database.Entities.Catalog.CardDefinition", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("AbilitiesJson")
.HasColumnType("jsonb")
.HasColumnName("abilities");
b.Property<string>("Affinity")
.IsRequired()
.HasColumnType("text");
b.Property<string>("AttackType")
.HasColumnType("text");
b.Property<bool?>("CanAttack")
.HasColumnType("boolean");
b.Property<bool?>("CanBeAttacked")
.HasColumnType("boolean");
b.Property<bool?>("CanBeBlocked")
.HasColumnType("boolean");
b.Property<bool?>("CanBeObstructed")
.HasColumnType("boolean");
b.Property<bool?>("CanBeSacrificed")
.HasColumnType("boolean");
b.Property<bool?>("CanDefend")
.HasColumnType("boolean");
b.Property<bool?>("CanMove")
.HasColumnType("boolean");
b.Property<bool?>("CanUseAbility")
.HasColumnType("boolean");
b.Property<string>("CardType")
.IsRequired()
.HasColumnType("text");
b.Property<int?>("CollectorNumber")
.HasColumnType("integer");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<int?>("Damage")
.HasColumnType("integer");
b.Property<string>("Description")
.IsRequired()
.HasColumnType("text");
b.Property<string>("EffectsJson")
.HasColumnType("jsonb")
.HasColumnName("effects");
b.Property<string[]>("Genus")
.HasColumnType("text[]");
b.Property<bool>("IsPublished")
.HasColumnType("boolean");
b.Property<int?>("MaxAttackRange")
.HasColumnType("integer");
b.Property<int?>("MaxChannelRange")
.HasColumnType("integer");
b.Property<int?>("MaxDefense")
.HasColumnType("integer");
b.Property<int?>("MaxHealth")
.HasColumnType("integer");
b.Property<int?>("MinAttackRange")
.HasColumnType("integer");
b.Property<int?>("MinChannelRange")
.HasColumnType("integer");
b.Property<int?>("MovementPoints")
.HasColumnType("integer");
b.Property<string>("MovementType")
.HasColumnType("text");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<string>("OtherCostsJson")
.HasColumnType("jsonb")
.HasColumnName("other_costs");
b.Property<Guid?>("PreviousTierId")
.HasColumnType("uuid");
b.Property<string>("Rarity")
.IsRequired()
.HasColumnType("text");
b.Property<bool?>("RequiresLos")
.HasColumnType("boolean");
b.Property<Guid?>("SetId")
.HasColumnType("uuid");
b.Property<int>("SpCost")
.HasColumnType("integer");
b.Property<int>("StCost")
.HasColumnType("integer");
b.Property<string>("TerramorphaMode")
.HasColumnType("text");
b.Property<int?>("Tier")
.HasColumnType("integer");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("Affinity");
b.HasIndex("CardType");
b.HasIndex("Name");
b.HasIndex("PreviousTierId");
b.HasIndex("Rarity");
b.HasIndex("SetId");
b.HasIndex("IsPublished", "SetId");
b.ToTable("card_definitions", "catalog");
});
modelBuilder.Entity("SOR.Database.Entities.Catalog.CardSet", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("Code")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Description")
.HasColumnType("text");
b.Property<bool>("IsActive")
.HasColumnType("boolean");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<DateOnly?>("ReleaseDate")
.HasColumnType("date");
b.HasKey("Id");
b.HasIndex("Code")
.IsUnique();
b.ToTable("card_sets", "catalog");
});
modelBuilder.Entity("SOR.Database.Entities.Catalog.CardAnimationBinding", b =>
{
b.HasOne("SOR.Database.Entities.Catalog.CardDefinition", "CardDefinition")
.WithMany("AnimationBindings")
.HasForeignKey("CardDefinitionId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("CardDefinition");
});
modelBuilder.Entity("SOR.Database.Entities.Catalog.CardAsset", b =>
{
b.HasOne("SOR.Database.Entities.Catalog.CardDefinition", "CardDefinition")
.WithMany("Assets")
.HasForeignKey("CardDefinitionId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("CardDefinition");
});
modelBuilder.Entity("SOR.Database.Entities.Catalog.CardDefinition", b =>
{
b.HasOne("SOR.Database.Entities.Catalog.CardDefinition", "PreviousTier")
.WithMany()
.HasForeignKey("PreviousTierId")
.OnDelete(DeleteBehavior.SetNull);
b.HasOne("SOR.Database.Entities.Catalog.CardSet", "Set")
.WithMany("Cards")
.HasForeignKey("SetId")
.OnDelete(DeleteBehavior.SetNull);
b.Navigation("PreviousTier");
b.Navigation("Set");
});
modelBuilder.Entity("SOR.Database.Entities.Catalog.CardDefinition", b =>
{
b.Navigation("AnimationBindings");
b.Navigation("Assets");
});
modelBuilder.Entity("SOR.Database.Entities.Catalog.CardSet", b =>
{
b.Navigation("Cards");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,57 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SOR.Database.Migrations.Catalog
{
/// <inheritdoc />
public partial class AddArchSpiritTierChain : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<Guid>(
name: "PreviousTierId",
schema: "catalog",
table: "card_definitions",
type: "uuid",
nullable: true);
migrationBuilder.CreateIndex(
name: "IX_card_definitions_PreviousTierId",
schema: "catalog",
table: "card_definitions",
column: "PreviousTierId");
migrationBuilder.AddForeignKey(
name: "FK_card_definitions_card_definitions_PreviousTierId",
schema: "catalog",
table: "card_definitions",
column: "PreviousTierId",
principalSchema: "catalog",
principalTable: "card_definitions",
principalColumn: "Id",
onDelete: ReferentialAction.SetNull);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_card_definitions_card_definitions_PreviousTierId",
schema: "catalog",
table: "card_definitions");
migrationBuilder.DropIndex(
name: "IX_card_definitions_PreviousTierId",
schema: "catalog",
table: "card_definitions");
migrationBuilder.DropColumn(
name: "PreviousTierId",
schema: "catalog",
table: "card_definitions");
}
}
}
@@ -178,6 +178,9 @@ namespace SOR.Database.Migrations.Catalog
.HasColumnType("jsonb")
.HasColumnName("other_costs");
b.Property<Guid?>("PreviousTierId")
.HasColumnType("uuid");
b.Property<string>("Rarity")
.IsRequired()
.HasColumnType("text");
@@ -211,6 +214,8 @@ namespace SOR.Database.Migrations.Catalog
b.HasIndex("Name");
b.HasIndex("PreviousTierId");
b.HasIndex("Rarity");
b.HasIndex("SetId");
@@ -275,11 +280,18 @@ namespace SOR.Database.Migrations.Catalog
modelBuilder.Entity("SOR.Database.Entities.Catalog.CardDefinition", b =>
{
b.HasOne("SOR.Database.Entities.Catalog.CardDefinition", "PreviousTier")
.WithMany()
.HasForeignKey("PreviousTierId")
.OnDelete(DeleteBehavior.SetNull);
b.HasOne("SOR.Database.Entities.Catalog.CardSet", "Set")
.WithMany("Cards")
.HasForeignKey("SetId")
.OnDelete(DeleteBehavior.SetNull);
b.Navigation("PreviousTier");
b.Navigation("Set");
});
@@ -0,0 +1,210 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using SOR.Database.Contexts;
#nullable disable
namespace SOR.Database.Migrations.Chat
{
[DbContext(typeof(ChatDbContext))]
[Migration("20260225174846_AddSocialGraph")]
partial class AddSocialGraph
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasDefaultSchema("chat")
.HasAnnotation("ProductVersion", "8.0.0")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("SOR.Database.Entities.Chat.BlockedUser", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Guid>("BlockedAccountId")
.HasColumnType("uuid");
b.Property<DateTimeOffset>("BlockedAt")
.HasColumnType("timestamp with time zone");
b.Property<Guid>("BlockerAccountId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("BlockerAccountId");
b.HasIndex("BlockerAccountId", "BlockedAccountId")
.IsUnique();
b.ToTable("blocked_users", "chat");
});
modelBuilder.Entity("SOR.Database.Entities.Chat.ChatChannel", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("ChannelType")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("MatchId")
.HasColumnType("text");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("ChannelType");
b.HasIndex("MatchId");
b.ToTable("channels", "chat");
});
modelBuilder.Entity("SOR.Database.Entities.Chat.ChatMember", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Guid>("AccountId")
.HasColumnType("uuid");
b.Property<Guid>("ChannelId")
.HasColumnType("uuid");
b.Property<DateTimeOffset>("JoinedAt")
.HasColumnType("timestamp with time zone");
b.Property<DateTimeOffset?>("LeftAt")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("AccountId");
b.HasIndex("ChannelId", "AccountId")
.IsUnique();
b.ToTable("members", "chat");
});
modelBuilder.Entity("SOR.Database.Entities.Chat.ChatMessage", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Guid>("ChannelId")
.HasColumnType("uuid");
b.Property<string>("Content")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset?>("EditedAt")
.HasColumnType("timestamp with time zone");
b.Property<bool>("IsDeleted")
.HasColumnType("boolean");
b.Property<Guid>("SenderAccountId")
.HasColumnType("uuid");
b.Property<DateTimeOffset>("SentAt")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("SenderAccountId");
b.HasIndex("ChannelId", "SentAt");
b.ToTable("messages", "chat");
});
modelBuilder.Entity("SOR.Database.Entities.Chat.FriendRequest", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<Guid>("RecipientAccountId")
.HasColumnType("uuid");
b.Property<Guid>("RequesterAccountId")
.HasColumnType("uuid");
b.Property<string>("Status")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("RecipientAccountId");
b.HasIndex("Status");
b.HasIndex("RequesterAccountId", "RecipientAccountId")
.IsUnique();
b.ToTable("friend_requests", "chat");
});
modelBuilder.Entity("SOR.Database.Entities.Chat.ChatMember", b =>
{
b.HasOne("SOR.Database.Entities.Chat.ChatChannel", "Channel")
.WithMany("Members")
.HasForeignKey("ChannelId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Channel");
});
modelBuilder.Entity("SOR.Database.Entities.Chat.ChatMessage", b =>
{
b.HasOne("SOR.Database.Entities.Chat.ChatChannel", "Channel")
.WithMany("Messages")
.HasForeignKey("ChannelId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Channel");
});
modelBuilder.Entity("SOR.Database.Entities.Chat.ChatChannel", b =>
{
b.Navigation("Members");
b.Navigation("Messages");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,91 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SOR.Database.Migrations.Chat
{
/// <inheritdoc />
public partial class AddSocialGraph : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "blocked_users",
schema: "chat",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
BlockerAccountId = table.Column<Guid>(type: "uuid", nullable: false),
BlockedAccountId = table.Column<Guid>(type: "uuid", nullable: false),
BlockedAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_blocked_users", x => x.Id);
});
migrationBuilder.CreateTable(
name: "friend_requests",
schema: "chat",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
RequesterAccountId = table.Column<Guid>(type: "uuid", nullable: false),
RecipientAccountId = table.Column<Guid>(type: "uuid", nullable: false),
Status = table.Column<string>(type: "text", nullable: false),
CreatedAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
UpdatedAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_friend_requests", x => x.Id);
});
migrationBuilder.CreateIndex(
name: "IX_blocked_users_BlockerAccountId",
schema: "chat",
table: "blocked_users",
column: "BlockerAccountId");
migrationBuilder.CreateIndex(
name: "IX_blocked_users_BlockerAccountId_BlockedAccountId",
schema: "chat",
table: "blocked_users",
columns: new[] { "BlockerAccountId", "BlockedAccountId" },
unique: true);
migrationBuilder.CreateIndex(
name: "IX_friend_requests_RecipientAccountId",
schema: "chat",
table: "friend_requests",
column: "RecipientAccountId");
migrationBuilder.CreateIndex(
name: "IX_friend_requests_RequesterAccountId_RecipientAccountId",
schema: "chat",
table: "friend_requests",
columns: new[] { "RequesterAccountId", "RecipientAccountId" },
unique: true);
migrationBuilder.CreateIndex(
name: "IX_friend_requests_Status",
schema: "chat",
table: "friend_requests",
column: "Status");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "blocked_users",
schema: "chat");
migrationBuilder.DropTable(
name: "friend_requests",
schema: "chat");
}
}
}
@@ -23,6 +23,31 @@ namespace SOR.Database.Migrations.Chat
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("SOR.Database.Entities.Chat.BlockedUser", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Guid>("BlockedAccountId")
.HasColumnType("uuid");
b.Property<DateTimeOffset>("BlockedAt")
.HasColumnType("timestamp with time zone");
b.Property<Guid>("BlockerAccountId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("BlockerAccountId");
b.HasIndex("BlockerAccountId", "BlockedAccountId")
.IsUnique();
b.ToTable("blocked_users", "chat");
});
modelBuilder.Entity("SOR.Database.Entities.Chat.ChatChannel", b =>
{
b.Property<Guid>("Id")
@@ -114,6 +139,40 @@ namespace SOR.Database.Migrations.Chat
b.ToTable("messages", "chat");
});
modelBuilder.Entity("SOR.Database.Entities.Chat.FriendRequest", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<Guid>("RecipientAccountId")
.HasColumnType("uuid");
b.Property<Guid>("RequesterAccountId")
.HasColumnType("uuid");
b.Property<string>("Status")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("RecipientAccountId");
b.HasIndex("Status");
b.HasIndex("RequesterAccountId", "RecipientAccountId")
.IsUnique();
b.ToTable("friend_requests", "chat");
});
modelBuilder.Entity("SOR.Database.Entities.Chat.ChatMember", b =>
{
b.HasOne("SOR.Database.Entities.Chat.ChatChannel", "Channel")
+2 -1
View File
@@ -13,6 +13,7 @@
// ENABLED_SERVICES=gateway → run only Gateway (dedicated gateway pod)
using SOR.Auth;
using SOR.Chat;
using SOR.Collection;
using SOR.Gateway;
using SOR.Networking.Nats;
@@ -129,11 +130,11 @@ builder.Services.AddRedisClientPush();
// Only services listed in ENABLED_SERVICES are started.
if (IsEnabled("auth")) builder.Services.AddAuthService(builder.Configuration);
if (IsEnabled("chat")) builder.Services.AddChatService(builder.Configuration);
if (IsEnabled("collection")) builder.Services.AddCollectionService(builder.Configuration);
if (IsEnabled("gateway")) builder.Services.AddGatewayService(builder.Configuration);
// TODO: Uncomment as each service is implemented:
// if (IsEnabled("chat")) builder.Services.AddChatService(builder.Configuration);
// if (IsEnabled("bazaar")) builder.Services.AddBazaarService(builder.Configuration);
// if (IsEnabled("leaderboard")) builder.Services.AddLeaderboardService(builder.Configuration);
// if (IsEnabled("content")) builder.Services.AddContentService(builder.Configuration);
+1
View File
@@ -29,6 +29,7 @@
<ProjectReference Include="..\SOR.Networking.Redis\SOR.Networking.Redis.csproj" />
<ProjectReference Include="..\SOR.Gateway\SOR.Gateway.csproj" />
<ProjectReference Include="..\SOR.Auth\SOR.Auth.csproj" />
<ProjectReference Include="..\SOR.Chat\SOR.Chat.csproj" />
<ProjectReference Include="..\SOR.Collection\SOR.Collection.csproj" />
</ItemGroup>
</Project>