forked from ddrilling/AsbCloudServer
61 lines
1.8 KiB
C#
61 lines
1.8 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;
|
|
|
|
namespace AsbCloudWebApi.SignalR.Services;
|
|
|
|
public class SignalRNotificationSender : INotificationSender
|
|
{
|
|
private readonly IConnectionManager connectionManager;
|
|
private readonly IHubContext<NotificationHub> notificationHubContext;
|
|
private readonly INotificationRepository notificationRepository;
|
|
|
|
public SignalRNotificationSender(IConnectionManager connectionManager,
|
|
IHubContext<NotificationHub> notificationHubContext,
|
|
INotificationRepository notificationRepository)
|
|
{
|
|
this.connectionManager = connectionManager;
|
|
this.notificationHubContext = notificationHubContext;
|
|
this.notificationRepository = notificationRepository;
|
|
}
|
|
|
|
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))
|
|
{
|
|
await notificationHubContext.Clients.Client(connectionId)
|
|
.SendAsync(method,
|
|
notification,
|
|
cancellationToken);
|
|
|
|
notification.SentDate = DateTime.UtcNow;
|
|
notification.NotificationState = NotificationState.Sent;
|
|
}
|
|
|
|
await notificationRepository.UpdateAsync(notification,
|
|
cancellationToken);
|
|
}
|
|
|
|
public async Task SendRangeAsync(IEnumerable<NotificationDto> notifications,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
foreach (var notification in notifications)
|
|
{
|
|
await SendAsync(notification,
|
|
cancellationToken);
|
|
}
|
|
}
|
|
} |