Files

74 lines
3.0 KiB
C#

using DbusSmsForward.Helper;
using DbusSmsForward.Models;
using DbusSmsForward.ModemHelper;
using DbusSmsForward.Notifications;
using DbusSmsForward.Services;
using DbusSmsForward.SettingModel;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System.Text.Json;
AppCommand command = CommandLineParser.Parse(args);
if (command.PrintSampleConfig)
{
DbusSmsForwardOptions sample = SampleConfigFactory.Create();
Console.WriteLine(JsonSerializer.Serialize(sample, SourceGenerationContext.Default.DbusSmsForwardOptions));
return;
}
HostApplicationBuilder builder = Host.CreateApplicationBuilder(args);
builder.Configuration.AddJsonFile("appsettings.json", optional: true, reloadOnChange: false);
builder.Services.Configure<DbusSmsForwardOptions>(builder.Configuration);
builder.Services.AddSingleton(sp =>
{
DbusSmsForwardOptions options = new();
builder.Configuration.Bind(options);
LegacyConfigurationBridge.Apply(builder.Configuration, options);
CommandLineConfigurationApplier.Apply(command, options);
return options;
});
builder.Services.AddSingleton<ModemManagerHelper>();
builder.Services.AddSingleton<NotificationDispatcher>();
builder.Services.AddSingleton<INotificationSender, EmailNotificationSender>();
builder.Services.AddSingleton<INotificationSender, PushPlusNotificationSender>();
builder.Services.AddSingleton<INotificationSender, BarkNotificationSender>();
builder.Services.AddSingleton<INotificationSender, TelegramNotificationSender>();
builder.Services.AddSingleton<INotificationSender, DingTalkNotificationSender>();
builder.Services.AddSingleton<INotificationSender, WeComApplicationNotificationSender>();
builder.Services.AddSingleton<INotificationSender, ShellNotificationSender>();
builder.Services.AddSingleton<INotificationSender, AutmanPushNotificationSender>();
builder.Services.AddHostedService<SmsForwardWorker>();
builder.Logging.ClearProviders();
builder.Logging.AddSimpleConsole();
using IHost host = builder.Build();
DbusSmsForwardOptions resolvedOptions = host.Services.GetRequiredService<DbusSmsForwardOptions>();
if (command.ValidateConfig || resolvedOptions.Daemon.ValidateOnStartup)
{
ConfigurationValidator.Validate(resolvedOptions, command);
}
if (string.Equals(command.Name, "send", StringComparison.OrdinalIgnoreCase))
{
await SendSmsAsync(host.Services, command);
return;
}
await host.RunAsync();
static async Task SendSmsAsync(IServiceProvider services, AppCommand command)
{
if (string.IsNullOrWhiteSpace(command.PhoneNumber) || string.IsNullOrWhiteSpace(command.Message))
{
throw new InvalidOperationException("send 模式需要 --to 和 --text 参数。 ");
}
ModemManagerHelper modemManagerHelper = services.GetRequiredService<ModemManagerHelper>();
bool success = await modemManagerHelper.SendSms(command.PhoneNumber, command.Message);
Console.WriteLine(success ? "短信已发送" : "短信发送失败");
}