// 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 . 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? _news; private readonly SemaphoreSlim _newsSemaphore = new(1); public async Task> 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 GetUserAsync(string id) => await redisService.GetAsync(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?> GetGuildsAsync(string userId) => await redisService.GetAsync>(GuildsKey(userId)); public async Task SetGuildsAsync(string userId, List guilds) => await redisService.SetAsync(GuildsKey(userId), guilds, expiry: TimeSpan.FromHours(1)); }