yavsc/src/cli/Commands/SendMailCommand.cs

76 lines
2.9 KiB
C#
Raw Normal View History

2018-07-28 01:55:13 +02:00
using Microsoft.AspNet.Hosting;
using Microsoft.Extensions.CommandLineUtils;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using cli.Services;
2018-08-05 04:16:21 +02:00
using cli.Model;
2021-05-30 12:30:39 +01:00
using System.Linq;
using Yavsc.Models;
using System.Collections.Generic;
using System;
2018-07-28 01:55:13 +02:00
2021-05-30 12:30:39 +01:00
namespace cli
{
public class SendMailCommandProvider : ICommander
{
readonly Dictionary<string, Func<ApplicationUser, bool>> Criterias =
new Dictionary<string, Func<ApplicationUser, bool>>
{
{"allow-monthly", u => u.AllowMonthlyEmail },
{ "email-not-confirmed", u => !u.EmailConfirmed }
};
2018-08-05 04:16:21 +02:00
public CommandLineApplication Integrate(CommandLineApplication rootApp)
2018-07-28 01:55:13 +02:00
{
2021-05-30 12:30:39 +01:00
CommandArgument codeCommandArg = null;
CommandArgument critCommandArg = null;
CommandOption sendHelpOption = null;
CommandLineApplication sendMailCommandApp
= rootApp.Command("send-monthly",
(target) =>
{
target.FullName = "Send email";
target.Description = "Sends monthly emails using given template from code";
sendHelpOption = target.HelpOption("-? | -h | --help");
codeCommandArg = target.Argument(
"code",
"template code of mailling to execute.");
critCommandArg = target.Argument(
"criteria",
"user selection criteria : 'allow-monthly' or 'email-not-confirmed'");
}, false);
2018-07-28 01:55:13 +02:00
sendMailCommandApp.OnExecute(() =>
{
2021-05-30 12:30:39 +01:00
int code;
bool showhelp = !int.TryParse(codeCommandArg.Value, out code)
|| Criterias.ContainsKey(critCommandArg.Value);
if (!showhelp)
2018-07-28 01:55:13 +02:00
{
var host = new WebHostBuilder();
2021-05-30 12:30:39 +01:00
var hostengnine = host.UseEnvironment(Program.HostingEnvironment.EnvironmentName)
2018-07-28 01:55:13 +02:00
.UseServer("cli")
.UseStartup<Startup>()
.Build();
var app = hostengnine.Start();
var mailer = app.Services.GetService<EMailer>();
var loggerFactory = app.Services.GetService<ILoggerFactory>();
2021-05-30 12:30:39 +01:00
var logger = loggerFactory.CreateLogger<Program>();
2018-07-28 01:55:13 +02:00
logger.LogInformation("Starting emailling");
2021-05-30 12:30:39 +01:00
mailer.SendEmailFromCriteria(code, Criterias[critCommandArg.Value]);
2018-07-28 01:55:13 +02:00
logger.LogInformation("Finished emailling");
}
else
{
sendMailCommandApp.ShowHelp();
2019-01-08 15:00:58 +00:00
return 1;
2018-07-28 01:55:13 +02:00
}
return 0;
});
return sendMailCommandApp;
}
}
2021-05-30 12:30:39 +01:00
}