diff --git a/Client/origin-client/scenes/chat/chat_overlay.gd b/Client/origin-client/scenes/chat/chat_overlay.gd index 0e03da5..0666480 100644 --- a/Client/origin-client/scenes/chat/chat_overlay.gd +++ b/Client/origin-client/scenes/chat/chat_overlay.gd @@ -52,6 +52,7 @@ var _content_nodes : Array[Control] = [] # one entry per Tab enum value var _input_bar : HBoxContainer = null var _message_input : LineEdit = null +var _send_button : Button = null # Per-tab content refs var _friends_list : VBoxContainer = null @@ -214,22 +215,35 @@ func _make_input_bar() -> Control: margin.add_child(inner) _message_input = LineEdit.new() - _message_input.placeholder_text = "Type a message…" + _message_input.placeholder_text = "Type a message..." _message_input.size_flags_horizontal = Control.SIZE_EXPAND_FILL _message_input.add_theme_font_size_override("font_size", 13) _message_input.max_length = 500 - _message_input.text_submitted.connect(_on_send) + _message_input.text_submitted.connect(func(_text: String) -> void: + _send_current_input()) inner.add_child(_message_input) - var send_btn := Button.new() - send_btn.text = "Send" - send_btn.custom_minimum_size = Vector2(52, 0) - send_btn.add_theme_font_size_override("font_size", 12) - send_btn.pressed.connect(func() -> void: _on_send(_message_input.text)) - inner.add_child(send_btn) + _send_button = Button.new() + _send_button.text = "Send" + _send_button.custom_minimum_size = Vector2(52, 0) + _send_button.add_theme_font_size_override("font_size", 12) + _send_button.pressed.connect(_send_current_input) + inner.add_child(_send_button) return _input_bar + +func _unhandled_input(event: InputEvent) -> void: + if not _panel.visible or not _input_bar.visible: + return + if not is_instance_valid(_message_input) or not _message_input.has_focus(): + return + if event is InputEventKey: + var key := event as InputEventKey + if key.pressed and not key.echo \ + and (key.keycode == KEY_ENTER or key.keycode == KEY_KP_ENTER): + _send_current_input() + get_viewport().set_input_as_handled() # ── Tab builders ────────────────────────────────────────────────────────────── func _build_tab_content(tab: Tab) -> Control: @@ -944,6 +958,11 @@ func _prompt_nickname(account_id: String, display_name: String) -> void: # ── Send ────────────────────────────────────────────────────────────────────── +func _send_current_input() -> void: + if not is_instance_valid(_message_input): + return + _on_send(_message_input.text) + func _on_send(text: String) -> void: var trimmed := text.strip_edges() if trimmed.is_empty() or _active_channel.is_empty(): @@ -1060,3 +1079,5 @@ func _make_section_label(text: String) -> Control: lbl.add_theme_font_size_override("font_size", 10) m.add_child(lbl) return m + + diff --git a/Server/src/SOR.Admin/Components/Pages/Chat/ChatChannelViewer.razor b/Server/src/SOR.Admin/Components/Pages/Chat/ChatChannelViewer.razor index 9a26e0d..0b5008a 100644 --- a/Server/src/SOR.Admin/Components/Pages/Chat/ChatChannelViewer.razor +++ b/Server/src/SOR.Admin/Components/Pages/Chat/ChatChannelViewer.razor @@ -370,6 +370,7 @@ else private static string TypeBadge(SOR.Database.Enums.ChatChannelType t) => t switch { SOR.Database.Enums.ChatChannelType.Global => "bg-primary", + SOR.Database.Enums.ChatChannelType.Lobby => "bg-secondary", 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", diff --git a/Server/src/SOR.Admin/Components/Pages/Chat/ChatOverview.razor b/Server/src/SOR.Admin/Components/Pages/Chat/ChatOverview.razor index b268a02..99d4bef 100644 --- a/Server/src/SOR.Admin/Components/Pages/Chat/ChatOverview.razor +++ b/Server/src/SOR.Admin/Components/Pages/Chat/ChatOverview.razor @@ -156,6 +156,7 @@ else private static string TypeBadge(ChatChannelType t) => t switch { ChatChannelType.Global => "bg-primary", + ChatChannelType.Lobby => "bg-secondary", ChatChannelType.Direct => "bg-info text-dark", ChatChannelType.Match => "bg-success", ChatChannelType.Guild => "bg-warning text-dark", diff --git a/Server/src/SOR.Chat/ChatChannelMembership.cs b/Server/src/SOR.Chat/ChatChannelMembership.cs new file mode 100644 index 0000000..e650583 --- /dev/null +++ b/Server/src/SOR.Chat/ChatChannelMembership.cs @@ -0,0 +1,155 @@ +namespace SOR.Chat; + +using Microsoft.EntityFrameworkCore; +using SOR.Database.Contexts; +using SOR.Database.Entities.Chat; +using SOR.Database.Enums; + +internal static class ChatChannelMembership +{ + public static async Task EnsureDefaultMembershipsAsync( + ChatDbContext chatDb, + Guid accountId, + CancellationToken ct) + { + var now = DateTimeOffset.UtcNow; + + var global = await GetOrCreateSingletonChannelAsync(chatDb, ChatChannelType.Global, "global", now, ct); + await EnsureMemberAsync(chatDb, global.Id, accountId, now, ct); + + var lobby = await GetOrCreateSingletonChannelAsync(chatDb, ChatChannelType.Lobby, "lobby", now, ct); + await EnsureMemberAsync(chatDb, lobby.Id, accountId, now, ct); + } + + public static async Task EnsureMatchMembershipsAsync( + ChatDbContext chatDb, + Guid matchId, + IReadOnlyCollection accountIds, + CancellationToken ct) + { + if (accountIds.Count == 0) + return; + + var now = DateTimeOffset.UtcNow; + var channel = await GetOrCreateMatchChannelAsync(chatDb, matchId, now, ct); + foreach (var accountId in accountIds.Distinct()) + await EnsureMemberAsync(chatDb, channel.Id, accountId, now, ct); + } + + public static async Task EndMatchMembershipsAsync( + ChatDbContext chatDb, + Guid matchId, + CancellationToken ct) + { + var matchKey = matchId.ToString("D"); + + var channel = await chatDb.Channels + .Where(c => c.ChannelType == ChatChannelType.Match && c.MatchId == matchKey) + .OrderBy(c => c.CreatedAt) + .FirstOrDefaultAsync(ct); + + if (channel is null) + return; + + var members = await chatDb.Members + .Where(m => m.ChannelId == channel.Id && m.LeftAt == null) + .ToListAsync(ct); + + if (members.Count == 0) + return; + + var now = DateTimeOffset.UtcNow; + foreach (var member in members) + member.LeftAt = now; + + await chatDb.SaveChangesAsync(ct); + } + + private static async Task GetOrCreateSingletonChannelAsync( + ChatDbContext chatDb, + ChatChannelType channelType, + string name, + DateTimeOffset now, + CancellationToken ct) + { + var existing = await chatDb.Channels + .Where(c => c.ChannelType == channelType && c.MatchId == null) + .OrderBy(c => c.CreatedAt) + .FirstOrDefaultAsync(ct); + + if (existing is not null) + return existing; + + var channel = new ChatChannel + { + Name = name, + ChannelType = channelType, + MatchId = null, + CreatedAt = now, + }; + + chatDb.Channels.Add(channel); + await chatDb.SaveChangesAsync(ct); + return channel; + } + + private static async Task GetOrCreateMatchChannelAsync( + ChatDbContext chatDb, + Guid matchId, + DateTimeOffset now, + CancellationToken ct) + { + var matchKey = matchId.ToString("D"); + + var existing = await chatDb.Channels + .Where(c => c.ChannelType == ChatChannelType.Match && c.MatchId == matchKey) + .OrderBy(c => c.CreatedAt) + .FirstOrDefaultAsync(ct); + + if (existing is not null) + return existing; + + var channel = new ChatChannel + { + Name = $"game:{matchKey}", + ChannelType = ChatChannelType.Match, + MatchId = matchKey, + CreatedAt = now, + }; + + chatDb.Channels.Add(channel); + await chatDb.SaveChangesAsync(ct); + return channel; + } + + private static async Task EnsureMemberAsync( + ChatDbContext chatDb, + Guid channelId, + Guid accountId, + DateTimeOffset now, + CancellationToken ct) + { + var member = await chatDb.Members + .FirstOrDefaultAsync(m => m.ChannelId == channelId && m.AccountId == accountId, ct); + + if (member is null) + { + chatDb.Members.Add(new ChatMember + { + ChannelId = channelId, + AccountId = accountId, + JoinedAt = now, + LeftAt = null, + }); + await chatDb.SaveChangesAsync(ct); + return; + } + + if (member.LeftAt is null) + return; + + member.LeftAt = null; + member.JoinedAt = now; + await chatDb.SaveChangesAsync(ct); + } +} diff --git a/Server/src/SOR.Chat/ChatLifecycleHostedService.cs b/Server/src/SOR.Chat/ChatLifecycleHostedService.cs new file mode 100644 index 0000000..10289c3 --- /dev/null +++ b/Server/src/SOR.Chat/ChatLifecycleHostedService.cs @@ -0,0 +1,82 @@ +namespace SOR.Chat; + +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using SOR.Database.Contexts; +using SOR.Networking.Abstractions.EventBus; +using SOR.Shared.Nats; + +internal sealed class ChatLifecycleHostedService : BackgroundService +{ + private readonly IServiceScopeFactory _scopeFactory; + private readonly IEventBus _eventBus; + private readonly ILogger _logger; + + public ChatLifecycleHostedService( + IServiceScopeFactory scopeFactory, + IEventBus eventBus, + ILogger logger) + { + _scopeFactory = scopeFactory; + _eventBus = eventBus; + _logger = logger; + } + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + var startedTask = RunGameStartedSubscriptionAsync(stoppingToken); + var endedTask = RunGameEndedSubscriptionAsync(stoppingToken); + + await Task.WhenAll(startedTask, endedTask); + } + + private async Task RunGameStartedSubscriptionAsync(CancellationToken ct) + { + try + { + await foreach (var evt in _eventBus + .SubscribeAsync(NatsSubjects.GameStarted, ct) + .WithCancellation(ct)) + { + await using var scope = _scopeFactory.CreateAsyncScope(); + var chatDb = scope.ServiceProvider.GetRequiredService(); + + await ChatChannelMembership.EnsureMatchMembershipsAsync( + chatDb, + evt.GameId, + evt.PlayerIds, + ct); + } + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) + { + } + catch (Exception ex) + { + _logger.LogError(ex, "Game-started subscription loop crashed."); + } + } + + private async Task RunGameEndedSubscriptionAsync(CancellationToken ct) + { + try + { + await foreach (var evt in _eventBus + .SubscribeAsync(NatsSubjects.GameEnded, ct) + .WithCancellation(ct)) + { + await using var scope = _scopeFactory.CreateAsyncScope(); + var chatDb = scope.ServiceProvider.GetRequiredService(); + await ChatChannelMembership.EndMatchMembershipsAsync(chatDb, evt.GameId, ct); + } + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) + { + } + catch (Exception ex) + { + _logger.LogError(ex, "Game-ended subscription loop crashed."); + } + } +} diff --git a/Server/src/SOR.Chat/Handlers/ChatGetChannelsHandler.cs b/Server/src/SOR.Chat/Handlers/ChatGetChannelsHandler.cs index d6d34c4..20e3cb1 100644 --- a/Server/src/SOR.Chat/Handlers/ChatGetChannelsHandler.cs +++ b/Server/src/SOR.Chat/Handlers/ChatGetChannelsHandler.cs @@ -24,6 +24,7 @@ internal sealed class ChatGetChannelsHandler : ChatHandlerBase, IMessageHandler CancellationToken cancellationToken) { var accountId = Guid.Parse(connection.UserId); + await ChatChannelMembership.EnsureDefaultMembershipsAsync(_chatDb, accountId, cancellationToken); var channels = await _chatDb.Members .Where(m => m.AccountId == accountId && m.LeftAt == null) diff --git a/Server/src/SOR.Chat/ServiceRegistration.cs b/Server/src/SOR.Chat/ServiceRegistration.cs index 83e9ef9..d2ef60b 100644 --- a/Server/src/SOR.Chat/ServiceRegistration.cs +++ b/Server/src/SOR.Chat/ServiceRegistration.cs @@ -35,6 +35,7 @@ public static class ServiceRegistration services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddHostedService(); return services; } diff --git a/Server/src/SOR.Database/Enums/ChatEnums.cs b/Server/src/SOR.Database/Enums/ChatEnums.cs index bd9d2e6..9af5180 100644 --- a/Server/src/SOR.Database/Enums/ChatEnums.cs +++ b/Server/src/SOR.Database/Enums/ChatEnums.cs @@ -4,6 +4,8 @@ public enum ChatChannelType { /// Server-wide public chat. Global, + /// Server-wide pre-game lobby chat. + Lobby, /// Private channel for an active match. Match, /// Direct message between two accounts. diff --git a/Server/src/SOR.Game/Handlers/GameJoinCustomLobbyHandler.cs b/Server/src/SOR.Game/Handlers/GameJoinCustomLobbyHandler.cs index 823194e..d3ee155 100644 --- a/Server/src/SOR.Game/Handlers/GameJoinCustomLobbyHandler.cs +++ b/Server/src/SOR.Game/Handlers/GameJoinCustomLobbyHandler.cs @@ -2,12 +2,15 @@ namespace SOR.Game.Handlers; using System.Text.Json; using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; using SOR.Database.Contexts; using SOR.Database.Entities.Game; using SOR.Database.Enums; +using SOR.Networking.Abstractions.EventBus; using SOR.Networking.Abstractions.Messaging; using SOR.Networking.Abstractions.Push; using SOR.Networking.Abstractions.Transport; +using SOR.Shared.Nats; using SOR.Shared.Networking; /// @@ -22,15 +25,21 @@ internal sealed class GameJoinCustomLobbyHandler : GameHandlerBase, IMessageHand private readonly IMessageSerializer _serializer; private readonly GameDbContext _gameDb; private readonly IClientPush _clientPush; + private readonly IEventBus _eventBus; + private readonly ILogger _logger; public GameJoinCustomLobbyHandler( IMessageSerializer serializer, GameDbContext gameDb, - IClientPush clientPush) + IClientPush clientPush, + IEventBus eventBus, + ILogger logger) { _serializer = serializer; _gameDb = gameDb; _clientPush = clientPush; + _eventBus = eventBus; + _logger = logger; } public string MessageType => "game.custom.join"; @@ -88,6 +97,23 @@ internal sealed class GameJoinCustomLobbyHandler : GameHandlerBase, IMessageHand await _gameDb.SaveChangesAsync(ct); + try + { + await _eventBus.PublishAsync( + NatsSubjects.GameStarted, + new GameStartedEvent( + session.Id, + new[] { lobby.HostAccountId, accountId }, + DateTimeOffset.UtcNow), + ct); + } + catch (Exception ex) + { + _logger.LogError(ex, + "Failed publishing game-started event for custom lobby session {SessionId}", + session.Id); + } + // Push game-started notification to both players. var push = new CustomLobbyGameStartedPush(session.Id, accountId); var pushToHost = new CustomLobbyGameStartedPush(session.Id, accountId); diff --git a/Server/src/SOR.Matchmaking/MatchmakerService.cs b/Server/src/SOR.Matchmaking/MatchmakerService.cs index e17693f..97171f1 100644 --- a/Server/src/SOR.Matchmaking/MatchmakerService.cs +++ b/Server/src/SOR.Matchmaking/MatchmakerService.cs @@ -9,7 +9,9 @@ using SOR.Database.Contexts; using SOR.Database.Entities.Game; using SOR.Database.Entities.Identity; using SOR.Database.Enums; +using SOR.Networking.Abstractions.EventBus; using SOR.Networking.Abstractions.Push; +using SOR.Shared.Nats; using SOR.Shared.Networking; /// @@ -67,6 +69,7 @@ internal sealed class MatchmakerService : BackgroundService var gameDb = scope.ServiceProvider.GetRequiredService(); var identityDb = scope.ServiceProvider.GetRequiredService(); var clientPush = scope.ServiceProvider.GetRequiredService(); + var eventBus = scope.ServiceProvider.GetRequiredService(); var now = DateTimeOffset.UtcNow; // Load all searching entries, ordered by wait time (longest waiting first). @@ -148,6 +151,23 @@ internal sealed class MatchmakerService : BackgroundService "Match found: {A} vs {B} (session {S})", entry.AccountId, opponent.AccountId, session.Id); + try + { + await eventBus.PublishAsync( + NatsSubjects.GameStarted, + new GameStartedEvent( + session.Id, + new[] { entry.AccountId, opponent.AccountId }, + now), + ct); + } + catch (Exception ex) + { + _logger.LogError(ex, + "Failed publishing game-started event for session {SessionId}", + session.Id); + } + // Fetch display names for the push payloads. var names = await identityDb.Set() .AsNoTracking() diff --git a/Server/src/SOR.Shared/Nats/NatsEvents.cs b/Server/src/SOR.Shared/Nats/NatsEvents.cs new file mode 100644 index 0000000..a18aa3a --- /dev/null +++ b/Server/src/SOR.Shared/Nats/NatsEvents.cs @@ -0,0 +1,13 @@ +namespace SOR.Shared.Nats; + +public sealed record GameStartedEvent( + Guid GameId, + IReadOnlyList PlayerIds, + DateTimeOffset StartedAt); + +public sealed record GameEndedEvent( + Guid GameId, + Guid WinnerId, + Guid LoserId, + int DurationSeconds, + DateTimeOffset EndedAt);