69 lines
2.4 KiB
C#
69 lines
2.4 KiB
C#
using HRM.UI.Realtime.Jobs;
|
|
using Microsoft.AspNetCore.SignalR;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace HRM.UI.Realtime
|
|
{
|
|
/// <summary>
|
|
/// The only way application code sends real-time messages. Inject it (singleton) wherever a push is needed;
|
|
/// never inject IHubContext directly, so a later move to Redis / Azure SignalR changes this one class only.
|
|
/// All methods are fire-safe: a failed send is logged, never thrown back into business code.
|
|
/// </summary>
|
|
public interface IRealtimePublisher
|
|
{
|
|
/// <summary>To every open tab of one user (the JWT "UserID" claim).</summary>
|
|
Task ToUserAsync(int userId, string topic, object payload);
|
|
|
|
/// <summary>To every user currently working in one payroll type.</summary>
|
|
Task ToPayrollTypeAsync(int payrollTypeId, string topic, object payload);
|
|
|
|
/// <summary>To every connected user.</summary>
|
|
Task ToAllAsync(string topic, object payload);
|
|
|
|
/// <summary>A job's progress to everybody following it. Used by the job runner; features rarely need it.</summary>
|
|
Task JobChangedAsync(JobSnapshot snapshot);
|
|
}
|
|
|
|
internal sealed class RealtimePublisher : IRealtimePublisher
|
|
{
|
|
private readonly IHubContext<AppHub, IAppClient> _hub;
|
|
|
|
public RealtimePublisher(IHubContext<AppHub, IAppClient> hub)
|
|
{
|
|
_hub = hub;
|
|
}
|
|
|
|
public Task ToUserAsync(int userId, string topic, object payload)
|
|
{
|
|
return Safe(_hub.Clients.User(userId.ToString()).Event(topic, payload));
|
|
}
|
|
|
|
public Task ToPayrollTypeAsync(int payrollTypeId, string topic, object payload)
|
|
{
|
|
return Safe(_hub.Clients.Group(RealtimeGroups.PayrollType(payrollTypeId)).Event(topic, payload));
|
|
}
|
|
|
|
public Task ToAllAsync(string topic, object payload)
|
|
{
|
|
return Safe(_hub.Clients.All.Event(topic, payload));
|
|
}
|
|
|
|
public Task JobChangedAsync(JobSnapshot snapshot)
|
|
{
|
|
return Safe(_hub.Clients.Group(RealtimeGroups.Job(snapshot.RunId)).JobProgress(snapshot));
|
|
}
|
|
|
|
private static async Task Safe(Task send)
|
|
{
|
|
try
|
|
{
|
|
await send.ConfigureAwait(false);
|
|
}
|
|
catch (System.Exception ex)
|
|
{
|
|
Ease.Core.Utility.ExceptionLog.Write(ex);
|
|
}
|
|
}
|
|
}
|
|
}
|