From 8f62a46016f0b772b3676e546cb74cdef0f17142 Mon Sep 17 00:00:00 2001 From: Kwoth Date: Sat, 15 Jul 2023 13:39:46 +0000 Subject: [PATCH] Split dangerous commands into cleanup commands for each module they belong to --- src/Nadeko.Bot.Common/CleanupModuleBase.cs | 25 +++ .../Extensions/DbExtensions.cs | 5 +- src/Nadeko.Bot.Common/NadekoModule.cs | 10 +- .../{Common => _Common}/AddRemove.cs | 0 .../{Common => _Common}/CmdStrings.cs | 0 .../{Common => _Common}/CommandData.cs | 0 .../{Common => _Common}/DownloadTracker.cs | 0 .../{Common => _Common}/Helpers.cs | 0 .../{Common => _Common}/ImageUrls.cs | 0 .../JsonConverters/CultureInfoConverter.cs | 0 .../JsonConverters/Rgba32Converter.cs | 0 .../{Common => _Common}/LbOpts.cs | 0 .../{Common => _Common}/Linq2DbExpressions.cs | 0 .../{Common => _Common}/LoginErrorHandler.cs | 0 .../{Common => _Common}/OldCreds.cs | 0 .../{Common => _Common}/OptionsParser.cs | 0 .../{Common => _Common}/OsuMapData.cs | 0 .../{Common => _Common}/OsuUserBets.cs | 0 .../Pokemon/PokemonNameId.cs | 0 .../Pokemon/SearchPokemon.cs | 0 .../Pokemon/SearchPokemonAbility.cs | 0 ...RequireObjectPropertiesContractResolver.cs | 0 .../TriviaQuestionModel.cs | 0 .../TypeReaders/EmoteTypeReader.cs | 0 .../TypeReaders/GuildTypeReader.cs | 0 .../TypeReaders/GuildUserTypeReader.cs | 0 .../TypeReaders/KwumTypeReader.cs | 0 .../TypeReaders/Models/PermissionAction.cs | 0 .../TypeReaders/Models/StoopidTime.cs | 0 .../TypeReaders/ModuleTypeReader.cs | 0 .../TypeReaders/PermissionActionTypeReader.cs | 0 .../TypeReaders/Rgba32TypeReader.cs | 0 .../TypeReaders/StoopidTimeTypeReader.cs | 0 .../Extensions/GuildConfigExtensions.cs | 6 +- src/Nadeko.Bot.Db/Models/AntiProtection.cs | 67 -------- src/Nadeko.Bot.Db/Models/PunishmentAction.cs | 15 ++ .../Models/anti/AntiAltSetting.cs | 11 ++ .../Models/anti/AntiRaidSetting.cs | 20 +++ .../Models/anti/AntiSpamIgnore.cs | 12 ++ .../Models/anti/AntiSpamSetting.cs | 13 ++ .../AutoAssignRoleService.cs | 2 +- .../DangerousCommands/DangerousCommands.cs | 50 ------ .../DangerousCommandsService.cs | 74 +------- .../ImageOnlyChannelService.cs | 16 +- .../Nadeko.Bot.Modules.Administration.csproj | 1 + .../PlayingRotate/PlayingRotateService.cs | 6 +- .../Self/SelfService.cs | 18 +- .../SelfAssignedRolesService.cs | 14 +- .../ServerLog/ServerLogCommandService.cs | 2 +- .../UserPunish/UserPunishService.cs | 162 +++++++++--------- .../NadekoExpressionsService.cs | 28 +-- .../Gambling/Bank/BankService.cs | 8 +- .../Gambling/CleanupCommands.cs | 39 +++++ .../Gambling/Gambling.cs | 10 +- .../Gambling/GamblingService.cs | 15 +- .../Gambling/PlantPick/PlantPickService.cs | 6 +- .../Gambling/Shop/ShopService.cs | 2 +- .../Gambling/Waifus/WaifuService.cs | 48 +++--- .../Gambling/Waifus/db}/Waifu.cs | 14 -- .../Gambling/Waifus/db}/WaifuExtensions.cs | 12 -- .../Gambling/Waifus/db/WaifuInfoStats.cs | 14 ++ .../Gambling/Waifus/db}/WaifuItem.cs | 0 .../Gambling/Waifus/db/WaifuLbResult.cs | 16 ++ .../Gambling/Waifus/db}/WaifuUpdate.cs | 6 - .../Gambling/Waifus/db/WaifuUpdateType.cs | 8 + .../_Common/IGamblingCleanupService.cs | 67 ++++++++ .../BaseShmartInputAmountReader.cs | 3 +- .../Games/ChatterBot/CleverBotCommands.cs | 5 +- .../Nadeko.Bot.Modules.Gambling.csproj | 1 + .../CleanupCommands.cs | 24 +++ .../Nadeko.Bot.Modules.Music.csproj | 1 + .../PlaylistCommands.cs | 12 +- .../Services/MusicService.cs | 6 +- .../db}/MusicPlayerSettingsExtensions.cs | 0 .../_Common/db}/MusicPlaylist.cs | 0 .../_Common/db}/MusicPlaylistExtensions.cs | 0 .../_Common/db}/MusicSettings.cs | 0 .../PermissionsService.cs | 2 +- .../Feeds/FeedsService.cs | 51 +++--- .../StreamNotificationService.cs | 2 +- .../Translate/TranslateService.cs | 12 +- .../Quote/QuoteCommands.cs | 22 +-- .../Remind/RemindCommands.cs | 12 +- .../Remind/RemindService.cs | 6 +- .../Repeater/RepeaterService.cs | 18 +- src/Nadeko.Bot.Modules.Xp/CleanupCommands.cs | 19 ++ src/Nadeko.Bot.Modules.Xp/Club/ClubService.cs | 32 ++-- src/Nadeko.Bot.Modules.Xp/XpService.cs | 24 +-- .../_Common/IXpCleanupService.cs | 6 + .../_Common/XpCleanupService.cs | 32 ++++ src/NadekoBot/Bot.cs | 5 +- 91 files changed, 616 insertions(+), 501 deletions(-) create mode 100644 src/Nadeko.Bot.Common/CleanupModuleBase.cs rename src/Nadeko.Bot.Common/{Common => _Common}/AddRemove.cs (100%) rename src/Nadeko.Bot.Common/{Common => _Common}/CmdStrings.cs (100%) rename src/Nadeko.Bot.Common/{Common => _Common}/CommandData.cs (100%) rename src/Nadeko.Bot.Common/{Common => _Common}/DownloadTracker.cs (100%) rename src/Nadeko.Bot.Common/{Common => _Common}/Helpers.cs (100%) rename src/Nadeko.Bot.Common/{Common => _Common}/ImageUrls.cs (100%) rename src/Nadeko.Bot.Common/{Common => _Common}/JsonConverters/CultureInfoConverter.cs (100%) rename src/Nadeko.Bot.Common/{Common => _Common}/JsonConverters/Rgba32Converter.cs (100%) rename src/Nadeko.Bot.Common/{Common => _Common}/LbOpts.cs (100%) rename src/Nadeko.Bot.Common/{Common => _Common}/Linq2DbExpressions.cs (100%) rename src/Nadeko.Bot.Common/{Common => _Common}/LoginErrorHandler.cs (100%) rename src/Nadeko.Bot.Common/{Common => _Common}/OldCreds.cs (100%) rename src/Nadeko.Bot.Common/{Common => _Common}/OptionsParser.cs (100%) rename src/Nadeko.Bot.Common/{Common => _Common}/OsuMapData.cs (100%) rename src/Nadeko.Bot.Common/{Common => _Common}/OsuUserBets.cs (100%) rename src/Nadeko.Bot.Common/{Common => _Common}/Pokemon/PokemonNameId.cs (100%) rename src/Nadeko.Bot.Common/{Common => _Common}/Pokemon/SearchPokemon.cs (100%) rename src/Nadeko.Bot.Common/{Common => _Common}/Pokemon/SearchPokemonAbility.cs (100%) rename src/Nadeko.Bot.Common/{Common => _Common}/RequireObjectPropertiesContractResolver.cs (100%) rename src/Nadeko.Bot.Common/{Common => _Common}/TriviaQuestionModel.cs (100%) rename src/Nadeko.Bot.Common/{Common => _Common}/TypeReaders/EmoteTypeReader.cs (100%) rename src/Nadeko.Bot.Common/{Common => _Common}/TypeReaders/GuildTypeReader.cs (100%) rename src/Nadeko.Bot.Common/{Common => _Common}/TypeReaders/GuildUserTypeReader.cs (100%) rename src/Nadeko.Bot.Common/{Common => _Common}/TypeReaders/KwumTypeReader.cs (100%) rename src/Nadeko.Bot.Common/{Common => _Common}/TypeReaders/Models/PermissionAction.cs (100%) rename src/Nadeko.Bot.Common/{Common => _Common}/TypeReaders/Models/StoopidTime.cs (100%) rename src/Nadeko.Bot.Common/{Common => _Common}/TypeReaders/ModuleTypeReader.cs (100%) rename src/Nadeko.Bot.Common/{Common => _Common}/TypeReaders/PermissionActionTypeReader.cs (100%) rename src/Nadeko.Bot.Common/{Common => _Common}/TypeReaders/Rgba32TypeReader.cs (100%) rename src/Nadeko.Bot.Common/{Common => _Common}/TypeReaders/StoopidTimeTypeReader.cs (100%) delete mode 100644 src/Nadeko.Bot.Db/Models/AntiProtection.cs create mode 100644 src/Nadeko.Bot.Db/Models/PunishmentAction.cs create mode 100644 src/Nadeko.Bot.Db/Models/anti/AntiAltSetting.cs create mode 100644 src/Nadeko.Bot.Db/Models/anti/AntiRaidSetting.cs create mode 100644 src/Nadeko.Bot.Db/Models/anti/AntiSpamIgnore.cs create mode 100644 src/Nadeko.Bot.Db/Models/anti/AntiSpamSetting.cs create mode 100644 src/Nadeko.Bot.Modules.Gambling/Gambling/CleanupCommands.cs rename src/{Nadeko.Bot.Db/Models => Nadeko.Bot.Modules.Gambling/Gambling/Waifus/db}/Waifu.cs (59%) rename src/{Nadeko.Bot.Db/Extensions => Nadeko.Bot.Modules.Gambling/Gambling/Waifus/db}/WaifuExtensions.cs (94%) create mode 100644 src/Nadeko.Bot.Modules.Gambling/Gambling/Waifus/db/WaifuInfoStats.cs rename src/{Nadeko.Bot.Db/Models => Nadeko.Bot.Modules.Gambling/Gambling/Waifus/db}/WaifuItem.cs (100%) create mode 100644 src/Nadeko.Bot.Modules.Gambling/Gambling/Waifus/db/WaifuLbResult.cs rename src/{Nadeko.Bot.Db/Models => Nadeko.Bot.Modules.Gambling/Gambling/Waifus/db}/WaifuUpdate.cs (86%) create mode 100644 src/Nadeko.Bot.Modules.Gambling/Gambling/Waifus/db/WaifuUpdateType.cs create mode 100644 src/Nadeko.Bot.Modules.Gambling/Gambling/_Common/IGamblingCleanupService.cs create mode 100644 src/Nadeko.Bot.Modules.Music/CleanupCommands.cs rename src/{Nadeko.Bot.Db/Extensions => Nadeko.Bot.Modules.Music/_Common/db}/MusicPlayerSettingsExtensions.cs (100%) rename src/{Nadeko.Bot.Db/Models => Nadeko.Bot.Modules.Music/_Common/db}/MusicPlaylist.cs (100%) rename src/{Nadeko.Bot.Db/Extensions => Nadeko.Bot.Modules.Music/_Common/db}/MusicPlaylistExtensions.cs (100%) rename src/{Nadeko.Bot.Db/Models => Nadeko.Bot.Modules.Music/_Common/db}/MusicSettings.cs (100%) create mode 100644 src/Nadeko.Bot.Modules.Xp/CleanupCommands.cs create mode 100644 src/Nadeko.Bot.Modules.Xp/_Common/IXpCleanupService.cs create mode 100644 src/Nadeko.Bot.Modules.Xp/_Common/XpCleanupService.cs diff --git a/src/Nadeko.Bot.Common/CleanupModuleBase.cs b/src/Nadeko.Bot.Common/CleanupModuleBase.cs new file mode 100644 index 000000000..625020d05 --- /dev/null +++ b/src/Nadeko.Bot.Common/CleanupModuleBase.cs @@ -0,0 +1,25 @@ +#nullable disable +namespace NadekoBot.Common; + +public abstract class CleanupModuleBase : NadekoModule +{ + protected async Task ConfirmActionInternalAsync(string name, Func action) + { + try + { + var embed = _eb.Create() + .WithTitle(GetText(strs.sql_confirm_exec)) + .WithDescription(name); + + if (!await PromptUserConfirmAsync(embed)) + return; + + await action(); + await ctx.OkAsync(); + } + catch (Exception ex) + { + await SendErrorAsync(ex.ToString()); + } + } +} \ No newline at end of file diff --git a/src/Nadeko.Bot.Common/Extensions/DbExtensions.cs b/src/Nadeko.Bot.Common/Extensions/DbExtensions.cs index 08fe9426a..fd2677298 100644 --- a/src/Nadeko.Bot.Common/Extensions/DbExtensions.cs +++ b/src/Nadeko.Bot.Common/Extensions/DbExtensions.cs @@ -1,4 +1,5 @@ -using NadekoBot.Db; +using Microsoft.EntityFrameworkCore; +using NadekoBot.Db; using NadekoBot.Db.Models; // todo fix these namespaces. It should only be Nadeko.Bot.Db using NadekoBot.Services.Database; @@ -7,6 +8,6 @@ namespace NadekoBot.Extensions; public static class DbExtensions { - public static DiscordUser GetOrCreateUser(this NadekoBaseContext ctx, IUser original, Func, IQueryable>? includes = null) + public static DiscordUser GetOrCreateUser(this DbContext ctx, IUser original, Func, IQueryable>? includes = null) => ctx.GetOrCreateUser(original.Id, original.Username, original.Discriminator, original.AvatarId, includes); } \ No newline at end of file diff --git a/src/Nadeko.Bot.Common/NadekoModule.cs b/src/Nadeko.Bot.Common/NadekoModule.cs index 33c492fff..f5811d484 100644 --- a/src/Nadeko.Bot.Common/NadekoModule.cs +++ b/src/Nadeko.Bot.Common/NadekoModule.cs @@ -30,15 +30,15 @@ public abstract class NadekoModule : ModuleBase protected string GetText(in LocStr data) => Strings.GetText(data, Culture); - + public Task SendErrorAsync( string title, string error, string url = null, - string footer = null, + string footer = null, NadekoInteraction inter = null) => ctx.Channel.SendErrorAsync(_eb, title, error, url, footer); - + public Task SendConfirmAsync( string title, string text, @@ -49,12 +49,14 @@ public abstract class NadekoModule : ModuleBase // public Task SendErrorAsync(string text, NadekoInteraction inter = null) => ctx.Channel.SendAsync(_eb, text, MsgType.Error, inter); + public Task SendConfirmAsync(string text, NadekoInteraction inter = null) => ctx.Channel.SendAsync(_eb, text, MsgType.Ok, inter); + public Task SendPendingAsync(string text, NadekoInteraction inter = null) => ctx.Channel.SendAsync(_eb, text, MsgType.Pending, inter); - + // localized normal public Task ErrorLocalizedAsync(LocStr str, NadekoInteraction inter = null) => SendErrorAsync(GetText(str), inter); diff --git a/src/Nadeko.Bot.Common/Common/AddRemove.cs b/src/Nadeko.Bot.Common/_Common/AddRemove.cs similarity index 100% rename from src/Nadeko.Bot.Common/Common/AddRemove.cs rename to src/Nadeko.Bot.Common/_Common/AddRemove.cs diff --git a/src/Nadeko.Bot.Common/Common/CmdStrings.cs b/src/Nadeko.Bot.Common/_Common/CmdStrings.cs similarity index 100% rename from src/Nadeko.Bot.Common/Common/CmdStrings.cs rename to src/Nadeko.Bot.Common/_Common/CmdStrings.cs diff --git a/src/Nadeko.Bot.Common/Common/CommandData.cs b/src/Nadeko.Bot.Common/_Common/CommandData.cs similarity index 100% rename from src/Nadeko.Bot.Common/Common/CommandData.cs rename to src/Nadeko.Bot.Common/_Common/CommandData.cs diff --git a/src/Nadeko.Bot.Common/Common/DownloadTracker.cs b/src/Nadeko.Bot.Common/_Common/DownloadTracker.cs similarity index 100% rename from src/Nadeko.Bot.Common/Common/DownloadTracker.cs rename to src/Nadeko.Bot.Common/_Common/DownloadTracker.cs diff --git a/src/Nadeko.Bot.Common/Common/Helpers.cs b/src/Nadeko.Bot.Common/_Common/Helpers.cs similarity index 100% rename from src/Nadeko.Bot.Common/Common/Helpers.cs rename to src/Nadeko.Bot.Common/_Common/Helpers.cs diff --git a/src/Nadeko.Bot.Common/Common/ImageUrls.cs b/src/Nadeko.Bot.Common/_Common/ImageUrls.cs similarity index 100% rename from src/Nadeko.Bot.Common/Common/ImageUrls.cs rename to src/Nadeko.Bot.Common/_Common/ImageUrls.cs diff --git a/src/Nadeko.Bot.Common/Common/JsonConverters/CultureInfoConverter.cs b/src/Nadeko.Bot.Common/_Common/JsonConverters/CultureInfoConverter.cs similarity index 100% rename from src/Nadeko.Bot.Common/Common/JsonConverters/CultureInfoConverter.cs rename to src/Nadeko.Bot.Common/_Common/JsonConverters/CultureInfoConverter.cs diff --git a/src/Nadeko.Bot.Common/Common/JsonConverters/Rgba32Converter.cs b/src/Nadeko.Bot.Common/_Common/JsonConverters/Rgba32Converter.cs similarity index 100% rename from src/Nadeko.Bot.Common/Common/JsonConverters/Rgba32Converter.cs rename to src/Nadeko.Bot.Common/_Common/JsonConverters/Rgba32Converter.cs diff --git a/src/Nadeko.Bot.Common/Common/LbOpts.cs b/src/Nadeko.Bot.Common/_Common/LbOpts.cs similarity index 100% rename from src/Nadeko.Bot.Common/Common/LbOpts.cs rename to src/Nadeko.Bot.Common/_Common/LbOpts.cs diff --git a/src/Nadeko.Bot.Common/Common/Linq2DbExpressions.cs b/src/Nadeko.Bot.Common/_Common/Linq2DbExpressions.cs similarity index 100% rename from src/Nadeko.Bot.Common/Common/Linq2DbExpressions.cs rename to src/Nadeko.Bot.Common/_Common/Linq2DbExpressions.cs diff --git a/src/Nadeko.Bot.Common/Common/LoginErrorHandler.cs b/src/Nadeko.Bot.Common/_Common/LoginErrorHandler.cs similarity index 100% rename from src/Nadeko.Bot.Common/Common/LoginErrorHandler.cs rename to src/Nadeko.Bot.Common/_Common/LoginErrorHandler.cs diff --git a/src/Nadeko.Bot.Common/Common/OldCreds.cs b/src/Nadeko.Bot.Common/_Common/OldCreds.cs similarity index 100% rename from src/Nadeko.Bot.Common/Common/OldCreds.cs rename to src/Nadeko.Bot.Common/_Common/OldCreds.cs diff --git a/src/Nadeko.Bot.Common/Common/OptionsParser.cs b/src/Nadeko.Bot.Common/_Common/OptionsParser.cs similarity index 100% rename from src/Nadeko.Bot.Common/Common/OptionsParser.cs rename to src/Nadeko.Bot.Common/_Common/OptionsParser.cs diff --git a/src/Nadeko.Bot.Common/Common/OsuMapData.cs b/src/Nadeko.Bot.Common/_Common/OsuMapData.cs similarity index 100% rename from src/Nadeko.Bot.Common/Common/OsuMapData.cs rename to src/Nadeko.Bot.Common/_Common/OsuMapData.cs diff --git a/src/Nadeko.Bot.Common/Common/OsuUserBets.cs b/src/Nadeko.Bot.Common/_Common/OsuUserBets.cs similarity index 100% rename from src/Nadeko.Bot.Common/Common/OsuUserBets.cs rename to src/Nadeko.Bot.Common/_Common/OsuUserBets.cs diff --git a/src/Nadeko.Bot.Common/Common/Pokemon/PokemonNameId.cs b/src/Nadeko.Bot.Common/_Common/Pokemon/PokemonNameId.cs similarity index 100% rename from src/Nadeko.Bot.Common/Common/Pokemon/PokemonNameId.cs rename to src/Nadeko.Bot.Common/_Common/Pokemon/PokemonNameId.cs diff --git a/src/Nadeko.Bot.Common/Common/Pokemon/SearchPokemon.cs b/src/Nadeko.Bot.Common/_Common/Pokemon/SearchPokemon.cs similarity index 100% rename from src/Nadeko.Bot.Common/Common/Pokemon/SearchPokemon.cs rename to src/Nadeko.Bot.Common/_Common/Pokemon/SearchPokemon.cs diff --git a/src/Nadeko.Bot.Common/Common/Pokemon/SearchPokemonAbility.cs b/src/Nadeko.Bot.Common/_Common/Pokemon/SearchPokemonAbility.cs similarity index 100% rename from src/Nadeko.Bot.Common/Common/Pokemon/SearchPokemonAbility.cs rename to src/Nadeko.Bot.Common/_Common/Pokemon/SearchPokemonAbility.cs diff --git a/src/Nadeko.Bot.Common/Common/RequireObjectPropertiesContractResolver.cs b/src/Nadeko.Bot.Common/_Common/RequireObjectPropertiesContractResolver.cs similarity index 100% rename from src/Nadeko.Bot.Common/Common/RequireObjectPropertiesContractResolver.cs rename to src/Nadeko.Bot.Common/_Common/RequireObjectPropertiesContractResolver.cs diff --git a/src/Nadeko.Bot.Common/Common/TriviaQuestionModel.cs b/src/Nadeko.Bot.Common/_Common/TriviaQuestionModel.cs similarity index 100% rename from src/Nadeko.Bot.Common/Common/TriviaQuestionModel.cs rename to src/Nadeko.Bot.Common/_Common/TriviaQuestionModel.cs diff --git a/src/Nadeko.Bot.Common/Common/TypeReaders/EmoteTypeReader.cs b/src/Nadeko.Bot.Common/_Common/TypeReaders/EmoteTypeReader.cs similarity index 100% rename from src/Nadeko.Bot.Common/Common/TypeReaders/EmoteTypeReader.cs rename to src/Nadeko.Bot.Common/_Common/TypeReaders/EmoteTypeReader.cs diff --git a/src/Nadeko.Bot.Common/Common/TypeReaders/GuildTypeReader.cs b/src/Nadeko.Bot.Common/_Common/TypeReaders/GuildTypeReader.cs similarity index 100% rename from src/Nadeko.Bot.Common/Common/TypeReaders/GuildTypeReader.cs rename to src/Nadeko.Bot.Common/_Common/TypeReaders/GuildTypeReader.cs diff --git a/src/Nadeko.Bot.Common/Common/TypeReaders/GuildUserTypeReader.cs b/src/Nadeko.Bot.Common/_Common/TypeReaders/GuildUserTypeReader.cs similarity index 100% rename from src/Nadeko.Bot.Common/Common/TypeReaders/GuildUserTypeReader.cs rename to src/Nadeko.Bot.Common/_Common/TypeReaders/GuildUserTypeReader.cs diff --git a/src/Nadeko.Bot.Common/Common/TypeReaders/KwumTypeReader.cs b/src/Nadeko.Bot.Common/_Common/TypeReaders/KwumTypeReader.cs similarity index 100% rename from src/Nadeko.Bot.Common/Common/TypeReaders/KwumTypeReader.cs rename to src/Nadeko.Bot.Common/_Common/TypeReaders/KwumTypeReader.cs diff --git a/src/Nadeko.Bot.Common/Common/TypeReaders/Models/PermissionAction.cs b/src/Nadeko.Bot.Common/_Common/TypeReaders/Models/PermissionAction.cs similarity index 100% rename from src/Nadeko.Bot.Common/Common/TypeReaders/Models/PermissionAction.cs rename to src/Nadeko.Bot.Common/_Common/TypeReaders/Models/PermissionAction.cs diff --git a/src/Nadeko.Bot.Common/Common/TypeReaders/Models/StoopidTime.cs b/src/Nadeko.Bot.Common/_Common/TypeReaders/Models/StoopidTime.cs similarity index 100% rename from src/Nadeko.Bot.Common/Common/TypeReaders/Models/StoopidTime.cs rename to src/Nadeko.Bot.Common/_Common/TypeReaders/Models/StoopidTime.cs diff --git a/src/Nadeko.Bot.Common/Common/TypeReaders/ModuleTypeReader.cs b/src/Nadeko.Bot.Common/_Common/TypeReaders/ModuleTypeReader.cs similarity index 100% rename from src/Nadeko.Bot.Common/Common/TypeReaders/ModuleTypeReader.cs rename to src/Nadeko.Bot.Common/_Common/TypeReaders/ModuleTypeReader.cs diff --git a/src/Nadeko.Bot.Common/Common/TypeReaders/PermissionActionTypeReader.cs b/src/Nadeko.Bot.Common/_Common/TypeReaders/PermissionActionTypeReader.cs similarity index 100% rename from src/Nadeko.Bot.Common/Common/TypeReaders/PermissionActionTypeReader.cs rename to src/Nadeko.Bot.Common/_Common/TypeReaders/PermissionActionTypeReader.cs diff --git a/src/Nadeko.Bot.Common/Common/TypeReaders/Rgba32TypeReader.cs b/src/Nadeko.Bot.Common/_Common/TypeReaders/Rgba32TypeReader.cs similarity index 100% rename from src/Nadeko.Bot.Common/Common/TypeReaders/Rgba32TypeReader.cs rename to src/Nadeko.Bot.Common/_Common/TypeReaders/Rgba32TypeReader.cs diff --git a/src/Nadeko.Bot.Common/Common/TypeReaders/StoopidTimeTypeReader.cs b/src/Nadeko.Bot.Common/_Common/TypeReaders/StoopidTimeTypeReader.cs similarity index 100% rename from src/Nadeko.Bot.Common/Common/TypeReaders/StoopidTimeTypeReader.cs rename to src/Nadeko.Bot.Common/_Common/TypeReaders/StoopidTimeTypeReader.cs diff --git a/src/Nadeko.Bot.Db/Extensions/GuildConfigExtensions.cs b/src/Nadeko.Bot.Db/Extensions/GuildConfigExtensions.cs index dea053769..5db6b81c6 100644 --- a/src/Nadeko.Bot.Db/Extensions/GuildConfigExtensions.cs +++ b/src/Nadeko.Bot.Db/Extensions/GuildConfigExtensions.cs @@ -29,7 +29,7 @@ public static class GuildConfigExtensions /// Db Context /// Id of the guild to get stream role settings for. /// Guild'p stream role settings - public static StreamRoleSettings GetStreamRoleSettings(this NadekoBaseContext ctx, ulong guildId) + public static StreamRoleSettings GetStreamRoleSettings(this DbContext ctx, ulong guildId) { var conf = ctx.GuildConfigsForId(guildId, set => set.Include(y => y.StreamRole) @@ -120,7 +120,7 @@ public static class GuildConfigExtensions // .First(x => x.GuildId == guildId); } - public static LogSetting LogSettingsFor(this NadekoBaseContext ctx, ulong guildId) + public static LogSetting LogSettingsFor(this DbContext ctx, ulong guildId) { var logSetting = ctx.Set() .AsQueryable() @@ -148,7 +148,7 @@ public static class GuildConfigExtensions return query.ToList(); } - public static GuildConfig GcWithPermissionsFor(this NadekoBaseContext ctx, ulong guildId) + public static GuildConfig GcWithPermissionsFor(this DbContext ctx, ulong guildId) { var config = ctx.Set().AsQueryable() .Where(gc => gc.GuildId == guildId) diff --git a/src/Nadeko.Bot.Db/Models/AntiProtection.cs b/src/Nadeko.Bot.Db/Models/AntiProtection.cs deleted file mode 100644 index 08c487d2c..000000000 --- a/src/Nadeko.Bot.Db/Models/AntiProtection.cs +++ /dev/null @@ -1,67 +0,0 @@ -#nullable disable -namespace NadekoBot.Services.Database.Models; - - -// todo db required, nullable? -public class AntiRaidSetting : DbEntity -{ - public int GuildConfigId { get; set; } - public GuildConfig GuildConfig { get; set; } - - public int UserThreshold { get; set; } - public int Seconds { get; set; } - public PunishmentAction Action { get; set; } - - /// - /// Duration of the punishment, in minutes. This works only for supported Actions, like: - /// Mute, Chatmute, Voicemute, etc... - /// - public int PunishDuration { get; set; } -} - -public class AntiSpamSetting : DbEntity -{ - public int GuildConfigId { get; set; } - public GuildConfig GuildConfig { get; set; } - - public PunishmentAction Action { get; set; } - public int MessageThreshold { get; set; } = 3; - public int MuteTime { get; set; } - public ulong? RoleId { get; set; } - public HashSet IgnoredChannels { get; set; } = new(); -} - -public class AntiAltSetting -{ - public int Id { get; set; } - public int GuildConfigId { get; set; } - public TimeSpan MinAge { get; set; } - public PunishmentAction Action { get; set; } - public int ActionDurationMinutes { get; set; } - public ulong? RoleId { get; set; } -} - -public enum PunishmentAction -{ - Mute, - Kick, - Ban, - Softban, - RemoveRoles, - ChatMute, - VoiceMute, - AddRole, - Warn, - TimeOut -} - -public class AntiSpamIgnore : DbEntity -{ - public ulong ChannelId { get; set; } - - public override int GetHashCode() - => ChannelId.GetHashCode(); - - public override bool Equals(object obj) - => obj is AntiSpamIgnore inst ? inst.ChannelId == ChannelId : false; -} \ No newline at end of file diff --git a/src/Nadeko.Bot.Db/Models/PunishmentAction.cs b/src/Nadeko.Bot.Db/Models/PunishmentAction.cs new file mode 100644 index 000000000..160145e84 --- /dev/null +++ b/src/Nadeko.Bot.Db/Models/PunishmentAction.cs @@ -0,0 +1,15 @@ +namespace NadekoBot.Services.Database.Models; + +public enum PunishmentAction +{ + Mute, + Kick, + Ban, + Softban, + RemoveRoles, + ChatMute, + VoiceMute, + AddRole, + Warn, + TimeOut +} \ No newline at end of file diff --git a/src/Nadeko.Bot.Db/Models/anti/AntiAltSetting.cs b/src/Nadeko.Bot.Db/Models/anti/AntiAltSetting.cs new file mode 100644 index 000000000..b10ed0d56 --- /dev/null +++ b/src/Nadeko.Bot.Db/Models/anti/AntiAltSetting.cs @@ -0,0 +1,11 @@ +namespace NadekoBot.Services.Database.Models; + +public class AntiAltSetting +{ + public int Id { get; set; } + public int GuildConfigId { get; set; } + public TimeSpan MinAge { get; set; } + public PunishmentAction Action { get; set; } + public int ActionDurationMinutes { get; set; } + public ulong? RoleId { get; set; } +} \ No newline at end of file diff --git a/src/Nadeko.Bot.Db/Models/anti/AntiRaidSetting.cs b/src/Nadeko.Bot.Db/Models/anti/AntiRaidSetting.cs new file mode 100644 index 000000000..4eb69bfa0 --- /dev/null +++ b/src/Nadeko.Bot.Db/Models/anti/AntiRaidSetting.cs @@ -0,0 +1,20 @@ +#nullable disable +namespace NadekoBot.Services.Database.Models; + + +// todo db required, nullable? +public class AntiRaidSetting : DbEntity +{ + public int GuildConfigId { get; set; } + public GuildConfig GuildConfig { get; set; } + + public int UserThreshold { get; set; } + public int Seconds { get; set; } + public PunishmentAction Action { get; set; } + + /// + /// Duration of the punishment, in minutes. This works only for supported Actions, like: + /// Mute, Chatmute, Voicemute, etc... + /// + public int PunishDuration { get; set; } +} \ No newline at end of file diff --git a/src/Nadeko.Bot.Db/Models/anti/AntiSpamIgnore.cs b/src/Nadeko.Bot.Db/Models/anti/AntiSpamIgnore.cs new file mode 100644 index 000000000..304a6c871 --- /dev/null +++ b/src/Nadeko.Bot.Db/Models/anti/AntiSpamIgnore.cs @@ -0,0 +1,12 @@ +namespace NadekoBot.Services.Database.Models; + +public class AntiSpamIgnore : DbEntity +{ + public ulong ChannelId { get; set; } + + public override int GetHashCode() + => ChannelId.GetHashCode(); + + public override bool Equals(object obj) + => obj is AntiSpamIgnore inst ? inst.ChannelId == ChannelId : false; +} \ No newline at end of file diff --git a/src/Nadeko.Bot.Db/Models/anti/AntiSpamSetting.cs b/src/Nadeko.Bot.Db/Models/anti/AntiSpamSetting.cs new file mode 100644 index 000000000..43fe1aacb --- /dev/null +++ b/src/Nadeko.Bot.Db/Models/anti/AntiSpamSetting.cs @@ -0,0 +1,13 @@ +namespace NadekoBot.Services.Database.Models; + +public class AntiSpamSetting : DbEntity +{ + public int GuildConfigId { get; set; } + public GuildConfig GuildConfig { get; set; } + + public PunishmentAction Action { get; set; } + public int MessageThreshold { get; set; } = 3; + public int MuteTime { get; set; } + public ulong? RoleId { get; set; } + public HashSet IgnoredChannels { get; set; } = new(); +} \ No newline at end of file diff --git a/src/Nadeko.Bot.Modules.Administration/AutoAssignableRoles/AutoAssignRoleService.cs b/src/Nadeko.Bot.Modules.Administration/AutoAssignableRoles/AutoAssignRoleService.cs index 3cce25802..00d58d070 100644 --- a/src/Nadeko.Bot.Modules.Administration/AutoAssignableRoles/AutoAssignRoleService.cs +++ b/src/Nadeko.Bot.Modules.Administration/AutoAssignableRoles/AutoAssignRoleService.cs @@ -118,7 +118,7 @@ public sealed class AutoAssignRoleService : INService { await using var uow = _db.GetDbContext(); - await uow.GuildConfigs.AsNoTracking() + await uow.Set().AsNoTracking() .Where(x => x.GuildId == guildId) .UpdateAsync(_ => new() { diff --git a/src/Nadeko.Bot.Modules.Administration/DangerousCommands/DangerousCommands.cs b/src/Nadeko.Bot.Modules.Administration/DangerousCommands/DangerousCommands.cs index cc6eee67b..51fc139bf 100644 --- a/src/Nadeko.Bot.Modules.Administration/DangerousCommands/DangerousCommands.cs +++ b/src/Nadeko.Bot.Modules.Administration/DangerousCommands/DangerousCommands.cs @@ -10,26 +10,6 @@ namespace NadekoBot.Modules.Administration [OwnerOnly] public partial class DangerousCommands : NadekoModule { - private async Task ConfirmActionInternalAsync(string name, Func action) - { - try - { - var embed = _eb.Create() - .WithTitle(GetText(strs.sql_confirm_exec)) - .WithDescription(name); - - if (!await PromptUserConfirmAsync(embed)) - return; - - await action(); - await ctx.OkAsync(); - } - catch (Exception ex) - { - await SendErrorAsync(ex.ToString()); - } - } - [Cmd] [OwnerOnly] public Task SqlSelect([Leftover] string sql) @@ -76,36 +56,6 @@ namespace NadekoBot.Modules.Administration } } - [Cmd] - [OwnerOnly] - public Task DeleteWaifus() - => ConfirmActionInternalAsync("Delete Waifus", () => _service.DeleteWaifus()); - - [Cmd] - [OwnerOnly] - public async Task DeleteWaifu(IUser user) - => await DeleteWaifu(user.Id); - - [Cmd] - [OwnerOnly] - public Task DeleteWaifu(ulong userId) - => ConfirmActionInternalAsync($"Delete Waifu {userId}", () => _service.DeleteWaifu(userId)); - - [Cmd] - [OwnerOnly] - public Task DeleteCurrency() - => ConfirmActionInternalAsync("Delete Currency", () => _service.DeleteCurrency()); - - [Cmd] - [OwnerOnly] - public Task DeletePlaylists() - => ConfirmActionInternalAsync("Delete Playlists", () => _service.DeletePlaylists()); - - [Cmd] - [OwnerOnly] - public Task DeleteXp() - => ConfirmActionInternalAsync("Delete Xp", () => _service.DeleteXp()); - [Cmd] [OwnerOnly] public async Task PurgeUser(ulong userId) diff --git a/src/Nadeko.Bot.Modules.Administration/DangerousCommands/DangerousCommandsService.cs b/src/Nadeko.Bot.Modules.Administration/DangerousCommands/DangerousCommandsService.cs index 01d77d447..979106f6f 100644 --- a/src/Nadeko.Bot.Modules.Administration/DangerousCommands/DangerousCommandsService.cs +++ b/src/Nadeko.Bot.Modules.Administration/DangerousCommands/DangerousCommandsService.cs @@ -14,74 +14,6 @@ public class DangerousCommandsService : INService public DangerousCommandsService(DbService db) => _db = db; - public async Task DeleteXp() - { - await using var ctx = _db.GetDbContext(); - await ctx.DiscordUser.UpdateAsync(_ => new DiscordUser() - { - ClubId = null, - // IsClubAdmin = false, - TotalXp = 0 - }); - - await ctx.UserXpStats.DeleteAsync(); - await ctx.ClubApplicants.DeleteAsync(); - await ctx.ClubBans.DeleteAsync(); - await ctx.Clubs.DeleteAsync(); - await ctx.SaveChangesAsync(); - } - - public async Task DeleteWaifus() - { - await using var ctx = _db.GetDbContext(); - await ctx.WaifuUpdates.DeleteAsync(); - await ctx.WaifuItem.DeleteAsync(); - await ctx.WaifuInfo.DeleteAsync(); - await ctx.SaveChangesAsync(); - } - - public async Task DeleteWaifu(ulong userId) - { - await using var ctx = _db.GetDbContext(); - await ctx.WaifuUpdates - .Where(x => x.User.UserId == userId) - .DeleteAsync(); - await ctx.WaifuItem - .Where(x => x.WaifuInfo.Waifu.UserId == userId) - .DeleteAsync(); - await ctx.WaifuInfo - .Where(x => x.Claimer.UserId == userId) - .UpdateAsync(old => new WaifuInfo() - { - ClaimerId = null, - }); - await ctx.WaifuInfo - .Where(x => x.Waifu.UserId == userId) - .DeleteAsync(); - await ctx.SaveChangesAsync(); - } - - public async Task DeletePlaylists() - { - await using var ctx = _db.GetDbContext(); - await ctx.MusicPlaylists.DeleteAsync(); - await ctx.SaveChangesAsync(); - } - - public async Task DeleteCurrency() - { - await using var ctx = _db.GetDbContext(); - await ctx.DiscordUser.UpdateAsync(_ => new DiscordUser() - { - CurrencyAmount = 0 - }); - - await ctx.CurrencyTransactions.DeleteAsync(); - await ctx.PlantedCurrency.DeleteAsync(); - await ctx.BankUsers.DeleteAsync(); - await ctx.SaveChangesAsync(); - } - public async Task ExecuteSql(string sql) { int res; @@ -130,7 +62,7 @@ public class DangerousCommandsService : INService if (wi is not null) { // remove updates which have new or old as this waifu - await uow.WaifuUpdates.DeleteAsync(wu => wu.New.UserId == userId || wu.Old.UserId == userId); + await uow.Set().DeleteAsync(wu => wu.New.UserId == userId || wu.Old.UserId == userId); // delete all items this waifu owns await uow.Set().DeleteAsync(x => x.WaifuInfoId == wi.Id); @@ -155,13 +87,13 @@ public class DangerousCommandsService : INService } // delete guild xp - await uow.UserXpStats.DeleteAsync(x => x.UserId == userId); + await uow.Set().DeleteAsync(x => x.UserId == userId); // delete currency transactions await uow.Set().DeleteAsync(x => x.UserId == userId); // delete user, currency, and clubs go away with it - await uow.DiscordUser.DeleteAsync(u => u.UserId == userId); + await uow.Set().DeleteAsync(u => u.UserId == userId); } public class SelectResult diff --git a/src/Nadeko.Bot.Modules.Administration/ImageOnlyChannelService.cs b/src/Nadeko.Bot.Modules.Administration/ImageOnlyChannelService.cs index 8f5de245e..9bf5f21cb 100644 --- a/src/Nadeko.Bot.Modules.Administration/ImageOnlyChannelService.cs +++ b/src/Nadeko.Bot.Modules.Administration/ImageOnlyChannelService.cs @@ -33,14 +33,14 @@ public sealed class SomethingOnlyChannelService : IExecOnMessage _db = db; using var uow = _db.GetDbContext(); - _imageOnly = uow.ImageOnlyChannels + _imageOnly = uow.Set() .Where(x => x.Type == OnlyChannelType.Image) .ToList() .GroupBy(x => x.GuildId) .ToDictionary(x => x.Key, x => new ConcurrentHashSet(x.Select(y => y.ChannelId))) .ToConcurrent(); - _linkOnly = uow.ImageOnlyChannels + _linkOnly = uow.Set() .Where(x => x.Type == OnlyChannelType.Link) .ToList() .GroupBy(x => x.GuildId) @@ -85,12 +85,12 @@ public sealed class SomethingOnlyChannelService : IExecOnMessage await using var uow = _db.GetDbContext(); if (forceDisable || (_imageOnly.TryGetValue(guildId, out var channels) && channels.TryRemove(channelId))) { - await uow.ImageOnlyChannels.DeleteAsync(x => x.ChannelId == channelId && x.Type == OnlyChannelType.Image); + await uow.Set().DeleteAsync(x => x.ChannelId == channelId && x.Type == OnlyChannelType.Image); } else { - await uow.ImageOnlyChannels.DeleteAsync(x => x.ChannelId == channelId); - uow.ImageOnlyChannels.Add(new() + await uow.Set().DeleteAsync(x => x.ChannelId == channelId); + uow.Set().Add(new() { GuildId = guildId, ChannelId = channelId, @@ -115,12 +115,12 @@ public sealed class SomethingOnlyChannelService : IExecOnMessage await using var uow = _db.GetDbContext(); if (forceDisable || (_linkOnly.TryGetValue(guildId, out var channels) && channels.TryRemove(channelId))) { - await uow.ImageOnlyChannels.DeleteAsync(x => x.ChannelId == channelId && x.Type == OnlyChannelType.Link); + await uow.Set().DeleteAsync(x => x.ChannelId == channelId && x.Type == OnlyChannelType.Link); } else { - await uow.ImageOnlyChannels.DeleteAsync(x => x.ChannelId == channelId); - uow.ImageOnlyChannels.Add(new() + await uow.Set().DeleteAsync(x => x.ChannelId == channelId); + uow.Set().Add(new() { GuildId = guildId, ChannelId = channelId, diff --git a/src/Nadeko.Bot.Modules.Administration/Nadeko.Bot.Modules.Administration.csproj b/src/Nadeko.Bot.Modules.Administration/Nadeko.Bot.Modules.Administration.csproj index 7e53c4371..e0f6e1f25 100644 --- a/src/Nadeko.Bot.Modules.Administration/Nadeko.Bot.Modules.Administration.csproj +++ b/src/Nadeko.Bot.Modules.Administration/Nadeko.Bot.Modules.Administration.csproj @@ -13,6 +13,7 @@ + diff --git a/src/Nadeko.Bot.Modules.Administration/PlayingRotate/PlayingRotateService.cs b/src/Nadeko.Bot.Modules.Administration/PlayingRotate/PlayingRotateService.cs index 2f1fd7cbe..2fb139dde 100644 --- a/src/Nadeko.Bot.Modules.Administration/PlayingRotate/PlayingRotateService.cs +++ b/src/Nadeko.Bot.Modules.Administration/PlayingRotate/PlayingRotateService.cs @@ -46,7 +46,7 @@ public sealed class PlayingRotateService : INService, IReadyExecutor IReadOnlyList rotatingStatuses; await using (var uow = _db.GetDbContext()) { - rotatingStatuses = uow.RotatingStatus.AsNoTracking().OrderBy(x => x.Id).ToList(); + rotatingStatuses = uow.Set().AsNoTracking().OrderBy(x => x.Id).ToList(); } if (rotatingStatuses.Count == 0) @@ -72,7 +72,7 @@ public sealed class PlayingRotateService : INService, IReadyExecutor throw new ArgumentOutOfRangeException(nameof(index)); await using var uow = _db.GetDbContext(); - var toRemove = await uow.RotatingStatus.AsQueryable().AsNoTracking().Skip(index).FirstOrDefaultAsync(); + var toRemove = await uow.Set().AsQueryable().AsNoTracking().Skip(index).FirstOrDefaultAsync(); if (toRemove is null) return null; @@ -104,6 +104,6 @@ public sealed class PlayingRotateService : INService, IReadyExecutor public IReadOnlyList GetRotatingStatuses() { using var uow = _db.GetDbContext(); - return uow.RotatingStatus.AsNoTracking().ToList(); + return uow.Set().AsNoTracking().ToList(); } } \ No newline at end of file diff --git a/src/Nadeko.Bot.Modules.Administration/Self/SelfService.cs b/src/Nadeko.Bot.Modules.Administration/Self/SelfService.cs index 9dab9b2b4..d5d4b265e 100644 --- a/src/Nadeko.Bot.Modules.Administration/Self/SelfService.cs +++ b/src/Nadeko.Bot.Modules.Administration/Self/SelfService.cs @@ -83,7 +83,7 @@ public sealed class SelfService : IExecNoCommand, IReadyExecutor, INService { await using var uow = _db.GetDbContext(); - autoCommands = uow.AutoCommands.AsNoTracking() + autoCommands = uow.Set().AsNoTracking() .Where(x => x.Interval >= 5) .AsEnumerable() .GroupBy(x => x.GuildId) @@ -91,7 +91,7 @@ public sealed class SelfService : IExecNoCommand, IReadyExecutor, INService y => y.ToDictionary(x => x.Id, TimerFromAutoCommand).ToConcurrent()) .ToConcurrent(); - var startupCommands = uow.AutoCommands.AsNoTracking().Where(x => x.Interval == 0); + var startupCommands = uow.Set().AsNoTracking().Where(x => x.Interval == 0); foreach (var cmd in startupCommands) { try @@ -136,7 +136,7 @@ public sealed class SelfService : IExecNoCommand, IReadyExecutor, INService { using (var uow = _db.GetDbContext()) { - uow.AutoCommands.Add(cmd); + uow.Set().Add(cmd); uow.SaveChanges(); } @@ -156,13 +156,13 @@ public sealed class SelfService : IExecNoCommand, IReadyExecutor, INService public IEnumerable GetStartupCommands() { using var uow = _db.GetDbContext(); - return uow.AutoCommands.AsNoTracking().Where(x => x.Interval == 0).OrderBy(x => x.Id).ToList(); + return uow.Set().AsNoTracking().Where(x => x.Interval == 0).OrderBy(x => x.Id).ToList(); } public IEnumerable GetAutoCommands() { using var uow = _db.GetDbContext(); - return uow.AutoCommands.AsNoTracking().Where(x => x.Interval >= 5).OrderBy(x => x.Id).ToList(); + return uow.Set().AsNoTracking().Where(x => x.Interval >= 5).OrderBy(x => x.Id).ToList(); } private async Task LoadOwnerChannels() @@ -264,7 +264,7 @@ public sealed class SelfService : IExecNoCommand, IReadyExecutor, INService public bool RemoveStartupCommand(int index, out AutoCommand cmd) { using var uow = _db.GetDbContext(); - cmd = uow.AutoCommands.AsNoTracking().Where(x => x.Interval == 0).Skip(index).FirstOrDefault(); + cmd = uow.Set().AsNoTracking().Where(x => x.Interval == 0).Skip(index).FirstOrDefault(); if (cmd is not null) { @@ -279,7 +279,7 @@ public sealed class SelfService : IExecNoCommand, IReadyExecutor, INService public bool RemoveAutoCommand(int index, out AutoCommand cmd) { using var uow = _db.GetDbContext(); - cmd = uow.AutoCommands.AsNoTracking().Where(x => x.Interval >= 5).Skip(index).FirstOrDefault(); + cmd = uow.Set().AsNoTracking().Where(x => x.Interval >= 5).Skip(index).FirstOrDefault(); if (cmd is not null) { @@ -323,9 +323,9 @@ public sealed class SelfService : IExecNoCommand, IReadyExecutor, INService public void ClearStartupCommands() { using var uow = _db.GetDbContext(); - var toRemove = uow.AutoCommands.AsNoTracking().Where(x => x.Interval == 0); + var toRemove = uow.Set().AsNoTracking().Where(x => x.Interval == 0); - uow.AutoCommands.RemoveRange(toRemove); + uow.Set().RemoveRange(toRemove); uow.SaveChanges(); } diff --git a/src/Nadeko.Bot.Modules.Administration/SelfAssignableRoles/SelfAssignedRolesService.cs b/src/Nadeko.Bot.Modules.Administration/SelfAssignableRoles/SelfAssignedRolesService.cs index 8742d8c92..7483e9043 100644 --- a/src/Nadeko.Bot.Modules.Administration/SelfAssignableRoles/SelfAssignedRolesService.cs +++ b/src/Nadeko.Bot.Modules.Administration/SelfAssignableRoles/SelfAssignedRolesService.cs @@ -32,11 +32,11 @@ public class SelfAssignedRolesService : INService public bool AddNew(ulong guildId, IRole role, int group) { using var uow = _db.GetDbContext(); - var roles = uow.SelfAssignableRoles.GetFromGuild(guildId); + var roles = uow.Set().GetFromGuild(guildId); if (roles.Any(s => s.RoleId == role.Id && s.GuildId == role.Guild.Id)) return false; - uow.SelfAssignableRoles.Add(new() + uow.Set().Add(new() { Group = group, RoleId = role.Id, @@ -166,7 +166,7 @@ public class SelfAssignedRolesService : INService { bool success; using var uow = _db.GetDbContext(); - success = uow.SelfAssignableRoles.DeleteByGuildAndRoleId(guildId, roleId); + success = uow.Set().DeleteByGuildAndRoleId(guildId, roleId); uow.SaveChanges(); return success; } @@ -177,7 +177,7 @@ public class SelfAssignedRolesService : INService var gc = uow.GuildConfigsForId(guildId, set => set); var autoDelete = gc.AutoDeleteSelfAssignedRoleMessages; var exclusive = gc.ExclusiveSelfAssignedRoles; - var roles = uow.SelfAssignableRoles.GetFromGuild(guildId); + var roles = uow.Set().GetFromGuild(guildId); return (autoDelete, exclusive, roles); } @@ -185,7 +185,7 @@ public class SelfAssignedRolesService : INService public bool SetLevelReq(ulong guildId, IRole role, int level) { using var uow = _db.GetDbContext(); - var roles = uow.SelfAssignableRoles.GetFromGuild(guildId); + var roles = uow.Set().GetFromGuild(guildId); var sar = roles.FirstOrDefault(x => x.RoleId == role.Id); if (sar is not null) { @@ -222,10 +222,10 @@ public class SelfAssignedRolesService : INService var gc = uow.GuildConfigsForId(guild.Id, set => set.Include(x => x.SelfAssignableRoleGroupNames)); exclusive = gc.ExclusiveSelfAssignedRoles; groupNames = gc.SelfAssignableRoleGroupNames.ToDictionary(x => x.Number, x => x.Name); - var roleModels = uow.SelfAssignableRoles.GetFromGuild(guild.Id); + var roleModels = uow.Set().GetFromGuild(guild.Id); roles = roleModels.Select(x => (Model: x, Role: guild.GetRole(x.RoleId))) .ToList(); - uow.SelfAssignableRoles.RemoveRange(roles.Where(x => x.Role is null).Select(x => x.Model).ToArray()); + uow.Set().RemoveRange(roles.Where(x => x.Role is null).Select(x => x.Model).ToArray()); uow.SaveChanges(); } diff --git a/src/Nadeko.Bot.Modules.Administration/ServerLog/ServerLogCommandService.cs b/src/Nadeko.Bot.Modules.Administration/ServerLog/ServerLogCommandService.cs index 21a489835..d52073a7e 100644 --- a/src/Nadeko.Bot.Modules.Administration/ServerLog/ServerLogCommandService.cs +++ b/src/Nadeko.Bot.Modules.Administration/ServerLog/ServerLogCommandService.cs @@ -52,7 +52,7 @@ public sealed class LogCommandService : ILogCommandService, IReadyExecutor using (var uow = db.GetDbContext()) { var guildIds = client.Guilds.Select(x => x.Id).ToList(); - var configs = uow.LogSettings.AsQueryable() + var configs = uow.Set().AsQueryable() .AsNoTracking() .Where(x => guildIds.Contains(x.GuildId)) .Include(ls => ls.LogIgnores) diff --git a/src/Nadeko.Bot.Modules.Administration/UserPunish/UserPunishService.cs b/src/Nadeko.Bot.Modules.Administration/UserPunish/UserPunishService.cs index 7141905d9..b3dcb0bc2 100644 --- a/src/Nadeko.Bot.Modules.Administration/UserPunish/UserPunishService.cs +++ b/src/Nadeko.Bot.Modules.Administration/UserPunish/UserPunishService.cs @@ -87,11 +87,11 @@ public class UserPunishService : INService, IReadyExecutor { ps = uow.GuildConfigsForId(guildId, set => set.Include(x => x.WarnPunishments)).WarnPunishments; - previousCount = uow.Warnings.ForId(guildId, userId) - .Where(w => !w.Forgiven && w.UserId == userId) - .Sum(x => x.Weight); + previousCount = uow.Set().ForId(guildId, userId) + .Where(w => !w.Forgiven && w.UserId == userId) + .Sum(x => x.Weight); - uow.Warnings.Add(warn); + uow.Set().Add(warn); await uow.SaveChangesAsync(); } @@ -99,9 +99,9 @@ public class UserPunishService : INService, IReadyExecutor _ = OnUserWarned(warn); var totalCount = previousCount + weight; - + var p = ps.Where(x => x.Count > previousCount && x.Count <= totalCount) - .MaxBy(x => x.Count); + .MaxBy(x => x.Count); if (p is not null) { @@ -241,34 +241,34 @@ public class UserPunishService : INService, IReadyExecutor public async Task CheckAllWarnExpiresAsync() { await using var uow = _db.GetDbContext(); - var cleared = await uow.Warnings - .Where(x => uow.GuildConfigs - .Any(y => y.GuildId == x.GuildId - && y.WarnExpireHours > 0 - && y.WarnExpireAction == WarnExpireAction.Clear) - && x.Forgiven == false - && x.DateAdded - < DateTime.UtcNow.AddHours(-uow.GuildConfigs - .Where(y => x.GuildId == y.GuildId) - .Select(y => y.WarnExpireHours) - .First())) - .UpdateAsync(_ => new() - { - Forgiven = true, - ForgivenBy = "expiry" - }); + var cleared = await uow.Set() + .Where(x => uow.Set() + .Any(y => y.GuildId == x.GuildId + && y.WarnExpireHours > 0 + && y.WarnExpireAction == WarnExpireAction.Clear) + && x.Forgiven == false + && x.DateAdded + < DateTime.UtcNow.AddHours(-uow.Set() + .Where(y => x.GuildId == y.GuildId) + .Select(y => y.WarnExpireHours) + .First())) + .UpdateAsync(_ => new() + { + Forgiven = true, + ForgivenBy = "expiry" + }); - var deleted = await uow.Warnings - .Where(x => uow.GuildConfigs - .Any(y => y.GuildId == x.GuildId - && y.WarnExpireHours > 0 - && y.WarnExpireAction == WarnExpireAction.Delete) - && x.DateAdded - < DateTime.UtcNow.AddHours(-uow.GuildConfigs - .Where(y => x.GuildId == y.GuildId) - .Select(y => y.WarnExpireHours) - .First())) - .DeleteAsync(); + var deleted = await uow.Set() + .Where(x => uow.Set() + .Any(y => y.GuildId == x.GuildId + && y.WarnExpireHours > 0 + && y.WarnExpireAction == WarnExpireAction.Delete) + && x.DateAdded + < DateTime.UtcNow.AddHours(-uow.Set() + .Where(y => x.GuildId == y.GuildId) + .Select(y => y.WarnExpireHours) + .First())) + .DeleteAsync(); if (cleared > 0 || deleted > 0) { @@ -290,22 +290,22 @@ public class UserPunishService : INService, IReadyExecutor if (config.WarnExpireAction == WarnExpireAction.Clear) { - await uow.Warnings - .Where(x => x.GuildId == guildId - && x.Forgiven == false - && x.DateAdded < DateTime.UtcNow.AddHours(-config.WarnExpireHours)) - .UpdateAsync(_ => new() - { - Forgiven = true, - ForgivenBy = "expiry" - }); + await uow.Set() + .Where(x => x.GuildId == guildId + && x.Forgiven == false + && x.DateAdded < DateTime.UtcNow.AddHours(-config.WarnExpireHours)) + .UpdateAsync(_ => new() + { + Forgiven = true, + ForgivenBy = "expiry" + }); } else if (config.WarnExpireAction == WarnExpireAction.Delete) { - await uow.Warnings - .Where(x => x.GuildId == guildId - && x.DateAdded < DateTime.UtcNow.AddHours(-config.WarnExpireHours)) - .DeleteAsync(); + await uow.Set() + .Where(x => x.GuildId == guildId + && x.DateAdded < DateTime.UtcNow.AddHours(-config.WarnExpireHours)) + .DeleteAsync(); } await uow.SaveChangesAsync(); @@ -339,13 +339,13 @@ public class UserPunishService : INService, IReadyExecutor public IGrouping[] WarnlogAll(ulong gid) { using var uow = _db.GetDbContext(); - return uow.Warnings.GetForGuild(gid).GroupBy(x => x.UserId).ToArray(); + return uow.Set().GetForGuild(gid).GroupBy(x => x.UserId).ToArray(); } public Warning[] UserWarnings(ulong gid, ulong userId) { using var uow = _db.GetDbContext(); - return uow.Warnings.ForId(gid, userId); + return uow.Set().ForId(gid, userId); } public async Task WarnClearAsync( @@ -357,9 +357,9 @@ public class UserPunishService : INService, IReadyExecutor var toReturn = true; await using var uow = _db.GetDbContext(); if (index == 0) - await uow.Warnings.ForgiveAll(guildId, userId, moderator); + await uow.Set().ForgiveAll(guildId, userId, moderator); else - toReturn = uow.Warnings.Forgive(guildId, userId, moderator, index - 1); + toReturn = uow.Set().Forgive(guildId, userId, moderator, index - 1); await uow.SaveChangesAsync(); return toReturn; } @@ -423,8 +423,8 @@ public class UserPunishService : INService, IReadyExecutor { using var uow = _db.GetDbContext(); return uow.GuildConfigsForId(guildId, gc => gc.Include(x => x.WarnPunishments)) - .WarnPunishments.OrderBy(x => x.Count) - .ToArray(); + .WarnPunishments.OrderBy(x => x.Count) + .ToArray(); } public (IReadOnlyCollection<(string Original, ulong? Id, string Reason)> Bans, int Missing) MassKill( @@ -434,20 +434,20 @@ public class UserPunishService : INService, IReadyExecutor var gusers = guild.Users; //get user objects and reasons var bans = people.Split("\n") - .Select(x => - { - var split = x.Trim().Split(" "); + .Select(x => + { + var split = x.Trim().Split(" "); - var reason = string.Join(" ", split.Skip(1)); + var reason = string.Join(" ", split.Skip(1)); - if (ulong.TryParse(split[0], out var id)) - return (Original: split[0], Id: id, Reason: reason); + if (ulong.TryParse(split[0], out var id)) + return (Original: split[0], Id: id, Reason: reason); - return (Original: split[0], - gusers.FirstOrDefault(u => u.ToString().ToLowerInvariant() == x)?.Id, - Reason: reason); - }) - .ToArray(); + return (Original: split[0], + gusers.FirstOrDefault(u => u.ToString().ToLowerInvariant() == x)?.Id, + Reason: reason); + }) + .ToArray(); //if user is null, means that person couldn't be found var missing = bans.Count(x => !x.Id.HasValue); @@ -463,14 +463,14 @@ public class UserPunishService : INService, IReadyExecutor public string GetBanTemplate(ulong guildId) { using var uow = _db.GetDbContext(); - var template = uow.BanTemplates.AsQueryable().FirstOrDefault(x => x.GuildId == guildId); + var template = uow.Set().AsQueryable().FirstOrDefault(x => x.GuildId == guildId); return template?.Text; } public void SetBanTemplate(ulong guildId, string text) { using var uow = _db.GetDbContext(); - var template = uow.BanTemplates.AsQueryable().FirstOrDefault(x => x.GuildId == guildId); + var template = uow.Set().AsQueryable().FirstOrDefault(x => x.GuildId == guildId); if (text is null) { @@ -481,7 +481,7 @@ public class UserPunishService : INService, IReadyExecutor } else if (template is null) { - uow.BanTemplates.Add(new() + uow.Set().Add(new() { GuildId = guildId, Text = text @@ -496,7 +496,7 @@ public class UserPunishService : INService, IReadyExecutor public async Task SetBanPruneAsync(ulong guildId, int? pruneDays) { await using var ctx = _db.GetDbContext(); - await ctx.BanTemplates + await ctx.Set() .ToLinqToDBTable() .InsertOrUpdateAsync(() => new() { @@ -518,7 +518,7 @@ public class UserPunishService : INService, IReadyExecutor public async Task GetBanPruneAsync(ulong guildId) { await using var ctx = _db.GetDbContext(); - return await ctx.BanTemplates + return await ctx.Set() .Where(x => x.GuildId == guildId) .Select(x => x.PruneDays) .FirstOrDefaultAsyncLinqToDB(); @@ -552,19 +552,19 @@ public class UserPunishService : INService, IReadyExecutor banReason = string.IsNullOrWhiteSpace(banReason) ? "-" : banReason; var replacer = new ReplacementBuilder().WithServer(client, guild) - .WithOverride("%ban.mod%", () => moderator.ToString()) - .WithOverride("%ban.mod.fullname%", () => moderator.ToString()) - .WithOverride("%ban.mod.name%", () => moderator.Username) - .WithOverride("%ban.mod.discrim%", () => moderator.Discriminator) - .WithOverride("%ban.user%", () => target.ToString()) - .WithOverride("%ban.user.fullname%", () => target.ToString()) - .WithOverride("%ban.user.name%", () => target.Username) - .WithOverride("%ban.user.discrim%", () => target.Discriminator) - .WithOverride("%reason%", () => banReason) - .WithOverride("%ban.reason%", () => banReason) - .WithOverride("%ban.duration%", - () => duration?.ToString(@"d\.hh\:mm") ?? "perma") - .Build(); + .WithOverride("%ban.mod%", () => moderator.ToString()) + .WithOverride("%ban.mod.fullname%", () => moderator.ToString()) + .WithOverride("%ban.mod.name%", () => moderator.Username) + .WithOverride("%ban.mod.discrim%", () => moderator.Discriminator) + .WithOverride("%ban.user%", () => target.ToString()) + .WithOverride("%ban.user.fullname%", () => target.ToString()) + .WithOverride("%ban.user.name%", () => target.Username) + .WithOverride("%ban.user.discrim%", () => target.Discriminator) + .WithOverride("%reason%", () => banReason) + .WithOverride("%ban.reason%", () => banReason) + .WithOverride("%ban.duration%", + () => duration?.ToString(@"d\.hh\:mm") ?? "perma") + .Build(); // if template isn't set, use the old message style if (string.IsNullOrWhiteSpace(template)) diff --git a/src/Nadeko.Bot.Modules.Expresssions/NadekoExpressionsService.cs b/src/Nadeko.Bot.Modules.Expresssions/NadekoExpressionsService.cs index 1ed7a3e0c..f63630a2b 100644 --- a/src/Nadeko.Bot.Modules.Expresssions/NadekoExpressionsService.cs +++ b/src/Nadeko.Bot.Modules.Expresssions/NadekoExpressionsService.cs @@ -110,7 +110,7 @@ public sealed class NadekoExpressionsService : IExecOnMessage, IReadyExecutor private async Task ReloadInternal(IReadOnlyList allGuildIds) { await using var uow = _db.GetDbContext(); - var guildItems = await uow.Expressions.AsNoTracking() + var guildItems = await uow.Set().AsNoTracking() .Where(x => allGuildIds.Contains(x.GuildId.Value)) .ToListAsync(); @@ -124,14 +124,14 @@ public sealed class NadekoExpressionsService : IExecOnMessage, IReadyExecutor .ToArray()) .ToConcurrent(); - _disabledGlobalExpressionGuilds = new(await uow.GuildConfigs + _disabledGlobalExpressionGuilds = new(await uow.Set() .Where(x => x.DisableGlobalExpressions) .Select(x => x.GuildId) .ToListAsyncLinqToDB()); lock (_gexprWriteLock) { - var globalItems = uow.Expressions.AsNoTracking() + var globalItems = uow.Set().AsNoTracking() .Where(x => x.GuildId == null || x.GuildId == 0) .AsEnumerable() .Select(x => @@ -344,7 +344,7 @@ public sealed class NadekoExpressionsService : IExecOnMessage, IReadyExecutor { NadekoExpression expr; await using var uow = _db.GetDbContext(); - expr = uow.Expressions.GetById(id); + expr = uow.Set().GetById(id); if (expr is null) return; @@ -459,7 +459,7 @@ public sealed class NadekoExpressionsService : IExecOnMessage, IReadyExecutor NadekoExpression expr; await using (var uow = _db.GetDbContext()) { - expr = uow.Expressions.GetById(id); + expr = uow.Set().GetById(id); if (expr is null) return; @@ -477,7 +477,7 @@ public sealed class NadekoExpressionsService : IExecOnMessage, IReadyExecutor NadekoExpression expr; await using (var uow = _db.GetDbContext()) { - expr = uow.Expressions.GetById(id); + expr = uow.Set().GetById(id); if (expr is null || expr.GuildId != guildId) return (false, false); @@ -501,7 +501,7 @@ public sealed class NadekoExpressionsService : IExecOnMessage, IReadyExecutor public NadekoExpression GetExpression(ulong? guildId, int id) { using var uow = _db.GetDbContext(); - var expr = uow.Expressions.GetById(id); + var expr = uow.Set().GetById(id); if (expr is null || expr.GuildId != guildId) return null; @@ -511,7 +511,7 @@ public sealed class NadekoExpressionsService : IExecOnMessage, IReadyExecutor public int DeleteAllExpressions(ulong guildId) { using var uow = _db.GetDbContext(); - var count = uow.Expressions.ClearFromGuild(guildId); + var count = uow.Set().ClearFromGuild(guildId); uow.SaveChanges(); newguildExpressions.TryRemove(guildId, out _); @@ -569,7 +569,7 @@ public sealed class NadekoExpressionsService : IExecOnMessage, IReadyExecutor foreach (var entry in data) { var trigger = entry.Key; - await uow.Expressions.AddRangeAsync(entry.Value.Where(expr => !string.IsNullOrWhiteSpace(expr.Res)) + await uow.Set().AddRangeAsync(entry.Value.Where(expr => !string.IsNullOrWhiteSpace(expr.Res)) .Select(expr => new NadekoExpression { GuildId = guildId, @@ -658,7 +658,7 @@ public sealed class NadekoExpressionsService : IExecOnMessage, IReadyExecutor private async Task OnJoinedGuild(GuildConfig gc) { await using var uow = _db.GetDbContext(); - var exprs = await uow.Expressions.AsNoTracking().Where(x => x.GuildId == gc.GuildId).ToArrayAsync(); + var exprs = await uow.Set().AsNoTracking().Where(x => x.GuildId == gc.GuildId).ToArrayAsync(); newguildExpressions[gc.GuildId] = exprs; } @@ -682,7 +682,7 @@ public sealed class NadekoExpressionsService : IExecOnMessage, IReadyExecutor await using (var uow = _db.GetDbContext()) { - uow.Expressions.Add(expr); + uow.Set().Add(expr); await uow.SaveChangesAsync(); } @@ -694,7 +694,7 @@ public sealed class NadekoExpressionsService : IExecOnMessage, IReadyExecutor public async Task EditAsync(ulong? guildId, int id, string message) { await using var uow = _db.GetDbContext(); - var expr = uow.Expressions.GetById(id); + var expr = uow.Set().GetById(id); if (expr is null || expr.GuildId != guildId) return null; @@ -720,14 +720,14 @@ public sealed class NadekoExpressionsService : IExecOnMessage, IReadyExecutor public async Task DeleteAsync(ulong? guildId, int id) { await using var uow = _db.GetDbContext(); - var toDelete = uow.Expressions.GetById(id); + var toDelete = uow.Set().GetById(id); if (toDelete is null) return null; if ((toDelete.IsGlobal() && guildId is null) || guildId == toDelete.GuildId) { - uow.Expressions.Remove(toDelete); + uow.Set().Remove(toDelete); await uow.SaveChangesAsync(); await DeleteInternalAsync(guildId, id); return toDelete; diff --git a/src/Nadeko.Bot.Modules.Gambling/Gambling/Bank/BankService.cs b/src/Nadeko.Bot.Modules.Gambling/Gambling/Bank/BankService.cs index 67237d9b8..19e87812a 100644 --- a/src/Nadeko.Bot.Modules.Gambling/Gambling/Bank/BankService.cs +++ b/src/Nadeko.Bot.Modules.Gambling/Gambling/Bank/BankService.cs @@ -45,7 +45,7 @@ public sealed class BankService : IBankService, INService throw new ArgumentOutOfRangeException(nameof(amount)); await using var ctx = _db.GetDbContext(); - var rows = await ctx.BankUsers + var rows = await ctx.Set() .ToLinqToDBTable() .Where(x => x.UserId == userId && x.Balance >= amount) .UpdateAsync((old) => new() @@ -65,7 +65,7 @@ public sealed class BankService : IBankService, INService return false; await using var ctx = _db.GetDbContext(); - await ctx.BankUsers + await ctx.Set() .ToLinqToDBTable() .InsertOrUpdateAsync(() => new() { @@ -90,7 +90,7 @@ public sealed class BankService : IBankService, INService throw new ArgumentOutOfRangeException(nameof(amount)); await using var ctx = _db.GetDbContext(); - var rows = await ctx.BankUsers + var rows = await ctx.Set() .ToLinqToDBTable() .Where(x => x.UserId == userId && x.Balance >= amount) .UpdateAsync((old) => new() @@ -110,7 +110,7 @@ public sealed class BankService : IBankService, INService public async Task GetBalanceAsync(ulong userId) { await using var ctx = _db.GetDbContext(); - return (await ctx.BankUsers + return (await ctx.Set() .ToLinqToDBTable() .FirstOrDefaultAsync(x => x.UserId == userId)) ?.Balance diff --git a/src/Nadeko.Bot.Modules.Gambling/Gambling/CleanupCommands.cs b/src/Nadeko.Bot.Modules.Gambling/Gambling/CleanupCommands.cs new file mode 100644 index 000000000..2a13d98ff --- /dev/null +++ b/src/Nadeko.Bot.Modules.Gambling/Gambling/CleanupCommands.cs @@ -0,0 +1,39 @@ +using Nadeko.Bot.Modules.Gambling.Gambling._Common; + +namespace NadekoBot.Modules.Gambling; + +public partial class Gambling +{ + [Group] + public class CleanupCommands : CleanupModuleBase + { + private readonly IGamblingCleanupService _gcs; + + public CleanupCommands(IGamblingCleanupService gcs) + { + _gcs = gcs; + } + + [Cmd] + [OwnerOnly] + public Task DeleteWaifus() + => ConfirmActionInternalAsync("Delete Waifus", () => _gcs.DeleteWaifus()); + + [Cmd] + [OwnerOnly] + public async Task DeleteWaifu(IUser user) + => await DeleteWaifu(user.Id); + + [Cmd] + [OwnerOnly] + public Task DeleteWaifu(ulong userId) + => ConfirmActionInternalAsync($"Delete Waifu {userId}", () => _gcs.DeleteWaifu(userId)); + + + [Cmd] + [OwnerOnly] + public Task DeleteCurrency() + => ConfirmActionInternalAsync("Delete Currency", () => _gcs.DeleteCurrency()); + + } +} \ No newline at end of file diff --git a/src/Nadeko.Bot.Modules.Gambling/Gambling/Gambling.cs b/src/Nadeko.Bot.Modules.Gambling/Gambling/Gambling.cs index 5fc6dc089..3f71683cd 100644 --- a/src/Nadeko.Bot.Modules.Gambling/Gambling/Gambling.cs +++ b/src/Nadeko.Bot.Modules.Gambling/Gambling/Gambling.cs @@ -290,7 +290,7 @@ public partial class Gambling : GamblingModule List trs; await using (var uow = _db.GetDbContext()) { - trs = await uow.CurrencyTransactions.GetPageFor(userId, page); + trs = await uow.Set().GetPageFor(userId, page); } var embed = _eb.Create() @@ -332,7 +332,7 @@ public partial class Gambling : GamblingModule int intId = id; await using var uow = _db.GetDbContext(); - var tr = await uow.CurrencyTransactions.ToLinqToDBTable() + var tr = await uow.Set().ToLinqToDBTable() .Where(x => x.Id == intId && x.UserId == ctx.User.Id) .FirstOrDefaultAsync(); @@ -739,7 +739,7 @@ public partial class Gambling : GamblingModule { await using (var uow = _db.GetDbContext()) { - cleanRichest = uow.DiscordUser.GetTopRichest(_client.CurrentUser.Id, 10_000); + cleanRichest = uow.Set().GetTopRichest(_client.CurrentUser.Id, 10_000); } await ctx.Channel.TriggerTypingAsync(); @@ -751,7 +751,7 @@ public partial class Gambling : GamblingModule else { await using var uow = _db.GetDbContext(); - cleanRichest = uow.DiscordUser.GetTopRichest(_client.CurrentUser.Id, 9, page).ToList(); + cleanRichest = uow.Set().GetTopRichest(_client.CurrentUser.Id, 9, page).ToList(); } await ctx.SendPaginatedConfirmAsync(page, @@ -763,7 +763,7 @@ public partial class Gambling : GamblingModule if (!opts.Clean) { using var uow = _db.GetDbContext(); - toSend = uow.DiscordUser.GetTopRichest(_client.CurrentUser.Id, 9, curPage); + toSend = uow.Set().GetTopRichest(_client.CurrentUser.Id, 9, curPage); } else { diff --git a/src/Nadeko.Bot.Modules.Gambling/Gambling/GamblingService.cs b/src/Nadeko.Bot.Modules.Gambling/Gambling/GamblingService.cs index dbd796296..3d0a5e809 100644 --- a/src/Nadeko.Bot.Modules.Gambling/Gambling/GamblingService.cs +++ b/src/Nadeko.Bot.Modules.Gambling/Gambling/GamblingService.cs @@ -6,6 +6,7 @@ using NadekoBot.Db; using NadekoBot.Db.Models; using NadekoBot.Modules.Gambling.Common; using NadekoBot.Modules.Gambling.Common.Connect4; +using NadekoBot.Services.Database.Models; namespace NadekoBot.Modules.Gambling.Services; @@ -52,7 +53,7 @@ public class GamblingService : INService, IReadyExecutor var now = DateTime.UtcNow; var days = TimeSpan.FromDays(lifetime); await using var uow = _db.GetDbContext(); - await uow.CurrencyTransactions + await uow.Set() .DeleteAsync(ct => ct.DateAdded == null || now - ct.DateAdded < days); } catch (Exception ex) @@ -104,7 +105,7 @@ public class GamblingService : INService, IReadyExecutor maxDecay = int.MaxValue; var decay = (double)config.Decay.Percent; - await uow.DiscordUser + await uow.Set() .Where(x => x.CurrencyAmount > config.Decay.MinThreshold && x.UserId != _client.CurrentUser.Id) .UpdateAsync(old => new() { @@ -135,11 +136,11 @@ public class GamblingService : INService, IReadyExecutor async () => { await using var uow = _db.GetDbContext(); - var cash = uow.DiscordUser.GetTotalCurrency(); - var onePercent = uow.DiscordUser.GetTopOnePercentCurrency(_client.CurrentUser.Id); - decimal planted = uow.PlantedCurrency.AsQueryable().Sum(x => x.Amount); - var waifus = uow.WaifuInfo.GetTotalValue(); - var bot = await uow.DiscordUser.GetUserCurrencyAsync(_client.CurrentUser.Id); + var cash = uow.Set().GetTotalCurrency(); + var onePercent = uow.Set().GetTopOnePercentCurrency(_client.CurrentUser.Id); + decimal planted = uow.Set().AsQueryable().Sum(x => x.Amount); + var waifus = uow.Set().GetTotalValue(); + var bot = await uow.Set().GetUserCurrencyAsync(_client.CurrentUser.Id); decimal bank = await uow.GetTable() .SumAsyncLinqToDB(x => x.Balance); diff --git a/src/Nadeko.Bot.Modules.Gambling/Gambling/PlantPick/PlantPickService.cs b/src/Nadeko.Bot.Modules.Gambling/Gambling/PlantPick/PlantPickService.cs index f4b5c05d0..820cb6a11 100644 --- a/src/Nadeko.Bot.Modules.Gambling/Gambling/PlantPick/PlantPickService.cs +++ b/src/Nadeko.Bot.Modules.Gambling/Gambling/PlantPick/PlantPickService.cs @@ -100,7 +100,7 @@ public class PlantPickService : INService, IExecNoCommand public IEnumerable GetAllGeneratingChannels() { using var uow = _db.GetDbContext(); - var chs = uow.GuildConfigs.GetGeneratingChannels(); + var chs = uow.Set().GetGeneratingChannels(); return chs; } @@ -259,7 +259,7 @@ public class PlantPickService : INService, IExecNoCommand pass = pass?.Trim().TrimTo(10, true).ToUpperInvariant(); // gets all plants in this channel with the same password - var entries = uow.PlantedCurrency.AsQueryable() + var entries = uow.Set().AsQueryable() .Where(x => x.ChannelId == ch.Id && pass == x.Password) .ToList(); // sum how much currency that is, and get all of the message ids (so that i can delete them) @@ -371,7 +371,7 @@ public class PlantPickService : INService, IExecNoCommand string pass) { await using var uow = _db.GetDbContext(); - uow.PlantedCurrency.Add(new() + uow.Set().Add(new() { Amount = amount, GuildId = gid, diff --git a/src/Nadeko.Bot.Modules.Gambling/Gambling/Shop/ShopService.cs b/src/Nadeko.Bot.Modules.Gambling/Gambling/Shop/ShopService.cs index fc02df61a..7bd47d5a8 100644 --- a/src/Nadeko.Bot.Modules.Gambling/Gambling/Shop/ShopService.cs +++ b/src/Nadeko.Bot.Modules.Gambling/Gambling/Shop/ShopService.cs @@ -13,7 +13,7 @@ public class ShopService : IShopService, INService public ShopService(DbService db) => _db = db; - private IndexedCollection GetEntriesInternal(NadekoContext uow, ulong guildId) + private IndexedCollection GetEntriesInternal(DbContext uow, ulong guildId) => uow.GuildConfigsForId(guildId, set => set.Include(x => x.ShopEntries).ThenInclude(x => x.Items)) .ShopEntries.ToIndexed(); diff --git a/src/Nadeko.Bot.Modules.Gambling/Gambling/Waifus/WaifuService.cs b/src/Nadeko.Bot.Modules.Gambling/Gambling/Waifus/WaifuService.cs index 319f42111..4f36d8b88 100644 --- a/src/Nadeko.Bot.Modules.Gambling/Gambling/Waifus/WaifuService.cs +++ b/src/Nadeko.Bot.Modules.Gambling/Gambling/Waifus/WaifuService.cs @@ -44,7 +44,7 @@ public class WaifuService : INService, IReadyExecutor var settings = _gss.Data; await using var uow = _db.GetDbContext(); - var waifu = uow.WaifuInfo.ByWaifuUserId(waifuId); + var waifu = uow.Set().ByWaifuUserId(waifuId); var ownerUser = uow.GetOrCreateUser(owner); // owner has to be the owner of the waifu @@ -85,14 +85,14 @@ public class WaifuService : INService, IReadyExecutor { var settings = _gss.Data; using var uow = _db.GetDbContext(); - var waifu = uow.WaifuInfo.ByWaifuUserId(user.Id); + var waifu = uow.Set().ByWaifuUserId(user.Id); if (waifu is null) return settings.Waifu.MinPrice; - var divorces = uow.WaifuUpdates.Count(x + var divorces = uow.Set().Count(x => x.Old != null && x.Old.UserId == user.Id && x.UpdateType == WaifuUpdateType.Claimed && x.New == null); - var affs = uow.WaifuUpdates.AsQueryable() + var affs = uow.Set().AsQueryable() .Where(w => w.User.UserId == user.Id && w.UpdateType == WaifuUpdateType.AffinityChanged && w.New != null) @@ -111,22 +111,22 @@ public class WaifuService : INService, IReadyExecutor if (!await _cs.RemoveAsync(user.Id, price, new("waifu", "reset"))) return false; - var affs = uow.WaifuUpdates.AsQueryable() + var affs = uow.Set().AsQueryable() .Where(w => w.User.UserId == user.Id && w.UpdateType == WaifuUpdateType.AffinityChanged && w.New != null); - var divorces = uow.WaifuUpdates.AsQueryable() + var divorces = uow.Set().AsQueryable() .Where(x => x.Old != null && x.Old.UserId == user.Id && x.UpdateType == WaifuUpdateType.Claimed && x.New == null); //reset changes of heart to 0 - uow.WaifuUpdates.RemoveRange(affs); + uow.Set().RemoveRange(affs); //reset divorces to 0 - uow.WaifuUpdates.RemoveRange(divorces); - var waifu = uow.WaifuInfo.ByWaifuUserId(user.Id); + uow.Set().RemoveRange(divorces); + var waifu = uow.Set().ByWaifuUserId(user.Id); //reset price, remove items //remove owner, remove affinity waifu.Price = 50; @@ -149,7 +149,7 @@ public class WaifuService : INService, IReadyExecutor bool isAffinity; await using (var uow = _db.GetDbContext()) { - w = uow.WaifuInfo.ByWaifuUserId(target.Id); + w = uow.Set().ByWaifuUserId(target.Id); isAffinity = w?.Affinity?.UserId == user.Id; if (w is null) { @@ -159,14 +159,14 @@ public class WaifuService : INService, IReadyExecutor result = WaifuClaimResult.NotEnoughFunds; else { - uow.WaifuInfo.Add(w = new() + uow.Set().Add(w = new() { Waifu = waifu, Claimer = claimer, Affinity = null, Price = amount }); - uow.WaifuUpdates.Add(new() + uow.Set().Add(new() { User = waifu, Old = null, @@ -187,7 +187,7 @@ public class WaifuService : INService, IReadyExecutor w.Price = amount + (amount / 4); result = WaifuClaimResult.Success; - uow.WaifuUpdates.Add(new() + uow.Set().Add(new() { User = w.Waifu, Old = oldClaimer, @@ -207,7 +207,7 @@ public class WaifuService : INService, IReadyExecutor w.Price = amount; result = WaifuClaimResult.Success; - uow.WaifuUpdates.Add(new() + uow.Set().Add(new() { User = w.Waifu, Old = oldClaimer, @@ -233,7 +233,7 @@ public class WaifuService : INService, IReadyExecutor TimeSpan? remaining = null; await using (var uow = _db.GetDbContext()) { - var w = uow.WaifuInfo.ByWaifuUserId(user.Id); + var w = uow.Set().ByWaifuUserId(user.Id); var newAff = target is null ? null : uow.GetOrCreateUser(target); if (w?.Affinity?.UserId == target?.Id) { @@ -249,7 +249,7 @@ public class WaifuService : INService, IReadyExecutor else if (w is null) { var thisUser = uow.GetOrCreateUser(user); - uow.WaifuInfo.Add(new() + uow.Set().Add(new() { Affinity = newAff, Waifu = thisUser, @@ -258,7 +258,7 @@ public class WaifuService : INService, IReadyExecutor }); success = true; - uow.WaifuUpdates.Add(new() + uow.Set().Add(new() { User = thisUser, Old = null, @@ -273,7 +273,7 @@ public class WaifuService : INService, IReadyExecutor w.Affinity = newAff; success = true; - uow.WaifuUpdates.Add(new() + uow.Set().Add(new() { User = w.Waifu, Old = oldAff, @@ -291,13 +291,13 @@ public class WaifuService : INService, IReadyExecutor public IEnumerable GetTopWaifusAtPage(int page) { using var uow = _db.GetDbContext(); - return uow.WaifuInfo.GetTop(9, page * 9); + return uow.Set().GetTop(9, page * 9); } public ulong GetWaifuUserId(ulong ownerId, string name) { using var uow = _db.GetDbContext(); - return uow.WaifuInfo.GetWaifuUserId(ownerId, name); + return uow.Set().GetWaifuUserId(ownerId, name); } private static TypedKey GetDivorceKey(ulong userId) @@ -314,7 +314,7 @@ public class WaifuService : INService, IReadyExecutor WaifuInfo w; await using (var uow = _db.GetDbContext()) { - w = uow.WaifuInfo.ByWaifuUserId(targetId); + w = uow.Set().ByWaifuUserId(targetId); if (w?.Claimer is null || w.Claimer.UserId != user.Id) result = DivorceResult.NotYourWife; else @@ -344,7 +344,7 @@ public class WaifuService : INService, IReadyExecutor var oldClaimer = w.Claimer; w.Claimer = null; - uow.WaifuUpdates.Add(new() + uow.Set().Add(new() { User = w.Waifu, Old = oldClaimer, @@ -365,10 +365,10 @@ public class WaifuService : INService, IReadyExecutor return false; await using var uow = _db.GetDbContext(); - var w = uow.WaifuInfo.ByWaifuUserId(giftedWaifu.Id, set => set.Include(x => x.Items).Include(x => x.Claimer)); + var w = uow.Set().ByWaifuUserId(giftedWaifu.Id, set => set.Include(x => x.Items).Include(x => x.Claimer)); if (w is null) { - uow.WaifuInfo.Add(w = new() + uow.Set().Add(w = new() { Affinity = null, Claimer = null, diff --git a/src/Nadeko.Bot.Db/Models/Waifu.cs b/src/Nadeko.Bot.Modules.Gambling/Gambling/Waifus/db/Waifu.cs similarity index 59% rename from src/Nadeko.Bot.Db/Models/Waifu.cs rename to src/Nadeko.Bot.Modules.Gambling/Gambling/Waifus/db/Waifu.cs index 0705f7992..80c0429a4 100644 --- a/src/Nadeko.Bot.Db/Models/Waifu.cs +++ b/src/Nadeko.Bot.Modules.Gambling/Gambling/Waifus/db/Waifu.cs @@ -16,18 +16,4 @@ public class WaifuInfo : DbEntity public long Price { get; set; } public List Items { get; set; } = new(); -} - -public class WaifuLbResult -{ - public string Username { get; set; } - public string Discrim { get; set; } - - public string Claimer { get; set; } - public string ClaimerDiscrim { get; set; } - - public string Affinity { get; set; } - public string AffinityDiscrim { get; set; } - - public long Price { get; set; } } \ No newline at end of file diff --git a/src/Nadeko.Bot.Db/Extensions/WaifuExtensions.cs b/src/Nadeko.Bot.Modules.Gambling/Gambling/Waifus/db/WaifuExtensions.cs similarity index 94% rename from src/Nadeko.Bot.Db/Extensions/WaifuExtensions.cs rename to src/Nadeko.Bot.Modules.Gambling/Gambling/Waifus/db/WaifuExtensions.cs index 0abb578a4..aafb09c31 100644 --- a/src/Nadeko.Bot.Db/Extensions/WaifuExtensions.cs +++ b/src/Nadeko.Bot.Modules.Gambling/Gambling/Waifus/db/WaifuExtensions.cs @@ -8,18 +8,6 @@ using NadekoBot.Services.Database.Models; namespace NadekoBot.Db; -public class WaifuInfoStats -{ - public int WaifuId { get; init; } - public string FullName { get; init; } - public long Price { get; init; } - public string ClaimerName { get; init; } - public string AffinityName { get; init; } - public int AffinityCount { get; init; } - public int DivorceCount { get; init; } - public int ClaimCount { get; init; } -} - public static class WaifuExtensions { public static WaifuInfo ByWaifuUserId( diff --git a/src/Nadeko.Bot.Modules.Gambling/Gambling/Waifus/db/WaifuInfoStats.cs b/src/Nadeko.Bot.Modules.Gambling/Gambling/Waifus/db/WaifuInfoStats.cs new file mode 100644 index 000000000..5060fa7ac --- /dev/null +++ b/src/Nadeko.Bot.Modules.Gambling/Gambling/Waifus/db/WaifuInfoStats.cs @@ -0,0 +1,14 @@ +#nullable disable +namespace NadekoBot.Db; + +public class WaifuInfoStats +{ + public int WaifuId { get; init; } + public string FullName { get; init; } + public long Price { get; init; } + public string ClaimerName { get; init; } + public string AffinityName { get; init; } + public int AffinityCount { get; init; } + public int DivorceCount { get; init; } + public int ClaimCount { get; init; } +} \ No newline at end of file diff --git a/src/Nadeko.Bot.Db/Models/WaifuItem.cs b/src/Nadeko.Bot.Modules.Gambling/Gambling/Waifus/db/WaifuItem.cs similarity index 100% rename from src/Nadeko.Bot.Db/Models/WaifuItem.cs rename to src/Nadeko.Bot.Modules.Gambling/Gambling/Waifus/db/WaifuItem.cs diff --git a/src/Nadeko.Bot.Modules.Gambling/Gambling/Waifus/db/WaifuLbResult.cs b/src/Nadeko.Bot.Modules.Gambling/Gambling/Waifus/db/WaifuLbResult.cs new file mode 100644 index 000000000..0bfe14b4f --- /dev/null +++ b/src/Nadeko.Bot.Modules.Gambling/Gambling/Waifus/db/WaifuLbResult.cs @@ -0,0 +1,16 @@ +#nullable disable +namespace NadekoBot.Services.Database.Models; + +public class WaifuLbResult +{ + public string Username { get; set; } + public string Discrim { get; set; } + + public string Claimer { get; set; } + public string ClaimerDiscrim { get; set; } + + public string Affinity { get; set; } + public string AffinityDiscrim { get; set; } + + public long Price { get; set; } +} \ No newline at end of file diff --git a/src/Nadeko.Bot.Db/Models/WaifuUpdate.cs b/src/Nadeko.Bot.Modules.Gambling/Gambling/Waifus/db/WaifuUpdate.cs similarity index 86% rename from src/Nadeko.Bot.Db/Models/WaifuUpdate.cs rename to src/Nadeko.Bot.Modules.Gambling/Gambling/Waifus/db/WaifuUpdate.cs index f5558e371..357127bb4 100644 --- a/src/Nadeko.Bot.Db/Models/WaifuUpdate.cs +++ b/src/Nadeko.Bot.Modules.Gambling/Gambling/Waifus/db/WaifuUpdate.cs @@ -14,10 +14,4 @@ public class WaifuUpdate : DbEntity public int? NewId { get; set; } public DiscordUser New { get; set; } -} - -public enum WaifuUpdateType -{ - AffinityChanged, - Claimed } \ No newline at end of file diff --git a/src/Nadeko.Bot.Modules.Gambling/Gambling/Waifus/db/WaifuUpdateType.cs b/src/Nadeko.Bot.Modules.Gambling/Gambling/Waifus/db/WaifuUpdateType.cs new file mode 100644 index 000000000..e5f9f7f1a --- /dev/null +++ b/src/Nadeko.Bot.Modules.Gambling/Gambling/Waifus/db/WaifuUpdateType.cs @@ -0,0 +1,8 @@ +#nullable disable +namespace NadekoBot.Services.Database.Models; + +public enum WaifuUpdateType +{ + AffinityChanged, + Claimed +} \ No newline at end of file diff --git a/src/Nadeko.Bot.Modules.Gambling/Gambling/_Common/IGamblingCleanupService.cs b/src/Nadeko.Bot.Modules.Gambling/Gambling/_Common/IGamblingCleanupService.cs new file mode 100644 index 000000000..07318422e --- /dev/null +++ b/src/Nadeko.Bot.Modules.Gambling/Gambling/_Common/IGamblingCleanupService.cs @@ -0,0 +1,67 @@ +using LinqToDB; +using NadekoBot.Db.Models; +using NadekoBot.Services.Database.Models; + +namespace Nadeko.Bot.Modules.Gambling.Gambling._Common; + +public interface IGamblingCleanupService +{ + Task DeleteWaifus(); + Task DeleteWaifu(ulong userId); + Task DeleteCurrency(); +} + +public class GamblingCleanupService : IGamblingCleanupService +{ + private readonly DbService _db; + + public GamblingCleanupService(DbService db) + { + _db = db; + } + + public async Task DeleteWaifus() + { + await using var ctx = _db.GetDbContext(); + await ctx.Set().DeleteAsync(); + await ctx.Set().DeleteAsync(); + await ctx.Set().DeleteAsync(); + await ctx.SaveChangesAsync(); + } + + public async Task DeleteWaifu(ulong userId) + { + await using var ctx = _db.GetDbContext(); + await ctx.Set() + .Where(x => x.User.UserId == userId) + .DeleteAsync(); + await ctx.Set() + .Where(x => x.WaifuInfo.Waifu.UserId == userId) + .DeleteAsync(); + await ctx.Set() + .Where(x => x.Claimer.UserId == userId) + .UpdateAsync(old => new WaifuInfo() + { + ClaimerId = null, + }); + await ctx.Set() + .Where(x => x.Waifu.UserId == userId) + .DeleteAsync(); + await ctx.SaveChangesAsync(); + } + + public async Task DeleteCurrency() + { + await using var uow = _db.GetDbContext(); + await uow.Set().UpdateAsync(_ => new DiscordUser() + { + CurrencyAmount = 0 + }); + + await uow.Set().DeleteAsync(); + await uow.Set().DeleteAsync(); + await uow.Set().DeleteAsync(); + await uow.SaveChangesAsync(); + } + +} \ No newline at end of file diff --git a/src/Nadeko.Bot.Modules.Gambling/Gambling/_Common/TypeReaders/BaseShmartInputAmountReader.cs b/src/Nadeko.Bot.Modules.Gambling/Gambling/_Common/TypeReaders/BaseShmartInputAmountReader.cs index 972714004..f6beb1c7b 100644 --- a/src/Nadeko.Bot.Modules.Gambling/Gambling/_Common/TypeReaders/BaseShmartInputAmountReader.cs +++ b/src/Nadeko.Bot.Modules.Gambling/Gambling/_Common/TypeReaders/BaseShmartInputAmountReader.cs @@ -1,5 +1,6 @@ using System.Text.RegularExpressions; using NadekoBot.Db; +using NadekoBot.Db.Models; using NadekoBot.Modules.Gambling.Services; using NCalc; using OneOf; @@ -69,7 +70,7 @@ public class BaseShmartInputAmountReader protected virtual async Task Cur(ICommandContext ctx) { await using var uow = _db.GetDbContext(); - return await uow.DiscordUser.GetUserCurrencyAsync(ctx.User.Id); + return await uow.Set().GetUserCurrencyAsync(ctx.User.Id); } protected virtual async Task Max(ICommandContext ctx) diff --git a/src/Nadeko.Bot.Modules.Gambling/Games/ChatterBot/CleverBotCommands.cs b/src/Nadeko.Bot.Modules.Gambling/Games/ChatterBot/CleverBotCommands.cs index e90bdc127..3265529e2 100644 --- a/src/Nadeko.Bot.Modules.Gambling/Games/ChatterBot/CleverBotCommands.cs +++ b/src/Nadeko.Bot.Modules.Gambling/Games/ChatterBot/CleverBotCommands.cs @@ -1,6 +1,7 @@ #nullable disable using NadekoBot.Db; using NadekoBot.Modules.Games.Services; +using NadekoBot.Services.Database.Models; namespace NadekoBot.Modules.Games; @@ -25,7 +26,7 @@ public partial class Games { await using (var uow = _db.GetDbContext()) { - uow.GuildConfigs.SetCleverbotEnabled(ctx.Guild.Id, false); + uow.Set().SetCleverbotEnabled(ctx.Guild.Id, false); await uow.SaveChangesAsync(); } @@ -37,7 +38,7 @@ public partial class Games await using (var uow = _db.GetDbContext()) { - uow.GuildConfigs.SetCleverbotEnabled(ctx.Guild.Id, true); + uow.Set().SetCleverbotEnabled(ctx.Guild.Id, true); await uow.SaveChangesAsync(); } diff --git a/src/Nadeko.Bot.Modules.Gambling/Nadeko.Bot.Modules.Gambling.csproj b/src/Nadeko.Bot.Modules.Gambling/Nadeko.Bot.Modules.Gambling.csproj index ff82a6739..8a68d457f 100644 --- a/src/Nadeko.Bot.Modules.Gambling/Nadeko.Bot.Modules.Gambling.csproj +++ b/src/Nadeko.Bot.Modules.Gambling/Nadeko.Bot.Modules.Gambling.csproj @@ -18,4 +18,5 @@ + diff --git a/src/Nadeko.Bot.Modules.Music/CleanupCommands.cs b/src/Nadeko.Bot.Modules.Music/CleanupCommands.cs new file mode 100644 index 000000000..1a2a847ee --- /dev/null +++ b/src/Nadeko.Bot.Modules.Music/CleanupCommands.cs @@ -0,0 +1,24 @@ +using LinqToDB; +using NadekoBot.Services.Database.Models; + +namespace NadekoBot.Modules.Music; + +public sealed partial class Music +{ + public class CleanupCommands : NadekoModule + { + private readonly DbService _db; + + public CleanupCommands(DbService db) + { + _db = db; + } + + public async Task DeletePlaylists() + { + await using var uow = _db.GetDbContext(); + await uow.Set().DeleteAsync(); + await uow.SaveChangesAsync(); + } + } +} \ No newline at end of file diff --git a/src/Nadeko.Bot.Modules.Music/Nadeko.Bot.Modules.Music.csproj b/src/Nadeko.Bot.Modules.Music/Nadeko.Bot.Modules.Music.csproj index 2e2dfd4c1..eab0fce08 100644 --- a/src/Nadeko.Bot.Modules.Music/Nadeko.Bot.Modules.Music.csproj +++ b/src/Nadeko.Bot.Modules.Music/Nadeko.Bot.Modules.Music.csproj @@ -18,4 +18,5 @@ + diff --git a/src/Nadeko.Bot.Modules.Music/PlaylistCommands.cs b/src/Nadeko.Bot.Modules.Music/PlaylistCommands.cs index 684666482..7f41570d8 100644 --- a/src/Nadeko.Bot.Modules.Music/PlaylistCommands.cs +++ b/src/Nadeko.Bot.Modules.Music/PlaylistCommands.cs @@ -46,7 +46,7 @@ public sealed partial class Music await using (var uow = _db.GetDbContext()) { - playlists = uow.MusicPlaylists.GetPlaylistsOnPage(num); + playlists = uow.Set().GetPlaylistsOnPage(num); } var embed = _eb.Create(ctx) @@ -66,13 +66,13 @@ public sealed partial class Music try { await using var uow = _db.GetDbContext(); - var pl = uow.MusicPlaylists.FirstOrDefault(x => x.Id == id); + var pl = uow.Set().FirstOrDefault(x => x.Id == id); if (pl is not null) { if (_creds.IsOwner(ctx.User) || pl.AuthorId == ctx.User.Id) { - uow.MusicPlaylists.Remove(pl); + uow.Set().Remove(pl); await uow.SaveChangesAsync(); success = true; } @@ -99,7 +99,7 @@ public sealed partial class Music MusicPlaylist mpl; await using (var uow = _db.GetDbContext()) { - mpl = uow.MusicPlaylists.GetWithSongs(id); + mpl = uow.Set().GetWithSongs(id); } await ctx.SendPaginatedConfirmAsync(page, @@ -146,7 +146,7 @@ public sealed partial class Music AuthorId = ctx.User.Id, Songs = songs.ToList() }; - uow.MusicPlaylists.Add(playlist); + uow.Set().Add(playlist); await uow.SaveChangesAsync(); } @@ -195,7 +195,7 @@ public sealed partial class Music MusicPlaylist mpl; await using (var uow = _db.GetDbContext()) { - mpl = uow.MusicPlaylists.GetWithSongs(id); + mpl = uow.Set().GetWithSongs(id); } if (mpl is null) diff --git a/src/Nadeko.Bot.Modules.Music/Services/MusicService.cs b/src/Nadeko.Bot.Modules.Music/Services/MusicService.cs index cb49cf0c5..968fd635f 100644 --- a/src/Nadeko.Bot.Modules.Music/Services/MusicService.cs +++ b/src/Nadeko.Bot.Modules.Music/Services/MusicService.cs @@ -331,7 +331,7 @@ public sealed class MusicService : IMusicService return settings; await using var uow = _db.GetDbContext(); - var toReturn = _settings[guildId] = await uow.MusicPlayerSettings.ForGuildAsync(guildId); + var toReturn = _settings[guildId] = await uow.Set().ForGuildAsync(guildId); await uow.SaveChangesAsync(); return toReturn; @@ -343,7 +343,7 @@ public sealed class MusicService : IMusicService TState state) { await using var uow = _db.GetDbContext(); - var ms = await uow.MusicPlayerSettings.ForGuildAsync(guildId); + var ms = await uow.Set().ForGuildAsync(guildId); action(ms, state); await uow.SaveChangesAsync(); _settings[guildId] = ms; @@ -431,7 +431,7 @@ public sealed class MusicService : IMusicService public async Task GetMusicQualityAsync(ulong guildId) { await using var uow = _db.GetDbContext(); - var settings = await uow.MusicPlayerSettings.ForGuildAsync(guildId); + var settings = await uow.Set().ForGuildAsync(guildId); return settings.QualityPreset; } diff --git a/src/Nadeko.Bot.Db/Extensions/MusicPlayerSettingsExtensions.cs b/src/Nadeko.Bot.Modules.Music/_Common/db/MusicPlayerSettingsExtensions.cs similarity index 100% rename from src/Nadeko.Bot.Db/Extensions/MusicPlayerSettingsExtensions.cs rename to src/Nadeko.Bot.Modules.Music/_Common/db/MusicPlayerSettingsExtensions.cs diff --git a/src/Nadeko.Bot.Db/Models/MusicPlaylist.cs b/src/Nadeko.Bot.Modules.Music/_Common/db/MusicPlaylist.cs similarity index 100% rename from src/Nadeko.Bot.Db/Models/MusicPlaylist.cs rename to src/Nadeko.Bot.Modules.Music/_Common/db/MusicPlaylist.cs diff --git a/src/Nadeko.Bot.Db/Extensions/MusicPlaylistExtensions.cs b/src/Nadeko.Bot.Modules.Music/_Common/db/MusicPlaylistExtensions.cs similarity index 100% rename from src/Nadeko.Bot.Db/Extensions/MusicPlaylistExtensions.cs rename to src/Nadeko.Bot.Modules.Music/_Common/db/MusicPlaylistExtensions.cs diff --git a/src/Nadeko.Bot.Db/Models/MusicSettings.cs b/src/Nadeko.Bot.Modules.Music/_Common/db/MusicSettings.cs similarity index 100% rename from src/Nadeko.Bot.Db/Models/MusicSettings.cs rename to src/Nadeko.Bot.Modules.Music/_Common/db/MusicSettings.cs diff --git a/src/Nadeko.Bot.Modules.Permisssions/PermissionsService.cs b/src/Nadeko.Bot.Modules.Permisssions/PermissionsService.cs index 532384cc0..93fed41eb 100644 --- a/src/Nadeko.Bot.Modules.Permisssions/PermissionsService.cs +++ b/src/Nadeko.Bot.Modules.Permisssions/PermissionsService.cs @@ -32,7 +32,7 @@ public class PermissionService : IExecPreCommand, INService _eb = eb; using var uow = _db.GetDbContext(); - foreach (var x in uow.GuildConfigs.PermissionsForAll(client.Guilds.ToArray().Select(x => x.Id).ToList())) + foreach (var x in uow.Set().PermissionsForAll(client.Guilds.ToArray().Select(x => x.Id).ToList())) { Cache.TryAdd(x.GuildId, new() diff --git a/src/Nadeko.Bot.Modules.Searches/Feeds/FeedsService.cs b/src/Nadeko.Bot.Modules.Searches/Feeds/FeedsService.cs index d14c2ceee..22c31c10c 100644 --- a/src/Nadeko.Bot.Modules.Searches/Feeds/FeedsService.cs +++ b/src/Nadeko.Bot.Modules.Searches/Feeds/FeedsService.cs @@ -30,14 +30,15 @@ public class FeedsService : INService using (var uow = db.GetDbContext()) { var guildConfigIds = bot.AllGuildConfigs.Select(x => x.Id).ToList(); - _subs = uow.GuildConfigs.AsQueryable() - .Where(x => guildConfigIds.Contains(x.Id)) - .Include(x => x.FeedSubs) - .ToList() - .SelectMany(x => x.FeedSubs) - .GroupBy(x => x.Url.ToLower()) - .ToDictionary(x => x.Key, x => x.ToList()) - .ToConcurrent(); + _subs = uow.Set() + .AsQueryable() + .Where(x => guildConfigIds.Contains(x.Id)) + .Include(x => x.FeedSubs) + .ToList() + .SelectMany(x => x.FeedSubs) + .GroupBy(x => x.Url.ToLower()) + .ToDictionary(x => x.Key, x => x.ToList()) + .ToConcurrent(); } _client = client; @@ -60,8 +61,8 @@ public class FeedsService : INService // remove from db await using var ctx = _db.GetDbContext(); await ctx.GetTable() - .DeleteAsync(x => ids.Contains(x.Id)); - + .DeleteAsync(x => ids.Contains(x.Id)); + // remove from the local cache _subs.TryRemove(url, out _); @@ -94,14 +95,14 @@ public class FeedsService : INService var feed = await FeedReader.ReadAsync(rssUrl); var items = feed - .Items.Select(item => (Item: item, - LastUpdate: item.PublishingDate?.ToUniversalTime() - ?? (item.SpecificItem as AtomFeedItem)?.UpdatedDate?.ToUniversalTime())) - .Where(data => data.LastUpdate is not null) - .Select(data => (data.Item, LastUpdate: (DateTime)data.LastUpdate)) - .OrderByDescending(data => data.LastUpdate) - .Reverse() // start from the oldest - .ToList(); + .Items.Select(item => (Item: item, + LastUpdate: item.PublishingDate?.ToUniversalTime() + ?? (item.SpecificItem as AtomFeedItem)?.UpdatedDate?.ToUniversalTime())) + .Where(data => data.LastUpdate is not null) + .Select(data => (data.Item, LastUpdate: (DateTime)data.LastUpdate)) + .OrderByDescending(data => data.LastUpdate) + .Reverse() // start from the oldest + .ToList(); if (!_lastPosts.TryGetValue(kvp.Key, out var lastFeedUpdate)) { @@ -140,12 +141,12 @@ public class FeedsService : INService if (!gotImage && feedItem.SpecificItem is AtomFeedItem afi) { var previewElement = afi.Element.Elements() - .FirstOrDefault(x => x.Name.LocalName == "preview"); + .FirstOrDefault(x => x.Name.LocalName == "preview"); if (previewElement is null) { previewElement = afi.Element.Elements() - .FirstOrDefault(x => x.Name.LocalName == "thumbnail"); + .FirstOrDefault(x => x.Name.LocalName == "thumbnail"); } if (previewElement is not null) @@ -184,7 +185,7 @@ public class FeedsService : INService catch (Exception ex) { var errorCount = await AddError(rssUrl, kvp.Value.Select(x => x.Id).ToList()); - + Log.Warning("An error occured while getting rss stream ({ErrorCount} / 100) {RssFeed}" + "\n {Message}", errorCount, @@ -201,8 +202,8 @@ public class FeedsService : INService { using var uow = _db.GetDbContext(); return uow.GuildConfigsForId(guildId, set => set.Include(x => x.FeedSubs)) - .FeedSubs.OrderBy(x => x.Id) - .ToList(); + .FeedSubs.OrderBy(x => x.Id) + .ToList(); } public FeedAddResult AddFeed(ulong guildId, ulong channelId, string rssFeed, string message) @@ -250,8 +251,8 @@ public class FeedsService : INService using var uow = _db.GetDbContext(); var items = uow.GuildConfigsForId(guildId, set => set.Include(x => x.FeedSubs)) - .FeedSubs.OrderBy(x => x.Id) - .ToList(); + .FeedSubs.OrderBy(x => x.Id) + .ToList(); if (items.Count <= index) return false; diff --git a/src/Nadeko.Bot.Modules.Searches/StreamNotification/StreamNotificationService.cs b/src/Nadeko.Bot.Modules.Searches/StreamNotification/StreamNotificationService.cs index a755d3235..7503cc52f 100644 --- a/src/Nadeko.Bot.Modules.Searches/StreamNotification/StreamNotificationService.cs +++ b/src/Nadeko.Bot.Modules.Searches/StreamNotification/StreamNotificationService.cs @@ -321,7 +321,7 @@ public sealed class StreamNotificationService : INService, IReadyExecutor { using (var uow = _db.GetDbContext()) { - var gc = uow.GuildConfigs.AsQueryable() + var gc = uow.Set().AsQueryable() .Include(x => x.FollowedStreams) .FirstOrDefault(x => x.GuildId == guildConfig.GuildId); diff --git a/src/Nadeko.Bot.Modules.Searches/Translate/TranslateService.cs b/src/Nadeko.Bot.Modules.Searches/Translate/TranslateService.cs index 8fb6f60e4..f920b17e0 100644 --- a/src/Nadeko.Bot.Modules.Searches/Translate/TranslateService.cs +++ b/src/Nadeko.Bot.Modules.Searches/Translate/TranslateService.cs @@ -36,7 +36,7 @@ public sealed class TranslateService : ITranslateService, IExecNoCommand, IReady await using (var ctx = _db.GetDbContext()) { var guilds = _bot.AllGuildConfigs.Select(x => x.GuildId).ToList(); - cs = await ctx.AutoTranslateChannels.Include(x => x.Users) + cs = await ctx.Set().Include(x => x.Users) .Where(x => guilds.Contains(x.GuildId)) .ToListAsyncEF(); } @@ -108,12 +108,12 @@ public sealed class TranslateService : ITranslateService, IExecNoCommand, IReady { await using var ctx = _db.GetDbContext(); - var old = await ctx.AutoTranslateChannels.ToLinqToDBTable() + var old = await ctx.Set().ToLinqToDBTable() .FirstOrDefaultAsyncLinqToDB(x => x.ChannelId == channelId); if (old is null) { - ctx.AutoTranslateChannels.Add(new() + ctx.Set().Add(new() { GuildId = guildId, ChannelId = channelId, @@ -138,7 +138,7 @@ public sealed class TranslateService : ITranslateService, IExecNoCommand, IReady return true; } - await ctx.AutoTranslateChannels.ToLinqToDBTable().DeleteAsync(x => x.ChannelId == channelId); + await ctx.Set().ToLinqToDBTable().DeleteAsync(x => x.ChannelId == channelId); await ctx.SaveChangesAsync(); _atcs.TryRemove(channelId, out _); @@ -168,7 +168,7 @@ public sealed class TranslateService : ITranslateService, IExecNoCommand, IReady return null; await using var ctx = _db.GetDbContext(); - var ch = await ctx.AutoTranslateChannels.GetByChannelId(channelId); + var ch = await ctx.Set().GetByChannelId(channelId); if (ch is null) return null; @@ -210,7 +210,7 @@ public sealed class TranslateService : ITranslateService, IExecNoCommand, IReady public async Task UnregisterUser(ulong channelId, ulong userId) { await using var ctx = _db.GetDbContext(); - var rows = await ctx.AutoTranslateUsers.ToLinqToDBTable() + var rows = await ctx.Set().ToLinqToDBTable() .DeleteAsync(x => x.UserId == userId && x.Channel.ChannelId == channelId); if (_users.TryGetValue(channelId, out var inner)) diff --git a/src/Nadeko.Bot.Modules.Utility/Quote/QuoteCommands.cs b/src/Nadeko.Bot.Modules.Utility/Quote/QuoteCommands.cs index f2290a59b..b820acaae 100644 --- a/src/Nadeko.Bot.Modules.Utility/Quote/QuoteCommands.cs +++ b/src/Nadeko.Bot.Modules.Utility/Quote/QuoteCommands.cs @@ -62,7 +62,7 @@ public partial class Utility IEnumerable quotes; await using (var uow = _db.GetDbContext()) { - quotes = uow.Quotes.GetGroup(ctx.Guild.Id, page, order); + quotes = uow.Set().GetGroup(ctx.Guild.Id, page, order); } if (quotes.Any()) @@ -88,7 +88,7 @@ public partial class Utility Quote quote; await using (var uow = _db.GetDbContext()) { - quote = await uow.Quotes.GetRandomQuoteByKeywordAsync(ctx.Guild.Id, keyword); + quote = await uow.Set().GetRandomQuoteByKeywordAsync(ctx.Guild.Id, keyword); //if (quote is not null) //{ // quote.UseCount += 1; @@ -114,7 +114,7 @@ public partial class Utility Quote? quote; await using (var uow = _db.GetDbContext()) { - quote = uow.Quotes.GetById(id); + quote = uow.Set().GetById(id); if (quote?.GuildId != ctx.Guild.Id) quote = null; } @@ -148,7 +148,7 @@ public partial class Utility Quote quote; await using (var uow = _db.GetDbContext()) { - quote = await uow.Quotes.SearchQuoteKeywordTextAsync(ctx.Guild.Id, keyword, textOrAuthor); + quote = await uow.Set().SearchQuoteKeywordTextAsync(ctx.Guild.Id, keyword, textOrAuthor); } if (quote is null) @@ -185,7 +185,7 @@ public partial class Utility await using (var uow = _db.GetDbContext()) { - quote = uow.Quotes.GetById(id); + quote = uow.Set().GetById(id); } if (quote is null || quote.GuildId != ctx.Guild.Id) @@ -216,7 +216,7 @@ public partial class Utility Quote q; await using (var uow = _db.GetDbContext()) { - uow.Quotes.Add(q = new() + uow.Set().Add(q = new() { AuthorId = ctx.Message.Author.Id, AuthorName = ctx.Message.Author.Username, @@ -240,13 +240,13 @@ public partial class Utility string response; await using (var uow = _db.GetDbContext()) { - var q = uow.Quotes.GetById(id); + var q = uow.Set().GetById(id); if (q?.GuildId != ctx.Guild.Id || (!hasManageMessages && q.AuthorId != ctx.Message.Author.Id)) response = GetText(strs.quotes_remove_none); else { - uow.Quotes.Remove(q); + uow.Set().Remove(q); await uow.SaveChangesAsync(); success = true; response = GetText(strs.quote_deleted(id)); @@ -293,7 +293,7 @@ public partial class Utility await using (var uow = _db.GetDbContext()) { - uow.Quotes.RemoveAllByKeyword(ctx.Guild.Id, keyword.ToUpperInvariant()); + uow.Set().RemoveAllByKeyword(ctx.Guild.Id, keyword.ToUpperInvariant()); await uow.SaveChangesAsync(); } @@ -309,7 +309,7 @@ public partial class Utility IEnumerable quotes; await using (var uow = _db.GetDbContext()) { - quotes = uow.Quotes.GetForGuild(ctx.Guild.Id).ToList(); + quotes = uow.Set().GetForGuild(ctx.Guild.Id).ToList(); } var exprsDict = quotes.GroupBy(x => x.Keyword) @@ -381,7 +381,7 @@ public partial class Utility foreach (var entry in data) { var keyword = entry.Key; - await uow.Quotes.AddRangeAsync(entry.Value.Where(quote => !string.IsNullOrWhiteSpace(quote.Txt)) + await uow.Set().AddRangeAsync(entry.Value.Where(quote => !string.IsNullOrWhiteSpace(quote.Txt)) .Select(quote => new Quote { GuildId = guildId, diff --git a/src/Nadeko.Bot.Modules.Utility/Remind/RemindCommands.cs b/src/Nadeko.Bot.Modules.Utility/Remind/RemindCommands.cs index 3f67921e2..68f22a03f 100644 --- a/src/Nadeko.Bot.Modules.Utility/Remind/RemindCommands.cs +++ b/src/Nadeko.Bot.Modules.Utility/Remind/RemindCommands.cs @@ -102,9 +102,9 @@ public partial class Utility await using (var uow = _db.GetDbContext()) { if (isServer) - rems = uow.Reminders.RemindersForServer(ctx.Guild.Id, page).ToList(); + rems = uow.Set().RemindersForServer(ctx.Guild.Id, page).ToList(); else - rems = uow.Reminders.RemindersFor(ctx.User.Id, page).ToList(); + rems = uow.Set().RemindersFor(ctx.User.Id, page).ToList(); } if (rems.Any()) @@ -150,14 +150,14 @@ public partial class Utility await using (var uow = _db.GetDbContext()) { var rems = isServer - ? uow.Reminders.RemindersForServer(ctx.Guild.Id, index / 10).ToList() - : uow.Reminders.RemindersFor(ctx.User.Id, index / 10).ToList(); + ? uow.Set().RemindersForServer(ctx.Guild.Id, index / 10).ToList() + : uow.Set().RemindersFor(ctx.User.Id, index / 10).ToList(); var pageIndex = index % 10; if (rems.Count > pageIndex) { rem = rems[pageIndex]; - uow.Reminders.Remove(rem); + uow.Set().Remove(rem); uow.SaveChanges(); } } @@ -198,7 +198,7 @@ public partial class Utility await using (var uow = _db.GetDbContext()) { - uow.Reminders.Add(rem); + uow.Set().Add(rem); await uow.SaveChangesAsync(); } diff --git a/src/Nadeko.Bot.Modules.Utility/Remind/RemindService.cs b/src/Nadeko.Bot.Modules.Utility/Remind/RemindService.cs index 60b4c992b..ea985a8a5 100644 --- a/src/Nadeko.Bot.Modules.Utility/Remind/RemindService.cs +++ b/src/Nadeko.Bot.Modules.Utility/Remind/RemindService.cs @@ -79,7 +79,7 @@ public class RemindService : INService, IReadyExecutor, IRemindService private async Task RemoveReminders(IEnumerable reminders) { await using var uow = _db.GetDbContext(); - await uow.Reminders + await uow.Set() .ToLinqToDBTable() .DeleteAsync(x => reminders.Contains(x.Id)); @@ -89,7 +89,7 @@ public class RemindService : INService, IReadyExecutor, IRemindService private async Task> GetRemindersBeforeAsync(DateTime now) { await using var uow = _db.GetDbContext(); - return await uow.Reminders + return await uow.Set() .ToLinqToDBTable() .Where(x => Linq2DbExpressions.GuildOnShard(x.ServerId, _creds.TotalShards, _client.ShardId) && x.When < now) @@ -245,7 +245,7 @@ public class RemindService : INService, IReadyExecutor, IRemindService }; await using var ctx = _db.GetDbContext(); - await ctx.Reminders + await ctx.Set() .AddAsync(rem); await ctx.SaveChangesAsync(); } diff --git a/src/Nadeko.Bot.Modules.Utility/Repeater/RepeaterService.cs b/src/Nadeko.Bot.Modules.Utility/Repeater/RepeaterService.cs index 9fe259ae4..a6f360a49 100644 --- a/src/Nadeko.Bot.Modules.Utility/Repeater/RepeaterService.cs +++ b/src/Nadeko.Bot.Modules.Utility/Repeater/RepeaterService.cs @@ -122,7 +122,7 @@ public sealed class RepeaterService : IReadyExecutor, INService { await using var uow = _db.GetDbContext(); - var toTrigger = await uow.Repeaters.AsNoTracking() + var toTrigger = await uow.Set().AsNoTracking() .Where(x => x.GuildId == guildId) .Skip(index) .FirstOrDefaultAsyncEF(); @@ -276,7 +276,7 @@ public sealed class RepeaterService : IReadyExecutor, INService _noRedundant.TryRemove(r.Id); await using var uow = _db.GetDbContext(); - await uow.Repeaters.DeleteAsync(x => x.Id == r.Id); + await uow.Set().DeleteAsync(x => x.Id == r.Id); await uow.SaveChangesAsync(); } @@ -297,7 +297,7 @@ public sealed class RepeaterService : IReadyExecutor, INService private async Task SetRepeaterLastMessageInternal(int repeaterId, ulong lastMsgId) { await using var uow = _db.GetDbContext(); - await uow.Repeaters.AsQueryable() + await uow.Set().AsQueryable() .Where(x => x.Id == repeaterId) .UpdateAsync(rep => new() { @@ -327,8 +327,8 @@ public sealed class RepeaterService : IReadyExecutor, INService await using var uow = _db.GetDbContext(); - if (await uow.Repeaters.CountAsyncEF(x => x.GuildId == guildId) < MAX_REPEATERS) - uow.Repeaters.Add(rep); + if (await uow.Set().CountAsyncEF(x => x.GuildId == guildId) < MAX_REPEATERS) + uow.Set().Add(rep); else return null; @@ -347,7 +347,7 @@ public sealed class RepeaterService : IReadyExecutor, INService throw new ArgumentOutOfRangeException(nameof(index)); await using var uow = _db.GetDbContext(); - var toRemove = await uow.Repeaters.AsNoTracking() + var toRemove = await uow.Set().AsNoTracking() .Where(x => x.GuildId == guildId) .Skip(index) .FirstOrDefaultAsyncEF(); @@ -362,7 +362,7 @@ public sealed class RepeaterService : IReadyExecutor, INService return null; _noRedundant.TryRemove(toRemove.Id); - uow.Repeaters.Remove(toRemove); + uow.Set().Remove(toRemove); await uow.SaveChangesAsync(); return removed; } @@ -378,7 +378,7 @@ public sealed class RepeaterService : IReadyExecutor, INService public async Task ToggleRedundantAsync(ulong guildId, int index) { await using var uow = _db.GetDbContext(); - var toToggle = await uow.Repeaters.AsQueryable() + var toToggle = await uow.Set().AsQueryable() .Where(x => x.GuildId == guildId) .Skip(index) .FirstOrDefaultAsyncEF(); @@ -399,7 +399,7 @@ public sealed class RepeaterService : IReadyExecutor, INService public async Task ToggleSkipNextAsync(ulong guildId, int index) { await using var ctx = _db.GetDbContext(); - var toSkip = await ctx.Repeaters + var toSkip = await ctx.Set() .Where(x => x.GuildId == guildId) .Skip(index) .FirstOrDefaultAsyncEF(); diff --git a/src/Nadeko.Bot.Modules.Xp/CleanupCommands.cs b/src/Nadeko.Bot.Modules.Xp/CleanupCommands.cs new file mode 100644 index 000000000..c43560596 --- /dev/null +++ b/src/Nadeko.Bot.Modules.Xp/CleanupCommands.cs @@ -0,0 +1,19 @@ +namespace NadekoBot.Modules.Xp; + +public sealed partial class Xp +{ + public class CleanupCommands : CleanupModuleBase + { + private readonly IXpCleanupService _service; + + public CleanupCommands(IXpCleanupService service) + { + _service = service; + } + + [Cmd] + [OwnerOnly] + public Task DeleteXp() + => ConfirmActionInternalAsync("Delete Xp", () => _service.DeleteXp()); + } +} \ No newline at end of file diff --git a/src/Nadeko.Bot.Modules.Xp/Club/ClubService.cs b/src/Nadeko.Bot.Modules.Xp/Club/ClubService.cs index d90b7ac17..a1fcbef5c 100644 --- a/src/Nadeko.Bot.Modules.Xp/Club/ClubService.cs +++ b/src/Nadeko.Bot.Modules.Xp/Club/ClubService.cs @@ -34,7 +34,7 @@ public class ClubService : INService, IClubService if (du.ClubId is not null) return ClubCreateResult.AlreadyInAClub; - if (await uow.Clubs.AnyAsyncEF(x => x.Name == clubName)) + if (await uow.Set().AnyAsyncEF(x => x.Name == clubName)) return ClubCreateResult.NameTaken; du.IsClubAdmin = true; @@ -43,7 +43,7 @@ public class ClubService : INService, IClubService Name = clubName, Owner = du }; - uow.Clubs.Add(du.Club); + uow.Set().Add(du.Club); await uow.SaveChangesAsync(); await uow.GetTable() @@ -55,7 +55,7 @@ public class ClubService : INService, IClubService public OneOf TransferClub(IUser from, IUser newOwner) { using var uow = _db.GetDbContext(); - var club = uow.Clubs.GetByOwner(@from.Id); + var club = uow.Set().GetByOwner(@from.Id); var newOwnerUser = uow.GetOrCreateUser(newOwner); if (club is null || club.Owner.UserId != from.Id) @@ -77,7 +77,7 @@ public class ClubService : INService, IClubService return ToggleAdminResult.CantTargetThyself; await using var uow = _db.GetDbContext(); - var club = uow.Clubs.GetByOwner(owner.Id); + var club = uow.Set().GetByOwner(owner.Id); var adminUser = uow.GetOrCreateUser(toAdmin); if (club is null) @@ -94,7 +94,7 @@ public class ClubService : INService, IClubService public ClubInfo GetClubByMember(IUser user) { using var uow = _db.GetDbContext(); - var member = uow.Clubs.GetByMember(user.Id); + var member = uow.Set().GetByMember(user.Id); return member; } @@ -113,7 +113,7 @@ public class ClubService : INService, IClubService } await using var uow = _db.GetDbContext(); - var club = uow.Clubs.GetByOwner(ownerUserId); + var club = uow.Set().GetByOwner(ownerUserId); if (club is null) return SetClubIconResult.NotOwner; @@ -127,7 +127,7 @@ public class ClubService : INService, IClubService public bool GetClubByName(string clubName, out ClubInfo club) { using var uow = _db.GetDbContext(); - club = uow.Clubs.GetByName(clubName); + club = uow.Set().GetByName(clubName); return club is not null; } @@ -165,7 +165,7 @@ public class ClubService : INService, IClubService { discordUser = null; using var uow = _db.GetDbContext(); - var club = uow.Clubs.GetByOwnerOrAdmin(clubOwnerUserId); + var club = uow.Set().GetByOwnerOrAdmin(clubOwnerUserId); if (club is null) return ClubAcceptResult.NotOwnerOrAdmin; @@ -190,7 +190,7 @@ public class ClubService : INService, IClubService public ClubInfo GetClubWithBansAndApplications(ulong ownerUserId) { using var uow = _db.GetDbContext(); - return uow.Clubs.GetByOwnerOrAdmin(ownerUserId); + return uow.Set().GetByOwnerOrAdmin(ownerUserId); } public ClubLeaveResult LeaveClub(IUser user) @@ -211,7 +211,7 @@ public class ClubService : INService, IClubService public bool SetDescription(ulong userId, string desc) { using var uow = _db.GetDbContext(); - var club = uow.Clubs.GetByOwner(userId); + var club = uow.Set().GetByOwner(userId); if (club is null) return false; @@ -224,11 +224,11 @@ public class ClubService : INService, IClubService public bool Disband(ulong userId, out ClubInfo club) { using var uow = _db.GetDbContext(); - club = uow.Clubs.GetByOwner(userId); + club = uow.Set().GetByOwner(userId); if (club is null) return false; - uow.Clubs.Remove(club); + uow.Set().Remove(club); uow.SaveChanges(); return true; } @@ -236,7 +236,7 @@ public class ClubService : INService, IClubService public ClubBanResult Ban(ulong bannerId, string userName, out ClubInfo club) { using var uow = _db.GetDbContext(); - club = uow.Clubs.GetByOwnerOrAdmin(bannerId); + club = uow.Set().GetByOwnerOrAdmin(bannerId); if (club is null) return ClubBanResult.NotOwnerOrAdmin; @@ -270,7 +270,7 @@ public class ClubService : INService, IClubService public ClubUnbanResult UnBan(ulong ownerUserId, string userName, out ClubInfo club) { using var uow = _db.GetDbContext(); - club = uow.Clubs.GetByOwnerOrAdmin(ownerUserId); + club = uow.Set().GetByOwnerOrAdmin(ownerUserId); if (club is null) return ClubUnbanResult.NotOwnerOrAdmin; @@ -288,7 +288,7 @@ public class ClubService : INService, IClubService public ClubKickResult Kick(ulong kickerId, string userName, out ClubInfo club) { using var uow = _db.GetDbContext(); - club = uow.Clubs.GetByOwnerOrAdmin(kickerId); + club = uow.Set().GetByOwnerOrAdmin(kickerId); if (club is null) return ClubKickResult.NotOwnerOrAdmin; @@ -314,6 +314,6 @@ public class ClubService : INService, IClubService throw new ArgumentOutOfRangeException(nameof(page)); using var uow = _db.GetDbContext(); - return uow.Clubs.GetClubLeaderboardPage(page); + return uow.Set().GetClubLeaderboardPage(page); } } \ No newline at end of file diff --git a/src/Nadeko.Bot.Modules.Xp/XpService.cs b/src/Nadeko.Bot.Modules.Xp/XpService.cs index 6ebbd766b..548c1d592 100644 --- a/src/Nadeko.Bot.Modules.Xp/XpService.cs +++ b/src/Nadeko.Bot.Modules.Xp/XpService.cs @@ -189,7 +189,7 @@ public class XpService : INService, IReadyExecutor, IExecNoCommand // group by xp amount and update the same amounts at the same time foreach (var group in globalToAdd.GroupBy(x => x.Value.XpAmount, x => x.Key)) { - var items = await ctx.DiscordUser + var items = await ctx.Set() .Where(x => group.Contains(x.UserId)) .UpdateWithOutputAsync(old => new() { @@ -197,7 +197,7 @@ public class XpService : INService, IReadyExecutor, IExecNoCommand }, (_, n) => n); - await ctx.Clubs + await ctx.Set() .Where(x => x.Members.Any(m => group.Contains(m.UserId))) .UpdateAsync(old => new() { @@ -212,7 +212,7 @@ public class XpService : INService, IReadyExecutor, IExecNoCommand foreach (var group in toAdd.GroupBy(x => x.Value.XpAmount, x => x.Key)) { var items = await ctx - .UserXpStats + .Set() .Where(x => x.GuildId == guildId) .Where(x => group.Contains(x.UserId)) .UpdateWithOutputAsync(old => new() @@ -227,7 +227,7 @@ public class XpService : INService, IReadyExecutor, IExecNoCommand foreach (var userId in missingUserIds) { await ctx - .UserXpStats + .Set() .ToLinqToDBTable() .InsertOrUpdateAsync(() => new UserXpStats() { @@ -250,7 +250,7 @@ public class XpService : INService, IReadyExecutor, IExecNoCommand if (missingUserIds.Length > 0) { - var missingItems = await ctx.UserXpStats + var missingItems = await ctx.Set() .ToLinqToDBTable() .Where(x => missingUserIds.Contains(x.UserId)) .ToArrayAsyncLinqToDB(); @@ -559,19 +559,19 @@ public class XpService : INService, IReadyExecutor, IExecNoCommand public List GetUserXps(ulong guildId, int page) { using var uow = _db.GetDbContext(); - return uow.UserXpStats.GetUsersFor(guildId, page); + return uow.Set().GetUsersFor(guildId, page); } public List GetTopUserXps(ulong guildId, int count) { using var uow = _db.GetDbContext(); - return uow.UserXpStats.GetTopUserXps(guildId, count); + return uow.Set().GetTopUserXps(guildId, count); } public DiscordUser[] GetUserXps(int page) { using var uow = _db.GetDbContext(); - return uow.DiscordUser.GetUsersXpLeaderboardFor(page); + return uow.Set().GetUsersXpLeaderboardFor(page); } public async Task ChangeNotificationType(ulong userId, ulong guildId, XpNotificationLocation type) @@ -876,8 +876,8 @@ public class XpService : INService, IReadyExecutor, IExecNoCommand await using var uow = _db.GetDbContext(); var du = uow.GetOrCreateUser(user, set => set.Include(x => x.Club)); var totalXp = du.TotalXp; - var globalRank = uow.DiscordUser.GetUserGlobalRank(user.Id); - var guildRank = uow.UserXpStats.GetUserGuildRanking(user.Id, user.GuildId); + var globalRank = uow.Set().GetUserGlobalRank(user.Id); + var guildRank = uow.Set().GetUserGuildRanking(user.Id, user.GuildId); var stats = uow.GetOrCreateUserXpStats(user.GuildId, user.Id); await uow.SaveChangesAsync(); @@ -1396,14 +1396,14 @@ public class XpService : INService, IReadyExecutor, IExecNoCommand public void XpReset(ulong guildId, ulong userId) { using var uow = _db.GetDbContext(); - uow.UserXpStats.ResetGuildUserXp(userId, guildId); + uow.Set().ResetGuildUserXp(userId, guildId); uow.SaveChanges(); } public void XpReset(ulong guildId) { using var uow = _db.GetDbContext(); - uow.UserXpStats.ResetGuildXp(guildId); + uow.Set().ResetGuildXp(guildId); uow.SaveChanges(); } diff --git a/src/Nadeko.Bot.Modules.Xp/_Common/IXpCleanupService.cs b/src/Nadeko.Bot.Modules.Xp/_Common/IXpCleanupService.cs new file mode 100644 index 000000000..c78e40763 --- /dev/null +++ b/src/Nadeko.Bot.Modules.Xp/_Common/IXpCleanupService.cs @@ -0,0 +1,6 @@ +namespace NadekoBot.Modules.Xp; + +public interface IXpCleanupService +{ + Task DeleteXp(); +} \ No newline at end of file diff --git a/src/Nadeko.Bot.Modules.Xp/_Common/XpCleanupService.cs b/src/Nadeko.Bot.Modules.Xp/_Common/XpCleanupService.cs new file mode 100644 index 000000000..7e8e54002 --- /dev/null +++ b/src/Nadeko.Bot.Modules.Xp/_Common/XpCleanupService.cs @@ -0,0 +1,32 @@ +using LinqToDB; +using NadekoBot.Db.Models; +using NadekoBot.Services.Database.Models; + +namespace NadekoBot.Modules.Xp; + +public sealed class XpCleanupService : IXpCleanupService +{ + private readonly DbService _db; + + public XpCleanupService(DbService db) + { + _db = db; + } + + public async Task DeleteXp() + { + await using var uow = _db.GetDbContext(); + await uow.Set().UpdateAsync(_ => new DiscordUser() + { + ClubId = null, + // IsClubAdmin = false, + TotalXp = 0 + }); + + await uow.Set().DeleteAsync(); + await uow.Set().DeleteAsync(); + await uow.Set().DeleteAsync(); + await uow.Set().DeleteAsync(); + await uow.SaveChangesAsync(); + } +} \ No newline at end of file diff --git a/src/NadekoBot/Bot.cs b/src/NadekoBot/Bot.cs index 8f857d517..832d2afc0 100644 --- a/src/NadekoBot/Bot.cs +++ b/src/NadekoBot/Bot.cs @@ -14,6 +14,7 @@ using NadekoBot.Modules.Permissions; using NadekoBot.Modules.Searches; using NadekoBot.Modules.Utility; using NadekoBot.Modules.Xp; +using NadekoBot.Services.Database; using NadekoBot.Services.Database.Models; using Ninject; using Ninject.Planning; @@ -56,7 +57,7 @@ public sealed class Bot : IBot _credsProvider = new BotCredsProvider(totalShards, credPath); _creds = _credsProvider.GetCreds(); - _db = new(_credsProvider); + _db = new NadekoDbService(_credsProvider); var messageCacheSize = #if GLOBAL_NADEKO @@ -120,7 +121,7 @@ public sealed class Bot : IBot using (var uow = _db.GetDbContext()) { uow.EnsureUserCreated(bot.Id, bot.Username, bot.Discriminator, bot.AvatarId); - AllGuildConfigs = uow.GuildConfigs.GetAllGuildConfigs(startingGuildIdList).ToImmutableArray(); + AllGuildConfigs = uow.Set().GetAllGuildConfigs(startingGuildIdList).ToImmutableArray(); } var svcs = new StandardKernel(new NinjectSettings()