init
This commit is contained in:
commit
ded4f4db26
43 changed files with 2052 additions and 0 deletions
56
Catalogger.Backend/Cache/ChannelCacheService.cs
Normal file
56
Catalogger.Backend/Cache/ChannelCacheService.cs
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
using System.Collections.Concurrent;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using Remora.Discord.API.Abstractions.Objects;
|
||||
using Remora.Rest.Core;
|
||||
|
||||
namespace Catalogger.Backend.Cache;
|
||||
|
||||
public class ChannelCacheService
|
||||
{
|
||||
private readonly ConcurrentDictionary<Snowflake, IChannel> _channels = new();
|
||||
private readonly ConcurrentDictionary<Snowflake, HashSet<Snowflake>> _guildChannels = new();
|
||||
|
||||
public void AddChannel(IChannel channel, Snowflake? guildId = null)
|
||||
{
|
||||
_channels[channel.ID] = channel;
|
||||
if (guildId == null)
|
||||
{
|
||||
if (!channel.GuildID.TryGet(out var snowflake)) return;
|
||||
guildId = snowflake;
|
||||
}
|
||||
|
||||
// Add to set of guild channels
|
||||
_guildChannels.AddOrUpdate(guildId.Value,
|
||||
_ => [channel.ID],
|
||||
(_, l) =>
|
||||
{
|
||||
l.Add(channel.ID);
|
||||
return l;
|
||||
});
|
||||
}
|
||||
|
||||
public bool GetChannel(Snowflake id, [NotNullWhen(true)] out IChannel? channel) => _channels.TryGetValue(id, out channel);
|
||||
|
||||
public void RemoveChannel(Snowflake? guildId, Snowflake id, out IChannel? channel)
|
||||
{
|
||||
_channels.Remove(id, out channel);
|
||||
if (guildId == null) return;
|
||||
// Remove from set of guild channels
|
||||
_guildChannels.AddOrUpdate(guildId.Value, _ => [], (_, s) =>
|
||||
{
|
||||
s.Remove(id);
|
||||
return s;
|
||||
});
|
||||
}
|
||||
|
||||
/// <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)
|
||||
? []
|
||||
: channelIds.Select(id => _channels.GetValueOrDefault(id))
|
||||
.Where(c => c != null).Select(c => c!);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue