using System.Text.Json; using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.SignalR.Client; namespace Heimdall.Web.Services; /// /// Client hub SignalR pour les notifications temps réel (badge compteur). /// S'abonne au groupe personnel "notif_{userId}" et expose l'événement /// . Un chargement API initial garantit le /// compteur même si la connexion temps réel n'est pas encore disponible. /// public class NotificationsHubClient : IAsyncDisposable, IDisposable { private readonly AuthState _authState; private readonly HeimdallApiClient _api; private readonly NavigationManager _navigation; private readonly ILogger _logger; private HubConnection? _connection; private bool _started; public NotificationsHubClient( AuthState authState, HeimdallApiClient api, NavigationManager navigation, ILogger logger) { _authState = authState; _api = api; _navigation = navigation; _logger = logger; } /// Compteur de notifications non lues (mis à jour par le hub). public int UnreadCount { get; private set; } public event Action? UnreadCountChanged; public async Task RefreshUnreadCountAsync() { try { var count = await _api.GetUnreadNotificationCountAsync(); UnreadCount = count; UnreadCountChanged?.Invoke(count); } catch (Exception ex) { _logger.LogDebug(ex, "NotificationsHubClient: chargement initial du compteur impossible"); } } public async Task StartAsync() { if (_started || !_authState.IsLoggedIn) return; try { var accessToken = _authState.AccessToken; if (string.IsNullOrEmpty(accessToken)) return; // session cookie (SSR/reload) : pas de JWT → pas de hub, fallback silencieux _connection = new HubConnectionBuilder() .WithUrl($"{_navigation.BaseUri}hubs/notifications", options => { options.AccessTokenProvider = GetAccessTokenAsync; }) .WithAutomaticReconnect() .Build(); _connection.On("UnreadCount", (payload) => { if (payload.ValueKind != JsonValueKind.Object || !payload.TryGetProperty("count", out var countElement) || !countElement.TryGetInt32(out var count) || count < 0) { _logger.LogWarning("NotificationsHubClient: unread count payload inattendu"); return; } UnreadCount = count; UnreadCountChanged?.Invoke(count); }); _connection.On("NewNotification", (_) => { UnreadCount++; UnreadCountChanged?.Invoke(UnreadCount); }); await _connection.StartAsync(); await _connection.InvokeAsync("JoinPersonalNotifications"); _started = true; _logger.LogDebug("NotificationsHubClient connecté"); } catch (Exception ex) { _logger.LogWarning(ex, "NotificationsHubClient: connexion impossible — fallback polling"); } } private Task GetAccessTokenAsync() => Task.FromResult(_authState.AccessToken); public void Dispose() { // Synchronous disposal cannot safely wait for SignalR network shutdown. // Start the asynchronous cleanup and return immediately; async consumers // should use DisposeAsync to observe its completion. _ = DisposeConnectionAsync(); GC.SuppressFinalize(this); } public async ValueTask DisposeAsync() { await DisposeConnectionAsync().ConfigureAwait(false); GC.SuppressFinalize(this); } private async Task DisposeConnectionAsync() { var connection = Interlocked.Exchange(ref _connection, null); _started = false; if (connection is null) return; try { await connection.StopAsync(CancellationToken.None).ConfigureAwait(false); } catch (Exception ex) { _logger.LogDebug(ex, "NotificationsHubClient: arrêt de la connexion impossible"); } try { await connection.DisposeAsync().ConfigureAwait(false); } catch (Exception ex) { _logger.LogDebug(ex, "NotificationsHubClient: libération de la connexion impossible"); } } }