Skip to content

Commit

Permalink
Build fix
Browse files Browse the repository at this point in the history
  • Loading branch information
PaGrom committed Nov 26, 2023
1 parent 5e03e3b commit 743d401
Show file tree
Hide file tree
Showing 13 changed files with 138 additions and 91 deletions.
2 changes: 1 addition & 1 deletion Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
</PropertyGroup>
<ItemGroup>
<PackageVersion Include="Autofac" Version="7.1.0" />
<PackageVersion Include="HttpToSocks5Proxy" Version="1.4.0" />
<PackageVersion Include="Microsoft.CSharp" Version="4.7.0" />
<PackageVersion Include="Microsoft.EntityFrameworkCore" Version="8.0.0" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.0">
Expand All @@ -20,6 +19,7 @@
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageVersion>
<PackageVersion Include="Microsoft.Extensions.Hosting.Abstractions" Version="8.0.0" />
<PackageVersion Include="Microsoft.Extensions.Http" Version="8.0.0" />
<PackageVersion Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.0" />
<PackageVersion Include="Microsoft.Extensions.Logging.Console" Version="8.0.0" />
<PackageVersion Include="Newtonsoft.Json" Version="13.0.3" />
Expand Down
17 changes: 6 additions & 11 deletions Telegrom.Core/Contexts/SessionManager.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Autofac;
using Autofac;
using Telegram.Bot.Types;

namespace Telegrom.Core.Contexts
Expand All @@ -12,9 +7,9 @@ public sealed class SessionManager : IAsyncDisposable
{
private readonly ILifetimeScope _lifetimeScope;
private readonly IIdentityService _identityService;
private readonly object _syncRoot = new object();
private readonly LinkedList<int> _recentSessionContextsQueue = new LinkedList<int>();
private readonly Dictionary<int, SessionContext> _sessionContexts = new Dictionary<int, SessionContext>();
private readonly object _syncRoot = new();
private readonly LinkedList<long> _recentSessionContextsQueue = [];
private readonly Dictionary<long, SessionContext> _sessionContexts = new();
private readonly int _maxActiveSessions;

public SessionManager(ILifetimeScope lifetimeScope, IIdentityService identityService, int maxActiveSessions)
Expand Down Expand Up @@ -65,9 +60,9 @@ public async Task<SessionContext> GetSessionContextAsync(User user, Cancellation
return sessionContext;
}

public async Task CompleteAllAsync()
public Task CompleteAllAsync()
{
await Task.WhenAll(_sessionContexts.Values.Select(sessionContext => sessionContext.Complete()));
return Task.WhenAll(_sessionContexts.Values.Select(sessionContext => sessionContext.Complete()));
}

public async ValueTask DisposeAsync()
Expand Down
6 changes: 3 additions & 3 deletions Telegrom.Core/ITelegramUpdateReceiver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@

namespace Telegrom.Core
{
public interface ITelegramUpdateReceiver : IDisposable
public interface ITelegramUpdateReceiver
{
void Start();
void SetUpdateReceivedHandler(Action<Update, CancellationToken> handler);
void Start(CancellationToken cancellationToken);
void SetUpdateReceivedHandler(Func<Update, CancellationToken, Task> handler);
}
}
2 changes: 1 addition & 1 deletion Telegrom.Core/IWakeUpService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,6 @@ namespace Telegrom.Core
{
public interface IWakeUpService
{
Task WakeUpAsync(Action<Update, CancellationToken> handler, CancellationToken cancellationToken);
Task WakeUpAsync(Func<Update, CancellationToken, Task> handler, CancellationToken cancellationToken);
}
}
2 changes: 1 addition & 1 deletion Telegrom.Database/Model/IdentityState.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ namespace Telegrom.Database.Model
public sealed class IdentityState
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int IdentityId { get; set; }
public long IdentityId { get; set; }
public string StateName { get; set; }
public byte[] RowVersion { get; set; }
}
Expand Down
2 changes: 1 addition & 1 deletion Telegrom.Database/Model/IdentityUser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ namespace Telegrom.Database.Model
public sealed class IdentityUser
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id { get; set; }
public long Id { get; set; }
public string Username { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
Expand Down
2 changes: 1 addition & 1 deletion Telegrom.Database/Model/SessionAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ public sealed class SessionAttribute
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public Guid Id { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int SessionId { get; set; }
public long SessionId { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public string Type { get; set; }
public string Value { get; set; }
Expand Down
2 changes: 1 addition & 1 deletion Telegrom.Database/Model/SessionUpdate.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ namespace Telegrom.Database.Model
public sealed class SessionUpdate
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int IdentityId { get; set; }
public long IdentityId { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int UpdateId { get; set; }
public string UpdateType { get; set; }
Expand Down
2 changes: 1 addition & 1 deletion Telegrom.Database/WakeUpService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public WakeUpService(DbContextOptions dbContextOptions)
_dbContextOptions = dbContextOptions;
}

public async Task WakeUpAsync(Action<Update, CancellationToken> handler, CancellationToken cancellationToken)
public async Task WakeUpAsync(Func<Update, CancellationToken, Task> handler, CancellationToken cancellationToken)
{
await using var context = new DatabaseContext(_dbContextOptions);
var notProcessedUpdates = await context.SessionUpdates
Expand Down
136 changes: 91 additions & 45 deletions Telegrom.TelegramService/TelegramServiceModule.cs
Original file line number Diff line number Diff line change
@@ -1,58 +1,104 @@
using System.Net;
using Autofac;
using MihaZupan;
using Microsoft.Extensions.DependencyInjection;
using Telegram.Bot;
using Telegrom.Core;
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member

namespace Telegrom.TelegramService
namespace Telegrom.TelegramService;

public sealed class TelegramServiceModule : Module
{
public class TelegramServiceModule : Module
private const string HttpClientName = "typicode";

protected override void Load(ContainerBuilder builder)
{
protected override void Load(ContainerBuilder builder)
var proxy = CreateProxy();

builder.Register(ctx =>
{
if (!string.IsNullOrEmpty(TelegramOptions.Current.ProxyAddress))
{
builder.RegisterInstance(new TelegramBotClient(
TelegramOptions.Current.TelegramApiToken,
new WebProxy(TelegramOptions.Current.ProxyAddress)
{
UseDefaultCredentials = true
}))
.AsImplementedInterfaces()
.SingleInstance();
}
else if (!string.IsNullOrEmpty(TelegramOptions.Current.Socks5HostName)
&& TelegramOptions.Current.Socks5Port.HasValue)
{
HttpToSocks5Proxy proxy;
if (!string.IsNullOrEmpty(TelegramOptions.Current.Socks5Username)
&& !string.IsNullOrEmpty(TelegramOptions.Current.Socks5Password))
{
proxy = new HttpToSocks5Proxy(
TelegramOptions.Current.Socks5HostName,
TelegramOptions.Current.Socks5Port.Value,
TelegramOptions.Current.Socks5Username,
TelegramOptions.Current.Socks5Password);
}
else
var services = new ServiceCollection();
services.AddHttpClient(HttpClientName)
.ConfigurePrimaryHttpMessageHandler(() =>
{
proxy = new HttpToSocks5Proxy(TelegramOptions.Current.Socks5HostName, TelegramOptions.Current.Socks5Port.Value);
}

builder.RegisterInstance(new TelegramBotClient(TelegramOptions.Current.TelegramApiToken, proxy))
.AsImplementedInterfaces()
.SingleInstance();
}
else
var handler = new SocketsHttpHandler();
if (proxy != null)
{
handler.Proxy = proxy;
handler.UseProxy = true;
}
return handler;
});

var provider = services.BuildServiceProvider();
return provider.GetRequiredService<IHttpClientFactory>();
}).SingleInstance();

builder.Register(c =>
{
builder.RegisterInstance(new TelegramBotClient(TelegramOptions.Current.TelegramApiToken))
.AsImplementedInterfaces()
.SingleInstance();
}

builder.RegisterType<TelegramUpdateReceiver>()
.As<ITelegramUpdateReceiver>()
.SingleInstance();
var httpClientFactory = c.Resolve<IHttpClientFactory>();
var httpClient = httpClientFactory.CreateClient(HttpClientName);
return new TelegramBotClient(TelegramOptions.Current.TelegramApiToken, httpClient);
})
.AsImplementedInterfaces()
.SingleInstance();

builder.RegisterType<TelegramUpdateReceiver>()
.As<ITelegramUpdateReceiver>()
.SingleInstance();
}

private static WebProxy? CreateProxy()
{
if (IsHttpProxyConfigured())
{
return CreateHttpProxy();
}

if (IsSocks5ProxyConfigured())
{
return CreateSocks5Proxy();
}

return null;
}

private static bool IsHttpProxyConfigured()
{
return !string.IsNullOrEmpty(TelegramOptions.Current.ProxyAddress);
}

private static WebProxy CreateHttpProxy()
{
return new WebProxy(TelegramOptions.Current.ProxyAddress)
{
UseDefaultCredentials = true
};
}

private static bool IsSocks5ProxyConfigured()
{
return !string.IsNullOrEmpty(TelegramOptions.Current.Socks5HostName)
&& TelegramOptions.Current.Socks5Port.HasValue;
}

private static WebProxy CreateSocks5Proxy()
{
var socks5Proxy = new WebProxy(TelegramOptions.Current.Socks5HostName,
TelegramOptions.Current.Socks5Port.Value);

if (IsSocks5CredentialsConfigured())
{
socks5Proxy.Credentials = new NetworkCredential(TelegramOptions.Current.Socks5Username,
TelegramOptions.Current.Socks5Password);
}

return socks5Proxy;
}

private static bool IsSocks5CredentialsConfigured()
{
return !string.IsNullOrEmpty(TelegramOptions.Current.Socks5Username)
&& !string.IsNullOrEmpty(TelegramOptions.Current.Socks5Password);
}
}
43 changes: 24 additions & 19 deletions Telegrom.TelegramService/TelegramUpdateReceiver.cs
Original file line number Diff line number Diff line change
@@ -1,18 +1,17 @@
using System;
using System.Threading;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging;
using Telegram.Bot;
using Telegram.Bot.Args;
using Telegram.Bot.Polling;
using Telegram.Bot.Types;
using Telegrom.Core;

namespace Telegrom.TelegramService
{
public class TelegramUpdateReceiver : ITelegramUpdateReceiver
public class TelegramUpdateReceiver : ITelegramUpdateReceiver, IDisposable
{
private readonly ITelegramBotClient _telegramBotClient;
private readonly ILogger<TelegramUpdateReceiver> _logger;
private Action<Update, CancellationToken> _updateReceivedHandler;
private Func<Update, CancellationToken, Task>? _updateReceivedHandler;
private CancellationTokenSource _cts;

public TelegramUpdateReceiver(ITelegramBotClient telegramBotClient,
ILogger<TelegramUpdateReceiver> logger)
Expand All @@ -23,34 +22,40 @@ public TelegramUpdateReceiver(ITelegramBotClient telegramBotClient,
var me = _telegramBotClient.GetMeAsync().GetAwaiter().GetResult();
_logger.LogInformation($"Hello, World! I am identityUser {me.Id} and my name is {me.FirstName}.");
}

public void Start()
public void SetUpdateReceivedHandler(Func<Update, CancellationToken, Task> handler)
{
RegisterHandlers();
_telegramBotClient.StartReceiving();
_updateReceivedHandler = handler;
}

private void RegisterHandlers()
public void Start(CancellationToken cancellationToken)
{
_telegramBotClient.OnUpdate += BotOnUpdateReceived;
_cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
var receiverOptions = new ReceiverOptions();

_telegramBotClient.StartReceiving(HandleUpdateAsync, HandleErrorAsync, receiverOptions, _cts.Token);
}

private void BotOnUpdateReceived(object sender, UpdateEventArgs e)
private async Task HandleUpdateAsync(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken)
{
var update = e.Update;
_logger.LogInformation("Get update {@update}", update);

_updateReceivedHandler?.Invoke(update, default);
if (_updateReceivedHandler != null)
{
await _updateReceivedHandler(update, cancellationToken);
}
}

public void SetUpdateReceivedHandler(Action<Update, CancellationToken> handler)
private Task HandleErrorAsync(ITelegramBotClient botClient, Exception exception, CancellationToken cancellationToken)
{
_updateReceivedHandler = handler;
_logger.LogError("An error occurred in receiving updates: {Exception}", exception);
return Task.CompletedTask;
}

public void Dispose()
{
_telegramBotClient.StopReceiving();
_cts.Cancel();
_logger.LogInformation("Receiver stopped");
}
}
}
2 changes: 1 addition & 1 deletion Telegrom.TelegramService/Telegrom.TelegramService.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

<ItemGroup>
<PackageReference Include="Autofac" />
<PackageReference Include="HttpToSocks5Proxy" />
<PackageReference Include="Microsoft.Extensions.Http" />
<PackageReference Include="Telegram.Bot" />
</ItemGroup>

Expand Down
11 changes: 6 additions & 5 deletions Telegrom/InternalBotService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ namespace Telegrom
internal class InternalBotService
{
private readonly SessionManager _sessionManager;
private readonly ITelegramUpdateReceiver _telegramUpdateReceiver;
private readonly IUpdateDispatcher _updateDispatcher;
private readonly IRequestDispatcher _requestDispatcher;
private readonly IWakeUpService _wakeUpService;
Expand All @@ -24,27 +25,27 @@ public InternalBotService(SessionManager sessionManager,
ILogger<InternalBotService> logger)
{
_sessionManager = sessionManager;
_telegramUpdateReceiver = telegramUpdateReceiver;
_updateDispatcher = updateDispatcher;
_requestDispatcher = requestDispatcher;
_wakeUpService = wakeUpService;
_logger = logger;

telegramUpdateReceiver.SetUpdateReceivedHandler(HandleTelegramMessageReceived);
telegramUpdateReceiver.Start();
}

public async Task RunAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("InternalBotService started");
_telegramUpdateReceiver.SetUpdateReceivedHandler(HandleTelegramMessageReceived);
_telegramUpdateReceiver.Start(cancellationToken);
_ = _updateDispatcher.RunAsync(cancellationToken);
await _wakeUpService.WakeUpAsync(HandleTelegramMessageReceived, cancellationToken);
await _requestDispatcher.RunAsync(cancellationToken);
await _sessionManager.CompleteAllAsync();
}

public async void HandleTelegramMessageReceived(Update update, CancellationToken cancellationToken)
private Task HandleTelegramMessageReceived(Update update, CancellationToken cancellationToken)
{
await _updateDispatcher.DispatchAsync(update, cancellationToken);
return _updateDispatcher.DispatchAsync(update, cancellationToken);
}
}
}

0 comments on commit 743d401

Please sign in to comment.