using Grpc.Core;
using JetBrains.Annotations;
using JOBot.Proto;
using JOBot.TClient.Infrastructure.Exceptions;
using Telegram.Bot;
using Telegram.Bot.Types;
using User = JOBot.Proto.User;
namespace JOBot.TClient.Services;
[UsedImplicitly]
public class PrepareUserService(ITelegramBotClient bot, User.UserClient userClient) : UserService(bot, userClient)
{
private readonly ITelegramBotClient _bot = bot;
private readonly User.UserClient _userClient = userClient;
///
/// Get or register user on system
///
/// Telegram Update object
/// Cancellation Token
/// RPC User Response
/// If something in server logic went wrong
/// If update.Message is null
public async Task RegisterUser(Update update, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(update.Message?.From);
var result = await _userClient.RegisterAsync(new RegisterRequest
{
UserId = update.Message.From.Id,
Username = update.Message.From.Username,
});
if (!result.Success)
{
await _bot.SendMessage(chatId: update.Message.Chat.Id,
TextResource.FallbackMessage,
cancellationToken: ct);
throw new FallbackException(TextResource.FallbackMessage, update.Message, _bot);
}
var user = await _userClient.GetUserAsync(new GetUserRequest()
{
UserId = update.Message.From.Id,
});
if (user == null)
throw new FallbackException(TextResource.FallbackMessage, update.Message, _bot);
return user;
}
///
/// Get Eula Agreement from user
///
/// Telegram Update object
/// Cancellation Token
/// If update.Message is null
public async Task AskForEulaAgreement(Update update, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(update.Message?.From);
await _bot.SendMessage(
update.Message.From.Id,
TextResource.EULA,
replyMarkup: new[] { ButtonResource.EULAAgrement }, cancellationToken: ct);
}
///
/// Accept EULA for user
///
/// Telegram update object
/// Cancellation Token
/// If something in server logic went wrong
public async Task AcceptEula(Update update, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(update.Message?.From);
var result = await _userClient.AcceptEulaAsync(new()
{
EulaAccepted = true,
UserId = update.Message.From.Id,
});
if (!result.Success)
throw new FallbackException(TextResource.FallbackMessage, update.Message, _bot);
}
}