update services to not restart periodic tasks on discord reconnect

This commit is contained in:
Stanley Dimant
2024-09-19 09:34:12 +02:00
parent d8831ba6eb
commit 82f9fc3719

View File

@@ -27,7 +27,6 @@ internal class DiscordBot : IHostedService
private InteractionService _interactionModule; private InteractionService _interactionModule;
private CancellationTokenSource? _processReportQueueCts; private CancellationTokenSource? _processReportQueueCts;
private CancellationTokenSource? _updateStatusCts; private CancellationTokenSource? _updateStatusCts;
private CancellationTokenSource? _vanityUpdateCts;
public DiscordBot(DiscordBotServices botServices, IServiceProvider services, IConfigurationService<ServicesConfiguration> configuration, public DiscordBot(DiscordBotServices botServices, IServiceProvider services, IConfigurationService<ServicesConfiguration> configuration,
IHubContext<MareHub> mareHubContext, IHubContext<MareHub> mareHubContext,
@@ -72,7 +71,6 @@ internal class DiscordBot : IHostedService
}; };
await _botServices.Start().ConfigureAwait(false); await _botServices.Start().ConfigureAwait(false);
_ = UpdateStatusAsync();
} }
} }
@@ -85,7 +83,6 @@ internal class DiscordBot : IHostedService
await _botServices.Stop().ConfigureAwait(false); await _botServices.Stop().ConfigureAwait(false);
_processReportQueueCts?.Cancel(); _processReportQueueCts?.Cancel();
_updateStatusCts?.Cancel(); _updateStatusCts?.Cancel();
_vanityUpdateCts?.Cancel();
await _discordClient.LogoutAsync().ConfigureAwait(false); await _discordClient.LogoutAsync().ConfigureAwait(false);
await _discordClient.StopAsync().ConfigureAwait(false); await _discordClient.StopAsync().ConfigureAwait(false);
@@ -203,17 +200,21 @@ internal class DiscordBot : IHostedService
{ {
var guild = (await _discordClient.Rest.GetGuildsAsync().ConfigureAwait(false)).First(); var guild = (await _discordClient.Rest.GetGuildsAsync().ConfigureAwait(false)).First();
await _interactionModule.RegisterCommandsToGuildAsync(guild.Id, true).ConfigureAwait(false); await _interactionModule.RegisterCommandsToGuildAsync(guild.Id, true).ConfigureAwait(false);
_updateStatusCts?.Cancel();
_updateStatusCts?.Dispose();
_updateStatusCts = new();
_ = UpdateStatusAsync(_updateStatusCts.Token);
await CreateOrUpdateModal(guild).ConfigureAwait(false); await CreateOrUpdateModal(guild).ConfigureAwait(false);
_botServices.UpdateGuild(guild); _botServices.UpdateGuild(guild);
await _botServices.LogToChannel("Bot startup complete.").ConfigureAwait(false); await _botServices.LogToChannel("Bot startup complete.").ConfigureAwait(false);
_ = UpdateVanityRoles(guild); _ = UpdateVanityRoles(guild, _updateStatusCts.Token);
_ = RemoveUsersNotInVanityRole(); _ = RemoveUsersNotInVanityRole(_updateStatusCts.Token);
} }
private async Task UpdateVanityRoles(RestGuild guild) private async Task UpdateVanityRoles(RestGuild guild, CancellationToken token)
{ {
while (!_updateStatusCts.IsCancellationRequested) while (!token.IsCancellationRequested)
{ {
try try
{ {
@@ -231,7 +232,7 @@ internal class DiscordBot : IHostedService
} }
} }
await Task.Delay(TimeSpan.FromSeconds(30), _updateStatusCts.Token).ConfigureAwait(false); await Task.Delay(TimeSpan.FromSeconds(30), token).ConfigureAwait(false);
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -317,13 +318,9 @@ internal class DiscordBot : IHostedService
return Task.CompletedTask; return Task.CompletedTask;
} }
private async Task RemoveUsersNotInVanityRole() private async Task RemoveUsersNotInVanityRole(CancellationToken token)
{ {
_vanityUpdateCts?.Cancel(); var guild = (await _discordClient.Rest.GetGuildsAsync().ConfigureAwait(false)).First();
_vanityUpdateCts?.Dispose();
_vanityUpdateCts = new();
var token = _vanityUpdateCts.Token;
var guild = (await _discordClient.Rest.GetGuildsAsync()).First();
var appId = await _discordClient.GetApplicationInfoAsync().ConfigureAwait(false); var appId = await _discordClient.GetApplicationInfoAsync().ConfigureAwait(false);
while (!token.IsCancellationRequested) while (!token.IsCancellationRequested)
@@ -333,7 +330,7 @@ internal class DiscordBot : IHostedService
_logger.LogInformation($"Cleaning up Vanity UIDs"); _logger.LogInformation($"Cleaning up Vanity UIDs");
await _botServices.LogToChannel("Cleaning up Vanity UIDs").ConfigureAwait(false); await _botServices.LogToChannel("Cleaning up Vanity UIDs").ConfigureAwait(false);
_logger.LogInformation("Getting application commands from guild {guildName}", guild.Name); _logger.LogInformation("Getting application commands from guild {guildName}", guild.Name);
var restGuild = await _discordClient.Rest.GetGuildAsync(guild.Id); var restGuild = await _discordClient.Rest.GetGuildAsync(guild.Id).ConfigureAwait(false);
Dictionary<ulong, string> allowedRoleIds = _configurationService.GetValueOrDefault(nameof(ServicesConfiguration.VanityRoles), new Dictionary<ulong, string>()); Dictionary<ulong, string> allowedRoleIds = _configurationService.GetValueOrDefault(nameof(ServicesConfiguration.VanityRoles), new Dictionary<ulong, string>());
_logger.LogInformation($"Allowed role ids: {string.Join(", ", allowedRoleIds)}"); _logger.LogInformation($"Allowed role ids: {string.Join(", ", allowedRoleIds)}");
@@ -341,8 +338,8 @@ internal class DiscordBot : IHostedService
if (allowedRoleIds.Any()) if (allowedRoleIds.Any())
{ {
await using var scope = _services.CreateAsyncScope(); await using var scope = _services.CreateAsyncScope();
await using (var db = scope.ServiceProvider.GetRequiredService<MareDbContext>()) await using var db = scope.ServiceProvider.GetRequiredService<MareDbContext>();
{
var aliasedUsers = await db.LodeStoneAuth.Include("User") var aliasedUsers = await db.LodeStoneAuth.Include("User")
.Where(c => c.User != null && !string.IsNullOrEmpty(c.User.Alias)).ToListAsync().ConfigureAwait(false); .Where(c => c.User != null && !string.IsNullOrEmpty(c.User.Alias)).ToListAsync().ConfigureAwait(false);
var aliasedGroups = await db.Groups.Include(u => u.Owner) var aliasedGroups = await db.Groups.Include(u => u.Owner)
@@ -367,10 +364,10 @@ internal class DiscordBot : IHostedService
db.Update(secondaryUser.User); db.Update(secondaryUser.User);
} }
db.Update(lodestoneAuth.User); db.Update(lodestoneAuth.User);
await db.SaveChangesAsync(token).ConfigureAwait(false);
} }
await db.SaveChangesAsync().ConfigureAwait(false); await Task.Delay(1000, token).ConfigureAwait(false);
await Task.Delay(1000);
} }
foreach (var group in aliasedGroups) foreach (var group in aliasedGroups)
@@ -391,11 +388,10 @@ internal class DiscordBot : IHostedService
_logger.LogInformation($"User {lodestoneUser.User.UID} not in allowed roles, deleting group alias"); _logger.LogInformation($"User {lodestoneUser.User.UID} not in allowed roles, deleting group alias");
group.Alias = null; group.Alias = null;
db.Update(group); db.Update(group);
await db.SaveChangesAsync(token).ConfigureAwait(false);
} }
await db.SaveChangesAsync().ConfigureAwait(false); await Task.Delay(1000, token).ConfigureAwait(false);
await Task.Delay(1000);
}
} }
} }
else else
@@ -409,17 +405,16 @@ internal class DiscordBot : IHostedService
} }
_logger.LogInformation("Vanity UID cleanup complete"); _logger.LogInformation("Vanity UID cleanup complete");
await Task.Delay(TimeSpan.FromHours(12), _vanityUpdateCts.Token).ConfigureAwait(false); await Task.Delay(TimeSpan.FromHours(12), token).ConfigureAwait(false);
} }
} }
private async Task UpdateStatusAsync() private async Task UpdateStatusAsync(CancellationToken token)
{ {
_updateStatusCts = new(); while (!token.IsCancellationRequested)
while (!_updateStatusCts.IsCancellationRequested)
{ {
var endPoint = _connectionMultiplexer.GetEndPoints().First(); var endPoint = _connectionMultiplexer.GetEndPoints().First();
var onlineUsers = await _connectionMultiplexer.GetServer(endPoint).KeysAsync(pattern: "UID:*").CountAsync(); var onlineUsers = await _connectionMultiplexer.GetServer(endPoint).KeysAsync(pattern: "UID:*").CountAsync().ConfigureAwait(false);
_logger.LogInformation("Users online: " + onlineUsers); _logger.LogInformation("Users online: " + onlineUsers);
await _discordClient.SetActivityAsync(new Game("Mare for " + onlineUsers + " Users")).ConfigureAwait(false); await _discordClient.SetActivityAsync(new Game("Mare for " + onlineUsers + " Users")).ConfigureAwait(false);