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

88 lines
2.7 KiB
C#
Raw Permalink 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/>.
using System.Collections.Concurrent;
using System.Diagnostics.CodeAnalysis;
using Remora.Discord.API.Abstractions.Objects;
using Remora.Rest.Core;
namespace Catalogger.Backend.Cache.InMemoryCache;
public class RoleCache
{
private readonly ConcurrentDictionary<Snowflake, IRole> _roles = new();
private readonly ConcurrentDictionary<Snowflake, HashSet<Snowflake>> _guildRoles = new();
public int Size => _roles.Count;
public void Set(IRole role, Snowflake guildId)
{
_roles[role.ID] = role;
// Add to set of guild channels
2024-10-09 17:35:11 +02:00
_guildRoles.AddOrUpdate(
guildId,
_ => [role.ID],
(_, l) =>
{
l.Add(role.ID);
return l;
2024-10-09 17:35:11 +02:00
}
);
}
public bool TryGet(Snowflake id, [NotNullWhen(true)] out IRole? role) =>
_roles.TryGetValue(id, out role);
public void Remove(Snowflake guildId, Snowflake id, out IRole? role)
{
_roles.Remove(id, out role);
// Remove from set of guild channels
2024-10-09 17:35:11 +02:00
_guildRoles.AddOrUpdate(
guildId,
_ => [],
(_, s) =>
{
s.Remove(id);
return s;
}
);
}
public void RemoveGuild(Snowflake guildId)
{
2024-10-09 17:35:11 +02:00
if (!_guildRoles.TryGetValue(guildId, out var roleIds))
return;
foreach (var id in roleIds)
{
_roles.Remove(id, out _);
}
_guildRoles.Remove(guildId, out _);
}
/// <summary>
/// Gets all of a guild's cached roles.
/// </summary>
/// <param name="guildId">The guild to get the roles of</param>
/// <returns>A list of cached roles</returns>
public IEnumerable<IRole> GuildRoles(Snowflake guildId) =>
!_guildRoles.TryGetValue(guildId, out var roleIds)
? []
2024-10-09 17:35:11 +02:00
: roleIds
.Select(id => _roles.GetValueOrDefault(id))
.Where(r => r != null)
.Select(r => r!);
}