From 371ff37d2efdfe8f67434cfd90cb012337874856 Mon Sep 17 00:00:00 2001 From: Olga Nemt Date: Thu, 21 Dec 2023 10:50:26 +0500 Subject: [PATCH] =?UTF-8?q?Worker=20=D0=B4=D0=BB=D1=8F=20=D0=BE=D1=82?= =?UTF-8?q?=D0=BF=D1=80=D0=B0=D0=B2=D0=BA=D0=B8=20email?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Background/WorkToSendEmail.cs | 73 +++++++++++++++++++ .../EmailNotificationTransportService.cs | 61 +++------------- 2 files changed, 83 insertions(+), 51 deletions(-) create mode 100644 AsbCloudInfrastructure/Background/WorkToSendEmail.cs diff --git a/AsbCloudInfrastructure/Background/WorkToSendEmail.cs b/AsbCloudInfrastructure/Background/WorkToSendEmail.cs new file mode 100644 index 00000000..da1f273f --- /dev/null +++ b/AsbCloudInfrastructure/Background/WorkToSendEmail.cs @@ -0,0 +1,73 @@ +using AsbCloudApp.Data; +using AsbCloudApp.Exceptions; +using AsbCloudApp.Repositories; +using AsbCloudApp.Services; +using AsbCloudDb.Model; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Net.Mail; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace AsbCloudInfrastructure.Background +{ + internal class WorkToSendEmail : Work + { + private NotificationDto notification; + private string sender; + private string smtpPassword; + private string smtpServer; + + public WorkToSendEmail(string workId, NotificationDto notification, string sender, string smtpPassword, string smtpServer) : base(workId) + { + this.notification = notification; + + this.sender = sender; + this.smtpPassword = smtpPassword; + this.smtpServer = smtpServer; + } + + protected override async Task Action(string id, IServiceProvider services, Action onProgressCallback, CancellationToken token) + { + var notificationRepository = services.GetRequiredService(); + var userRepository = services.GetRequiredService(); + + 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."); + throw new ArgumentInvalidException(nameof(user.Email), $"Mail {user.Email} is not null."); + } + + var from = new MailAddress(sender); + var message = new MailMessage + { + From = from + }; + + message.To.Add(mailAddress.Address); + message.BodyEncoding = System.Text.Encoding.UTF8; + message.Body = notification.Message; + message.Subject = notification.Title; + message.IsBodyHtml = true; + + using var client = new SmtpClient(smtpServer); + client.EnableSsl = true; + client.UseDefaultCredentials = false; + client.Credentials = new System.Net.NetworkCredential(sender, smtpPassword); + + 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}"); + } + } +} diff --git a/AsbCloudInfrastructure/Services/Email/EmailNotificationTransportService.cs b/AsbCloudInfrastructure/Services/Email/EmailNotificationTransportService.cs index e56e423f..e345c351 100644 --- a/AsbCloudInfrastructure/Services/Email/EmailNotificationTransportService.cs +++ b/AsbCloudInfrastructure/Services/Email/EmailNotificationTransportService.cs @@ -10,6 +10,7 @@ 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; @@ -24,6 +25,7 @@ namespace AsbCloudInfrastructure.Services.Email private readonly string sender; private readonly string smtpServer; private readonly string smtpPassword; + private IConfiguration configuration; public EmailNotificationTransportService(BackgroundWorker backgroundWorker, IConfiguration configuration) @@ -32,6 +34,7 @@ namespace AsbCloudInfrastructure.Services.Email 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); @@ -45,19 +48,18 @@ namespace AsbCloudInfrastructure.Services.Email public Task SendAsync(NotificationDto notification, CancellationToken cancellationToken) { - if (!IsConfigured) - { - Trace.TraceWarning("smtp is not configured"); - return Task.CompletedTask; - } + //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 workAction = MakeEmailSendWorkAction(notification); - - var work = Work.CreateByDelegate(workId, workAction); + var work = new WorkToSendEmail(workId, notification, sender, smtpPassword, smtpServer); backgroundWorker.Enqueue(work); + } return Task.CompletedTask; @@ -71,49 +73,6 @@ namespace AsbCloudInfrastructure.Services.Email return Task.WhenAll(tasks); } - private Func, CancellationToken, Task> MakeEmailSendWorkAction(NotificationDto notification) - { - return async (_, serviceProvider, onProgress, token) => - { - var notificationRepository = serviceProvider.GetRequiredService(); - var userRepository = serviceProvider.GetRequiredService(); - - 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."); - throw new ArgumentInvalidException(nameof(user.Email), $"Mail {user.Email} is not null."); - } - - var from = new MailAddress(sender); - var message = new MailMessage - { - From = from - }; - - message.To.Add(mailAddress.Address); - message.BodyEncoding = System.Text.Encoding.UTF8; - message.Body = notification.Message; - message.Subject = notification.Title; - message.IsBodyHtml = true; - - using var client = new SmtpClient(smtpServer); - client.EnableSsl = true; - client.UseDefaultCredentials = false; - client.Credentials = new System.Net.NetworkCredential(sender, smtpPassword); - - 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}"); - }; - } - private static string MakeWorkId(int idUser, string subject, string content) { var hash = idUser.GetHashCode();