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

129 lines
4.9 KiB
C#
Raw Normal View History

using System;
2022-02-28 14:44:26 +05:00
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 Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
2022-02-28 14:44:26 +05:00
namespace AsbCloudInfrastructure.Services.Email
2022-02-28 14:44:26 +05:00
{
public class EmailNotificationTransportService : INotificationTransportService
2022-02-28 14:44:26 +05:00
{
private readonly BackgroundWorker backgroundWorker;
2022-02-28 14:44:26 +05:00
private readonly bool IsConfigured;
private readonly string sender;
private readonly string smtpServer;
private readonly string smtpPassword;
public EmailNotificationTransportService(BackgroundWorker backgroundWorker,
IConfiguration configuration)
2022-02-28 14:44:26 +05:00
{
sender = configuration.GetValue("email:sender", string.Empty);
smtpPassword = configuration.GetValue("email:password", string.Empty);
smtpServer = configuration.GetValue("email:smtpServer", string.Empty);
2022-02-28 14:44:26 +05:00
var configError = string.IsNullOrEmpty(sender) ||
2022-02-28 14:44:26 +05:00
string.IsNullOrEmpty(smtpPassword) ||
string.IsNullOrEmpty(smtpServer);
2022-02-28 14:44:26 +05:00
IsConfigured = !configError;
this.backgroundWorker = backgroundWorker;
}
public int IdTransportType => 1;
public Task SendAsync(NotificationDto notification, CancellationToken cancellationToken)
2022-02-28 14:44:26 +05:00
{
2022-04-11 18:00:34 +05:00
if (!IsConfigured)
2022-02-28 14:44:26 +05:00
{
Trace.TraceWarning("smtp is not configured");
return Task.CompletedTask;
}
var workId = MakeWorkId(notification.IdUser, notification.Title, notification.Message);
if (!backgroundWorker.Contains(workId))
2022-02-28 14:44:26 +05:00
{
var workAction = MakeEmailSendWorkAction(notification);
var work = new WorkBase(workId, workAction);
backgroundWorker.Push(work);
2022-04-11 18:00:34 +05:00
}
return Task.CompletedTask;
}
public Task SendRangeAsync(IEnumerable<NotificationDto> notifications, CancellationToken cancellationToken)
{
var tasks = notifications
.Select(notification => SendAsync(notification, cancellationToken));
return Task.WhenAll(tasks);
2022-02-28 14:44:26 +05:00
}
2022-02-28 14:44:26 +05:00
private Func<string, IServiceProvider, CancellationToken, Task> MakeEmailSendWorkAction(NotificationDto notification)
2022-02-28 14:44:26 +05:00
{
if (string.IsNullOrWhiteSpace(notification.Title))
throw new ArgumentInvalidException($"{nameof(notification.Title)} should be set", nameof(notification.Title));
2022-04-11 18:00:34 +05:00
return async (_, serviceProvider, token) =>
2022-02-28 14:44:26 +05:00
{
var notificationRepository = serviceProvider.GetRequiredService<INotificationRepository>();
var userRepository = serviceProvider.GetRequiredService<IUserRepository>();
var user = await userRepository.GetOrDefaultAsync(notification.IdUser, token)
?? throw new ArgumentInvalidException("Пользователь не найден" , nameof(notification.IdUser));
if(!MailAddress.TryCreate(user.Email, out var mailAddress))
Trace.TraceWarning($"Mail {user.Email} is not correct.");
if (mailAddress is null)
throw new ArgumentInvalidException($"Mail {user.Email} is not null.", nameof(user.Email));
2022-02-28 14:44:26 +05:00
var from = new MailAddress(sender);
var message = new MailMessage
{
From = from
};
message.To.Add(mailAddress.Address);
2022-05-05 13:28:48 +05:00
message.BodyEncoding = System.Text.Encoding.UTF8;
message.Body = notification.Message;
message.Subject = notification.Title;
2022-02-28 14:44:26 +05:00
message.IsBodyHtml = true;
2022-05-05 10:45:04 +05:00
using var client = new SmtpClient(smtpServer);
2022-02-28 14:44:26 +05:00
client.EnableSsl = true;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential(sender, smtpPassword);
2022-04-11 18:00:34 +05:00
2022-05-05 13:28:48 +05:00
await client.SendMailAsync(message, token);
notification.SentDate = DateTime.UtcNow;
await notificationRepository.UpdateAsync(notification, token);
Trace.TraceInformation($"Send email to {user.Email} subj:{notification.Title} html body count {notification.Message.Length}");
2022-02-28 14:44:26 +05:00
};
2022-04-11 18:00:34 +05:00
}
2022-02-28 14:44:26 +05:00
private static string MakeWorkId(int idUser, string subject, string content)
2022-02-28 14:44:26 +05:00
{
var hash = idUser.GetHashCode();
2022-02-28 14:44:26 +05:00
hash ^= subject.GetHashCode();
hash ^= content.GetHashCode();
return hash.ToString("x");
}
}
}