PluralKit/Myriad/Extensions/CacheExtensions.cs

69 lines
2.4 KiB
C#
Raw Normal View History

using Myriad.Cache;
2020-12-25 13:19:35 +01:00
using Myriad.Rest;
using Myriad.Types;
namespace Myriad.Extensions;
public static class CacheExtensions
{
public static async Task<Guild> GetGuild(this IDiscordCache cache, ulong guildId)
{
if (!(await cache.TryGetGuild(guildId) is Guild guild))
throw new NotFoundInCacheException(guildId, "guild");
return guild;
}
2021-08-27 11:03:47 -04:00
2024-09-14 12:19:47 +09:00
public static async Task<Channel> GetChannel(this IDiscordCache cache, ulong guildId, ulong channelId)
{
2024-09-14 12:19:47 +09:00
if (!(await cache.TryGetChannel(guildId, channelId) is Channel channel))
throw new NotFoundInCacheException(channelId, "channel");
return channel;
}
public static async ValueTask<User?> GetOrFetchUser(this IDiscordCache cache, DiscordApiClient rest,
ulong userId)
{
if (await cache.TryGetUser(userId) is User cacheUser)
return cacheUser;
2020-12-25 13:19:35 +01:00
var restUser = await rest.GetUser(userId);
if (restUser != null)
await cache.SaveUser(restUser);
return restUser;
}
2021-08-27 11:03:47 -04:00
public static async ValueTask<Channel?> GetOrFetchChannel(this IDiscordCache cache, DiscordApiClient rest,
2024-09-14 12:19:47 +09:00
ulong guildId, ulong channelId)
{
2024-09-14 12:19:47 +09:00
if (await cache.TryGetChannel(guildId, channelId) is { } cacheChannel)
return cacheChannel;
2020-12-25 13:58:45 +01:00
var restChannel = await rest.GetChannel(channelId);
if (restChannel != null)
await cache.SaveChannel(restChannel);
return restChannel;
}
2020-12-25 13:58:45 +01:00
2024-09-14 12:19:47 +09:00
public static async Task<Channel> GetRootChannel(this IDiscordCache cache, ulong guildId, ulong channelOrThread)
{
2024-09-14 12:19:47 +09:00
var channel = await cache.GetChannel(guildId, channelOrThread);
if (!channel.IsThread())
return channel;
2021-08-27 11:03:47 -04:00
var parent = await cache.TryGetChannel(guildId, channel.ParentId!.Value);
if (parent == null) throw new Exception($"failed to find parent channel for thread {channelOrThread} in cache");
return parent;
}
}
public class NotFoundInCacheException: Exception
{
public ulong EntityId { get; init; }
public string EntityType { get; init; }
public NotFoundInCacheException(ulong id, string type) : base("expected entity in discord cache but was not found")
{
EntityId = id;
EntityType = type;
}
}