Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
21cb23e
Telegram.Bot upgraded to Version="19.*"
granstel Jun 7, 2024
1853ad7
upgraded Dapper
granstel Jun 7, 2024
db7d37d
fixed SetWebhookAsync_Invocation_Success
granstel Jun 9, 2024
e0148bf
fixed GetMeAsync_Invokations_Success
granstel Jun 9, 2024
8f65c2a
renamed
granstel Jun 9, 2024
28ae5a2
fixed NotifyAbout_AdminNotifications_SentOnlyToAdminUsers
granstel Jun 9, 2024
870406d
fixed NotifyAbout_AnyNotificationsAndUsers_SentAllNotificationsToAllU…
granstel Jun 9, 2024
e208167
clean
granstel Jun 9, 2024
bce7ba1
try to use custom UnixDateTimeConverter
granstel Jun 10, 2024
cf0ee0c
dotnet 8
granstel Jun 11, 2024
a38dec2
default scheme for webhook is https
granstel Jun 11, 2024
449c951
register ITelegramBotClient as singleton
granstel Jun 11, 2024
dc31377
full dotnet 8
granstel Jun 11, 2024
f464635
upgraded AutoMapper to Version="13.*"
granstel Jun 11, 2024
c40f066
internal Response as response of Telegram endpoint
granstel Jun 11, 2024
604f744
SerializerSettings as object, because the same type of the parameter …
granstel Jun 11, 2024
d1763ce
set JsonNamingPolicy.SnakeCaseLower to accept requests of telegram we…
granstel Jun 11, 2024
9a26e80
used preregistered JsonSerializerOptions with JsonSerializerDefaults.…
granstel Jun 11, 2024
2a311c7
disable jobs at Development environment
granstel Jun 12, 2024
204d62e
AddControllers instead of AddMvc
granstel Jun 12, 2024
f62fc99
log telegram endpoint
granstel Jun 12, 2024
020e90c
fixed tests
granstel Jun 12, 2024
e454607
custom deserialization for Telegram endpoint and example of keyed dep…
granstel Jun 12, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/dotnet.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ jobs:
- name: Setup .NET
uses: actions/setup-dotnet@v3
with:
dotnet-version: 6.0.x
dotnet-version: 8.0.x

- name: Restore dependencies
run: dotnet restore
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>

<IsPackable>false</IsPackable>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<OutputType>Library</OutputType>
</PropertyGroup>

Expand Down
6 changes: 3 additions & 3 deletions Dodo1000Bot.Api/DependencyConfiguration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@ namespace Dodo1000Bot.Api
{
internal static class DependencyConfiguration
{
internal static void Configure(IServiceCollection services, IConfiguration appConfiguration)
internal static void Configure(IServiceCollection services, IConfiguration appConfiguration, bool isDevelopment)
{
var configuration = appConfiguration.Get<AppConfiguration>();

services.AddSingleton(configuration);
services.AddSingleton(configuration.HttpLog);
services.AddSingleton(configuration.PushNotifications);
Expand All @@ -25,7 +25,7 @@ internal static void Configure(IServiceCollection services, IConfiguration appCo
services.AddSingleton(configuration.YouTube);

services.AddInternalServices();
services.AddJobs(configuration);
services.AddJobs(configuration, isDevelopment);

services.AddExternalServices(configuration);
services.AddMigrations(configuration);
Expand Down
18 changes: 11 additions & 7 deletions Dodo1000Bot.Api/DependencyModules/JobsRegistration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,20 @@ namespace Dodo1000Bot.Api.DependencyModules;

public static class JobsRegistration
{
internal static void AddJobs(this IServiceCollection services, AppConfiguration appConfiguration)
internal static void AddJobs(this IServiceCollection services, AppConfiguration appConfiguration, bool isDevelopment)
{
services.AddHostedService(serviceProvider => new MigrationsJob(appConfiguration.MysqlConnectionString, serviceProvider));
services.AddHostedService<FirstRunJob>();
services.AddHostedService<PushNotificationsRepeatableJob>();

services.AddHostedService<UnitsCheckAndNotifyJob>();
services.AddHostedService<StatisticsCheckAndNotifyJob>();
services.AddHostedService<YoutubeCheckAndNotifyJob>();

if (!isDevelopment)
{
services.AddHostedService<FirstRunJob>();
services.AddHostedService<PushNotificationsRepeatableJob>();

services.AddHostedService<UnitsCheckAndNotifyJob>();
services.AddHostedService<StatisticsCheckAndNotifyJob>();
services.AddHostedService<YoutubeCheckAndNotifyJob>();
}

var channelOptions = new BoundedChannelOptions(1_000)
{
FullMode = BoundedChannelFullMode.DropWrite,
Expand Down
2 changes: 1 addition & 1 deletion Dodo1000Bot.Api/Dodo1000Bot.Api.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<Version>1.29.0</Version>
<UserSecretsId>f449de95-800a-40ef-8716-6e80b7f0977d</UserSecretsId>
</PropertyGroup>
Expand Down
9 changes: 6 additions & 3 deletions Dodo1000Bot.Api/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Prometheus;
Expand All @@ -19,10 +20,12 @@ namespace Dodo1000Bot.Api
public class Startup
{
private readonly IConfiguration _configuration;
private readonly IWebHostEnvironment _environment;

public Startup(IConfiguration configuration, ILoggerFactory loggerFactory)
public Startup(IConfiguration configuration, IWebHostEnvironment environment, ILoggerFactory loggerFactory)
{
_configuration = configuration;
_environment = environment;
InternalLoggerFactory.Factory = loggerFactory;
}

Expand All @@ -43,7 +46,7 @@ public void ConfigureServices(IServiceCollection services)

return options.JsonSerializerOptions;
})
.AddMvc()
.AddControllers()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
Expand All @@ -55,7 +58,7 @@ public void ConfigureServices(IServiceCollection services)
o.LoggingFields = HttpLoggingFields.All;
});

DependencyConfiguration.Configure(services, _configuration);
DependencyConfiguration.Configure(services, _configuration, _environment.IsDevelopment());
}


Expand Down
2 changes: 1 addition & 1 deletion Dodo1000Bot.Api/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
"Enabled": true,
"AddRequestIdHeader": true,
"ExcludeBodiesWithWords": [ "ping", "pong" ],
"IncludeEndpoints": ["dialogflow", "events"]
"IncludeEndpoints": ["dialogflow", "events", "telegram"]
},
"PushNotifications": {
"EveryTime": "0:01:00"
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<IsTestProject>true</IsTestProject>
<IsPackable>false</IsPackable>
</PropertyGroup>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Threading.Tasks;
using System.Text.Json;
using System.Threading.Tasks;
using AutoFixture;
using Dodo1000Bot.Messengers.Tests.Controllers;
using Microsoft.AspNetCore.Mvc;
Expand All @@ -14,6 +15,7 @@ public class TelegramControllerTests : ControllerTests<TelegramController>
{
private Mock<ITelegramService> _telegramService;
private Mock<TelegramConfiguration> _configuration;
private JsonSerializerOptions _jsonOptions;

[SetUp]
public void InitTest()
Expand All @@ -23,8 +25,9 @@ public void InitTest()
var loggerMock = Mock.Of<ILogger<TelegramController>>();
_telegramService = MockRepository.Create<ITelegramService>();
_configuration = MockRepository.Create<TelegramConfiguration>();
_jsonOptions = new JsonSerializerOptions();

Target = new TelegramController(loggerMock, _telegramService.Object, _configuration.Object);
Target = new TelegramController(loggerMock, _telegramService.Object, _configuration.Object, _jsonOptions);
}

[Test]
Expand Down
32 changes: 18 additions & 14 deletions Dodo1000Bot.Messengers.Telegram.Tests/TelegramNotifyServiceTests.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.Immutable;
using AutoFixture;
using Dodo1000Bot.Models;
using Dodo1000Bot.Models.Domain;
Expand All @@ -11,9 +10,9 @@
using System.Threading;
using System.Threading.Tasks;
using Telegram.Bot;
using Telegram.Bot.Requests;
using Telegram.Bot.Requests.Abstractions;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
using Telegram.Bot.Types.ReplyMarkups;
using Domain = Dodo1000Bot.Models.Domain;

namespace Dodo1000Bot.Messengers.Telegram.Tests
Expand Down Expand Up @@ -96,11 +95,13 @@ public async Task NotifyAbout_AnyNotificationsAndUsers_SentAllNotificationsToAll
var ct = CancellationToken.None;

_usersServiceMock.Setup(r => r.GetUsers(Source.Telegram, ct)).ReturnsAsync(new []{user});
_clientMock.Setup(c => c.SendTextMessageAsync(user.MessengerUserId, notification.Payload.Text,
It.IsAny<ParseMode>(), It.IsAny<IEnumerable<MessageEntity>>(),
It.IsAny<bool>(), It.IsAny<bool>(),
It.IsAny<int>(), It.IsAny<bool>(),
It.IsAny<IReplyMarkup>(), ct)).ReturnsAsync(() => null);
_clientMock.Setup(c => c.MakeRequestAsync(It.IsAny<SendMessageRequest>(), ct))
.Callback((IRequest<Message> request, CancellationToken _) =>
{
var sendMessageRequest = request as SendMessageRequest;
Assert.AreEqual(sendMessageRequest?.Text, notification.Payload.Text);
Assert.AreEqual(sendMessageRequest?.ChatId, (ChatId)user.MessengerUserId);
}).ReturnsAsync(() => null);

var pushedNotifications = (await _target.NotifyAbout(new []{notification}, ct)).ToArray();

Expand Down Expand Up @@ -135,11 +136,14 @@ public async Task NotifyAbout_AdminNotifications_SentOnlyToAdminUsers()
var ct = CancellationToken.None;

_usersServiceMock.Setup(r => r.GetUsers(Source.Telegram, ct)).ReturnsAsync(new []{ adminUser, ordinaryUser });
_clientMock.Setup(c => c.SendTextMessageAsync(adminUser.MessengerUserId, notification.Payload.Text,
It.IsAny<ParseMode>(), It.IsAny<IEnumerable<MessageEntity>>(),
It.IsAny<bool>(), It.IsAny<bool>(),
It.IsAny<int>(), It.IsAny<bool>(),
It.IsAny<IReplyMarkup>(), ct)).ReturnsAsync(() => null);
_clientMock.Setup(c => c.MakeRequestAsync(It.IsAny<SendMessageRequest>(), ct))
.Callback((IRequest<Message> request, CancellationToken _) =>
{
var sendMessageRequest = request as SendMessageRequest;
Assert.AreEqual(sendMessageRequest?.Text, notification.Payload.Text);
Assert.AreEqual(sendMessageRequest?.ChatId, (ChatId)adminUser.MessengerUserId);
})
.ReturnsAsync(() => null);

var pushedNotifications = (await _target.NotifyAbout(new []{notification}, ct)).ToArray();

Expand Down
9 changes: 5 additions & 4 deletions Dodo1000Bot.Messengers.Telegram.Tests/TelegramServiceTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using Moq;
using NUnit.Framework;
using Telegram.Bot;
using Telegram.Bot.Requests;
using Telegram.Bot.Types;

namespace Dodo1000Bot.Messengers.Telegram.Tests
Expand Down Expand Up @@ -41,15 +42,15 @@ public void InitTest()
}

[Test]
public async Task GetMeAsync_Invokations_Success()
public async Task GetMeAsync_Invocations_Success()
{
await _target.GetMeAsync();

_telegramBotClient.Verify(c => c.GetMeAsync(It.IsAny<CancellationToken>()));
_telegramBotClient.Verify(c => c.MakeRequestAsync(It.IsAny<GetMeRequest>(), It.IsAny<CancellationToken>()));
}

[Test]
public async Task TestApiAsync_Invokations_Success()
public async Task TestApiAsync_Invocations_Success()
{
await _target.TestApiAsync();

Expand All @@ -61,7 +62,7 @@ public async Task SetWebhookAsync_Invocation_Success()
{
await _target.SetWebhookAsync(It.IsAny<string>(), CancellationToken.None);

_telegramBotClient.Verify(c => c.SetWebhookAsync(It.IsAny<string>(), null, null, It.IsAny<int>(), null, It.IsAny<bool>(), It.IsAny<CancellationToken>()));
_telegramBotClient.Verify(c => c.MakeRequestAsync(It.IsAny<SetWebhookRequest>(), It.IsAny<CancellationToken>()));
}

[Test]
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<OutputType>Library</OutputType>
<UserSecretsId>14ecb2eb-f151-49bb-a3a5-ec5619569d45</UserSecretsId>
</PropertyGroup>
Expand All @@ -14,7 +14,7 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="Telegram.Bot" Version="16.*" />
<PackageReference Include="Telegram.Bot" Version="19.*" />
</ItemGroup>

<ItemGroup>
Expand Down
3 changes: 2 additions & 1 deletion Dodo1000Bot.Messengers.Telegram/ITelegramService.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
using System.Threading.Tasks;
using Dodo1000Bot.Models;
using Dodo1000Bot.Services;
using Telegram.Bot.Types;

namespace Dodo1000Bot.Messengers.Telegram
{
public interface ITelegramService : IMessengerService<Update, string>
public interface ITelegramService : IMessengerService<Update, Response>
{
Task<bool> TestApiAsync();

Expand Down
26 changes: 23 additions & 3 deletions Dodo1000Bot.Messengers.Telegram/TelegramController.cs
Original file line number Diff line number Diff line change
@@ -1,18 +1,27 @@
using System.Threading.Tasks;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Dodo1000Bot.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Telegram.Bot.Types;

namespace Dodo1000Bot.Messengers.Telegram
{
public class TelegramController : MessengerController<Update, string>
public class TelegramController : MessengerController<Update, Response>
{
private readonly ITelegramService _telegramService;

public TelegramController(ILogger<TelegramController> log, ITelegramService telegramService, TelegramConfiguration configuration)
public TelegramController(
ILogger<TelegramController> log,
ITelegramService telegramService,
TelegramConfiguration configuration,
[FromKeyedServices($"{nameof(TelegramController)}{nameof(JsonSerializerOptions)}")] JsonSerializerOptions jsonOptions)
: base(log, telegramService, configuration)
{
_telegramService = telegramService;
SerializerSettings = jsonOptions;
}

[HttpGet("TestTelegramApi")]
Expand All @@ -30,5 +39,16 @@ public async Task<IActionResult> GetMeAsync()

return new JsonResult(user);
}

public new async Task<IActionResult> WebHook(string token, CancellationToken cancellationToken)
{

// using var memoryReader = new StreamReader(HttpContext.Request.Body);
// var bodyReadResult = await memoryReader.ReadToEndAsync(cancellationToken);
var update= await JsonSerializer.DeserializeAsync<Update>(HttpContext.Request.Body, SerializerSettings as JsonSerializerOptions, cancellationToken);
var response = await _telegramService.ProcessIncomingAsync(update, cancellationToken);

return Json(response, SerializerSettings);
}
}
}
6 changes: 3 additions & 3 deletions Dodo1000Bot.Messengers.Telegram/TelegramService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

namespace Dodo1000Bot.Messengers.Telegram
{
public class TelegramService : MessengerService<Update, string>, ITelegramService
public class TelegramService : MessengerService<Update, Response>, ITelegramService
{
private readonly ITelegramBotClient _client;

Expand Down Expand Up @@ -69,13 +69,13 @@ public override async Task<bool> DeleteWebhookAsync(CancellationToken cancellati
return false;
}

protected override async Task<string> AfterAsync(Update input, Response response)
protected override async Task<Response> AfterAsync(Update input, Response response)
{
var answer = response.Text;

await SendTextMessageAsync(long.Parse(response.ChatHash), answer);

return answer;
return response;
}

private async Task SendTextMessageAsync(long chatId, string text)
Expand Down
Loading