2021-02-02 06:31:24 +00:00
|
|
|
|
using BirthdayBot.Data;
|
2022-11-22 03:17:07 +00:00
|
|
|
|
using Microsoft.EntityFrameworkCore;
|
2021-02-02 06:31:24 +00:00
|
|
|
|
|
2021-10-14 04:36:00 +00:00
|
|
|
|
namespace BirthdayBot.BackgroundServices;
|
|
|
|
|
/// <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) {
|
2022-03-21 19:11:30 +00:00
|
|
|
|
// Take action if a guild's cache is incomplete...
|
2022-11-23 07:19:37 +00:00
|
|
|
|
var incompleteCaches = ShardInstance.DiscordClient.Guilds.Where(g => !g.HasAllMembers).Select(g => g.Id).ToHashSet();
|
2022-03-21 19:11:30 +00:00
|
|
|
|
// ...and if the guild contains any user data
|
2022-11-23 07:19:37 +00:00
|
|
|
|
IEnumerable<ulong> mustFetch;
|
2022-11-22 03:17:07 +00:00
|
|
|
|
try {
|
|
|
|
|
await DbConcurrentOperationsLock.WaitAsync(token);
|
|
|
|
|
using var db = new BotDatabaseContext();
|
|
|
|
|
mustFetch = db.UserEntries.AsNoTracking()
|
|
|
|
|
.Where(e => incompleteCaches.Contains(e.GuildId)).Select(e => e.GuildId).Distinct()
|
|
|
|
|
.ToList();
|
|
|
|
|
} finally {
|
|
|
|
|
try {
|
|
|
|
|
DbConcurrentOperationsLock.Release();
|
|
|
|
|
} catch (ObjectDisposedException) { }
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
var processed = 0;
|
2022-03-21 19:11:30 +00:00
|
|
|
|
foreach (var item in mustFetch) {
|
|
|
|
|
// May cause a disconnect in certain situations. Cancel all further attempts until the next pass if it happens.
|
2022-03-22 06:33:24 +00:00
|
|
|
|
if (ShardInstance.DiscordClient.ConnectionState != ConnectionState.Connected) break;
|
2021-10-14 04:36:00 +00:00
|
|
|
|
|
2022-03-21 19:11:30 +00:00
|
|
|
|
var guild = ShardInstance.DiscordClient.GetGuild((ulong)item);
|
|
|
|
|
if (guild == null) continue; // A guild disappeared...?
|
|
|
|
|
await guild.DownloadUsersAsync().ConfigureAwait(false); // We're already on a seperate thread, no need to use Task.Run
|
|
|
|
|
await Task.Delay(200, CancellationToken.None).ConfigureAwait(false); // Must delay, or else it seems to hang...
|
2022-03-22 06:33:24 +00:00
|
|
|
|
processed++;
|
2021-02-02 06:31:24 +00:00
|
|
|
|
}
|
2022-03-22 06:33:24 +00:00
|
|
|
|
|
2022-11-22 03:17:07 +00:00
|
|
|
|
if (processed > 25) Log($"Explicit user list request processed for {processed} guild(s).");
|
2021-10-14 04:36:00 +00:00
|
|
|
|
}
|
2021-02-02 06:31:24 +00:00
|
|
|
|
}
|