DD.WellWorkover.Cloud/AsbCloudInfrastructure/Services/Email/EmailNotificationTransportService.cs

85 lines
2.9 KiB
C#

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Mail;
using System.Threading;
using System.Threading.Tasks;
using AsbCloudApp.Data;
using AsbCloudApp.Exceptions;
using AsbCloudApp.Repositories;
using AsbCloudApp.Services.Notifications;
using AsbCloudInfrastructure.Background;
using AsbCloudInfrastructure.Background.PeriodicWorks;
using DocumentFormat.OpenXml.Presentation;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace AsbCloudInfrastructure.Services.Email
{
public class EmailNotificationTransportService : INotificationTransportService
{
private readonly BackgroundWorker backgroundWorker;
private readonly bool IsConfigured;
private readonly string sender;
private readonly string smtpServer;
private readonly string smtpPassword;
private IConfiguration configuration;
public EmailNotificationTransportService(BackgroundWorker backgroundWorker,
IConfiguration configuration)
{
sender = configuration.GetValue("email:sender", string.Empty);
smtpPassword = configuration.GetValue("email:password", string.Empty);
smtpServer = configuration.GetValue("email:smtpServer", string.Empty);
var configError = string.IsNullOrEmpty(sender) ||
string.IsNullOrEmpty(smtpPassword) ||
string.IsNullOrEmpty(smtpServer);
IsConfigured = !configError;
this.backgroundWorker = backgroundWorker;
}
public int IdTransportType => 1;
public Task SendAsync(NotificationDto notification, CancellationToken cancellationToken)
{
//if (!IsConfigured)
//{
// Trace.TraceWarning("smtp is not configured");
// return Task.CompletedTask;
//}
var workId = MakeWorkId(notification.IdUser, notification.Title, notification.Message);
if (!backgroundWorker.Works.Any(w=>w.Id==workId))
{
var work = new WorkToSendEmail(workId, notification, sender, smtpPassword, smtpServer);
backgroundWorker.Enqueue(work);
}
return Task.CompletedTask;
}
public Task SendRangeAsync(IEnumerable<NotificationDto> notifications, CancellationToken cancellationToken)
{
var tasks = notifications
.Select(notification => SendAsync(notification, cancellationToken));
return Task.WhenAll(tasks);
}
private static string MakeWorkId(int idUser, string subject, string content)
{
var hash = idUser.GetHashCode();
hash ^= subject.GetHashCode();
hash ^= content.GetHashCode();
return hash.ToString("x");
}
}
}