DD.WellWorkover.Cloud/AsbCloudWebApi/SignalR/Services/SignalRNotificationTransportService.cs

67 lines
1.9 KiB
C#
Raw Normal View History

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 SignalRNotificationTransportService : INotificationTransportService
{
private readonly IConnectionManager connectionManager;
private readonly IHubContext<NotificationHub> notificationHubContext;
private readonly IServiceProvider serviceProvider;
public SignalRNotificationTransportService(IConnectionManager connectionManager,
IHubContext<NotificationHub> notificationHubContext,
IServiceProvider serviceProvider)
{
this.connectionManager = connectionManager;
this.notificationHubContext = notificationHubContext;
this.serviceProvider = serviceProvider;
}
public int IdTransportType => 0;
public async Task SendAsync(NotificationDto notification,
CancellationToken cancellationToken)
{
const string method = "notifications";
var connectionId = connectionManager.GetConnectionIdByUserId(notification.IdUser);
if (!string.IsNullOrWhiteSpace(connectionId))
{
notification.SentDate = DateTime.UtcNow;
await notificationHubContext.Clients.Client(connectionId)
.SendAsync(method,
notification,
cancellationToken);
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);
}
}
}