Files
telegram-bot/Core/Service/UserService.cs
T

90 lines
2.5 KiB
C#
Raw Normal View History

#nullable enable
using System;
2022-01-04 17:45:06 +02:00
using System.Collections.Generic;
using System.Linq;
2022-02-14 14:39:55 +02:00
using System.Threading.Tasks;
using BotFramework.Abstractions;
using Kruzya.TelegramBot.Core.Cache;
2022-01-04 17:45:06 +02:00
using Microsoft.Extensions.Configuration;
2022-02-14 14:39:55 +02:00
using Microsoft.Extensions.Logging;
using Telegram.Bot;
2022-01-04 17:45:06 +02:00
using Telegram.Bot.Types;
2023-07-29 15:14:52 +03:00
namespace Kruzya.TelegramBot.Core.Service;
public class UserService
2022-01-04 17:45:06 +02:00
{
2023-07-29 15:14:52 +03:00
private readonly List<long> _superUsers;
private readonly Dictionary<long, string> _statusMap;
private readonly ICacheStorage<long, User> _userCache;
private readonly ITelegramBotClient _bot;
private readonly ILogger<UserService> _logger;
2022-02-14 14:39:55 +02:00
2023-07-29 15:14:52 +03:00
public UserService(
IConfiguration configuration,
IBotInstance bot,
ICacheStorage<long, User> userCache,
ILogger<UserService> logger)
{
_superUsers = configuration.GetSection("SuperUsers")
.GetChildren()
.Select(q => Convert.ToInt64(q.Value))
.ToList();
2023-07-29 15:14:52 +03:00
_statusMap = configuration.GetSection("CustomMemberStatus")
.GetChildren()
.ToDictionary(x => Convert.ToInt64(x.Key), x => x.Value);
2022-02-14 14:39:55 +02:00
2023-07-29 15:14:52 +03:00
_userCache = userCache;
_bot = bot.BotClient;
_logger = logger;
}
2022-02-14 14:39:55 +02:00
2023-07-29 15:14:52 +03:00
public async Task<User> GetUser(long userId, long chatId, bool bypassCache = false)
{
if (bypassCache || !_userCache.TryGetValue(userId, out var user))
2022-02-14 14:39:55 +02:00
{
2023-07-29 15:14:52 +03:00
if (bypassCache)
2022-02-14 14:39:55 +02:00
{
2023-07-29 15:14:52 +03:00
_logger.LogDebug("Bypassing cache for {UserId}.", userId);
}
else
{
_logger.LogDebug("User {UserId} is not found in cache. Fetching from Telegram API.", userId);
2022-02-14 14:39:55 +02:00
}
2023-07-29 15:14:52 +03:00
user = await GetUserByChat(chatId, userId);
CacheUser(user);
2022-02-14 14:39:55 +02:00
}
2023-07-29 15:14:52 +03:00
return user;
}
private void CacheUser(User user)
{
// TODO: config entry for TTL
_userCache.SetValue(user.Id, user, Convert.ToInt32(TimeSpan.FromHours(1).TotalSeconds));
}
2022-02-14 14:39:55 +02:00
2023-07-29 15:14:52 +03:00
private async Task<User> GetUserByChat(long chatId, long userId)
{
return (await _bot.GetChatMemberAsync(chatId, userId)).User;
}
2022-01-04 17:45:06 +02:00
2023-07-29 15:14:52 +03:00
public bool IsUserSuper(User user)
{
return IsUserSuper(user.Id);
}
2022-01-04 17:45:06 +02:00
2023-07-29 15:14:52 +03:00
public bool IsUserSuper(long userId)
{
return _superUsers.Contains(userId);
}
2023-07-29 15:14:52 +03:00
public string? GetUserCustomStatus(long userId)
{
return _statusMap.ContainsKey(userId) ? _statusMap[userId] : null;
2022-01-04 17:45:06 +02:00
}
}