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