Catalogger.NET/Catalogger.Backend/Api/ApiCache.cs

72 lines
2.5 KiB
C#

// Copyright (C) 2021-present sam (starshines.gay)
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
using Catalogger.Backend.Database.Redis;
using Remora.Discord.API;
using Remora.Discord.API.Abstractions.Objects;
using Remora.Discord.API.Abstractions.Rest;
namespace Catalogger.Backend.Api;
public class ApiCache(RedisService redisService, IDiscordRestChannelAPI channelApi, Config config)
{
private List<IMessage>? _news;
private readonly SemaphoreSlim _newsSemaphore = new(1);
public async Task<List<IMessage>> GetNewsAsync()
{
await _newsSemaphore.WaitAsync();
try
{
if (_news != null)
return _news;
if (config.Web.NewsChannel == null)
return [];
var res = await channelApi.GetChannelMessagesAsync(
DiscordSnowflake.New(config.Web.NewsChannel.Value),
limit: 5
);
if (res.IsSuccess)
return _news = res.Entity.ToList();
return [];
}
finally
{
_newsSemaphore.Release();
}
}
private static string UserKey(string id) => $"api-user:{id}";
private static string GuildsKey(string userId) => $"api-user-guilds:{userId}";
public async Task<User?> GetUserAsync(string id) =>
await redisService.GetAsync<User>(UserKey(id));
public async Task SetUserAsync(User user) =>
await redisService.SetAsync(UserKey(user.Id), user, expiry: TimeSpan.FromHours(1));
public async Task ExpireUserAsync(string id) =>
await redisService.GetDatabase().KeyDeleteAsync([UserKey(id), GuildsKey(id)]);
public async Task<List<Guild>?> GetGuildsAsync(string userId) =>
await redisService.GetAsync<List<Guild>>(GuildsKey(userId));
public async Task SetGuildsAsync(string userId, List<Guild> guilds) =>
await redisService.SetAsync(GuildsKey(userId), guilds, expiry: TimeSpan.FromHours(1));
}