DD.WellWorkover.Cloud/AsbCloudWebApi/SignalR/Services/SignalRNotificationSender.cs
Степанов Дмитрий Александрович 83ee280fbb Рефакторинг
1. Поменял время жизни для отправителей уведомлений.
2. Добавил метод в контроллере для получения уведомления по Id.
3. Поправил хаб уведомлений
4. Небольшие фиксы в репозитории и сервисах
2023-07-12 13:31:55 +05:00

70 lines
2.1 KiB
C#

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using AsbCloudApp.Data;
using AsbCloudApp.Repositories;
using AsbCloudApp.Services.Notifications;
using AsbCloudWebApi.SignalR.ConnectionManager;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.DependencyInjection;
namespace AsbCloudWebApi.SignalR.Services;
public class SignalRNotificationSender : INotificationSender
{
private readonly IConnectionManager connectionManager;
private readonly IHubContext<NotificationHub> notificationHubContext;
private readonly IServiceProvider serviceProvider;
public SignalRNotificationSender(IConnectionManager connectionManager,
IHubContext<NotificationHub> notificationHubContext,
IServiceProvider serviceProvider)
{
this.connectionManager = connectionManager;
this.notificationHubContext = notificationHubContext;
this.serviceProvider = serviceProvider;
}
public NotificationTransport NotificationTransport => NotificationTransport.SignalR;
public async Task SendAsync(NotificationDto notification,
CancellationToken cancellationToken)
{
const string method = "notifications";
var connectionId = connectionManager.GetConnectionIdByUserId(notification.IdUser);
if (!string.IsNullOrWhiteSpace(connectionId))
{
string message = $"IdNotification: {notification.Id}";
await notificationHubContext.Clients.Client(connectionId)
.SendAsync(method,
message,
cancellationToken);
notification.SentDate = DateTime.UtcNow;
notification.NotificationState = NotificationState.Sent;
var scope = serviceProvider.CreateScope();
var notificationRepository = scope.ServiceProvider.GetService<INotificationRepository>();
if (notificationRepository != null)
{
await notificationRepository.UpdateAsync(notification, cancellationToken);
}
}
}
public async Task SendRangeAsync(IEnumerable<NotificationDto> notifications,
CancellationToken cancellationToken)
{
foreach (var notification in notifications)
{
await SendAsync(notification,
cancellationToken);
}
}
}