70 lines
2.2 KiB
C#
70 lines
2.2 KiB
C#
using StackExchange.Redis;
|
|
|
|
|
|
namespace nsszcontactbot;
|
|
public class FavoriteContactsManager
|
|
{
|
|
private readonly IDatabase _redisDb;
|
|
|
|
public FavoriteContactsManager(ConnectionMultiplexer redis)
|
|
{
|
|
_redisDb = redis.GetDatabase();
|
|
}
|
|
|
|
private static string GetUserKey(long userId) => $"user:favorites:{userId}";
|
|
private static string GetContactKey(string contactId) => $"contact:favorites:{contactId}";
|
|
|
|
/// <summary>
|
|
/// Добавить контакт в избранное.
|
|
/// </summary>
|
|
public async Task AddFavoriteAsync(long userId, string contactId)
|
|
{
|
|
string userKey = GetUserKey(userId);
|
|
string contactKey = GetContactKey(contactId);
|
|
await Task.WhenAll(
|
|
_redisDb.SetAddAsync(userKey, contactId),
|
|
_redisDb.SetAddAsync(contactKey, userId.ToString())
|
|
);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Удалить контакт из избранного.
|
|
/// </summary>
|
|
public async Task RemoveFavoriteAsync(long userId, string contactId)
|
|
{
|
|
string userKey = GetUserKey(userId);
|
|
string contactKey = GetContactKey(contactId);
|
|
await Task.WhenAll(
|
|
_redisDb.SetRemoveAsync(userKey, contactId),
|
|
_redisDb.SetRemoveAsync(contactKey, userId.ToString())
|
|
);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Проверить, является ли контакт избранным.
|
|
/// </summary>
|
|
public async Task<bool> IsFavoriteAsync(long userId, string contactId)
|
|
{
|
|
string key = GetUserKey(userId);
|
|
return await _redisDb.SetContainsAsync(key, contactId);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Получить список всех избранных контактов пользователя.
|
|
/// </summary>
|
|
public async Task<List<string>> GetAllFavoritesAsync(long userId)
|
|
{
|
|
string key = GetUserKey(userId);
|
|
var members = await _redisDb.SetMembersAsync(key);
|
|
return [.. members.Select(m => m.ToString())];
|
|
}
|
|
|
|
public async Task<List<long>> GetUsersWithFavoriteAsync(string contactId)
|
|
{
|
|
string contactKey = GetContactKey(contactId);
|
|
var members = await _redisDb.SetMembersAsync(contactKey);
|
|
return [.. members.Select(m => long.Parse(m.ToString()))];
|
|
}
|
|
|
|
}
|