Переделал всё на DI

This commit is contained in:
ftc
2024-01-20 18:37:52 +03:00
parent 2a8348df44
commit d641de9689
5 changed files with 66 additions and 35 deletions
+20 -16
View File
@@ -1,13 +1,10 @@
using System; using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Text.Json; using System.Text.Json;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Telegram.Bot; using Telegram.Bot;
using Telegram.Bot.Args;
using Telegram.Bot.Types.ReplyMarkups;
using ZaoBot.Config; using ZaoBot.Config;
namespace ZaoBot namespace ZaoBot
@@ -18,42 +15,49 @@ namespace ZaoBot
static ITelegramBotClient botClient; static ITelegramBotClient botClient;
Dictionary<long, IUserState> userStates = new Dictionary<long, IUserState>(); Dictionary<long, IUserState> userStates = new Dictionary<long, IUserState>();
private OpenHab.OpenHabClient openhab; private OpenHab.OpenHabClient openhab;
private IServiceProvider services;
bool shouldRestart = false; bool shouldRestart = false;
public BotService(IConfig config, OpenHab.OpenHabClient openhab) public BotService(IServiceProvider services, IConfig config, OpenHab.OpenHabClient openhab)
{ {
this.services = services;
this.config = config.Data; this.config = config.Data;
this.openhab = openhab; this.openhab = openhab;
} }
public void Run() public void Run()
{ {
var token = config.RootElement.GetProperty("token").GetString(); shouldRestart = false;
while (true)
var botClient = services.GetRequiredService<ITelegramBotClient>();
using CancellationTokenSource cts = new CancellationTokenSource();
try
{ {
shouldRestart = false;
botClient = new TelegramBotClient(token);
using CancellationTokenSource cts = new CancellationTokenSource();
var me = botClient.GetMeAsync().Result; var me = botClient.GetMeAsync().Result;
Console.WriteLine($"Hello, World! I am user {me.Id} and my name is {me.FirstName}."); Console.WriteLine($"Hello, World! I am user {me.Id} and my name is {me.FirstName}.");
botClient.StartReceiving( botClient.StartReceiving(
updateHandler: OnBotUpdateAsync, updateHandler: OnBotUpdateAsync,
pollingErrorHandler: OnPollingError pollingErrorHandler: OnPollingError,
cancellationToken: cts.Token
); );
while (!shouldRestart) while (!shouldRestart)
{ {
Thread.Sleep(1000); Thread.Sleep(1000);
} }
} }
finally
{
cts.Cancel();
}
} }
private Task OnPollingError(ITelegramBotClient bot, Exception exception, CancellationToken cts) private Task OnPollingError(ITelegramBotClient bot, Exception exception, CancellationToken cts)
{ {
Console.WriteLine("Error on polling: " + exception.Message); Console.WriteLine("Error on polling: " + exception.Message);
Console.WriteLine("Will restart"); Console.WriteLine("Will restart");
shouldRestart = true;
return Task.CompletedTask; return Task.CompletedTask;
} }
@@ -72,7 +76,7 @@ namespace ZaoBot
} }
if (state == null) if (state == null)
{ {
state = new MainMenuUserState(botClient, config, openhab); state = services.GetService<MainMenuUserState>();
} }
state = await state.ProcessMessage(state, updateInfo); state = await state.ProcessMessage(state, updateInfo);
if (state == null) if (state == null)
@@ -81,7 +85,7 @@ namespace ZaoBot
chatId: updateInfo.Message.Chat, chatId: updateInfo.Message.Chat,
text: "Я запутался, давайте сначала" text: "Я запутался, давайте сначала"
); );
state = new MainMenuUserState(botClient, config, openhab); state = services.GetService<MainMenuUserState>();
state = await state.ProcessMessage(state, updateInfo); state = await state.ProcessMessage(state, updateInfo);
} }
userStates[id] = state; userStates[id] = state;
+9 -5
View File
@@ -1,4 +1,5 @@
using System; using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Net; using System.Net;
@@ -7,6 +8,7 @@ using System.Text.Json;
using System.Threading.Tasks; using System.Threading.Tasks;
using Telegram.Bot; using Telegram.Bot;
using Telegram.Bot.Types.ReplyMarkups; using Telegram.Bot.Types.ReplyMarkups;
using ZaoBot.Config;
using ZaoBot.OpenHab; using ZaoBot.OpenHab;
namespace ZaoBot namespace ZaoBot
@@ -25,14 +27,16 @@ namespace ZaoBot
private JsonDocument config; private JsonDocument config;
List<CameraConfigData> cameras; List<CameraConfigData> cameras;
OpenHabClient openhab; OpenHabClient openhab;
IServiceProvider services;
public CamerasMenuUserState(ITelegramBotClient botClient, JsonDocument config, OpenHabClient openhab) public CamerasMenuUserState(IServiceProvider services, ITelegramBotClient botClient, IConfig config, OpenHabClient openhab)
{ {
this.botClient = botClient; this.botClient = botClient;
this.config = config; this.config = config.Data;
this.openhab = openhab; this.openhab = openhab;
this.services = services;
cameras = new List<CameraConfigData>(); cameras = new List<CameraConfigData>();
foreach (var element in config.RootElement.GetProperty("cameras").EnumerateObject()) foreach (var element in this.config.RootElement.GetProperty("cameras").EnumerateObject())
{ {
var cam = new CameraConfigData() var cam = new CameraConfigData()
{ {
@@ -47,7 +51,7 @@ namespace ZaoBot
{ {
if (e.Message.Text == CMD_BACK) if (e.Message.Text == CMD_BACK)
{ {
var newState = new MainMenuUserState(botClient, config, openhab); var newState = services.GetRequiredService<MainMenuUserState>();
await newState.ProcessMessage(this, e); await newState.ProcessMessage(this, e);
return newState; return newState;
} }
+9 -7
View File
@@ -1,12 +1,12 @@
using System; using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Net.Http; using System.Net.Http;
using System.Text;
using System.Text.Json; using System.Text.Json;
using System.Threading.Tasks; using System.Threading.Tasks;
using Telegram.Bot; using Telegram.Bot;
using Telegram.Bot.Args;
using Telegram.Bot.Types.ReplyMarkups; using Telegram.Bot.Types.ReplyMarkups;
using ZaoBot.Config;
using ZaoBot.OpenHab; using ZaoBot.OpenHab;
namespace ZaoBot namespace ZaoBot
@@ -23,11 +23,13 @@ namespace ZaoBot
private JsonDocument config; private JsonDocument config;
HttpClient http = new HttpClient(); HttpClient http = new HttpClient();
OpenHabClient openhab; OpenHabClient openhab;
IServiceProvider services;
public MainMenuUserState(ITelegramBotClient botClient, JsonDocument config, OpenHabClient openhab) public MainMenuUserState(IServiceProvider services, ITelegramBotClient botClient, IConfig config, OpenHabClient openhab)
{ {
this.services = services;
this.botClient = botClient; this.botClient = botClient;
this.config = config; this.config = config.Data;
this.openhab = openhab; this.openhab = openhab;
} }
@@ -61,13 +63,13 @@ namespace ZaoBot
} }
else if (e.Message.Text == CMD_STATUS) else if (e.Message.Text == CMD_STATUS)
{ {
var newState = new StatusMenuUserState(botClient, config, openhab); var newState = services.GetRequiredService<StatusMenuUserState>();
await newState.ProcessMessage(this, e); await newState.ProcessMessage(this, e);
return newState; return newState;
} }
else if (e.Message.Text == CMD_CAMERAS) else if (e.Message.Text == CMD_CAMERAS)
{ {
var newState = new CamerasMenuUserState(botClient, config, openhab); var newState = services.GetRequiredService<CamerasMenuUserState>();
await newState.ProcessMessage(this, e); await newState.ProcessMessage(this, e);
return newState; return newState;
} }
+20 -3
View File
@@ -5,6 +5,7 @@ using System.IO;
using System.Reflection; using System.Reflection;
using System.Text.Json; using System.Text.Json;
using System.Threading; using System.Threading;
using Telegram.Bot;
using ZaoBot.Config; using ZaoBot.Config;
using ZaoBot.OpenHab; using ZaoBot.OpenHab;
@@ -23,9 +24,16 @@ namespace ZaoBot
config = LoadConfig(); config = LoadConfig();
services = new ServiceCollection(); services = new ServiceCollection();
services.AddSingleton<IConfig, Config.Config>(CreateConfig); services.AddSingleton<IConfig, Config.Config>(CreateConfig);
services.AddSingleton<BotService, BotService>();
services.AddSingleton<OpenHabClient, OpenHabClient>(); services.AddSingleton<OpenHabClient, OpenHabClient>();
services.AddSingleton<NotificationReceiver, NotificationReceiver>(); services.AddSingleton<NotificationReceiver, NotificationReceiver>();
services.AddScoped<BotService, BotService>();
services.AddScoped<IServiceProvider, IServiceProvider>(p => p);
services.AddScoped<ITelegramBotClient, TelegramBotClient>(CreateTelegramBot);
services.AddTransient<MainMenuUserState, MainMenuUserState>();
services.AddTransient<StatusMenuUserState, StatusMenuUserState>();
services.AddTransient<CamerasMenuUserState, CamerasMenuUserState>();
using (var provider = services.BuildServiceProvider()) using (var provider = services.BuildServiceProvider())
{ {
var receiver = provider.GetRequiredService<NotificationReceiver>(); var receiver = provider.GetRequiredService<NotificationReceiver>();
@@ -35,8 +43,11 @@ namespace ZaoBot
{ {
try try
{ {
bot = provider.GetRequiredService<BotService>(); using (var scope = provider.CreateScope())
bot.Run(); {
bot = scope.ServiceProvider.GetRequiredService<BotService>();
bot.Run();
}
} }
catch (Exception e) catch (Exception e)
{ {
@@ -49,6 +60,12 @@ namespace ZaoBot
} }
} }
private static TelegramBotClient CreateTelegramBot(IServiceProvider arg)
{
var token = config.RootElement.GetProperty("token").GetString();
return new TelegramBotClient(token);
}
private static Config.Config CreateConfig(IServiceProvider arg) private static Config.Config CreateConfig(IServiceProvider arg)
{ {
return new Config.Config(config); return new Config.Config(config);
+8 -4
View File
@@ -1,4 +1,5 @@
using System; using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Net.Http; using System.Net.Http;
using System.Text; using System.Text;
@@ -7,6 +8,7 @@ using System.Threading.Tasks;
using Telegram.Bot; using Telegram.Bot;
using Telegram.Bot.Args; using Telegram.Bot.Args;
using Telegram.Bot.Types.ReplyMarkups; using Telegram.Bot.Types.ReplyMarkups;
using ZaoBot.Config;
using ZaoBot.OpenHab; using ZaoBot.OpenHab;
namespace ZaoBot namespace ZaoBot
@@ -19,12 +21,14 @@ namespace ZaoBot
private JsonDocument config; private JsonDocument config;
HttpClient http = new HttpClient(); HttpClient http = new HttpClient();
OpenHabClient openhab; OpenHabClient openhab;
IServiceProvider services;
public StatusMenuUserState(ITelegramBotClient botClient, JsonDocument config, OpenHabClient openhab) public StatusMenuUserState(IServiceProvider services, ITelegramBotClient botClient, IConfig config, OpenHabClient openhab)
{ {
this.botClient = botClient; this.botClient = botClient;
this.config = config; this.config = config.Data;
this.openhab = openhab; this.openhab = openhab;
this.services = services;
} }
public async Task<IUserState> ProcessMessage(IUserState previous, Telegram.Bot.Types.Update e) public async Task<IUserState> ProcessMessage(IUserState previous, Telegram.Bot.Types.Update e)
@@ -47,7 +51,7 @@ namespace ZaoBot
} }
else if (e.Message.Text == CMD_BACK) else if (e.Message.Text == CMD_BACK)
{ {
var newState = new MainMenuUserState(botClient, config, openhab); var newState = services.GetRequiredService<MainMenuUserState>();
await newState.ProcessMessage(this, e); await newState.ProcessMessage(this, e);
return newState; return newState;
} }