chore: cleanup
This commit is contained in:
parent
7ceb8f656e
commit
b15a77557e
@ -8,16 +8,17 @@ namespace JOBot.Backend.Controllers;
|
||||
public class HeadHunterHookController(HeadHunterService hhService)
|
||||
: ControllerBase
|
||||
{
|
||||
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> Get(int userId, string? error, string code)
|
||||
{
|
||||
var res = await hhService.AuthUser(userId, code, error);
|
||||
return res switch
|
||||
{
|
||||
HeadHunterService.Status.Success => Ok("Авторизация завершена успешно. Вернитесь в Telegram для продолжения."),
|
||||
HeadHunterService.Status.Success => Ok(
|
||||
"Авторизация завершена успешно. Вернитесь в Telegram для продолжения."),
|
||||
HeadHunterService.Status.UserNotFoundError => NotFound("Пользователь не найден."),
|
||||
_ => BadRequest("Авторизация завершена с ошибкой. Вернитесь в Telegram для продолжения.") //TODO: Add resource
|
||||
_ => BadRequest(
|
||||
"Авторизация завершена с ошибкой. Вернитесь в Telegram для продолжения.") //TODO: Add resource
|
||||
};
|
||||
}
|
||||
}
|
@ -1,8 +1,8 @@
|
||||
namespace JOBot.Backend.DAL.Context;
|
||||
|
||||
using Models;
|
||||
using JOBot.Backend.DAL.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace JOBot.Backend.DAL.Context;
|
||||
|
||||
public class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(options)
|
||||
{
|
||||
public DbSet<User> Users { get; set; }
|
||||
|
@ -9,10 +9,10 @@ public class User
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
|
||||
[Key]
|
||||
public required long UserId { get; set; }
|
||||
[MaxLength(255)]
|
||||
public string? Username { get; set; }
|
||||
[Key] public required long UserId { get; set; }
|
||||
|
||||
[MaxLength(255)] public string? Username { get; set; }
|
||||
|
||||
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
|
||||
|
||||
[MaxLength(255)] public string? AccessToken { get; set; } = null;
|
||||
|
@ -15,6 +15,15 @@ public class HeadHunterService(
|
||||
IOptions<HeadHunterConfig> config,
|
||||
AppDbContext dbContext)
|
||||
{
|
||||
public enum Status
|
||||
{
|
||||
UserAuthRejectedError,
|
||||
HeadHunterAuthRejectedError,
|
||||
UserNotFoundError,
|
||||
HeadHunterResponseDeserializationFailedError,
|
||||
Success
|
||||
}
|
||||
|
||||
private readonly HeadHunterConfig _config = config.Value;
|
||||
|
||||
/// <summary>
|
||||
@ -24,11 +33,10 @@ public class HeadHunterService(
|
||||
/// <returns>Link for auth</returns>
|
||||
public string GenerateAuthLink(long userId)
|
||||
{
|
||||
|
||||
return string.Format(_config.Links.AuthLink, [_config.ClientId, GetRedirectUrl(userId)]);
|
||||
}
|
||||
|
||||
public async Task<Status> AuthUser(int userId, string authorizationCode, string? error)
|
||||
public async Task<Status> AuthUser(int userId, string authorizationCode, string? error) //TODO: Разбить этот метод
|
||||
{
|
||||
logger.LogInformation($"Authorization for user {userId} in process...");
|
||||
|
||||
@ -99,7 +107,7 @@ public class HeadHunterService(
|
||||
RabbitQueues.AuthQueue,
|
||||
Encoding.UTF8.GetBytes(userId.ToString()));
|
||||
|
||||
logger.LogInformation($"RabbitMQ event was created");
|
||||
logger.LogInformation("RabbitMQ event was created");
|
||||
|
||||
return Status.Success;
|
||||
}
|
||||
@ -114,13 +122,4 @@ public class HeadHunterService(
|
||||
Query = $"?userId={userId}"
|
||||
}.ToString();
|
||||
}
|
||||
|
||||
public enum Status
|
||||
{
|
||||
UserAuthRejectedError,
|
||||
HeadHunterAuthRejectedError,
|
||||
UserNotFoundError,
|
||||
HeadHunterResponseDeserializationFailedError,
|
||||
Success
|
||||
}
|
||||
}
|
@ -1,4 +1,3 @@
|
||||
using Google.Protobuf.WellKnownTypes;
|
||||
using Grpc.Core;
|
||||
using JOBot.Backend.DAL.Context;
|
||||
using JOBot.Backend.DAL.Models;
|
||||
|
@ -23,7 +23,7 @@ public class Startup(IConfiguration configuration)
|
||||
HostName = "jobot-rabbitmq"
|
||||
}.CreateConnectionAsync();
|
||||
await using var channel = await rabbitMqConnection.CreateChannelAsync();
|
||||
await channel.QueueDeclareAsync(RabbitQueues.AuthQueue, false, false, autoDelete: false);
|
||||
await channel.QueueDeclareAsync(RabbitQueues.AuthQueue, false, false, false);
|
||||
services.AddSingleton(channel);
|
||||
|
||||
services.AddDbContext<AppDbContext>(options =>
|
||||
|
@ -1,7 +1,8 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
|
||||
<root>
|
||||
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
|
||||
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" id="root"
|
||||
xmlns="">
|
||||
<xsd:element name="root" msdata:IsDataSet="true">
|
||||
|
||||
</xsd:element>
|
||||
@ -13,10 +14,14 @@
|
||||
<value>1.3</value>
|
||||
</resheader>
|
||||
<resheader name="reader">
|
||||
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral,
|
||||
PublicKeyToken=b77a5c561934e089
|
||||
</value>
|
||||
</resheader>
|
||||
<resheader name="writer">
|
||||
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral,
|
||||
PublicKeyToken=b77a5c561934e089
|
||||
</value>
|
||||
</resheader>
|
||||
<data name="EULAAgrement" xml:space="preserve">
|
||||
<value>Соглашаюсь с условиями использования ✅</value>
|
||||
|
@ -1,9 +1,7 @@
|
||||
using JOBot.Proto;
|
||||
using JOBot.TClient.Infrastructure.Attributes.Authorization;
|
||||
using JOBot.TClient.Services;
|
||||
using JOBot.TClient.Statements;
|
||||
using Telegram.Bot.Types;
|
||||
using Telegram.Bot.Types.Enums;
|
||||
|
||||
namespace JOBot.TClient.Commands.Buttons;
|
||||
|
||||
|
@ -1,17 +1,18 @@
|
||||
using JOBot.Proto;
|
||||
using Telegram.Bot;
|
||||
using Telegram.Bot.Types;
|
||||
|
||||
namespace JOBot.TClient.Commands;
|
||||
|
||||
public interface IAuthorizedTelegramCommand : ITelegramCommand
|
||||
{
|
||||
public Task ExecuteAsync(Update update, GetUserResponse user, CancellationToken ct);
|
||||
|
||||
/// <exception cref="UnauthorizedAccessException">Throws if you try to use ITelegramCommand.ExecuteAsync
|
||||
/// instead of IAuthorizedTelegramCommand.ExecuteAsync</exception>
|
||||
/// <exception cref="UnauthorizedAccessException">
|
||||
/// Throws if you try to use ITelegramCommand.ExecuteAsync
|
||||
/// instead of IAuthorizedTelegramCommand.ExecuteAsync
|
||||
/// </exception>
|
||||
Task ITelegramCommand.ExecuteAsync(Update update, CancellationToken ct)
|
||||
{
|
||||
throw new UnauthorizedAccessException("You do not have permission to access this command.");
|
||||
}
|
||||
|
||||
public Task ExecuteAsync(Update update, GetUserResponse user, CancellationToken ct);
|
||||
}
|
@ -5,10 +5,10 @@ using JOBot.TClient.Infrastructure.Attributes.Authorization;
|
||||
using JOBot.TClient.Infrastructure.Extensions;
|
||||
using JOBot.TClient.Services;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Telegram.Bot;
|
||||
using Telegram.Bot.Types;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
|
||||
namespace JOBot.TClient.Core.HostedServices;
|
||||
|
||||
@ -22,8 +22,8 @@ public sealed class BotBackgroundService(
|
||||
protected override Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
botClient.StartReceiving(
|
||||
updateHandler: HandleUpdateAsync,
|
||||
errorHandler: HandleErrorAsync,
|
||||
HandleUpdateAsync,
|
||||
HandleErrorAsync,
|
||||
cancellationToken: stoppingToken);
|
||||
|
||||
return Task.CompletedTask;
|
||||
@ -40,7 +40,7 @@ public sealed class BotBackgroundService(
|
||||
["/info"] = scope.ServiceProvider.GetRequiredService<InfoCommand>(),
|
||||
|
||||
//Buttons
|
||||
[ButtonResource.EULAAgrement] = scope.ServiceProvider.GetRequiredService<EulaAgreementButtonCommand>(),
|
||||
[ButtonResource.EULAAgrement] = scope.ServiceProvider.GetRequiredService<EulaAgreementButtonCommand>()
|
||||
};
|
||||
|
||||
if (update.Message is { Text: { } text, From: not null })
|
||||
@ -69,7 +69,10 @@ public sealed class BotBackgroundService(
|
||||
|
||||
await authorizedTelegramCommand.ExecuteAsync(update, user, ct);
|
||||
}
|
||||
else await command.ExecuteAsync(update, ct);
|
||||
else
|
||||
{
|
||||
await command.ExecuteAsync(update, ct);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
@ -23,26 +23,34 @@ public static class DependencyInjection
|
||||
?? throw new MissingFieldException("Host is not defined")));
|
||||
|
||||
#region Commands
|
||||
|
||||
services.AddScoped<StartCommand>();
|
||||
services.AddScoped<MenuCommand>();
|
||||
services.AddScoped<InfoCommand>();
|
||||
|
||||
//buttons
|
||||
services.AddScoped<EulaAgreementButtonCommand>();
|
||||
|
||||
#endregion
|
||||
|
||||
#region gRPC Clients
|
||||
|
||||
services.AddGrpcClient<User.UserClient>(o => o.Address = new Uri("http://backend:5001"));
|
||||
|
||||
#endregion
|
||||
|
||||
#region Services
|
||||
|
||||
services.AddSingleton<UserService>();
|
||||
services.AddScoped<PrepareUserService>();
|
||||
services.AddScoped<MenuService>();
|
||||
|
||||
#endregion
|
||||
|
||||
#region States
|
||||
|
||||
services.AddScoped<PrepareUserState>();
|
||||
|
||||
#endregion
|
||||
|
||||
// Bot service
|
||||
|
@ -11,7 +11,7 @@ public class FallbackException : Exception
|
||||
{
|
||||
public FallbackException(string message, Message botMessage, ITelegramBotClient botClient) : base(message)
|
||||
{
|
||||
botClient.SendMessage(chatId: botMessage.Chat.Id,
|
||||
botClient.SendMessage(botMessage.Chat.Id,
|
||||
TextResource.FallbackMessage);
|
||||
}
|
||||
}
|
@ -4,6 +4,9 @@ namespace JOBot.TClient.Infrastructure.Extensions;
|
||||
|
||||
public static class GRpcModelsExtensions
|
||||
{
|
||||
public static bool IsPrepared(this GetUserResponse user) => user is { Eula: true, IsLogged: true } &&
|
||||
public static bool IsPrepared(this GetUserResponse user)
|
||||
{
|
||||
return user is { Eula: true, IsLogged: true } &&
|
||||
!string.IsNullOrEmpty(user.CVUrl);
|
||||
}
|
||||
}
|
@ -6,7 +6,6 @@ var host = Host.CreateDefaultBuilder(args)
|
||||
{
|
||||
// Настройка DI
|
||||
services.ConfigureServices(context.Configuration);
|
||||
|
||||
})
|
||||
.Build();
|
||||
|
||||
|
@ -1,6 +1,5 @@
|
||||
using Telegram.Bot;
|
||||
using Telegram.Bot.Types;
|
||||
using User = JOBot.Proto.User;
|
||||
|
||||
namespace JOBot.TClient.Services;
|
||||
|
||||
|
@ -26,21 +26,21 @@ public class PrepareUserService(ITelegramBotClient bot, User.UserClient userClie
|
||||
var result = await _userClient.RegisterAsync(new RegisterRequest
|
||||
{
|
||||
UserId = update.Message.From.Id,
|
||||
Username = update.Message.From.Username,
|
||||
Username = update.Message.From.Username
|
||||
});
|
||||
|
||||
if (!result.Success)
|
||||
{
|
||||
await _bot.SendMessage(chatId: update.Message.Chat.Id,
|
||||
await _bot.SendMessage(update.Message.Chat.Id,
|
||||
TextResource.FallbackMessage,
|
||||
cancellationToken: ct);
|
||||
|
||||
throw new FallbackException(TextResource.FallbackMessage, update.Message, _bot);
|
||||
}
|
||||
|
||||
var user = await _userClient.GetUserAsync(new GetUserRequest()
|
||||
var user = await _userClient.GetUserAsync(new GetUserRequest
|
||||
{
|
||||
UserId = update.Message.From.Id,
|
||||
UserId = update.Message.From.Id
|
||||
});
|
||||
|
||||
if (user == null)
|
||||
@ -74,10 +74,10 @@ public class PrepareUserService(ITelegramBotClient bot, User.UserClient userClie
|
||||
public async Task AcceptEula(Update update, CancellationToken ct = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(update.Message?.From);
|
||||
var result = await _userClient.AcceptEulaAsync(new()
|
||||
var result = await _userClient.AcceptEulaAsync(new AcceptEulaRequest
|
||||
{
|
||||
EulaAccepted = true,
|
||||
UserId = update.Message.From.Id,
|
||||
UserId = update.Message.From.Id
|
||||
});
|
||||
|
||||
if (!result.Success)
|
||||
@ -88,7 +88,7 @@ public class PrepareUserService(ITelegramBotClient bot, User.UserClient userClie
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(update.Message?.From);
|
||||
|
||||
var url = await _userClient.GetHeadHunterAuthHookAsync(new GetHeadHunterAuthHookRequest()
|
||||
var url = await _userClient.GetHeadHunterAuthHookAsync(new GetHeadHunterAuthHookRequest
|
||||
{
|
||||
UserId = update.Message.From.Id
|
||||
});
|
||||
@ -103,6 +103,7 @@ public class PrepareUserService(ITelegramBotClient bot, User.UserClient userClie
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(update.Message?.From);
|
||||
|
||||
await _bot.SendMessage(update.Message.From.Id, "Давайте выберем одно из доступных резюме:", cancellationToken: ct); //TODO: https://git.lisoveliy.su/Lisoveliy/JOBot/issues/9
|
||||
await _bot.SendMessage(update.Message.From.Id, "Давайте выберем одно из доступных резюме:",
|
||||
cancellationToken: ct); //TODO: https://git.lisoveliy.su/Lisoveliy/JOBot/issues/9
|
||||
}
|
||||
}
|
@ -26,7 +26,7 @@ public class UserService(ITelegramBotClient bot, User.UserClient userClient)
|
||||
{
|
||||
user = await userClient.GetUserAsync(new GetUserRequest() //Получаем пользователя
|
||||
{
|
||||
UserId = update.Message.From.Id,
|
||||
UserId = update.Message.From.Id
|
||||
});
|
||||
}
|
||||
catch (RpcException e) //Пользователь не найден?
|
||||
@ -36,6 +36,7 @@ public class UserService(ITelegramBotClient bot, User.UserClient userClient)
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
return user;
|
||||
}
|
||||
}
|
@ -32,7 +32,7 @@ public class PrepareUserState(PrepareUserService prepareUserService, MenuService
|
||||
/// <param name="ct"></param>
|
||||
public async Task AcceptEula(GetUserResponse user, Update update, CancellationToken ct = default)
|
||||
{
|
||||
await prepareUserService.AcceptEula(update, ct: ct);
|
||||
await prepareUserService.AcceptEula(update, ct);
|
||||
await OnUserEulaValidStage(user, update, ct);
|
||||
}
|
||||
|
||||
@ -49,6 +49,7 @@ public class PrepareUserState(PrepareUserService prepareUserService, MenuService
|
||||
await prepareUserService.Auth(update, ct);
|
||||
return;
|
||||
}
|
||||
|
||||
await OnAuthStage(user, update, ct);
|
||||
}
|
||||
|
||||
@ -60,10 +61,7 @@ public class PrepareUserState(PrepareUserService prepareUserService, MenuService
|
||||
/// <param name="ct"></param>
|
||||
private async Task OnAuthStage(GetUserResponse user, Update update, CancellationToken ct = default)
|
||||
{
|
||||
if (string.IsNullOrEmpty(user.CVUrl))
|
||||
{
|
||||
await prepareUserService.SelectCv(update, ct);
|
||||
}
|
||||
if (string.IsNullOrEmpty(user.CVUrl)) await prepareUserService.SelectCv(update, ct);
|
||||
await menuService.RenderMenu(update, ct); //boilerplate
|
||||
}
|
||||
}
|
@ -1,7 +1,8 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
|
||||
<root>
|
||||
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
|
||||
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" id="root"
|
||||
xmlns="">
|
||||
<xsd:element name="root" msdata:IsDataSet="true">
|
||||
|
||||
</xsd:element>
|
||||
@ -13,10 +14,14 @@
|
||||
<value>1.3</value>
|
||||
</resheader>
|
||||
<resheader name="reader">
|
||||
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral,
|
||||
PublicKeyToken=b77a5c561934e089
|
||||
</value>
|
||||
</resheader>
|
||||
<resheader name="writer">
|
||||
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral,
|
||||
PublicKeyToken=b77a5c561934e089
|
||||
</value>
|
||||
</resheader>
|
||||
<data name="EULA" xml:space="preserve">
|
||||
<value>Продолжая, вы принимаете политику конфиденциальности и правила сервиса
|
||||
|
10
README.md
10
README.md
@ -31,21 +31,25 @@ Telegram-бот для автоматизации поиска работы че
|
||||
## 🚀 Запуск
|
||||
|
||||
### Требования
|
||||
|
||||
- .NET 8 SDK
|
||||
- Docker (для работы с БД)
|
||||
- Аккаунт разработчика на [dev.hh.ru](https://dev.hh.ru)
|
||||
|
||||
### 1. Настройка конфигурации
|
||||
|
||||
Создайте `appsettings.json` в `JOBot.TClient` на основе `appsettings.Example.json`
|
||||
|
||||
### 2. Запуск через Docker
|
||||
|
||||
```
|
||||
docker-compose up -d --build
|
||||
```
|
||||
|
||||
## 📌 Команды бота
|
||||
|
||||
| Команда | Описание |
|
||||
|-------|--------|
|
||||
|---------|----------------------------------------------|
|
||||
| /start | Начало работы |
|
||||
| /menu | Настройка откликов и резюме по предпочтениям |
|
||||
| /info | Информация о боте |
|
||||
@ -55,6 +59,8 @@ MIT License. Подробнее в файле LICENSE.
|
||||
|
||||
## Отказ от ответственности
|
||||
|
||||
Продолжая, вы принимаете [политику конфиденциальности](https://hh.ru/article/personal_data?backurl=%2F&role=applicant) и [правила сервиса](https://hh.ru/account/agreement?backurl=%2Faccount%2Fsignup%3Fbackurl%3D%252F%26role%3Dapplicant&role=applicant) hh.ru
|
||||
Продолжая, вы принимаете [политику конфиденциальности](https://hh.ru/article/personal_data?backurl=%2F&role=applicant)
|
||||
и [правила сервиса](https://hh.ru/account/agreement?backurl=%2Faccount%2Fsignup%3Fbackurl%3D%252F%26role%3Dapplicant&role=applicant)
|
||||
hh.ru
|
||||
|
||||
Этот сервис никак не связан с HeadHunter™ (далее hh.ru), не выдаёт себя за hh.ru и не является hh.ru
|
Loading…
x
Reference in New Issue
Block a user