Files
Heimdall/src/Heimdall.Web/Services/NotificationsHubClient.cs
T
Arnaud Dartois 6530304887
Heimdall Gitea / Detect CI scope (pull_request) Successful in 5s
Heimdall Gitea / Build and tests (pull_request) Failing after 2m16s
Heimdall Gitea / Build and scan server image (pull_request) Skipped
Heimdall Gitea / Build and scan agent image (pull_request) Skipped
Heimdall Gitea / Publish Docker Hub latest tags (pull_request) Skipped
Heimdall Gitea / Publish versioned release (pull_request) Skipped
Heimdall Gitea / CI policy (pull_request) Failing after 1s
fix(pwa): load notification count on badge mount
2026-10-25 18:15:45 +01:00

129 lines
4.2 KiB
C#

using System.Text.Json;
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"/>. Un chargement API initial garantit le
/// compteur même si la connexion temps réel n'est pas encore disponible.
/// </summary>
public class NotificationsHubClient : IAsyncDisposable, IDisposable
{
private readonly AuthState _authState;
private readonly HeimdallApiClient _api;
private readonly NavigationManager _navigation;
private readonly ILogger<NotificationsHubClient> _logger;
private HubConnection? _connection;
private bool _started;
public NotificationsHubClient(
AuthState authState,
HeimdallApiClient api,
NavigationManager navigation,
ILogger<NotificationsHubClient> logger)
{
_authState = authState;
_api = api;
_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 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<JsonElement>("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<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;
}
}