Files
Heimdall/src/Heimdall.Web/Services/NotificationsHubClient.cs
T

111 lines
3.7 KiB
C#
Raw Normal View History

using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.SignalR.Client;
namespace Heimdall.Web.Services;
/// <summary>
/// Client hub SignalR pour les notifications temps réel (badge compteur).
/// S'abonne au groupe personnel "notif_{userId}" et expose l'événement
/// <see cref="UnreadCountChanged"/>. Le polling est le fallback : si la
/// connexion échoue (pas de JWT en session cookie, hub indisponible), le
/// badge reste silencieux sans casser l'UI.
/// </summary>
public class NotificationsHubClient : IAsyncDisposable, IDisposable
{
private readonly AuthState _authState;
private readonly NavigationManager _navigation;
private readonly ILogger<NotificationsHubClient> _logger;
private HubConnection? _connection;
private bool _started;
public NotificationsHubClient(
AuthState authState,
NavigationManager navigation,
ILogger<NotificationsHubClient> logger)
{
_authState = authState;
_navigation = navigation;
_logger = logger;
}
/// <summary>Compteur de notifications non lues (mis à jour par le hub).</summary>
public int UnreadCount { get; private set; }
public event Action<int>? UnreadCountChanged;
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<object>("UnreadCount", (payload) =>
{
try
{
var count = (int)((IDictionary<string, object>)payload)["count"];
UnreadCount = count;
UnreadCountChanged?.Invoke(count);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "NotificationsHubClient: UnreadCount payload inattendu");
}
});
_connection.On<object>("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<string?> GetAccessTokenAsync() => Task.FromResult(_authState.AccessToken);
public void Dispose()
{
// Dispose synchrone (requis par certains conteneurs / bUnit) :
// déconnexion best-effort sans attendre la fermeture réseau.
if (_connection is not null)
{
try
{
_connection.StopAsync(CancellationToken.None).Wait(TimeSpan.FromMilliseconds(500));
_connection.DisposeAsync().AsTask().GetAwaiter().GetResult();
}
catch { /* best effort */ }
}
_started = false;
GC.SuppressFinalize(this);
}
public async ValueTask DisposeAsync()
{
Dispose();
GC.SuppressFinalize(this);
await Task.CompletedTask;
}
}