Skip to content

Commit

Permalink
Merge branch 'release/v1.1'
Browse files Browse the repository at this point in the history
  • Loading branch information
EvilLord666 committed Feb 22, 2023
2 parents 737d738 + 66d8546 commit e99f311
Show file tree
Hide file tree
Showing 47 changed files with 579 additions and 92 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -348,3 +348,5 @@ MigrationBackup/

# Ionide (cross platform F# VS Code tools) working folder
.ionide/

Wissance.MossbauerLab.Watcher/Wissance.MossbauerLab.Watcher.Web/Wissance.MossbauerLab.Watcher.db
Original file line number Diff line number Diff line change
@@ -1,19 +1,17 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using System.Text;

namespace Wissance.MossbauerLab.Watcher.Web.Config
namespace Wissance.MossbauerLab.Watcher.Common.Data.Notification
{
public class MailConfig
public class MailSendRequisites
{
public MailConfig()
public MailSendRequisites()
{

}

public MailConfig(string host, int port, string sender, string password, string[] recipients)
public MailSendRequisites(string host, int port, string sender, string password, string[] recipients)
{
Host = host;
Port = port;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using System.Text;

namespace Wissance.MossbauerLab.Watcher.Common.Data.Notification
{
public class TelegramSendRequisites
{
public TelegramSendRequisites()
{
}

public TelegramSendRequisites(string group, string botKey, string templateFilePath)
{
Group = group;
BotKey = botKey;
TemplateFilePath = templateFilePath;
}

public string Group { get; set; }
public string BotKey { get; set; }
public string TemplateFilePath { get; set; }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
using System.Linq;
using System.Threading.Tasks;

namespace Wissance.MossbauerLab.Watcher.Web.Data
namespace Wissance.MossbauerLab.Watcher.Common.Data
{
public class Sm2201SpectrumNameData
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
using System.Linq;
using System.Threading.Tasks;

namespace Wissance.MossbauerLab.Watcher.Web.Data
namespace Wissance.MossbauerLab.Watcher.Common.Data
{
public class SpectrumReadyData
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Wissance.MossbauerLab.Watcher.Web.Data;

namespace Wissance.MossbauerLab.Watcher.Web.Utils
using Wissance.MossbauerLab.Watcher.Common.Data;

namespace Wissance.MossbauerLab.Watcher.Common.Utils
{
public static class Sm2201SpectrumNameParser
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>

<ItemGroup>
<Compile Remove="Config\**" />
<EmbeddedResource Remove="Config\**" />
<None Remove="Config\**" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ public SpectrumEntity(string name, string description, string location, DateTime
Name = name;
Description = description;
Location = location;
measureStartDate = MeasureStartDate;
MeasureStartDate = measureStartDate;
First = first;
Last = last;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;

namespace Wissance.MossbauerLab.Watcher.Web.Extensions
namespace Wissance.MossbauerLab.Watcher.Common.Extensions
{
public static class ServiceCollectionExtension
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="5.0.17" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Proxies" Version="5.0.17" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="5.0.17" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="5.0.17">
<PrivateAssets>all</PrivateAssets>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,42 +1,44 @@
using System;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Threading.Tasks;

using Microsoft.Extensions.Logging;
using Wissance.MossbauerLab.Watcher.Web.Config;
using Wissance.MossbauerLab.Watcher.Web.Data;

namespace Wissance.MossbauerLab.Watcher.Web.Services.Notification
using Wissance.MossbauerLab.Watcher.Common.Data;
using Wissance.MossbauerLab.Watcher.Common.Data.Notification;

namespace Wissance.MossbauerLab.Watcher.Services.Notification
{
public class EmailNotifier : ISpectrumReadyNotifier
{
public EmailNotifier(ApplicationConfig config, ILoggerFactory loggerFactory)
public EmailNotifier(MailSendRequisites mailRequisites, ILoggerFactory loggerFactory)
{
_config = config;
_mailRequisites = mailRequisites;
_logger = loggerFactory.CreateLogger<EmailNotifier>();
_smtpClient = new SmtpClient(_config.NotificationSettings.MailSettings.Host, _config.NotificationSettings.MailSettings.Port)
_smtpClient = new SmtpClient(_mailRequisites.Host, _mailRequisites.Port)
{
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(_config.NotificationSettings.MailSettings.Sender, _config.NotificationSettings.MailSettings.Password)
Credentials = new NetworkCredential(_mailRequisites.Sender, _mailRequisites.Password)
};
}

public async Task<bool> NotifySpectrumSavedAsync(IList<SpectrumReadyData> spectra)
{
try
{
string recipients = String.Join(",", _config.NotificationSettings.MailSettings.Recipients);
MailMessage msg = new MailMessage(_config.NotificationSettings.MailSettings.Sender, recipients);
string recipients = string.Join(",", _mailRequisites.Recipients);
MailMessage msg = new MailMessage(_mailRequisites.Sender, recipients);
msg.IsBodyHtml = true;
msg.Subject = SpectrumAutoSaveMailSubject;
string mailTemplate = await File.ReadAllTextAsync(Path.GetFullPath(SpectrumAutoSaveMailTemplate));
// prepare
msg.Body = FormatMailMessage(mailTemplate, spectra);
msg.Body = NotificationMessageFormatter.FormatMailMessage(mailTemplate, spectra);
foreach (SpectrumReadyData spec in spectra)
{
Stream stream = new MemoryStream(spec.Spectrum);
Expand Down Expand Up @@ -73,14 +75,14 @@ public string FormatMailMessage(string template, IList<SpectrumReadyData> spectr

private const int MaxAllowedTimeout = 10000;
private const string SpectrumAutoSaveMailSubject = "Автоматически сохраненные спектры";
private const string SpectrumAutoSaveMailTemplate = @"Templates/autosaveNotifications.html";
private const string SpectrumAutoSaveMailTemplate = @"Notification/Templates/autosaveNotifications.html";

private const string CurrentSatePlaceholder = "{currDate}";
private const string AutosavedSpectraPlaceholder = "{savedSpectra}";
// <!--<li>Спектр {msSpName} по каналу {msChNumber} сохранен {msSaveDate}</li>-->
private const string SavedSpectrumDescriptionTemplate = "<li>Спектр {0} по каналу {1} сохранен {2}</li>";

private readonly ApplicationConfig _config;
private readonly MailSendRequisites _mailRequisites;
private readonly ILogger<EmailNotifier> _logger;
private readonly SmtpClient _smtpClient;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Wissance.MossbauerLab.Watcher.Web.Data;

namespace Wissance.MossbauerLab.Watcher.Web.Services.Notification
using Wissance.MossbauerLab.Watcher.Common.Data;

namespace Wissance.MossbauerLab.Watcher.Services.Notification
{
public interface ISpectrumReadyNotifier
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Wissance.MossbauerLab.Watcher.Common.Data;

namespace Wissance.MossbauerLab.Watcher.Services.Notification
{
internal static class NotificationMessageFormatter
{

public static string FormatMailMessage(string template, IList<SpectrumReadyData> spectra)
{
string mailMessage = template.Replace(CurrentSatePlaceholder, DateTime.Now.ToString("yyyy-MM-dd:HH-mm-ss"));
IList<string> lines = spectra.Select(s => string.Format(SavedSpectrumDescriptionTemplate, s.Name, s.Channel, s.RawInfo.LastWriteTime.ToString("yyyy-MM-dd:HH-mm-ss"))).ToList();
string linesStr = string.Join(Environment.NewLine, lines);
mailMessage = mailMessage.Replace(AutosavedSpectraPlaceholder, linesStr);

return mailMessage;
}
public static string FormatTelegramMessage(string template, IList<SpectrumReadyData> spectra)
{
string mailMessage = template.Replace(CurrentSatePlaceholder, DateTime.Now.ToString("yyyy-MM-dd:HH-mm-ss"));
IList<string> lines = spectra.Select(s => string.Format(SavedSpectrumTelegramDescriptionTemplate, s.Name, s.Channel, s.RawInfo.LastWriteTime.ToString("yyyy-MM-dd:HH-mm-ss"))).ToList();
string linesStr = string.Join(Environment.NewLine, lines);
mailMessage = mailMessage.Replace(AutosavedSpectraPlaceholder, linesStr);

return mailMessage;
}

private const string AutosavedSpectraPlaceholder = "{savedSpectra}";
// <!--<li>Спектр {msSpName} по каналу {msChNumber} сохранен {msSaveDate}</li>-->
private const string SavedSpectrumDescriptionTemplate = "<li>Спектр {0} по каналу {1} сохранен {2}</li>";
private const string CurrentSatePlaceholder = "{currDate}";
private const string SavedSpectrumTelegramDescriptionTemplate = "- Спектр {0} по каналу {1} сохранен {2}";
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
using Microsoft.Extensions.Logging;

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

using Telegram.Bot;
using Telegram.Bot.Polling;
using Telegram.Bot.Requests;
using Telegram.Bot.Types;

using Wissance.MossbauerLab.Watcher.Common.Data;
using Wissance.MossbauerLab.Watcher.Common.Data.Notification;

namespace Wissance.MossbauerLab.Watcher.Services.Notification
{
public class TelegramNotifier : ISpectrumReadyNotifier
{

public TelegramNotifier(TelegramSendRequisites tgRequisites, ILoggerFactory loggerFactory)
{
_tgRequisites = tgRequisites;
_logger = loggerFactory.CreateLogger<TelegramNotifier>();
}
public async Task<bool> NotifySpectrumSavedAsync(IList<SpectrumReadyData> spectra)
{
ITelegramBotClient client = new TelegramBotClient(_tgRequisites.BotKey);

string targetGroupName = _tgRequisites.Group;
ChatId targetChatId = new ChatId(targetGroupName);

Message msg = new Message();
string template = !string.IsNullOrEmpty(_tgRequisites.TemplateFilePath) ? _tgRequisites.TemplateFilePath : DefaultSpectrumAutoSaveMailTemplate;
string mailTemplate = System.IO.File.ReadAllText(template);
msg.Text = NotificationMessageFormatter.FormatTelegramMessage(mailTemplate, spectra);

try
{
await client.SendTextMessageAsync(targetChatId, msg.Text);
}
catch (Exception e )
{
_logger.LogError($"An error occurred during sending message to telegram group {targetGroupName}: {e.Message}");
return false;
}
return true;
}

private const string DefaultSpectrumAutoSaveMailTemplate = @"Notification/Templates/tgAutosaveDone.txt";
private readonly TelegramSendRequisites _tgRequisites;
private readonly ILogger<TelegramNotifier> _logger;

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Уведомление
На {currDate} были получены следующие наиболее актуальные спектры, файлы этих спектров отправлены на почту
{savedSpectra}
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
using System.IO;
using System.Threading.Tasks;

namespace Wissance.MossbauerLab.Watcher.Web.Services.Store
namespace Wissance.MossbauerLab.Watcher.Services.Store
{
public interface IFileStoreService
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Quartz" Version="3.4.0" />
<PackageReference Include="Quartz.Extensions.DependencyInjection" Version="3.4.0" />
<PackageReference Include="Quartz.Extensions.Hosting" Version="3.4.0" />
<PackageReference Include="SMBLibrary" Version="1.4.8" />
<PackageReference Include="Telegram.Bot" Version="18.0.0" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\Wissance.MossbauerLab.Watcher.Common\Wissance.MossbauerLab.Watcher.Common.csproj" />
<ProjectReference Include="..\Wissance.MossbauerLab.Watcher.Data\Wissance.MossbauerLab.Watcher.Data.csproj" />
</ItemGroup>

<ItemGroup>
<None Include="Notification/Templates/**" CopyToOutputDirectory="PreserveNewest" LinkBase="Templates/"/>
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;

using System;
using System.Text;
using System.Collections.Generic;

using Wissance.MossbauerLab.Watcher.Common.Data;
using Wissance.MossbauerLab.Watcher.Services.Notification;
using Microsoft.QualityTools.Testing.Fakes;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Wissance.MossbauerLab.Watcher.Common.Data.Notification;

namespace Wissance.MossbauerLab.Watcher.Services.Tests
{
[TestClass]
public class TelegramNotificationsTests
{
[TestMethod]
public async Task SendNotificationTest()
{
byte[] bin = Convert.FromBase64String("NjI1MzUyNzMxNjpBQUYzWGZuSnE2azlTMnFldTc2bmd6SHhEU29id3BMcm50SQ==");
string key = Encoding.UTF8.GetString(bin);

TelegramSendRequisites tgRequisites = new TelegramSendRequisites("@WissanceBotTest", key, "Templates\\testTelegramMessageTemplate.txt");

SpectrumReadyData spectra = new SpectrumReadyData
{
Spectrum = new byte[] { 4, 5, 6 },
Name = "Test spectra",
Channel = 1,
Updated = DateTime.Now,
RawInfo = new System.IO.FileInfo("textFileForFileInfo.txt")
};

TelegramNotifier telegramNotifier = new TelegramNotifier(tgRequisites, new LoggerFactory());
bool result = await telegramNotifier.NotifySpectrumSavedAsync(new List<SpectrumReadyData> { spectra, spectra });
Assert.IsTrue(result);

}
}
}
Loading

0 comments on commit e99f311

Please sign in to comment.