using System.Security.Claims; using Heimdall.Api.Security; using Heimdall.Application.DTOs; using Heimdall.Application.Metrics; using Heimdall.Application.Services; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.SignalR; namespace Heimdall.Api.Hubs; /// /// SignalR hub for in-app notifications with badge count. /// JWT-authenticated users receive new notifications and unread count updates /// without polling. /// Personal notification subscriptions are reauthorized before each broadcast. /// [Authorize(AuthenticationSchemes = "JwtBearer")] public class NotificationsHub : Hub { private readonly ILogger _logger; private readonly ResourceAccess _access; private readonly LiveSubscriptions _subscriptions; public NotificationsHub(ILogger logger, ResourceAccess access, LiveSubscriptions subscriptions) { _logger = logger; _access = access; _subscriptions = subscriptions; } /// /// Clients call this to join their personal notification channel. /// Identity and account session are resolved from persisted state. /// public async Task JoinPersonalNotifications() { var requester = await _access.ResolveAsync(Context.User, Context.ConnectionAborted); if (requester is null || requester.Kind != RequesterKind.Human) throw new HubException("Access denied"); var userId = requester.Id.ToString(); _subscriptions.Join("notifications", Context.ConnectionId, userId, Context.User!); _logger.LogDebug("Client {ConnectionId} joined personal notifications for user {UserId}", Context.ConnectionId, userId); } public Task LeavePersonalNotifications() { var id = Context.User?.FindFirstValue(ClaimTypes.NameIdentifier); if (id is not null) _subscriptions.Leave("notifications", Context.ConnectionId, id); return Task.CompletedTask; } public override async Task OnConnectedAsync() { HeimdallMetrics.SignalRConnectionAdded(); _logger.LogDebug("Client connected to notifications hub: {ConnectionId}", Context.ConnectionId); await base.OnConnectedAsync(); } public override async Task OnDisconnectedAsync(Exception? exception) { _subscriptions.Disconnect("notifications", Context.ConnectionId); HeimdallMetrics.SignalRConnectionRemoved(); _logger.LogDebug("Client disconnected from notifications hub: {ConnectionId}", Context.ConnectionId); await base.OnDisconnectedAsync(exception); } } /// /// Broadcasts notifications to connected clients via SignalR. /// Uses IHubContext for thread-safe broadcasting outside of hub connections. /// public class NotificationBroadcastService : INotificationBroadcastService { private readonly IHubContext _hubContext; private readonly ILogger _logger; private readonly ResourceAccess _access; private readonly LiveSubscriptions _subscriptions; public NotificationBroadcastService(IHubContext hubContext, ILogger logger, ResourceAccess access, LiveSubscriptions subscriptions) { _hubContext = hubContext; _logger = logger; _access = access; _subscriptions = subscriptions; } public async Task NotifyNewNotification(NotificationDto notification, CancellationToken ct = default) { _logger.LogDebug("Broadcasting new notification: {NotificationId} to user {UserId}", notification.Id, notification.UserId); var recipients = await RecipientsAsync(notification.UserId, ct); await _hubContext.Clients.Clients(recipients).SendAsync("NewNotification", notification, ct); } public async Task NotifyUnreadCount(Guid userId, int count, CancellationToken ct = default) { _logger.LogDebug("Broadcasting unread count: User={UserId} Count={Count}", userId, count); var recipients = await RecipientsAsync(userId, ct); await _hubContext.Clients.Clients(recipients).SendAsync("UnreadCount", new { count }, ct); } private Task> RecipientsAsync(Guid userId, CancellationToken ct) => _subscriptions.AuthorizedAsync("notifications", userId.ToString(), _access, r => Task.FromResult(r.Kind == RequesterKind.Human && r.Id == userId), ct); }