Catalogger.NET/Catalogger.Backend/Cache/InMemoryCache/ChannelCache.cs

85 lines
2.7 KiB
C#
Raw Normal View History

// 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/>.
2024-08-13 13:08:50 +02:00
using System.Collections.Concurrent;
using System.Diagnostics.CodeAnalysis;
using Remora.Discord.API.Abstractions.Objects;
using Remora.Rest.Core;
namespace Catalogger.Backend.Cache.InMemoryCache;
2024-08-13 13:08:50 +02:00
public class ChannelCache
2024-08-13 13:08:50 +02:00
{
private readonly ConcurrentDictionary<Snowflake, IChannel> _channels = new();
private readonly ConcurrentDictionary<Snowflake, HashSet<Snowflake>> _guildChannels = new();
2024-08-13 16:48:54 +02:00
public int Size => _channels.Count;
public void Set(IChannel channel, Snowflake? guildId = null)
2024-08-13 13:08:50 +02:00
{
_channels[channel.ID] = channel;
if (guildId == null)
{
2024-10-09 17:35:11 +02:00
if (!channel.GuildID.TryGet(out var snowflake))
return;
2024-08-13 13:08:50 +02:00
guildId = snowflake;
}
// Add to set of guild channels
2024-10-09 17:35:11 +02:00
_guildChannels.AddOrUpdate(
guildId.Value,
2024-08-13 13:08:50 +02:00
_ => [channel.ID],
(_, l) =>
{
l.Add(channel.ID);
return l;
2024-10-09 17:35:11 +02:00
}
);
2024-08-13 13:08:50 +02:00
}
2024-08-16 17:04:24 +02:00
public bool TryGet(Snowflake id, [NotNullWhen(true)] out IChannel? channel) =>
_channels.TryGetValue(id, out channel);
2024-08-13 13:08:50 +02:00
2024-08-13 16:48:54 +02:00
public void Remove(Snowflake? guildId, Snowflake id, out IChannel? channel)
2024-08-13 13:08:50 +02:00
{
_channels.Remove(id, out channel);
2024-10-09 17:35:11 +02:00
if (guildId == null)
return;
2024-08-13 13:08:50 +02:00
// Remove from set of guild channels
2024-10-09 17:35:11 +02:00
_guildChannels.AddOrUpdate(
guildId.Value,
_ => [],
(_, s) =>
{
s.Remove(id);
return s;
}
);
2024-08-13 13:08:50 +02:00
}
/// <summary>
/// Gets all of a guild's cached channels.
/// </summary>
/// <param name="guildId">The guild to get the channels of</param>
/// <returns>A list of cached channels</returns>
public IEnumerable<IChannel> GuildChannels(Snowflake guildId) =>
!_guildChannels.TryGetValue(guildId, out var channelIds)
? []
2024-10-09 17:35:11 +02:00
: channelIds
.Select(id => _channels.GetValueOrDefault(id))
.Where(c => c != null)
.Select(c => c!);
}