forked from ddrilling/AsbCloudServer
82 lines
2.7 KiB
C#
82 lines
2.7 KiB
C#
using System;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
using AsbCloudApp.Data;
|
|
using AsbCloudApp.Exceptions;
|
|
using AsbCloudApp.Repositories;
|
|
using AsbCloudApp.Services.Notifications;
|
|
|
|
namespace AsbCloudInfrastructure.Services.Notifications;
|
|
|
|
public class NotificationService : INotificationService
|
|
{
|
|
private readonly INotificationSenderManager notificationSenderManager;
|
|
private readonly INotificationRepository notificationRepository;
|
|
|
|
public NotificationService(INotificationSenderManager notificationSenderManager,
|
|
INotificationRepository notificationRepository)
|
|
{
|
|
this.notificationSenderManager = notificationSenderManager;
|
|
this.notificationRepository = notificationRepository;
|
|
}
|
|
|
|
public async Task NotifyAsync(int idUser,
|
|
int idNotificationCategory,
|
|
string title,
|
|
string message,
|
|
TimeSpan timeToLife,
|
|
NotificationTransport notificationTransport,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
NotificationDto notification = new()
|
|
{
|
|
IdUser = idUser,
|
|
IdNotificationCategory = idNotificationCategory,
|
|
Title = title,
|
|
Message = message,
|
|
TimeToLife = timeToLife,
|
|
NotificationTransport = notificationTransport,
|
|
NotificationState = NotificationState.Registered
|
|
};
|
|
|
|
await notificationRepository.InsertAsync(notification,
|
|
cancellationToken);
|
|
|
|
var notificationSender = notificationSenderManager.GetOrDefault(notificationTransport);
|
|
|
|
if(notificationSender is null)
|
|
throw new ArgumentInvalidException("Метод отправки уведомления не найден", nameof(notificationTransport));
|
|
|
|
await notificationSender.SendAsync(notification, cancellationToken);
|
|
}
|
|
|
|
public async Task UpdateNotificationAsync(int idNotification,
|
|
bool isRead,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
var notification = await notificationRepository.GetOrDefaultAsync(idNotification,
|
|
cancellationToken) ?? throw new ArgumentInvalidException("Уведомление не найдено",
|
|
nameof(idNotification));
|
|
|
|
notification.NotificationState = isRead ? NotificationState.Read : NotificationState.Sent;
|
|
|
|
await notificationRepository.UpdateAsync(notification,
|
|
cancellationToken);
|
|
}
|
|
|
|
public async Task ResendNotificationAsync(int idUser,
|
|
NotificationTransport notificationTransport,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
var notifications = await notificationRepository.GetUnsentNotificationsAsync(idUser,
|
|
notificationTransport,
|
|
cancellationToken);
|
|
|
|
var notificationSender = notificationSenderManager.GetOrDefault(notificationTransport);
|
|
|
|
if(notificationSender is null)
|
|
throw new ArgumentInvalidException("Отправитель уведомления не найден", nameof(notificationTransport));
|
|
|
|
await notificationSender.SendRangeAsync(notifications, cancellationToken);
|
|
}
|
|
} |