2021-02-02 06:31:24 +00:00
|
|
|
|
using BirthdayBot.Data;
|
|
|
|
|
|
2021-10-14 04:36:00 +00:00
|
|
|
|
namespace BirthdayBot.BackgroundServices;
|
2021-02-02 06:31:24 +00:00
|
|
|
|
|
2021-10-14 04:36:00 +00:00
|
|
|
|
/// <summary>
|
2021-11-22 21:40:08 +00:00
|
|
|
|
/// Proactively fills the user cache for guilds in which any birthday data already exists.
|
2021-10-14 04:36:00 +00:00
|
|
|
|
/// </summary>
|
2021-12-06 01:20:05 +00:00
|
|
|
|
class AutoUserDownload : BackgroundService {
|
|
|
|
|
public AutoUserDownload(ShardInstance instance) : base(instance) { }
|
2021-02-02 06:31:24 +00:00
|
|
|
|
|
2021-10-15 01:55:04 +00:00
|
|
|
|
public override async Task OnTick(int tickCount, CancellationToken token) {
|
2021-10-14 04:36:00 +00:00
|
|
|
|
foreach (var guild in ShardInstance.DiscordClient.Guilds) {
|
2021-10-15 01:55:04 +00:00
|
|
|
|
// Has the potential to disconnect while in the middle of processing.
|
|
|
|
|
if (ShardInstance.DiscordClient.ConnectionState != ConnectionState.Connected) return;
|
2021-10-14 04:36:00 +00:00
|
|
|
|
|
|
|
|
|
// Determine if there is action to be taken...
|
2021-11-22 21:40:08 +00:00
|
|
|
|
if (!guild.HasAllMembers && await GuildUserAnyAsync(guild.Id).ConfigureAwait(false)) {
|
|
|
|
|
await guild.DownloadUsersAsync().ConfigureAwait(false); // This is already on a separate thread; no need to Task.Run
|
|
|
|
|
await Task.Delay(200, CancellationToken.None).ConfigureAwait(false); // Must delay, or else it seems to hang...
|
2021-02-02 06:31:24 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
2021-10-14 04:36:00 +00:00
|
|
|
|
}
|
2021-02-02 06:31:24 +00:00
|
|
|
|
|
2021-10-14 04:36:00 +00:00
|
|
|
|
/// <summary>
|
|
|
|
|
/// Determines if the user database contains any entries corresponding to this guild.
|
|
|
|
|
/// </summary>
|
|
|
|
|
/// <returns>True if any entries exist.</returns>
|
|
|
|
|
private static async Task<bool> GuildUserAnyAsync(ulong guildId) {
|
|
|
|
|
using var db = await Database.OpenConnectionAsync().ConfigureAwait(false);
|
|
|
|
|
using var c = db.CreateCommand();
|
|
|
|
|
c.CommandText = $"select true from {GuildUserConfiguration.BackingTable} where guild_id = @Gid limit 1";
|
|
|
|
|
c.Parameters.Add("@Gid", NpgsqlTypes.NpgsqlDbType.Bigint).Value = (long)guildId;
|
|
|
|
|
await c.PrepareAsync(CancellationToken.None).ConfigureAwait(false);
|
|
|
|
|
using var r = await c.ExecuteReaderAsync(CancellationToken.None).ConfigureAwait(false);
|
|
|
|
|
return r.Read();
|
|
|
|
|
}
|
2021-02-02 06:31:24 +00:00
|
|
|
|
}
|