Add DM support

This commit is contained in:
Ske
2020-12-25 13:19:35 +01:00
parent 2e0c30eb5d
commit a2c8cbb560
9 changed files with 79 additions and 45 deletions

View File

@@ -55,16 +55,5 @@ namespace Myriad.Cache
foreach (var mention in evt.Mentions)
await cache.SaveUser(mention);
}
public static async ValueTask<User?> GetOrFetchUser(this IDiscordCache cache, DiscordApiClient rest, ulong userId)
{
if (cache.TryGetUser(userId, out var cacheUser))
return cacheUser;
var restUser = await rest.GetUser(userId);
if (restUser != null)
await cache.SaveUser(restUser);
return restUser;
}
}
}

View File

@@ -19,6 +19,7 @@ namespace Myriad.Cache
public bool TryGetGuild(ulong guildId, out Guild guild);
public bool TryGetChannel(ulong channelId, out Channel channel);
public bool TryGetDmChannel(ulong userId, out Channel channel);
public bool TryGetUser(ulong userId, out User user);
public bool TryGetRole(ulong roleId, out Role role);

View File

@@ -10,19 +10,12 @@ namespace Myriad.Cache
{
public class MemoryDiscordCache: IDiscordCache
{
private readonly ConcurrentDictionary<ulong, Channel> _channels;
private readonly ConcurrentDictionary<ulong, CachedGuild> _guilds;
private readonly ConcurrentDictionary<ulong, Role> _roles;
private readonly ConcurrentDictionary<ulong, User> _users;
public MemoryDiscordCache()
{
_guilds = new ConcurrentDictionary<ulong, CachedGuild>();
_channels = new ConcurrentDictionary<ulong, Channel>();
_users = new ConcurrentDictionary<ulong, User>();
_roles = new ConcurrentDictionary<ulong, Role>();
}
private readonly ConcurrentDictionary<ulong, Channel> _channels = new();
private readonly ConcurrentDictionary<ulong, ulong> _dmChannels = new();
private readonly ConcurrentDictionary<ulong, CachedGuild> _guilds = new();
private readonly ConcurrentDictionary<ulong, Role> _roles = new();
private readonly ConcurrentDictionary<ulong, User> _users = new();
public ValueTask SaveGuild(Guild guild)
{
SaveGuildRaw(guild);
@@ -35,14 +28,21 @@ namespace Myriad.Cache
return default;
}
public ValueTask SaveChannel(Channel channel)
public async ValueTask SaveChannel(Channel channel)
{
_channels[channel.Id] = channel;
if (channel.GuildId != null && _guilds.TryGetValue(channel.GuildId.Value, out var guild))
guild.Channels.TryAdd(channel.Id, true);
return default;
if (channel.Recipients != null)
{
foreach (var recipient in channel.Recipients)
{
_dmChannels[recipient.Id] = channel.Id;
await SaveUser(recipient);
}
}
}
public ValueTask SaveUser(User user)
@@ -125,6 +125,14 @@ namespace Myriad.Cache
public bool TryGetChannel(ulong channelId, out Channel channel) =>
_channels.TryGetValue(channelId, out channel!);
public bool TryGetDmChannel(ulong userId, out Channel channel)
{
channel = default!;
if (!_dmChannels.TryGetValue(userId, out var channelId))
return false;
return TryGetChannel(channelId, out channel);
}
public bool TryGetUser(ulong userId, out User user) =>
_users.TryGetValue(userId, out user!);