Files
monorepo/LCU.API.Internal.ArchiverApi/LCU.Api.Internal.ArchiverApi/Services/NotificationService.cs
T
2026-03-17 10:03:23 -05:00

94 lines
3.4 KiB
C#

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Serilog;
using LCU.Api.Internal.ArchiverApi.Configuration;
using LCU.API.Internal.NotificationsApiLib.Models;
using LCU.Library.Internal.ArchiverApi.Utilities;
using LCU.Library.Internal.ArchiverApiModel.Models;
namespace LCU.Api.Internal.ArchiverApi.Services;
public class NotificationService : INotificationService
{
private readonly ArchiverApiConfig _ArchiverApiConfig;
private const string TableRowsTag = "{TableRows}";
public NotificationService(ArchiverApiConfig ArchiverApiConfig)
{
_ArchiverApiConfig = ArchiverApiConfig;
}
public async Task<bool> SendEmailAsync(List<string> recipients, string subject, string emailTemplate)
{
try
{
var emailRequest = new EmailRequest
{
Recipient = recipients,
Subject = subject,
Body = emailTemplate
};
var encoded = JsonConvert.SerializeObject(emailRequest);
var client = HttpUtilities.GetClient(_ArchiverApiConfig.NotificationApiEmail);
var content = new StringContent(encoded, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(_ArchiverApiConfig.NotificationApiEmail, content);
response.EnsureSuccessStatusCode();
return response.IsSuccessStatusCode;
}
catch (Exception ex)
{
Log.Error(ex, $"Failure to send email from Archiver Api");
return false;
}
}
public async Task<bool> SendErrorEmailAsync(List<ErrorDetail> errorDetails)
{
if (!errorDetails.Any())
{
return true;
}
var basePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory);
string rowsOfErrors = "";
foreach (var errorDetail in errorDetails)
{
rowsOfErrors += CreateErrorRow(errorDetail, basePath);
}
var emailTemplate = CreateErrorMonitoringEmail(rowsOfErrors, basePath);
var successfullySent = await SendEmailAsync(_ArchiverApiConfig.ErrorRecipients,
_ArchiverApiConfig.ErrorMonitoringSubject,
emailTemplate);
return successfullySent;
}
public string CreateErrorRow(ErrorDetail errorDetail, string basePath)
{
var errorRowReader = new StreamReader($"{basePath}{_ArchiverApiConfig.ErrorRowTemplate}");
string errorRowOutput = errorRowReader.ReadToEnd();
foreach (var property in errorDetail.GetType().GetProperties())
{
string value = property.GetValue(errorDetail) == null ?
string.Empty :
property.GetValue(errorDetail).ToString();
errorRowOutput = errorRowOutput.Replace($"{{{property.Name}}}", value);
}
return errorRowOutput;
}
public string CreateErrorMonitoringEmail(string errorRows, string basePath)
{
var errorMonitoringReader = new StreamReader($"{basePath}{_ArchiverApiConfig.ErrorMonitoringTemplate}");
string errorMonitoringOutput = errorMonitoringReader.ReadToEnd();
return errorMonitoringOutput.Replace(TableRowsTag, errorRows);
}
}