forked from ddrilling/AsbCloudServer
Merge pull request 'Создание отдельных ворков с самостоятельными экшнами' (#182) from fix/create-workers into dev
Reviewed-on: http://test.digitaldrilling.ru:8080/DDrilling/AsbCloudServer/pulls/182
This commit is contained in:
commit
ed9ae9c44c
94
AsbCloudInfrastructure/Background/WorkToSendEmail.cs
Normal file
94
AsbCloudInfrastructure/Background/WorkToSendEmail.cs
Normal file
@ -0,0 +1,94 @@
|
||||
using AsbCloudApp.Data;
|
||||
using AsbCloudApp.Exceptions;
|
||||
using AsbCloudApp.Repositories;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.Net.Mail;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace AsbCloudInfrastructure.Background
|
||||
{
|
||||
/// <summary>
|
||||
/// Класс для отправки email
|
||||
/// </summary>
|
||||
internal class WorkToSendEmail : Work
|
||||
{
|
||||
private NotificationDto notification;
|
||||
private string sender;
|
||||
private string smtpPassword;
|
||||
private string smtpServer;
|
||||
private bool IsConfigured;
|
||||
|
||||
public WorkToSendEmail(NotificationDto notification, IConfiguration configuration) : base(MakeWorkId(notification))
|
||||
{
|
||||
this.notification = notification;
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
|
||||
protected override async Task Action(string id, IServiceProvider services, Action<string, double?> onProgressCallback, CancellationToken token)
|
||||
{
|
||||
if (!IsConfigured)
|
||||
{
|
||||
Trace.TraceWarning("smtp is not configured");
|
||||
return;
|
||||
}
|
||||
|
||||
var notificationRepository = services.GetRequiredService<INotificationRepository>();
|
||||
var userRepository = services.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.");
|
||||
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(NotificationDto notification)
|
||||
{
|
||||
var hash = notification.IdUser.GetHashCode();
|
||||
hash ^= notification.Title.GetHashCode();
|
||||
hash ^= notification.Message.GetHashCode();
|
||||
return hash.ToString("x");
|
||||
}
|
||||
}
|
||||
}
|
@ -1,62 +1,34 @@
|
||||
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.Data;
|
||||
using AsbCloudApp.Services.Notifications;
|
||||
using AsbCloudInfrastructure.Background;
|
||||
using DocumentFormat.OpenXml.Presentation;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace AsbCloudInfrastructure.Services.Email
|
||||
{
|
||||
|
||||
public class EmailNotificationTransportService : INotificationTransportService
|
||||
{
|
||||
private readonly IConfiguration configuration;
|
||||
private readonly BackgroundWorker backgroundWorker;
|
||||
private readonly bool IsConfigured;
|
||||
private readonly string sender;
|
||||
private readonly string smtpServer;
|
||||
private readonly string smtpPassword;
|
||||
|
||||
public EmailNotificationTransportService(BackgroundWorker backgroundWorker,
|
||||
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.configuration = configuration;
|
||||
this.backgroundWorker = backgroundWorker;
|
||||
}
|
||||
|
||||
public int IdTransportType => 1;
|
||||
|
||||
|
||||
public Task SendAsync(NotificationDto notification, CancellationToken cancellationToken)
|
||||
{
|
||||
if (!IsConfigured)
|
||||
var work = new WorkToSendEmail(notification, configuration);
|
||||
if (!backgroundWorker.Works.Any(w => w.Id == work.Id))
|
||||
{
|
||||
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);
|
||||
backgroundWorker.Enqueue(work);
|
||||
}
|
||||
|
||||
@ -70,56 +42,7 @@ namespace AsbCloudInfrastructure.Services.Email
|
||||
|
||||
return Task.WhenAll(tasks);
|
||||
}
|
||||
|
||||
private Func<string, IServiceProvider, Action<string, double?>, CancellationToken, Task> MakeEmailSendWorkAction(NotificationDto notification)
|
||||
{
|
||||
return async (_, serviceProvider, onProgress, token) =>
|
||||
{
|
||||
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.");
|
||||
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();
|
||||
hash ^= subject.GetHashCode();
|
||||
hash ^= content.GetHashCode();
|
||||
return hash.ToString("x");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user