JOBot/JOBot.TClient/Services/PrepareUserService.cs

89 lines
3.1 KiB
C#

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;
/// <summary>
/// Get or register user on system
/// </summary>
/// <param name="update">Telegram Update object</param>
/// <param name="ct">Cancellation Token</param>
/// <returns>RPC User Response</returns>
/// <exception cref="FallbackException">If something in server logic went wrong</exception>
/// <exception cref="ArgumentNullException">If update.Message is null</exception>
public async Task<GetUserResponse> 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;
}
/// <summary>
/// Get Eula Agreement from user
/// </summary>
/// <param name="update">Telegram Update object</param>
/// <param name="ct">Cancellation Token</param>
/// <exception cref="ArgumentNullException">If update.Message is null</exception>
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);
}
/// <summary>
/// Accept EULA for user
/// </summary>
/// <param name="update">Telegram update object</param>
/// <param name="ct">Cancellation Token</param>
/// <exception cref="FallbackException">If something in server logic went wrong</exception>
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);
}
}