feat: created auth hook on TClient

This commit is contained in:
Pavel-Savely Savianok 2025-07-25 18:35:59 +03:00
parent f115760713
commit 970526d84e
12 changed files with 141 additions and 71 deletions

View File

@ -14,6 +14,7 @@ public class HeadHunterService(
IChannel channel,
ILogger<HeadHunterService> logger,
IOptions<HeadHunterConfig> config,
IWebHostEnvironment env,
AppDbContext dbContext)
{
public enum Status
@ -47,45 +48,54 @@ public class HeadHunterService(
return Status.UserAuthRejectedError;
}
using var client = new HttpClient();
var form = new Dictionary<string, string>
HeadHunterTokenResponseDto? responseDto;
if (!env.IsDevelopment()) //Production server
{
{ "client_id", _config.ClientId },
{ "client_secret", _config.Secret },
{ "code", authorizationCode },
{ "grant_type", "authorization_code" },
{ "redirect_uri", GetRedirectUrl(userId) }
};
client.BaseAddress = new UriBuilder(_config.Links.HeadHunterApiDomain)
{
Port = -1,
Scheme = "https"
}.Uri;
client.DefaultRequestHeaders.UserAgent.ParseAdd("Jobot BackEnd Service");
using var res = await client.SendAsync(
new HttpRequestMessage(
HttpMethod.Post,
_config.Links.HeadHunterTokenRoute)
using var client = new HttpClient();
var form = new Dictionary<string, string>
{
Content = new FormUrlEncodedContent(form)
});
{ "client_id", _config.ClientId },
{ "client_secret", _config.Secret },
{ "code", authorizationCode },
{ "grant_type", "authorization_code" },
{ "redirect_uri", GetRedirectUrl(userId) }
};
client.BaseAddress = new UriBuilder(_config.Links.HeadHunterApiDomain)
{
Port = -1,
Scheme = "https"
}.Uri;
client.DefaultRequestHeaders.UserAgent.ParseAdd("Jobot BackEnd Service");
if (!res.IsSuccessStatusCode)
{
logger.LogWarning($"Response of HttpRequest {_config.Links.HeadHunterApiDomain}" +
$"{_config.Links.HeadHunterTokenRoute} has unsuccessful status code {res.StatusCode}");
logger.LogWarning($"{res.Content.ReadAsStringAsync().Result}");
return Status.HeadHunterAuthRejectedError;
using var res = await client.SendAsync(
new HttpRequestMessage(
HttpMethod.Post,
_config.Links.HeadHunterTokenRoute)
{
Content = new FormUrlEncodedContent(form)
});
if (!res.IsSuccessStatusCode)
{
logger.LogWarning($"Response of HttpRequest {_config.Links.HeadHunterApiDomain}" +
$"{_config.Links.HeadHunterTokenRoute} has unsuccessful status code {res.StatusCode}");
logger.LogWarning($"{res.Content.ReadAsStringAsync().Result}");
return Status.HeadHunterAuthRejectedError;
}
responseDto =
JsonSerializer.Deserialize<HeadHunterTokenResponseDto>(await res.Content.ReadAsStringAsync());
if (responseDto == null)
{
logger.LogWarning($"User {userId} auth completed with error " +
$"{nameof(Status.HeadHunterResponseDeserializationFailedError)}");
return Status.HeadHunterResponseDeserializationFailedError;
}
}
var responseDto = JsonSerializer.Deserialize<HeadHunterTokenResponseDto>(await res.Content.ReadAsStringAsync());
if (responseDto == null)
else
{
logger.LogWarning($"User {userId} auth completed with error " +
$"{nameof(Status.HeadHunterResponseDeserializationFailedError)}");
return Status.HeadHunterResponseDeserializationFailedError;
responseDto = new HeadHunterTokenResponseDto("testtoken", 0, "testtoken", "--");
}
var user = await dbContext.Users.FirstOrDefaultAsync(x => x.UserId == userId);

View File

@ -19,9 +19,9 @@ public class Startup(IConfiguration configuration)
services.AddControllers();
services.AddLogging();
await using var rabbitMqConnection = await new ConnectionFactory
var rabbitMqConnection = await new ConnectionFactory
{
HostName = "jobot-rabbitmq"
HostName = "rabbitmq"
}.CreateConnectionAsync();
var channel = await rabbitMqConnection.CreateChannelAsync();
await channel.QueueDeclareAsync(

View File

@ -1,3 +1,4 @@
using JOBot.TClient.Infrastructure.Extensions;
using Telegram.Bot;
using Telegram.Bot.Types;
@ -9,6 +10,6 @@ public class InfoCommand(ITelegramBotClient bot) : ITelegramCommand
{
ArgumentNullException.ThrowIfNull(update.Message?.From);
await bot.SendMessage(update.Message.From.Id, TextResource.Info, cancellationToken: ct);
await bot.SendMessageRemK(update.Message.From.Id, TextResource.Info, cancellationToken: ct);
}
}

View File

@ -77,7 +77,7 @@ public sealed class BotBackgroundService(
return;
}
await bot.SendMessage(update.Message.From.Id, TextResource.CommandNotFound, cancellationToken: ct);
await bot.SendMessageRemK(update.Message.From.Id, TextResource.CommandNotFound, cancellationToken: ct);
}
}

View File

@ -1,3 +1,4 @@
using JOBot.TClient.Infrastructure.Extensions;
using Telegram.Bot;
using Telegram.Bot.Types;
@ -11,7 +12,7 @@ public class FallbackException : Exception
{
public FallbackException(string message, Message botMessage, ITelegramBotClient botClient) : base(message)
{
botClient.SendMessage(botMessage.Chat.Id,
botClient.SendMessageRemK(botMessage.Chat.Id,
TextResource.FallbackMessage);
}
}

View File

@ -0,0 +1,52 @@
using Telegram.Bot;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
using Telegram.Bot.Types.ReplyMarkups;
namespace JOBot.TClient.Infrastructure.Extensions;
public static class TelegramBotClientExtensions
{
/// <summary>
/// Extension method for auto-remove of reply keyboard if is null
/// </summary>
/// <param name="bot"></param>
/// <param name="chatId"></param>
/// <param name="text"></param>
/// <param name="parseMode"></param>
/// <param name="replyParameters"></param>
/// <param name="replyMarkup"></param>
/// <param name="linkPreviewOptions"></param>
/// <param name="messageThreadId"></param>
/// <param name="entities"></param>
/// <param name="disableNotification"></param>
/// <param name="protectContent"></param>
/// <param name="messageEffectId"></param>
/// <param name="businessConnectionId"></param>
/// <param name="allowPaidBroadcast"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public static Task<Message> SendMessageRemK(
this ITelegramBotClient bot,
ChatId chatId,
string text,
ParseMode parseMode = default,
ReplyParameters? replyParameters = null,
ReplyMarkup? replyMarkup = null,
LinkPreviewOptions? linkPreviewOptions = null,
int? messageThreadId = null,
IEnumerable<MessageEntity>? entities = null,
bool disableNotification = false,
bool protectContent = false,
string? messageEffectId = null,
string? businessConnectionId = null,
bool allowPaidBroadcast = false,
CancellationToken cancellationToken = default)
{
replyMarkup ??= new ReplyKeyboardRemove();
return bot.SendMessage(chatId, text, parseMode, replyParameters, replyMarkup, linkPreviewOptions, messageThreadId,
entities, disableNotification, protectContent, messageEffectId, businessConnectionId, allowPaidBroadcast,
cancellationToken);
}
}

View File

@ -1,26 +1,24 @@
using System.Text;
using JOBot.Infrastructure.Config;
using JOBot.TClient.Services;
using Microsoft.Extensions.Hosting;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
namespace JOBot.TClient.Queues;
public class AuthQueue
public class AuthQueue(IChannel channel, PrepareUserService prepareUserService) : BackgroundService
{
private readonly PrepareUserService _prepareUserService;
public AuthQueue(
IChannel channel, PrepareUserService prepareUserService)
{
_prepareUserService = prepareUserService;
var consumer = new AsyncEventingBasicConsumer(channel);
consumer.ReceivedAsync += OnDataReceivedAsync;
channel.BasicConsumeAsync(RabbitQueues.AuthQueue, autoAck: true, consumer: consumer);
}
private async Task OnDataReceivedAsync(object sender, BasicDeliverEventArgs eventArgs)
{
await _prepareUserService.SelectCv(Convert.ToInt64(Encoding.UTF8.GetString(eventArgs.Body.ToArray())));
await prepareUserService.AuthHookReceived(Convert.ToInt64(Encoding.UTF8.GetString(eventArgs.Body.ToArray())));
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
var consumer = new AsyncEventingBasicConsumer(channel);
consumer.ReceivedAsync += OnDataReceivedAsync;
await channel.BasicConsumeAsync(RabbitQueues.AuthQueue, autoAck: true, consumer: consumer, cancellationToken: stoppingToken);
}
}

View File

@ -1,3 +1,4 @@
using JOBot.TClient.Infrastructure.Extensions;
using Telegram.Bot;
using Telegram.Bot.Types;
@ -9,6 +10,6 @@ public class MenuService(ITelegramBotClient bot)
{
ArgumentNullException.ThrowIfNull(update.Message?.From);
await bot.SendMessage(update.Message.From.Id, "PrepareUser stage is done.", cancellationToken: ct);
await bot.SendMessageRemK(update.Message.From.Id, "PrepareUser stage is done.", cancellationToken: ct);
}
}

View File

@ -1,5 +1,6 @@
using JOBot.Proto;
using JOBot.TClient.Infrastructure.Exceptions;
using JOBot.TClient.Infrastructure.Extensions;
using Telegram.Bot;
using Telegram.Bot.Types;
using User = JOBot.Proto.User;
@ -31,7 +32,7 @@ public class PrepareUserService(ITelegramBotClient bot, User.UserClient userClie
if (!result.Success)
{
await _bot.SendMessage(update.Message.Chat.Id,
await _bot.SendMessageRemK(update.Message.Chat.Id,
TextResource.FallbackMessage,
cancellationToken: ct);
@ -59,7 +60,7 @@ public class PrepareUserService(ITelegramBotClient bot, User.UserClient userClie
{
ArgumentNullException.ThrowIfNull(update.Message?.From);
await _bot.SendMessage(
await _bot.SendMessageRemK(
update.Message.From.Id,
TextResource.EULA,
replyMarkup: new[] { ButtonResource.EULAAgrement }, cancellationToken: ct);
@ -93,7 +94,7 @@ public class PrepareUserService(ITelegramBotClient bot, User.UserClient userClie
UserId = update.Message.From.Id
});
await _bot.SendMessage(
await _bot.SendMessageRemK(
update.Message.From.Id,
string.Format(TextResource.AskForAuth, [url.RegistrationUrl]),
cancellationToken: ct);
@ -101,7 +102,7 @@ public class PrepareUserService(ITelegramBotClient bot, User.UserClient userClie
public async Task AuthHookReceived(long userId, CancellationToken ct = default)
{
await _bot.SendMessage(userId, "Авторизация завершена успешно!", cancellationToken: ct);
await _bot.SendMessageRemK(userId, "Авторизация завершена успешно!", cancellationToken: ct);
await SelectCv(userId, ct);
}
@ -114,7 +115,7 @@ public class PrepareUserService(ITelegramBotClient bot, User.UserClient userClie
public async Task SelectCv(long userId, CancellationToken ct = default)
{
await _bot.SendMessage(userId, "Давайте выберем одно из доступных резюме:",
await _bot.SendMessageRemK(userId, "Давайте выберем одно из доступных резюме:",
cancellationToken: ct); //TODO: https://git.lisoveliy.su/Lisoveliy/JOBot/issues/9
}
}

View File

@ -23,17 +23,17 @@ public static class Startup
{
services.AddSingleton(config);
services.AddScoped<ChannelBase, GrpcChannel>(_ => GrpcChannel.ForAddress(config.GetValue<string>("BackendHost")
?? throw new MissingFieldException("Host is not defined")));
services.AddSingleton(_ => GrpcChannel.ForAddress(config.GetValue<string>("BackendHost")
?? throw new MissingFieldException("Host is not defined")));
#region Commands
services.AddScoped<StartCommand>();
services.AddScoped<MenuCommand>();
services.AddScoped<InfoCommand>();
services.AddSingleton<StartCommand>();
services.AddSingleton<MenuCommand>();
services.AddSingleton<InfoCommand>();
//buttons
services.AddScoped<EulaAgreementButtonCommand>();
services.AddSingleton<EulaAgreementButtonCommand>();
#endregion
@ -46,21 +46,21 @@ public static class Startup
#region Services
services.AddSingleton<UserService>();
services.AddScoped<PrepareUserService>();
services.AddScoped<MenuService>();
services.AddSingleton<PrepareUserService>();
services.AddSingleton<MenuService>();
#endregion
#region States
services.AddScoped<PrepareUserState>();
services.AddSingleton<PrepareUserState>();
#endregion
#region RabbitMQ Clients
var factory = new ConnectionFactory { HostName = "localhost" };
using var connection = factory.CreateConnectionAsync().Result;
var factory = new ConnectionFactory { HostName = "rabbitmq" };
var connection = factory.CreateConnectionAsync().Result;
var channel = connection.CreateChannelAsync().Result;
channel.QueueDeclareAsync(
@ -69,8 +69,9 @@ public static class Startup
false,
false,
arguments: null).Wait();
services.AddSingleton<AuthQueue>();
services.AddSingleton(channel);
services.AddHostedService<AuthQueue>();
#endregion

View File

@ -9,6 +9,8 @@ services:
- "15672:15672"
volumes:
- rabbitmq_data:/var/lib/rabbitmq/
networks:
- jobot
postgres:
image: postgres:15
@ -28,6 +30,7 @@ services:
dockerfile: JOBot.Backend/Dockerfile
depends_on:
- postgres
- rabbitmq
ports:
- "5000:5000"
- "5001:5001"

View File

@ -6,6 +6,8 @@ services:
image: rabbitmq:4
volumes:
- rabbitmq_data:/var/lib/rabbitmq/
networks:
- jobot
postgres:
image: postgres:15
@ -23,7 +25,7 @@ services:
dockerfile: JOBot.Backend/Dockerfile
depends_on:
- postgres
- image
- rabbitmq
ports:
- "5000:5000"
networks: