2023-07-11 19:07:57 +05:00
|
|
|
using System;
|
|
|
|
using System.Collections.Generic;
|
2023-07-14 11:40:57 +05:00
|
|
|
using System.Linq;
|
2023-07-11 19:07:57 +05:00
|
|
|
using System.Threading;
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
using AsbCloudApp.Data;
|
|
|
|
using AsbCloudApp.Services.Notifications;
|
2023-07-26 15:41:51 +05:00
|
|
|
using AsbCloudInfrastructure.Background;
|
|
|
|
using Microsoft.Extensions.DependencyInjection;
|
2023-07-11 19:07:57 +05:00
|
|
|
|
|
|
|
namespace AsbCloudWebApi.SignalR.Services;
|
|
|
|
|
2023-07-13 14:44:40 +05:00
|
|
|
public class SignalRNotificationTransportService : INotificationTransportService
|
2023-07-11 19:07:57 +05:00
|
|
|
{
|
2024-07-04 11:02:45 +05:00
|
|
|
private readonly NotificationBackgroundWorker backgroundWorker;
|
|
|
|
|
|
|
|
public SignalRNotificationTransportService(NotificationBackgroundWorker backgroundWorker)
|
|
|
|
{
|
|
|
|
this.backgroundWorker = backgroundWorker;
|
|
|
|
}
|
|
|
|
|
|
|
|
public int IdTransportType => 0;
|
|
|
|
|
|
|
|
public Task SendAsync(NotificationDto notification,
|
|
|
|
CancellationToken cancellationToken) => SendRangeAsync(new[] { notification }, cancellationToken);
|
|
|
|
|
|
|
|
public Task SendRangeAsync(IEnumerable<NotificationDto> notifications,
|
|
|
|
CancellationToken cancellationToken)
|
|
|
|
{
|
|
|
|
var workId = HashCode.Combine(notifications.Select(n => n.Id)).ToString("x");
|
|
|
|
|
|
|
|
if (backgroundWorker.Works.Any(w => w.Id == workId))
|
|
|
|
return Task.CompletedTask;
|
|
|
|
|
|
|
|
var workAction = MakeSignalRSendWorkAction(notifications);
|
|
|
|
var work = Work.CreateByDelegate(workId, workAction);
|
|
|
|
backgroundWorker.Enqueue(work);
|
|
|
|
|
|
|
|
return Task.CompletedTask;
|
|
|
|
}
|
|
|
|
|
|
|
|
private Func<string, IServiceProvider, Action<string, double?>, CancellationToken, Task> MakeSignalRSendWorkAction(IEnumerable<NotificationDto> notifications)
|
|
|
|
{
|
|
|
|
return async (_, serviceProvider, onProgress, cancellationToken) =>
|
|
|
|
{
|
|
|
|
var notificationPublisher = serviceProvider.GetRequiredService<NotificationPublisher>();
|
|
|
|
|
|
|
|
var groupedNotificationsByUsers = notifications.GroupBy(n => n.IdUser);
|
|
|
|
|
|
|
|
foreach (var groupedNotificationByUser in groupedNotificationsByUsers)
|
|
|
|
{
|
|
|
|
await notificationPublisher.PublishAsync(groupedNotificationByUser, cancellationToken);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|
2023-07-11 19:07:57 +05:00
|
|
|
}
|