From dfb4c778d20a7fb4e7e803840a60256d338450bb Mon Sep 17 00:00:00 2001 From: Master Kwoth Date: Sun, 28 May 2017 01:51:22 +0200 Subject: [PATCH] All modules compile, except log commands. Working on todos now --- .../Attributes/OwnerOnlyAttribute.cs | 2 - src/NadekoBot/DataStructures/AsyncLazy.cs | 3 - src/NadekoBot/DataStructures/CREmbed.cs | 5 - .../DataStructures/DisposableImutableList.cs | 4 - .../ModuleBehaviors/IBlockingExecutor.cs | 4 - .../TypeReaders/BotCommandTypeReader.cs | 67 ++-- .../TypeReaders/ModuleTypeReader.cs | 1 - .../Migrations/20161224032833_logsettings.cs | 4 +- .../20170110111159_repeater-drop.cs | 1 - .../Migrations/20170110111302_repeater-new.cs | 1 - .../Migrations/20170110180534_protection.cs | 4 +- .../20170112185538_currency-modifications.cs | 4 +- .../20170118202307_ok-error-colors.cs | 4 +- .../Migrations/20170122044958_waifus.cs | 4 +- ...0170213164350_guild-timezone-and-locale.cs | 4 +- .../Migrations/20170222162505_dateadded.cs | 1 - .../Migrations/20170308033058_permsv2.cs | 1 - .../20170310210952_unmute-timers.cs | 1 - .../Migrations/20170311054632_vcrole.cs | 1 - .../20170318190018_crad-and-crdm.cs | 4 +- .../20170320090138_command-aliasing.cs | 1 - .../20170330000613_warning-commands.cs | 1 - .../20170331093025_startup-commands.cs | 1 - .../20170401161600_slowmode-whitelist.cs | 1 - .../20170401205753_patreon-rewards.cs | 1 - .../Migrations/20170405161814_flower-shop.cs | 1 - .../20170408162851_game-voice-channel.cs | 4 +- .../20170409193757_gmod-and-cmod.cs | 1 - .../Migrations/20170501103455_patreon-id.cs | 4 +- .../Modules/Administration/Administration.cs | 32 -- .../Administration/Commands/Migration.cs | 6 +- .../Administration/Commands/MuteCommands.cs | 7 - .../Commands/RatelimitCommand.cs | 5 - .../Administration/Commands/SelfCommands.cs | 3 - .../Administration/Commands/VcRoleCommands.cs | 5 +- .../Commands/VoicePlusTextCommands.cs | 5 - .../Modules/Gambling/Commands/DrawCommand.cs | 1 - .../Modules/Gambling/Commands/FlowerShop.cs | 1 - src/NadekoBot/Modules/Gambling/Gambling.cs | 3 +- .../Modules/Games/Commands/Acropobia.cs | 1 - .../Modules/Games/Commands/LeetCommands.cs | 3 +- .../Games/Commands/PlantAndPickCommands.cs | 9 +- .../Modules/Games/Commands/PollCommands.cs | 4 +- src/NadekoBot/Modules/Games/Games.cs | 9 - src/NadekoBot/Modules/Music/Music.cs | 1 - src/NadekoBot/Modules/NadekoModule.cs | 1 - .../Modules/NadekoModuleExtensions.cs | 10 +- .../Permissions/Commands/BlacklistCommands.cs | 29 +- .../Permissions/Commands/CmdCdsCommands.cs | 34 +- .../Commands/CommandCostCommands.cs | 14 +- .../Permissions/Commands/FilterCommands.cs | 76 ++--- .../Commands/GlobalPermissionCommands.cs | 43 ++- .../Commands/ResetPermissionsCommands.cs | 62 ++++ .../Modules/Permissions/Permissions.cs | 190 ++--------- .../Modules/Searches/Commands/JokeCommands.cs | 5 - .../Searches/Commands/MemegenCommands.cs | 1 - .../Searches/Commands/Models/DefineModel.cs | 6 +- .../Commands/Models/GoogleSearchResult.cs | 8 +- .../Commands/Models/OverwatchApiModel.cs | 2 - .../Searches/Commands/Models/TimeModels.cs | 5 - .../Searches/Commands/Models/WeatherModels.cs | 6 +- .../Searches/Commands/OMDB/OmdbProvider.cs | 1 - .../Commands/PokemonSearchCommands.cs | 4 - .../Commands/StreamNotificationCommands.cs | 1 - .../Modules/Searches/Commands/Translator.cs | 3 - .../Utility/Commands/CommandMapCommands.cs | 1 + .../Commands/CrossServerTextChannel.cs | 3 +- .../Utility/Commands/MessageRepeater.cs | 6 +- .../Modules/Utility/Commands/Remind.cs | 14 +- .../Utility/Commands/UnitConversion.cs | 11 +- .../Modules/Utility/Models/PatreonData.cs | 5 - .../Modules/Utility/Models/PatreonPledge.cs | 8 +- .../Modules/Utility/Models/PatreonUser.cs | 8 +- src/NadekoBot/Modules/Utility/Utility.cs | 7 +- .../Modules/Utility/UtilityService.cs | 319 ------------------ src/NadekoBot/NadekoBot.cs | 158 +++++---- src/NadekoBot/NadekoBot.csproj | 3 - .../Administration/AdministrationService.cs | 1 - .../Administration/PlayingRotateService.cs | 2 - .../Administration/ProtectionService.cs | 1 - .../Services/Administration/Ratelimiter.cs | 1 - .../Services/Administration/SelfService.cs | 5 - .../Services/Administration/UserSpamStats.cs | 3 - .../Services/Administration/VcRoleService.cs | 1 - .../Services/Administration/VplusTService.cs | 1 - .../ClashOfClans/ClashOfClansService.cs | 5 +- .../Services/CustomReactions/Extensions.cs | 1 - .../Database/Models/AntiProtection.cs | 6 +- .../Services/Database/Models/BotConfig.cs | 12 +- .../Services/Database/Models/CommandCost.cs | 8 +- .../Services/Database/Models/CommandPrice.cs | 8 +- .../Services/Database/Models/DiscordUser.cs | 8 +- .../Services/Database/Models/Waifu.cs | 5 - .../Services/Database/Models/WaifuUpdate.cs | 8 +- .../Repositories/IDiscordUserRepository.cs | 5 - .../Database/Repositories/IWaifuRepository.cs | 1 - .../Repositories/Impl/BotConfigRepository.cs | 1 + .../Impl/DiscordUserRepository.cs | 4 - .../Repositories/Impl/WaifuRepository.cs | 2 - .../Repositories/Impl/WarningsRepository.cs | 1 - src/NadekoBot/Services/DbHandler.cs | 4 +- .../Discord/SocketMessageEventWrapper.cs | 3 - .../Services/Games/ChatterBotSession.cs | 1 - .../Services/GreetSettingsService.cs | 2 - src/NadekoBot/Services/IBotCredentials.cs | 1 - src/NadekoBot/Services/IImagesService.cs | 7 +- src/NadekoBot/Services/Impl/ImagesService.cs | 1 - src/NadekoBot/Services/Impl/Localization.cs | 5 - src/NadekoBot/Services/Impl/NadekoStrings.cs | 2 - src/NadekoBot/Services/Impl/StatsService.cs | 1 - src/NadekoBot/Services/Music/Song.cs | 1 - .../Services/Permissions/BlacklistService.cs | 21 ++ .../Services/Permissions/CmdCdService.cs | 26 ++ .../Services/Permissions/FilterService.cs | 50 +++ .../Permissions/GlobalPermissionService.cs | 18 + .../Services/Permissions/PermissionCache.cs | 5 - .../Permissions/PermissionExtensions.cs | 6 +- .../Permissions/PermissionsCollection.cs | 2 - .../Permissions/PermissionsService.cs | 150 +++++++- src/NadekoBot/Services/ServiceProvider.cs | 3 - .../Services/Utility/ConverterService.cs | 116 +++++++ .../Utility/MessageRepeaterService.cs | 36 ++ .../Services/Utility/RemindService.cs | 103 ++++++ .../Utility}/RepeatRunner.cs | 6 +- .../Services/Utility/UtilityService.cs | 83 +++++ 125 files changed, 954 insertions(+), 1063 deletions(-) create mode 100644 src/NadekoBot/Modules/Permissions/Commands/ResetPermissionsCommands.cs delete mode 100644 src/NadekoBot/Modules/Utility/UtilityService.cs create mode 100644 src/NadekoBot/Services/Permissions/BlacklistService.cs create mode 100644 src/NadekoBot/Services/Permissions/CmdCdService.cs create mode 100644 src/NadekoBot/Services/Permissions/FilterService.cs create mode 100644 src/NadekoBot/Services/Permissions/GlobalPermissionService.cs rename src/NadekoBot/{Modules => Services}/Permissions/PermissionExtensions.cs (96%) create mode 100644 src/NadekoBot/Services/Utility/ConverterService.cs create mode 100644 src/NadekoBot/Services/Utility/MessageRepeaterService.cs create mode 100644 src/NadekoBot/Services/Utility/RemindService.cs rename src/NadekoBot/{Modules/Utility/Models => Services/Utility}/RepeatRunner.cs (95%) create mode 100644 src/NadekoBot/Services/Utility/UtilityService.cs diff --git a/src/NadekoBot/Attributes/OwnerOnlyAttribute.cs b/src/NadekoBot/Attributes/OwnerOnlyAttribute.cs index 6f018aea..9799dbcd 100644 --- a/src/NadekoBot/Attributes/OwnerOnlyAttribute.cs +++ b/src/NadekoBot/Attributes/OwnerOnlyAttribute.cs @@ -1,8 +1,6 @@ using System.Threading.Tasks; using Discord.Commands; using System; -using NadekoBot.Services.Impl; -using Discord; using NadekoBot.Services; namespace NadekoBot.Attributes diff --git a/src/NadekoBot/DataStructures/AsyncLazy.cs b/src/NadekoBot/DataStructures/AsyncLazy.cs index 40800755..f739968f 100644 --- a/src/NadekoBot/DataStructures/AsyncLazy.cs +++ b/src/NadekoBot/DataStructures/AsyncLazy.cs @@ -1,8 +1,5 @@ using System; -using System.Collections.Generic; -using System.Linq; using System.Runtime.CompilerServices; -using System.Text; using System.Threading.Tasks; namespace NadekoBot.DataStructures diff --git a/src/NadekoBot/DataStructures/CREmbed.cs b/src/NadekoBot/DataStructures/CREmbed.cs index cb67503b..c0bb37f9 100644 --- a/src/NadekoBot/DataStructures/CREmbed.cs +++ b/src/NadekoBot/DataStructures/CREmbed.cs @@ -1,11 +1,6 @@ using Discord; using Newtonsoft.Json; using NLog; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace NadekoBot.DataStructures { diff --git a/src/NadekoBot/DataStructures/DisposableImutableList.cs b/src/NadekoBot/DataStructures/DisposableImutableList.cs index 71bda6de..391365e5 100644 --- a/src/NadekoBot/DataStructures/DisposableImutableList.cs +++ b/src/NadekoBot/DataStructures/DisposableImutableList.cs @@ -1,10 +1,6 @@ using System; using System.Collections; using System.Collections.Generic; -using System.Collections.Immutable; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace NadekoBot.DataStructures { diff --git a/src/NadekoBot/DataStructures/ModuleBehaviors/IBlockingExecutor.cs b/src/NadekoBot/DataStructures/ModuleBehaviors/IBlockingExecutor.cs index 3754faa6..8a338e7b 100644 --- a/src/NadekoBot/DataStructures/ModuleBehaviors/IBlockingExecutor.cs +++ b/src/NadekoBot/DataStructures/ModuleBehaviors/IBlockingExecutor.cs @@ -1,9 +1,5 @@ using Discord; using Discord.WebSocket; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; using System.Threading.Tasks; namespace NadekoBot.DataStructures.ModuleBehaviors diff --git a/src/NadekoBot/DataStructures/TypeReaders/BotCommandTypeReader.cs b/src/NadekoBot/DataStructures/TypeReaders/BotCommandTypeReader.cs index 629c7df3..3403dc73 100644 --- a/src/NadekoBot/DataStructures/TypeReaders/BotCommandTypeReader.cs +++ b/src/NadekoBot/DataStructures/TypeReaders/BotCommandTypeReader.cs @@ -1,4 +1,5 @@ using Discord.Commands; +using NadekoBot.Services.CustomReactions; using System.Linq; using System.Threading.Tasks; @@ -29,37 +30,43 @@ namespace NadekoBot.TypeReaders } } - //public class CommandOrCrTypeReader : CommandTypeReader - //{ - // public override async Task Read(ICommandContext context, string input) - // { - // input = input.ToUpperInvariant(); - - // if (CustomReactions.GlobalReactions.Any(x => x.Trigger.ToUpperInvariant() == input)) - // { - // return TypeReaderResult.FromSuccess(new CommandOrCrInfo(input)); - // } - // var guild = context.Guild; - // if (guild != null) - // { - // CustomReaction[] crs; - // if (CustomReactions.GuildReactions.TryGetValue(guild.Id, out crs)) - // { - // if (crs.Any(x => x.Trigger.ToUpperInvariant() == input)) - // { - // return TypeReaderResult.FromSuccess(new CommandOrCrInfo(input)); - // } - // } - // } + public class CommandOrCrTypeReader : CommandTypeReader + { + private readonly CustomReactionsService _crs; - // var cmd = await base.Read(context, input); - // if (cmd.IsSuccess) - // { - // return TypeReaderResult.FromSuccess(new CommandOrCrInfo(((CommandInfo)cmd.Values.First().Value).Aliases.First())); - // } - // return TypeReaderResult.FromError(CommandError.ParseFailed, "No such command or cr found."); - // } - //} + public CommandOrCrTypeReader(CustomReactionsService crs, CommandService cmds) : base(cmds) + { + _crs = crs; + } + + public override async Task Read(ICommandContext context, string input) + { + input = input.ToUpperInvariant(); + + if (_crs.GlobalReactions.Any(x => x.Trigger.ToUpperInvariant() == input)) + { + return TypeReaderResult.FromSuccess(new CommandOrCrInfo(input)); + } + var guild = context.Guild; + if (guild != null) + { + if (_crs.GuildReactions.TryGetValue(guild.Id, out var crs)) + { + if (crs.Concat(_crs.GlobalReactions).Any(x => x.Trigger.ToUpperInvariant() == input)) + { + return TypeReaderResult.FromSuccess(new CommandOrCrInfo(input)); + } + } + } + + var cmd = await base.Read(context, input); + if (cmd.IsSuccess) + { + return TypeReaderResult.FromSuccess(new CommandOrCrInfo(((CommandInfo)cmd.Values.First().Value).Aliases.First())); + } + return TypeReaderResult.FromError(CommandError.ParseFailed, "No such command or cr found."); + } + } public class CommandOrCrInfo { diff --git a/src/NadekoBot/DataStructures/TypeReaders/ModuleTypeReader.cs b/src/NadekoBot/DataStructures/TypeReaders/ModuleTypeReader.cs index 88f953ad..88645835 100644 --- a/src/NadekoBot/DataStructures/TypeReaders/ModuleTypeReader.cs +++ b/src/NadekoBot/DataStructures/TypeReaders/ModuleTypeReader.cs @@ -1,6 +1,5 @@ using Discord.Commands; using NadekoBot.Extensions; -using NadekoBot.Services; using System.Linq; using System.Threading.Tasks; diff --git a/src/NadekoBot/Migrations/20161224032833_logsettings.cs b/src/NadekoBot/Migrations/20161224032833_logsettings.cs index 609e8d24..c5260152 100644 --- a/src/NadekoBot/Migrations/20161224032833_logsettings.cs +++ b/src/NadekoBot/Migrations/20161224032833_logsettings.cs @@ -1,6 +1,4 @@ -using System; -using System.Collections.Generic; -using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Migrations; namespace NadekoBot.Migrations { diff --git a/src/NadekoBot/Migrations/20170110111159_repeater-drop.cs b/src/NadekoBot/Migrations/20170110111159_repeater-drop.cs index d05e6672..386ea2dd 100644 --- a/src/NadekoBot/Migrations/20170110111159_repeater-drop.cs +++ b/src/NadekoBot/Migrations/20170110111159_repeater-drop.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using Microsoft.EntityFrameworkCore.Migrations; namespace NadekoBot.Migrations diff --git a/src/NadekoBot/Migrations/20170110111302_repeater-new.cs b/src/NadekoBot/Migrations/20170110111302_repeater-new.cs index 0decfad8..e514df08 100644 --- a/src/NadekoBot/Migrations/20170110111302_repeater-new.cs +++ b/src/NadekoBot/Migrations/20170110111302_repeater-new.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using Microsoft.EntityFrameworkCore.Migrations; namespace NadekoBot.Migrations diff --git a/src/NadekoBot/Migrations/20170110180534_protection.cs b/src/NadekoBot/Migrations/20170110180534_protection.cs index fca7f541..7c29ab39 100644 --- a/src/NadekoBot/Migrations/20170110180534_protection.cs +++ b/src/NadekoBot/Migrations/20170110180534_protection.cs @@ -1,6 +1,4 @@ -using System; -using System.Collections.Generic; -using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Migrations; namespace NadekoBot.Migrations { diff --git a/src/NadekoBot/Migrations/20170112185538_currency-modifications.cs b/src/NadekoBot/Migrations/20170112185538_currency-modifications.cs index e29e5c8c..bbe4689e 100644 --- a/src/NadekoBot/Migrations/20170112185538_currency-modifications.cs +++ b/src/NadekoBot/Migrations/20170112185538_currency-modifications.cs @@ -1,6 +1,4 @@ -using System; -using System.Collections.Generic; -using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Migrations; namespace NadekoBot.Migrations { diff --git a/src/NadekoBot/Migrations/20170118202307_ok-error-colors.cs b/src/NadekoBot/Migrations/20170118202307_ok-error-colors.cs index b52bee10..f9c544a6 100644 --- a/src/NadekoBot/Migrations/20170118202307_ok-error-colors.cs +++ b/src/NadekoBot/Migrations/20170118202307_ok-error-colors.cs @@ -1,6 +1,4 @@ -using System; -using System.Collections.Generic; -using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Migrations; namespace NadekoBot.Migrations { diff --git a/src/NadekoBot/Migrations/20170122044958_waifus.cs b/src/NadekoBot/Migrations/20170122044958_waifus.cs index 4396ae77..1f6be9bc 100644 --- a/src/NadekoBot/Migrations/20170122044958_waifus.cs +++ b/src/NadekoBot/Migrations/20170122044958_waifus.cs @@ -1,6 +1,4 @@ -using System; -using System.Collections.Generic; -using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Migrations; namespace NadekoBot.Migrations { diff --git a/src/NadekoBot/Migrations/20170213164350_guild-timezone-and-locale.cs b/src/NadekoBot/Migrations/20170213164350_guild-timezone-and-locale.cs index 757d9150..bf1fd5b0 100644 --- a/src/NadekoBot/Migrations/20170213164350_guild-timezone-and-locale.cs +++ b/src/NadekoBot/Migrations/20170213164350_guild-timezone-and-locale.cs @@ -1,6 +1,4 @@ -using System; -using System.Collections.Generic; -using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Migrations; namespace NadekoBot.Migrations { diff --git a/src/NadekoBot/Migrations/20170222162505_dateadded.cs b/src/NadekoBot/Migrations/20170222162505_dateadded.cs index 5f96eca8..b7e112a9 100644 --- a/src/NadekoBot/Migrations/20170222162505_dateadded.cs +++ b/src/NadekoBot/Migrations/20170222162505_dateadded.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using Microsoft.EntityFrameworkCore.Migrations; namespace NadekoBot.Migrations diff --git a/src/NadekoBot/Migrations/20170308033058_permsv2.cs b/src/NadekoBot/Migrations/20170308033058_permsv2.cs index c40879ed..17ec3691 100644 --- a/src/NadekoBot/Migrations/20170308033058_permsv2.cs +++ b/src/NadekoBot/Migrations/20170308033058_permsv2.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using Microsoft.EntityFrameworkCore.Migrations; namespace NadekoBot.Migrations diff --git a/src/NadekoBot/Migrations/20170310210952_unmute-timers.cs b/src/NadekoBot/Migrations/20170310210952_unmute-timers.cs index d76e96a6..2bef2691 100644 --- a/src/NadekoBot/Migrations/20170310210952_unmute-timers.cs +++ b/src/NadekoBot/Migrations/20170310210952_unmute-timers.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using Microsoft.EntityFrameworkCore.Migrations; namespace NadekoBot.Migrations diff --git a/src/NadekoBot/Migrations/20170311054632_vcrole.cs b/src/NadekoBot/Migrations/20170311054632_vcrole.cs index 363f88f5..3d0075cc 100644 --- a/src/NadekoBot/Migrations/20170311054632_vcrole.cs +++ b/src/NadekoBot/Migrations/20170311054632_vcrole.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using Microsoft.EntityFrameworkCore.Migrations; namespace NadekoBot.Migrations diff --git a/src/NadekoBot/Migrations/20170318190018_crad-and-crdm.cs b/src/NadekoBot/Migrations/20170318190018_crad-and-crdm.cs index 898a19ca..ceb7956d 100644 --- a/src/NadekoBot/Migrations/20170318190018_crad-and-crdm.cs +++ b/src/NadekoBot/Migrations/20170318190018_crad-and-crdm.cs @@ -1,6 +1,4 @@ -using System; -using System.Collections.Generic; -using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Migrations; namespace NadekoBot.Migrations { diff --git a/src/NadekoBot/Migrations/20170320090138_command-aliasing.cs b/src/NadekoBot/Migrations/20170320090138_command-aliasing.cs index d3ee3411..8a5978da 100644 --- a/src/NadekoBot/Migrations/20170320090138_command-aliasing.cs +++ b/src/NadekoBot/Migrations/20170320090138_command-aliasing.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using Microsoft.EntityFrameworkCore.Migrations; namespace NadekoBot.Migrations diff --git a/src/NadekoBot/Migrations/20170330000613_warning-commands.cs b/src/NadekoBot/Migrations/20170330000613_warning-commands.cs index 5fb96271..9a9b9986 100644 --- a/src/NadekoBot/Migrations/20170330000613_warning-commands.cs +++ b/src/NadekoBot/Migrations/20170330000613_warning-commands.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using Microsoft.EntityFrameworkCore.Migrations; namespace NadekoBot.Migrations diff --git a/src/NadekoBot/Migrations/20170331093025_startup-commands.cs b/src/NadekoBot/Migrations/20170331093025_startup-commands.cs index d3cd52a9..bc4b12c9 100644 --- a/src/NadekoBot/Migrations/20170331093025_startup-commands.cs +++ b/src/NadekoBot/Migrations/20170331093025_startup-commands.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using Microsoft.EntityFrameworkCore.Migrations; namespace NadekoBot.Migrations diff --git a/src/NadekoBot/Migrations/20170401161600_slowmode-whitelist.cs b/src/NadekoBot/Migrations/20170401161600_slowmode-whitelist.cs index fc2be484..0b6dcc95 100644 --- a/src/NadekoBot/Migrations/20170401161600_slowmode-whitelist.cs +++ b/src/NadekoBot/Migrations/20170401161600_slowmode-whitelist.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using Microsoft.EntityFrameworkCore.Migrations; namespace NadekoBot.Migrations diff --git a/src/NadekoBot/Migrations/20170401205753_patreon-rewards.cs b/src/NadekoBot/Migrations/20170401205753_patreon-rewards.cs index 83057ff5..be6e90c5 100644 --- a/src/NadekoBot/Migrations/20170401205753_patreon-rewards.cs +++ b/src/NadekoBot/Migrations/20170401205753_patreon-rewards.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using Microsoft.EntityFrameworkCore.Migrations; namespace NadekoBot.Migrations diff --git a/src/NadekoBot/Migrations/20170405161814_flower-shop.cs b/src/NadekoBot/Migrations/20170405161814_flower-shop.cs index 7d0cde56..4b7bc8a2 100644 --- a/src/NadekoBot/Migrations/20170405161814_flower-shop.cs +++ b/src/NadekoBot/Migrations/20170405161814_flower-shop.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using Microsoft.EntityFrameworkCore.Migrations; namespace NadekoBot.Migrations diff --git a/src/NadekoBot/Migrations/20170408162851_game-voice-channel.cs b/src/NadekoBot/Migrations/20170408162851_game-voice-channel.cs index 3b9cb6c6..9477b97a 100644 --- a/src/NadekoBot/Migrations/20170408162851_game-voice-channel.cs +++ b/src/NadekoBot/Migrations/20170408162851_game-voice-channel.cs @@ -1,6 +1,4 @@ -using System; -using System.Collections.Generic; -using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Migrations; namespace NadekoBot.Migrations { diff --git a/src/NadekoBot/Migrations/20170409193757_gmod-and-cmod.cs b/src/NadekoBot/Migrations/20170409193757_gmod-and-cmod.cs index 5cef1a06..82794d89 100644 --- a/src/NadekoBot/Migrations/20170409193757_gmod-and-cmod.cs +++ b/src/NadekoBot/Migrations/20170409193757_gmod-and-cmod.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using Microsoft.EntityFrameworkCore.Migrations; namespace NadekoBot.Migrations diff --git a/src/NadekoBot/Migrations/20170501103455_patreon-id.cs b/src/NadekoBot/Migrations/20170501103455_patreon-id.cs index f7a9a784..a5654ef3 100644 --- a/src/NadekoBot/Migrations/20170501103455_patreon-id.cs +++ b/src/NadekoBot/Migrations/20170501103455_patreon-id.cs @@ -1,6 +1,4 @@ -using System; -using System.Collections.Generic; -using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Migrations; namespace NadekoBot.Migrations { diff --git a/src/NadekoBot/Modules/Administration/Administration.cs b/src/NadekoBot/Modules/Administration/Administration.cs index 1284d71b..4ba3b959 100644 --- a/src/NadekoBot/Modules/Administration/Administration.cs +++ b/src/NadekoBot/Modules/Administration/Administration.cs @@ -24,38 +24,6 @@ namespace NadekoBot.Modules.Administration _admin = admin; } - ////todo permissions - //[NadekoCommand, Usage, Description, Aliases] - //[RequireContext(ContextType.Guild)] - //[RequireUserPermission(GuildPermission.Administrator)] - //public async Task ResetPermissions() - //{ - // using (var uow = _db.UnitOfWork) - // { - // var config = uow.GuildConfigs.GcWithPermissionsv2For(Context.Guild.Id); - // config.Permissions = Permissionv2.GetDefaultPermlist; - // await uow.CompleteAsync(); - // UpdateCache(config); - // } - // await ReplyConfirmLocalized("perms_reset").ConfigureAwait(false); - //} - //[NadekoCommand, Usage, Description, Aliases] - //[OwnerOnly] - //public async Task ResetGlobalPermissions() - //{ - // using (var uow = _db.UnitOfWork) - // { - // var gc = uow.BotConfig.GetOrCreate(); - // gc.BlockedCommands.Clear(); - // gc.BlockedModules.Clear(); - - // GlobalPermissionCommands.BlockedCommands.Clear(); - // GlobalPermissionCommands.BlockedModules.Clear(); - // await uow.CompleteAsync(); - // } - // await ReplyConfirmLocalized("global_perms_reset").ConfigureAwait(false); - //} - [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] [RequireUserPermission(GuildPermission.Administrator)] diff --git a/src/NadekoBot/Modules/Administration/Commands/Migration.cs b/src/NadekoBot/Modules/Administration/Commands/Migration.cs index 93dfcadf..054445d8 100644 --- a/src/NadekoBot/Modules/Administration/Commands/Migration.cs +++ b/src/NadekoBot/Modules/Administration/Commands/Migration.cs @@ -400,9 +400,9 @@ namespace NadekoBot.Modules.Administration }); //Blacklist - var blacklist = new HashSet(oldConfig.ServerBlacklist.Select(server => new BlacklistItem() { ItemId = server, Type = BlacklistItem.BlacklistType.Server })); - blacklist.AddRange(oldConfig.ChannelBlacklist.Select(channel => new BlacklistItem() { ItemId = channel, Type = BlacklistItem.BlacklistType.Channel })); - blacklist.AddRange(oldConfig.UserBlacklist.Select(user => new BlacklistItem() { ItemId = user, Type = BlacklistItem.BlacklistType.User })); + var blacklist = new HashSet(oldConfig.ServerBlacklist.Select(server => new BlacklistItem() { ItemId = server, Type = BlacklistType.Server })); + blacklist.AddRange(oldConfig.ChannelBlacklist.Select(channel => new BlacklistItem() { ItemId = channel, Type = BlacklistType.Channel })); + blacklist.AddRange(oldConfig.UserBlacklist.Select(user => new BlacklistItem() { ItemId = user, Type = BlacklistType.User })); botConfig.Blacklist = blacklist; //Eightball diff --git a/src/NadekoBot/Modules/Administration/Commands/MuteCommands.cs b/src/NadekoBot/Modules/Administration/Commands/MuteCommands.cs index 86345ab4..90fb4199 100644 --- a/src/NadekoBot/Modules/Administration/Commands/MuteCommands.cs +++ b/src/NadekoBot/Modules/Administration/Commands/MuteCommands.cs @@ -1,16 +1,9 @@ using Discord; using Discord.Commands; -using Discord.WebSocket; -using Microsoft.EntityFrameworkCore; using NadekoBot.Attributes; using NadekoBot.Services; using NadekoBot.Services.Administration; -using NadekoBot.Services.Database.Models; -using NLog; using System; -using System.Collections.Concurrent; -using System.Linq; -using System.Threading; using System.Threading.Tasks; namespace NadekoBot.Modules.Administration diff --git a/src/NadekoBot/Modules/Administration/Commands/RatelimitCommand.cs b/src/NadekoBot/Modules/Administration/Commands/RatelimitCommand.cs index 7c491fe7..c4d3b0ca 100644 --- a/src/NadekoBot/Modules/Administration/Commands/RatelimitCommand.cs +++ b/src/NadekoBot/Modules/Administration/Commands/RatelimitCommand.cs @@ -1,18 +1,13 @@ using Discord; using Discord.Commands; -using Discord.WebSocket; using Microsoft.EntityFrameworkCore; using NadekoBot.Attributes; using NadekoBot.Extensions; using NadekoBot.Services; using NadekoBot.Services.Administration; using NadekoBot.Services.Database.Models; -using NLog; -using System; -using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; -using System.Threading; using System.Threading.Tasks; namespace NadekoBot.Modules.Administration diff --git a/src/NadekoBot/Modules/Administration/Commands/SelfCommands.cs b/src/NadekoBot/Modules/Administration/Commands/SelfCommands.cs index d33fdeda..fbb973f5 100644 --- a/src/NadekoBot/Modules/Administration/Commands/SelfCommands.cs +++ b/src/NadekoBot/Modules/Administration/Commands/SelfCommands.cs @@ -12,9 +12,6 @@ using Discord.WebSocket; using NadekoBot.Services; using NadekoBot.Services.Database.Models; using Microsoft.EntityFrameworkCore; -using System.Collections.Immutable; -using NadekoBot.DataStructures; -using NLog; using NadekoBot.Services.Administration; namespace NadekoBot.Modules.Administration diff --git a/src/NadekoBot/Modules/Administration/Commands/VcRoleCommands.cs b/src/NadekoBot/Modules/Administration/Commands/VcRoleCommands.cs index 177dcd60..d1746e5c 100644 --- a/src/NadekoBot/Modules/Administration/Commands/VcRoleCommands.cs +++ b/src/NadekoBot/Modules/Administration/Commands/VcRoleCommands.cs @@ -1,5 +1,4 @@ -using System; -using System.Collections.Concurrent; +using System.Collections.Concurrent; using System.Linq; using Discord; using Discord.Commands; @@ -32,7 +31,7 @@ namespace NadekoBot.Modules.Administration [RequireUserPermission(GuildPermission.ManageRoles)] [RequireUserPermission(GuildPermission.ManageChannels)] [RequireBotPermission(GuildPermission.ManageRoles)] - // todo wait for the fix [RequireBotPermission(GuildPermission.ManageChannels)] + //todo discord.net [RequireBotPermission(GuildPermission.ManageChannels)] [RequireContext(ContextType.Guild)] public async Task VcRole([Remainder]IRole role = null) { diff --git a/src/NadekoBot/Modules/Administration/Commands/VoicePlusTextCommands.cs b/src/NadekoBot/Modules/Administration/Commands/VoicePlusTextCommands.cs index 0a5a8835..899cfa83 100644 --- a/src/NadekoBot/Modules/Administration/Commands/VoicePlusTextCommands.cs +++ b/src/NadekoBot/Modules/Administration/Commands/VoicePlusTextCommands.cs @@ -1,18 +1,13 @@ using Discord; using Discord.Commands; -using Discord.WebSocket; using NadekoBot.Attributes; using NadekoBot.Extensions; using NadekoBot.Services; using NadekoBot.Services.Administration; -using NLog; using System; -using System.Collections.Concurrent; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using System.Text.RegularExpressions; -using System.Threading; using System.Threading.Tasks; namespace NadekoBot.Modules.Administration diff --git a/src/NadekoBot/Modules/Gambling/Commands/DrawCommand.cs b/src/NadekoBot/Modules/Gambling/Commands/DrawCommand.cs index ce5f9176..61b65425 100644 --- a/src/NadekoBot/Modules/Gambling/Commands/DrawCommand.cs +++ b/src/NadekoBot/Modules/Gambling/Commands/DrawCommand.cs @@ -1,6 +1,5 @@ using Discord; using Discord.Commands; -using ImageSharp; using NadekoBot.Attributes; using NadekoBot.Extensions; using NadekoBot.Modules.Gambling.Models; diff --git a/src/NadekoBot/Modules/Gambling/Commands/FlowerShop.cs b/src/NadekoBot/Modules/Gambling/Commands/FlowerShop.cs index e519562c..20d4cb8f 100644 --- a/src/NadekoBot/Modules/Gambling/Commands/FlowerShop.cs +++ b/src/NadekoBot/Modules/Gambling/Commands/FlowerShop.cs @@ -6,7 +6,6 @@ using NadekoBot.Attributes; using NadekoBot.DataStructures; using NadekoBot.Extensions; using NadekoBot.Services; -using NadekoBot.Services.Database; using NadekoBot.Services.Database.Models; using System; using System.Collections.Generic; diff --git a/src/NadekoBot/Modules/Gambling/Gambling.cs b/src/NadekoBot/Modules/Gambling/Gambling.cs index 927c8f93..e24caa6e 100644 --- a/src/NadekoBot/Modules/Gambling/Gambling.cs +++ b/src/NadekoBot/Modules/Gambling/Gambling.cs @@ -1,5 +1,4 @@ -using System; -using Discord; +using Discord; using Discord.Commands; using NadekoBot.Attributes; using NadekoBot.Extensions; diff --git a/src/NadekoBot/Modules/Games/Commands/Acropobia.cs b/src/NadekoBot/Modules/Games/Commands/Acropobia.cs index 2b3494be..6e561527 100644 --- a/src/NadekoBot/Modules/Games/Commands/Acropobia.cs +++ b/src/NadekoBot/Modules/Games/Commands/Acropobia.cs @@ -10,7 +10,6 @@ using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; -using System.Text; using System.Threading; using System.Threading.Tasks; diff --git a/src/NadekoBot/Modules/Games/Commands/LeetCommands.cs b/src/NadekoBot/Modules/Games/Commands/LeetCommands.cs index 62d2930e..e1f79c56 100644 --- a/src/NadekoBot/Modules/Games/Commands/LeetCommands.cs +++ b/src/NadekoBot/Modules/Games/Commands/LeetCommands.cs @@ -1,5 +1,4 @@ -using Discord; -using Discord.Commands; +using Discord.Commands; using NadekoBot.Attributes; using NadekoBot.Extensions; using System.Text; diff --git a/src/NadekoBot/Modules/Games/Commands/PlantAndPickCommands.cs b/src/NadekoBot/Modules/Games/Commands/PlantAndPickCommands.cs index bf837979..159f6865 100644 --- a/src/NadekoBot/Modules/Games/Commands/PlantAndPickCommands.cs +++ b/src/NadekoBot/Modules/Games/Commands/PlantAndPickCommands.cs @@ -1,17 +1,12 @@ using Discord; using Discord.Commands; -using Discord.WebSocket; using Microsoft.EntityFrameworkCore; using NadekoBot.Attributes; using NadekoBot.Extensions; using NadekoBot.Services; using NadekoBot.Services.Database.Models; using NadekoBot.Services.Games; -using NLog; -using System; -using System.Collections.Concurrent; using System.Collections.Generic; -using System.Collections.Immutable; using System.Linq; using System.Threading.Tasks; @@ -81,9 +76,7 @@ namespace NadekoBot.Modules.Games var imgData = _games.GetRandomCurrencyImage(); - //todo upload all currency images to transfer.sh and use that one as cdn - //and then - + //todo 81 upload all currency images to transfer.sh and use that one as cdn var msgToSend = GetText("planted", Format.Bold(Context.User.ToString()), amount + _bc.CurrencySign, diff --git a/src/NadekoBot/Modules/Games/Commands/PollCommands.cs b/src/NadekoBot/Modules/Games/Commands/PollCommands.cs index c5424bbe..1773c4d7 100644 --- a/src/NadekoBot/Modules/Games/Commands/PollCommands.cs +++ b/src/NadekoBot/Modules/Games/Commands/PollCommands.cs @@ -1,5 +1,4 @@ -using System; -using Discord; +using Discord; using Discord.Commands; using Discord.WebSocket; using NadekoBot.Attributes; @@ -9,7 +8,6 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; -using ImageSharp.Processing; using NadekoBot.Services; namespace NadekoBot.Modules.Games diff --git a/src/NadekoBot/Modules/Games/Games.cs b/src/NadekoBot/Modules/Games/Games.cs index 5257d710..5c4e0f61 100644 --- a/src/NadekoBot/Modules/Games/Games.cs +++ b/src/NadekoBot/Modules/Games/Games.cs @@ -4,16 +4,7 @@ using NadekoBot.Services; using System.Threading.Tasks; using NadekoBot.Attributes; using System; -using System.Collections.Concurrent; -using System.Linq; -using System.Collections.Immutable; -using System.IO; -using System.Threading; using NadekoBot.Extensions; -using System.Net.Http; -using ImageSharp; -using NadekoBot.DataStructures; -using NLog; using NadekoBot.Services.Games; namespace NadekoBot.Modules.Games diff --git a/src/NadekoBot/Modules/Music/Music.cs b/src/NadekoBot/Modules/Music/Music.cs index 4c798d39..35f15c98 100644 --- a/src/NadekoBot/Modules/Music/Music.cs +++ b/src/NadekoBot/Modules/Music/Music.cs @@ -357,7 +357,6 @@ namespace NadekoBot.Modules.Music var cancelSource = new CancellationTokenSource(); var gusr = (IGuildUser)Context.User; - //todo use grouping while (ids.Any() && !cancelSource.IsCancellationRequested) { var tasks = Task.WhenAll(ids.Take(5).Select(async id => diff --git a/src/NadekoBot/Modules/NadekoModule.cs b/src/NadekoBot/Modules/NadekoModule.cs index 6fc26e2a..7ef38f17 100644 --- a/src/NadekoBot/Modules/NadekoModule.cs +++ b/src/NadekoBot/Modules/NadekoModule.cs @@ -3,7 +3,6 @@ using Discord.Commands; using NadekoBot.Extensions; using NadekoBot.Services; using NLog; -using System; using System.Globalization; using System.Threading.Tasks; diff --git a/src/NadekoBot/Modules/NadekoModuleExtensions.cs b/src/NadekoBot/Modules/NadekoModuleExtensions.cs index 09625409..6c53169c 100644 --- a/src/NadekoBot/Modules/NadekoModuleExtensions.cs +++ b/src/NadekoBot/Modules/NadekoModuleExtensions.cs @@ -1,12 +1,4 @@ -using Discord; -using NadekoBot.Extensions; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace NadekoBot.Modules +namespace NadekoBot.Modules { public static class NadekoModuleExtensions { diff --git a/src/NadekoBot/Modules/Permissions/Commands/BlacklistCommands.cs b/src/NadekoBot/Modules/Permissions/Commands/BlacklistCommands.cs index 7cc8e62f..4820e8b4 100644 --- a/src/NadekoBot/Modules/Permissions/Commands/BlacklistCommands.cs +++ b/src/NadekoBot/Modules/Permissions/Commands/BlacklistCommands.cs @@ -1,14 +1,13 @@ using Discord; using Discord.Commands; using NadekoBot.Attributes; -using NadekoBot.Extensions; using NadekoBot.Modules.Games.Trivia; using NadekoBot.Services; using NadekoBot.Services.Database.Models; +using NadekoBot.Services.Permissions; using System.Collections.Concurrent; using System.Linq; using System.Threading.Tasks; -using static NadekoBot.Services.Database.Models.BlacklistItem; namespace NadekoBot.Modules.Permissions { @@ -23,19 +22,19 @@ namespace NadekoBot.Modules.Permissions [Group] public class BlacklistCommands : NadekoSubmodule { - public static ConcurrentHashSet BlacklistedUsers { get; set; } - public static ConcurrentHashSet BlacklistedGuilds { get; set; } - public static ConcurrentHashSet BlacklistedChannels { get; set; } + private readonly BlacklistService _bs; + private readonly DbHandler _db; + private readonly IBotCredentials _creds; - static BlacklistCommands() + private ConcurrentHashSet BlacklistedUsers => _bs.BlacklistedUsers; + private ConcurrentHashSet BlacklistedGuilds => _bs.BlacklistedGuilds; + private ConcurrentHashSet BlacklistedChannels => _bs.BlacklistedChannels; + + public BlacklistCommands(BlacklistService bs, DbHandler db, IBotCredentials creds) { - using (var uow = DbHandler.UnitOfWork()) - { - var blacklist = uow.BotConfig.GetOrCreate().Blacklist; - BlacklistedUsers = new ConcurrentHashSet(blacklist.Where(bi => bi.Type == BlacklistType.User).Select(c => c.ItemId)); - BlacklistedGuilds = new ConcurrentHashSet(blacklist.Where(bi => bi.Type == BlacklistType.Server).Select(c => c.ItemId)); - BlacklistedChannels = new ConcurrentHashSet(blacklist.Where(bi => bi.Type == BlacklistType.Channel).Select(c => c.ItemId)); - } + _bs = bs; + _db = db; + _creds = creds; } [NadekoCommand, Usage, Description, Aliases] @@ -65,10 +64,10 @@ namespace NadekoBot.Modules.Permissions private async Task Blacklist(AddRemove action, ulong id, BlacklistType type) { - if(action == AddRemove.Add && NadekoBot.Credentials.OwnerIds.Contains(id)) + if(action == AddRemove.Add && _creds.OwnerIds.Contains(id)) return; - using (var uow = DbHandler.UnitOfWork()) + using (var uow = _db.UnitOfWork) { if (action == AddRemove.Add) { diff --git a/src/NadekoBot/Modules/Permissions/Commands/CmdCdsCommands.cs b/src/NadekoBot/Modules/Permissions/Commands/CmdCdsCommands.cs index cfccebde..9138abc3 100644 --- a/src/NadekoBot/Modules/Permissions/Commands/CmdCdsCommands.cs +++ b/src/NadekoBot/Modules/Permissions/Commands/CmdCdsCommands.cs @@ -5,6 +5,7 @@ using NadekoBot.Attributes; using NadekoBot.Extensions; using NadekoBot.Services; using NadekoBot.Services.Database.Models; +using NadekoBot.Services.Permissions; using System.Collections.Concurrent; using System.Linq; using System.Threading.Tasks; @@ -13,24 +14,23 @@ namespace NadekoBot.Modules.Permissions { public partial class Permissions { - - public class ActiveCooldown - { - public string Command { get; set; } - public ulong UserId { get; set; } - } - [Group] public class CmdCdsCommands : NadekoSubmodule { - public static ConcurrentDictionary> CommandCooldowns { get; } - private static ConcurrentDictionary> activeCooldowns { get; } = new ConcurrentDictionary>(); + private readonly DbHandler _db; + private readonly CmdCdService _service; - static CmdCdsCommands() + private ConcurrentDictionary> CommandCooldowns + => _service.CommandCooldowns; + private ConcurrentDictionary> ActiveCooldowns + => _service.ActiveCooldowns; + + public CmdCdsCommands(CmdCdService service, DbHandler db) { - var configs = NadekoBot.AllGuildConfigs; - CommandCooldowns = new ConcurrentDictionary>(configs.ToDictionary(k => k.GuildId, v => new ConcurrentHashSet(v.CommandCooldowns))); + _service = service; + _db = db; } + [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] public async Task CmdCooldown(CommandInfo command, int secs) @@ -42,7 +42,7 @@ namespace NadekoBot.Modules.Permissions return; } - using (var uow = DbHandler.UnitOfWork()) + using (var uow = _db.UnitOfWork) { var config = uow.GuildConfigs.For(channel.Guild.Id, set => set.Include(gc => gc.CommandCooldowns)); var localSet = CommandCooldowns.GetOrAdd(channel.Guild.Id, new ConcurrentHashSet()); @@ -63,7 +63,7 @@ namespace NadekoBot.Modules.Permissions } if (secs == 0) { - var activeCds = activeCooldowns.GetOrAdd(channel.Guild.Id, new ConcurrentHashSet()); + var activeCds = ActiveCooldowns.GetOrAdd(channel.Guild.Id, new ConcurrentHashSet()); activeCds.RemoveWhere(ac => ac.Command == command.Aliases.First().ToLowerInvariant()); await ReplyConfirmLocalized("cmdcd_cleared", Format.Bold(command.Aliases.First())).ConfigureAwait(false); @@ -89,15 +89,15 @@ namespace NadekoBot.Modules.Permissions await channel.SendTableAsync("", localSet.Select(c => c.CommandName + ": " + c.Seconds + GetText("sec")), s => $"{s,-30}", 2).ConfigureAwait(false); } - public static bool HasCooldown(CommandInfo cmd, IGuild guild, IUser user) + public bool HasCooldown(CommandInfo cmd, IGuild guild, IUser user) { if (guild == null) return false; - var cmdcds = CmdCdsCommands.CommandCooldowns.GetOrAdd(guild.Id, new ConcurrentHashSet()); + var cmdcds = CommandCooldowns.GetOrAdd(guild.Id, new ConcurrentHashSet()); CommandCooldown cdRule; if ((cdRule = cmdcds.FirstOrDefault(cc => cc.CommandName == cmd.Aliases.First().ToLowerInvariant())) != null) { - var activeCdsForGuild = activeCooldowns.GetOrAdd(guild.Id, new ConcurrentHashSet()); + var activeCdsForGuild = ActiveCooldowns.GetOrAdd(guild.Id, new ConcurrentHashSet()); if (activeCdsForGuild.FirstOrDefault(ac => ac.UserId == user.Id && ac.Command == cmd.Aliases.First().ToLowerInvariant()) != null) { return true; diff --git a/src/NadekoBot/Modules/Permissions/Commands/CommandCostCommands.cs b/src/NadekoBot/Modules/Permissions/Commands/CommandCostCommands.cs index 91b8a7d2..13651ca3 100644 --- a/src/NadekoBot/Modules/Permissions/Commands/CommandCostCommands.cs +++ b/src/NadekoBot/Modules/Permissions/Commands/CommandCostCommands.cs @@ -1,16 +1,6 @@ -using Discord; -using Discord.Commands; -using NadekoBot.Attributes; -using NadekoBot.Extensions; -using NadekoBot.Services; -using NadekoBot.Services.Database; -using NadekoBot.Services.Database.Models; -using System; +using Discord.Commands; using System.Collections.Concurrent; using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace NadekoBot.Modules.Permissions { @@ -67,7 +57,7 @@ namespace NadekoBot.Modules.Permissions // Cost = cost // }; - // using (var uow = DbHandler.UnitOfWork()) + // using (var uow = _db.UnitOfWork) // { // var bc = uow.BotConfig.GetOrCreate(); diff --git a/src/NadekoBot/Modules/Permissions/Commands/FilterCommands.cs b/src/NadekoBot/Modules/Permissions/Commands/FilterCommands.cs index fe2cf36d..782a7f83 100644 --- a/src/NadekoBot/Modules/Permissions/Commands/FilterCommands.cs +++ b/src/NadekoBot/Modules/Permissions/Commands/FilterCommands.cs @@ -4,8 +4,8 @@ using Microsoft.EntityFrameworkCore; using NadekoBot.Attributes; using NadekoBot.Extensions; using NadekoBot.Services; +using NadekoBot.Services.Permissions; using System.Collections.Concurrent; -using System.Linq; using System.Threading.Tasks; namespace NadekoBot.Modules.Permissions @@ -15,46 +15,13 @@ namespace NadekoBot.Modules.Permissions [Group] public class FilterCommands : NadekoSubmodule { - public static ConcurrentHashSet InviteFilteringChannels { get; } - public static ConcurrentHashSet InviteFilteringServers { get; } + private readonly DbHandler _db; + private readonly FilterService _service; - //serverid, filteredwords - private static ConcurrentDictionary> serverFilteredWords { get; } - - public static ConcurrentHashSet WordFilteringChannels { get; } - public static ConcurrentHashSet WordFilteringServers { get; } - - public static ConcurrentHashSet FilteredWordsForChannel(ulong channelId, ulong guildId) + public FilterCommands(FilterService service, DbHandler db) { - ConcurrentHashSet words = new ConcurrentHashSet(); - if(WordFilteringChannels.Contains(channelId)) - serverFilteredWords.TryGetValue(guildId, out words); - return words; - } - - public static ConcurrentHashSet FilteredWordsForServer(ulong guildId) - { - var words = new ConcurrentHashSet(); - if(WordFilteringServers.Contains(guildId)) - serverFilteredWords.TryGetValue(guildId, out words); - return words; - } - - static FilterCommands() - { - var guildConfigs = NadekoBot.AllGuildConfigs; - - InviteFilteringServers = new ConcurrentHashSet(guildConfigs.Where(gc => gc.FilterInvites).Select(gc => gc.GuildId)); - InviteFilteringChannels = new ConcurrentHashSet(guildConfigs.SelectMany(gc => gc.FilterInvitesChannelIds.Select(fci => fci.ChannelId))); - - var dict = guildConfigs.ToDictionary(gc => gc.GuildId, gc => new ConcurrentHashSet(gc.FilteredWords.Select(fw => fw.Word))); - - serverFilteredWords = new ConcurrentDictionary>(dict); - - var serverFiltering = guildConfigs.Where(gc => gc.FilterWords); - WordFilteringServers = new ConcurrentHashSet(serverFiltering.Select(gc => gc.GuildId)); - - WordFilteringChannels = new ConcurrentHashSet(guildConfigs.SelectMany(gc => gc.FilterWordsChannelIds.Select(fwci => fwci.ChannelId))); + _service = service; + _db = db; } [NadekoCommand, Usage, Description, Aliases] @@ -64,21 +31,21 @@ namespace NadekoBot.Modules.Permissions var channel = (ITextChannel)Context.Channel; bool enabled; - using (var uow = DbHandler.UnitOfWork()) + using (var uow = _db.UnitOfWork) { var config = uow.GuildConfigs.For(channel.Guild.Id, set => set); enabled = config.FilterInvites = !config.FilterInvites; await uow.CompleteAsync().ConfigureAwait(false); } - + if (enabled) { - InviteFilteringServers.Add(channel.Guild.Id); + _service.InviteFilteringServers.Add(channel.Guild.Id); await ReplyConfirmLocalized("invite_filter_server_on").ConfigureAwait(false); } else { - InviteFilteringServers.TryRemove(channel.Guild.Id); + _service.InviteFilteringServers.TryRemove(channel.Guild.Id); await ReplyConfirmLocalized("invite_filter_server_off").ConfigureAwait(false); } } @@ -90,7 +57,7 @@ namespace NadekoBot.Modules.Permissions var channel = (ITextChannel)Context.Channel; int removed; - using (var uow = DbHandler.UnitOfWork()) + using (var uow = _db.UnitOfWork) { var config = uow.GuildConfigs.For(channel.Guild.Id, set => set.Include(gc => gc.FilterInvitesChannelIds)); removed = config.FilterInvitesChannelIds.RemoveWhere(fc => fc.ChannelId == channel.Id); @@ -106,7 +73,7 @@ namespace NadekoBot.Modules.Permissions if (removed == 0) { - InviteFilteringChannels.Add(channel.Id); + _service.InviteFilteringChannels.Add(channel.Id); await ReplyConfirmLocalized("invite_filter_channel_on").ConfigureAwait(false); } else @@ -122,7 +89,7 @@ namespace NadekoBot.Modules.Permissions var channel = (ITextChannel)Context.Channel; bool enabled; - using (var uow = DbHandler.UnitOfWork()) + using (var uow = _db.UnitOfWork) { var config = uow.GuildConfigs.For(channel.Guild.Id, set => set); enabled = config.FilterWords = !config.FilterWords; @@ -131,12 +98,12 @@ namespace NadekoBot.Modules.Permissions if (enabled) { - WordFilteringServers.Add(channel.Guild.Id); + _service.WordFilteringServers.Add(channel.Guild.Id); await ReplyConfirmLocalized("word_filter_server_on").ConfigureAwait(false); } else { - WordFilteringServers.TryRemove(channel.Guild.Id); + _service.WordFilteringServers.TryRemove(channel.Guild.Id); await ReplyConfirmLocalized("word_filter_server_off").ConfigureAwait(false); } } @@ -148,7 +115,7 @@ namespace NadekoBot.Modules.Permissions var channel = (ITextChannel)Context.Channel; int removed; - using (var uow = DbHandler.UnitOfWork()) + using (var uow = _db.UnitOfWork) { var config = uow.GuildConfigs.For(channel.Guild.Id, set => set.Include(gc => gc.FilterWordsChannelIds)); removed = config.FilterWordsChannelIds.RemoveWhere(fc => fc.ChannelId == channel.Id); @@ -164,12 +131,12 @@ namespace NadekoBot.Modules.Permissions if (removed == 0) { - WordFilteringChannels.Add(channel.Id); + _service.WordFilteringChannels.Add(channel.Id); await ReplyConfirmLocalized("word_filter_channel_on").ConfigureAwait(false); } else { - WordFilteringChannels.TryRemove(channel.Id); + _service.WordFilteringChannels.TryRemove(channel.Id); await ReplyConfirmLocalized("word_filter_channel_off").ConfigureAwait(false); } } @@ -186,7 +153,7 @@ namespace NadekoBot.Modules.Permissions return; int removed; - using (var uow = DbHandler.UnitOfWork()) + using (var uow = _db.UnitOfWork) { var config = uow.GuildConfigs.For(channel.Guild.Id, set => set.Include(gc => gc.FilteredWords)); @@ -198,7 +165,7 @@ namespace NadekoBot.Modules.Permissions await uow.CompleteAsync().ConfigureAwait(false); } - var filteredWords = serverFilteredWords.GetOrAdd(channel.Guild.Id, new ConcurrentHashSet()); + var filteredWords = _service.ServerFilteredWords.GetOrAdd(channel.Guild.Id, new ConcurrentHashSet()); if (removed == 0) { @@ -218,8 +185,7 @@ namespace NadekoBot.Modules.Permissions { var channel = (ITextChannel)Context.Channel; - ConcurrentHashSet filteredWords; - serverFilteredWords.TryGetValue(channel.Guild.Id, out filteredWords); + _service.ServerFilteredWords.TryGetValue(channel.Guild.Id, out ConcurrentHashSet filteredWords); await channel.SendConfirmAsync(GetText("filter_word_list"), string.Join("\n", filteredWords)) .ConfigureAwait(false); diff --git a/src/NadekoBot/Modules/Permissions/Commands/GlobalPermissionCommands.cs b/src/NadekoBot/Modules/Permissions/Commands/GlobalPermissionCommands.cs index e493f03d..0d12d651 100644 --- a/src/NadekoBot/Modules/Permissions/Commands/GlobalPermissionCommands.cs +++ b/src/NadekoBot/Modules/Permissions/Commands/GlobalPermissionCommands.cs @@ -1,16 +1,11 @@ using Discord; using Discord.Commands; using NadekoBot.Attributes; -using NadekoBot.DataStructures; using NadekoBot.Extensions; using NadekoBot.Services; -using NadekoBot.Services.Database; +using NadekoBot.Services.Permissions; using NadekoBot.TypeReaders; -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; using System.Linq; -using System.Text; using System.Threading.Tasks; namespace NadekoBot.Modules.Permissions @@ -20,20 +15,20 @@ namespace NadekoBot.Modules.Permissions [Group] public class GlobalPermissionCommands : NadekoSubmodule { - public static readonly ConcurrentHashSet BlockedModules; - public static readonly ConcurrentHashSet BlockedCommands; + private GlobalPermissionService _service; + private readonly DbHandler _db; - static GlobalPermissionCommands() + public GlobalPermissionCommands(GlobalPermissionService service, DbHandler db) { - BlockedModules = new ConcurrentHashSet(NadekoBot.BotConfig.BlockedModules.Select(x => x.Name)); - BlockedCommands = new ConcurrentHashSet(NadekoBot.BotConfig.BlockedCommands.Select(x => x.Name)); + _service = service; + _db = db; } [NadekoCommand, Usage, Description, Aliases] [OwnerOnly] public async Task Lgp() { - if (!BlockedModules.Any() && !BlockedCommands.Any()) + if (!_service.BlockedModules.Any() && !_service.BlockedCommands.Any()) { await ReplyErrorLocalized("lgp_none").ConfigureAwait(false); return; @@ -41,11 +36,11 @@ namespace NadekoBot.Modules.Permissions var embed = new EmbedBuilder().WithOkColor(); - if (BlockedModules.Any()) - embed.AddField(efb => efb.WithName(GetText("blocked_modules")).WithValue(string.Join("\n", BlockedModules)).WithIsInline(false)); + if (_service.BlockedModules.Any()) + embed.AddField(efb => efb.WithName(GetText("blocked_modules")).WithValue(string.Join("\n", _service.BlockedModules)).WithIsInline(false)); - if (BlockedCommands.Any()) - embed.AddField(efb => efb.WithName(GetText("blocked_commands")).WithValue(string.Join("\n", BlockedCommands)).WithIsInline(false)); + if (_service.BlockedCommands.Any()) + embed.AddField(efb => efb.WithName(GetText("blocked_commands")).WithValue(string.Join("\n", _service.BlockedCommands)).WithIsInline(false)); await Context.Channel.EmbedAsync(embed).ConfigureAwait(false); } @@ -55,9 +50,9 @@ namespace NadekoBot.Modules.Permissions public async Task Gmod(ModuleOrCrInfo module) { var moduleName = module.Name.ToLowerInvariant(); - if (BlockedModules.Add(moduleName)) + if (_service.BlockedModules.Add(moduleName)) { - using (var uow = DbHandler.UnitOfWork()) + using (var uow = _db.UnitOfWork) { var bc = uow.BotConfig.GetOrCreate(); bc.BlockedModules.Add(new Services.Database.Models.BlockedCmdOrMdl @@ -69,9 +64,9 @@ namespace NadekoBot.Modules.Permissions await ReplyConfirmLocalized("gmod_add", Format.Bold(module.Name)).ConfigureAwait(false); return; } - else if (BlockedModules.TryRemove(moduleName)) + else if (_service.BlockedModules.TryRemove(moduleName)) { - using (var uow = DbHandler.UnitOfWork()) + using (var uow = _db.UnitOfWork) { var bc = uow.BotConfig.GetOrCreate(); bc.BlockedModules.RemoveWhere(x => x.Name == moduleName); @@ -87,9 +82,9 @@ namespace NadekoBot.Modules.Permissions public async Task Gcmd(CommandOrCrInfo cmd) { var commandName = cmd.Name.ToLowerInvariant(); - if (BlockedCommands.Add(commandName)) + if (_service.BlockedCommands.Add(commandName)) { - using (var uow = DbHandler.UnitOfWork()) + using (var uow = _db.UnitOfWork) { var bc = uow.BotConfig.GetOrCreate(); bc.BlockedCommands.Add(new Services.Database.Models.BlockedCmdOrMdl @@ -101,9 +96,9 @@ namespace NadekoBot.Modules.Permissions await ReplyConfirmLocalized("gcmd_add", Format.Bold(cmd.Name)).ConfigureAwait(false); return; } - else if (BlockedCommands.TryRemove(commandName)) + else if (_service.BlockedCommands.TryRemove(commandName)) { - using (var uow = DbHandler.UnitOfWork()) + using (var uow = _db.UnitOfWork) { var bc = uow.BotConfig.GetOrCreate(); bc.BlockedCommands.RemoveWhere(x => x.Name == commandName); diff --git a/src/NadekoBot/Modules/Permissions/Commands/ResetPermissionsCommands.cs b/src/NadekoBot/Modules/Permissions/Commands/ResetPermissionsCommands.cs new file mode 100644 index 00000000..bef22270 --- /dev/null +++ b/src/NadekoBot/Modules/Permissions/Commands/ResetPermissionsCommands.cs @@ -0,0 +1,62 @@ +using Discord; +using Discord.Commands; +using NadekoBot.Attributes; +using NadekoBot.Services; +using NadekoBot.Services.Database.Models; +using NadekoBot.Services.Permissions; +using System.Threading.Tasks; + +namespace NadekoBot.Modules.Permissions.Commands +{ + public partial class Permissions + { + [Group] + public class ResetPermissionsCommands : NadekoSubmodule + { + private readonly PermissionsService _service; + private readonly DbHandler _db; + private readonly GlobalPermissionService _globalPerms; + + public ResetPermissionsCommands(PermissionsService service, GlobalPermissionService globalPerms, DbHandler db) + { + _service = service; + _db = db; + _globalPerms = globalPerms; + } + + [NadekoCommand, Usage, Description, Aliases] + [RequireContext(ContextType.Guild)] + [RequireUserPermission(GuildPermission.Administrator)] + public async Task ResetPermissions() + { + //todo 80 move to service + using (var uow = _db.UnitOfWork) + { + var config = uow.GuildConfigs.GcWithPermissionsv2For(Context.Guild.Id); + config.Permissions = Permissionv2.GetDefaultPermlist; + await uow.CompleteAsync(); + _service.UpdateCache(config); + } + await ReplyConfirmLocalized("perms_reset").ConfigureAwait(false); + } + + [NadekoCommand, Usage, Description, Aliases] + [OwnerOnly] + public async Task ResetGlobalPermissions() + { + //todo 80 move to service + using (var uow = _db.UnitOfWork) + { + var gc = uow.BotConfig.GetOrCreate(); + gc.BlockedCommands.Clear(); + gc.BlockedModules.Clear(); + + _globalPerms.BlockedCommands.Clear(); + _globalPerms.BlockedModules.Clear(); + await uow.CompleteAsync(); + } + await ReplyConfirmLocalized("global_perms_reset").ConfigureAwait(false); + } + } + } +} diff --git a/src/NadekoBot/Modules/Permissions/Permissions.cs b/src/NadekoBot/Modules/Permissions/Permissions.cs index d51218ba..8d920a47 100644 --- a/src/NadekoBot/Modules/Permissions/Permissions.cs +++ b/src/NadekoBot/Modules/Permissions/Permissions.cs @@ -6,169 +6,34 @@ using Discord.Commands; using NadekoBot.Services; using Discord; using NadekoBot.Services.Database.Models; -using System.Collections.Concurrent; using System.Collections.Generic; using Discord.WebSocket; -using System.Diagnostics; -using Microsoft.EntityFrameworkCore; -using NadekoBot.DataStructures; using NadekoBot.TypeReaders; -using NLog; +using NadekoBot.Services.Permissions; namespace NadekoBot.Modules.Permissions { - [NadekoModule("Permissions", ";")] public partial class Permissions : NadekoTopLevelModule { - //guildid, root permission - public static ConcurrentDictionary Cache { get; } = - new ConcurrentDictionary(); + private readonly DbHandler _db; + private readonly PermissionsService _service; - static Permissions() + public Permissions(PermissionsService service, DbHandler db) { - var log = LogManager.GetCurrentClassLogger(); - var sw = Stopwatch.StartNew(); - - TryMigratePermissions(); - - using (var uow = DbHandler.UnitOfWork()) - { - foreach (var x in uow.GuildConfigs.Permissionsv2ForAll()) - { - Cache.TryAdd(x.GuildId, new PermissionCache() - { - Verbose = x.VerbosePermissions, - PermRole = x.PermissionRole, - Permissions = new PermissionsCollection(x.Permissions) - }); - } - } - - sw.Stop(); - log.Debug($"Loaded in {sw.Elapsed.TotalSeconds:F2}s"); - } - - public static PermissionCache GetCache(ulong guildId) - { - PermissionCache pc; - if (!Permissions.Cache.TryGetValue(guildId, out pc)) - { - using (var uow = DbHandler.UnitOfWork()) - { - var config = uow.GuildConfigs.For(guildId, - set => set.Include(x => x.Permissions)); - Permissions.UpdateCache(config); - } - Permissions.Cache.TryGetValue(guildId, out pc); - if (pc == null) - throw new Exception("Cache is null."); - } - return pc; - } - - private static void TryMigratePermissions() - { - var log = LogManager.GetCurrentClassLogger(); - using (var uow = DbHandler.UnitOfWork()) - { - var oldCache = new ConcurrentDictionary(uow.GuildConfigs - .OldPermissionsForAll() - .Where(x => x.RootPermission != null) // there is a check inside already, but just in case - .ToDictionary(k => k.GuildId, - v => new OldPermissionCache() - { - RootPermission = v.RootPermission, - Verbose = v.VerbosePermissions, - PermRole = v.PermissionRole - })); - - if (oldCache.Any()) - { - log.Info("Old permissions found. Performing one-time migration to v2."); - var i = 0; - foreach (var oc in oldCache) - { - if (i % 3 == 0) - log.Info("Migrating Permissions #" + i + " - GuildId: " + oc.Key); - i++; - var gc = uow.GuildConfigs.GcWithPermissionsv2For(oc.Key); - - var oldPerms = oc.Value.RootPermission.AsEnumerable().Reverse().ToList(); - uow._context.Set().RemoveRange(oldPerms); - gc.RootPermission = null; - if (oldPerms.Count > 2) - { - - var newPerms = oldPerms.Take(oldPerms.Count - 1) - .Select(x => x.Tov2()) - .ToList(); - - var allowPerm = Permissionv2.AllowAllPerm; - var firstPerm = newPerms[0]; - if (allowPerm.State != firstPerm.State || - allowPerm.PrimaryTarget != firstPerm.PrimaryTarget || - allowPerm.SecondaryTarget != firstPerm.SecondaryTarget || - allowPerm.PrimaryTargetId != firstPerm.PrimaryTargetId || - allowPerm.SecondaryTargetName != firstPerm.SecondaryTargetName) - newPerms.Insert(0, Permissionv2.AllowAllPerm); - Cache.TryAdd(oc.Key, new PermissionCache - { - Permissions = new PermissionsCollection(newPerms), - Verbose = gc.VerbosePermissions, - PermRole = gc.PermissionRole, - }); - gc.Permissions = newPerms; - } - } - log.Info("Permission migration to v2 is done."); - uow.Complete(); - } - } - } - - private static async Task AddPermissions(ulong guildId, params Permissionv2[] perms) - { - using (var uow = DbHandler.UnitOfWork()) - { - var config = uow.GuildConfigs.GcWithPermissionsv2For(guildId); - //var orderedPerms = new PermissionsCollection(config.Permissions); - var max = config.Permissions.Max(x => x.Index); //have to set its index to be the highest - foreach (var perm in perms) - { - perm.Index = ++max; - config.Permissions.Add(perm); - } - await uow.CompleteAsync().ConfigureAwait(false); - UpdateCache(config); - } - } - - public static void UpdateCache(GuildConfig config) - { - Cache.AddOrUpdate(config.GuildId, new PermissionCache() - { - Permissions = new PermissionsCollection(config.Permissions), - PermRole = config.PermissionRole, - Verbose = config.VerbosePermissions - }, (id, old) => - { - old.Permissions = new PermissionsCollection(config.Permissions); - old.PermRole = config.PermissionRole; - old.Verbose = config.VerbosePermissions; - return old; - }); + _db = db; + _service = service; } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] public async Task Verbose(PermissionAction action) { - using (var uow = DbHandler.UnitOfWork()) + using (var uow = _db.UnitOfWork) { var config = uow.GuildConfigs.GcWithPermissionsv2For(Context.Guild.Id); config.VerbosePermissions = action.Value; await uow.CompleteAsync().ConfigureAwait(false); - UpdateCache(config); + _service.UpdateCache(config); } if (action.Value) { @@ -187,7 +52,7 @@ namespace NadekoBot.Modules.Permissions if (role != null && role == role.Guild.EveryoneRole) return; - using (var uow = DbHandler.UnitOfWork()) + using (var uow = _db.UnitOfWork) { var config = uow.GuildConfigs.GcWithPermissionsv2For(Context.Guild.Id); if (role == null) @@ -197,7 +62,7 @@ namespace NadekoBot.Modules.Permissions } config.PermissionRole = role.Name.Trim(); await uow.CompleteAsync().ConfigureAwait(false); - UpdateCache(config); + _service.UpdateCache(config); } await ReplyConfirmLocalized("permrole_changed", Format.Bold(role.Name)).ConfigureAwait(false); @@ -210,10 +75,9 @@ namespace NadekoBot.Modules.Permissions if (page < 1) return; - PermissionCache permCache; IList perms; - if (Cache.TryGetValue(Context.Guild.Id, out permCache)) + if (_service.Cache.TryGetValue(Context.Guild.Id, out var permCache)) { perms = permCache.Permissions.Source.ToList(); } @@ -249,7 +113,7 @@ namespace NadekoBot.Modules.Permissions try { Permissionv2 p; - using (var uow = DbHandler.UnitOfWork()) + using (var uow = _db.UnitOfWork) { var config = uow.GuildConfigs.GcWithPermissionsv2For(Context.Guild.Id); var permsCol = new PermissionsCollection(config.Permissions); @@ -257,7 +121,7 @@ namespace NadekoBot.Modules.Permissions permsCol.RemoveAt(index); uow._context.Remove(p); await uow.CompleteAsync().ConfigureAwait(false); - UpdateCache(config); + _service.UpdateCache(config); } await ReplyConfirmLocalized("removed", index + 1, @@ -280,7 +144,7 @@ namespace NadekoBot.Modules.Permissions try { Permissionv2 fromPerm; - using (var uow = DbHandler.UnitOfWork()) + using (var uow = _db.UnitOfWork) { var config = uow.GuildConfigs.GcWithPermissionsv2For(Context.Guild.Id); var permsCol = new PermissionsCollection(config.Permissions); @@ -304,7 +168,7 @@ namespace NadekoBot.Modules.Permissions permsCol.RemoveAt(from); permsCol.Insert(to, fromPerm); await uow.CompleteAsync().ConfigureAwait(false); - UpdateCache(config); + _service.UpdateCache(config); } await ReplyConfirmLocalized("moved_permission", Format.Code(fromPerm.GetCommand((SocketGuild) Context.Guild)), @@ -324,7 +188,7 @@ namespace NadekoBot.Modules.Permissions [RequireContext(ContextType.Guild)] public async Task SrvrCmd(CommandOrCrInfo command, PermissionAction action) { - await AddPermissions(Context.Guild.Id, new Permissionv2 + await _service.AddPermissions(Context.Guild.Id, new Permissionv2 { PrimaryTarget = PrimaryPermissionType.Server, PrimaryTargetId = 0, @@ -351,7 +215,7 @@ namespace NadekoBot.Modules.Permissions [RequireContext(ContextType.Guild)] public async Task SrvrMdl(ModuleOrCrInfo module, PermissionAction action) { - await AddPermissions(Context.Guild.Id, new Permissionv2 + await _service.AddPermissions(Context.Guild.Id, new Permissionv2 { PrimaryTarget = PrimaryPermissionType.Server, PrimaryTargetId = 0, @@ -378,7 +242,7 @@ namespace NadekoBot.Modules.Permissions [RequireContext(ContextType.Guild)] public async Task UsrCmd(CommandOrCrInfo command, PermissionAction action, [Remainder] IGuildUser user) { - await AddPermissions(Context.Guild.Id, new Permissionv2 + await _service.AddPermissions(Context.Guild.Id, new Permissionv2 { PrimaryTarget = PrimaryPermissionType.User, PrimaryTargetId = user.Id, @@ -407,7 +271,7 @@ namespace NadekoBot.Modules.Permissions [RequireContext(ContextType.Guild)] public async Task UsrMdl(ModuleOrCrInfo module, PermissionAction action, [Remainder] IGuildUser user) { - await AddPermissions(Context.Guild.Id, new Permissionv2 + await _service.AddPermissions(Context.Guild.Id, new Permissionv2 { PrimaryTarget = PrimaryPermissionType.User, PrimaryTargetId = user.Id, @@ -439,7 +303,7 @@ namespace NadekoBot.Modules.Permissions if (role == role.Guild.EveryoneRole) return; - await AddPermissions(Context.Guild.Id, new Permissionv2 + await _service.AddPermissions(Context.Guild.Id, new Permissionv2 { PrimaryTarget = PrimaryPermissionType.Role, PrimaryTargetId = role.Id, @@ -471,7 +335,7 @@ namespace NadekoBot.Modules.Permissions if (role == role.Guild.EveryoneRole) return; - await AddPermissions(Context.Guild.Id, new Permissionv2 + await _service.AddPermissions(Context.Guild.Id, new Permissionv2 { PrimaryTarget = PrimaryPermissionType.Role, PrimaryTargetId = role.Id, @@ -501,7 +365,7 @@ namespace NadekoBot.Modules.Permissions [RequireContext(ContextType.Guild)] public async Task ChnlCmd(CommandOrCrInfo command, PermissionAction action, [Remainder] ITextChannel chnl) { - await AddPermissions(Context.Guild.Id, new Permissionv2 + await _service.AddPermissions(Context.Guild.Id, new Permissionv2 { PrimaryTarget = PrimaryPermissionType.Channel, PrimaryTargetId = chnl.Id, @@ -530,7 +394,7 @@ namespace NadekoBot.Modules.Permissions [RequireContext(ContextType.Guild)] public async Task ChnlMdl(ModuleOrCrInfo module, PermissionAction action, [Remainder] ITextChannel chnl) { - await AddPermissions(Context.Guild.Id, new Permissionv2 + await _service.AddPermissions(Context.Guild.Id, new Permissionv2 { PrimaryTarget = PrimaryPermissionType.Channel, PrimaryTargetId = chnl.Id, @@ -559,7 +423,7 @@ namespace NadekoBot.Modules.Permissions [RequireContext(ContextType.Guild)] public async Task AllChnlMdls(PermissionAction action, [Remainder] ITextChannel chnl) { - await AddPermissions(Context.Guild.Id, new Permissionv2 + await _service.AddPermissions(Context.Guild.Id, new Permissionv2 { PrimaryTarget = PrimaryPermissionType.Channel, PrimaryTargetId = chnl.Id, @@ -587,7 +451,7 @@ namespace NadekoBot.Modules.Permissions if (role == role.Guild.EveryoneRole) return; - await AddPermissions(Context.Guild.Id, new Permissionv2 + await _service.AddPermissions(Context.Guild.Id, new Permissionv2 { PrimaryTarget = PrimaryPermissionType.Role, PrimaryTargetId = role.Id, @@ -612,7 +476,7 @@ namespace NadekoBot.Modules.Permissions [RequireContext(ContextType.Guild)] public async Task AllUsrMdls(PermissionAction action, [Remainder] IUser user) { - await AddPermissions(Context.Guild.Id, new Permissionv2 + await _service.AddPermissions(Context.Guild.Id, new Permissionv2 { PrimaryTarget = PrimaryPermissionType.User, PrimaryTargetId = user.Id, @@ -655,7 +519,7 @@ namespace NadekoBot.Modules.Permissions State = true, }; - await AddPermissions(Context.Guild.Id, + await _service.AddPermissions(Context.Guild.Id, newPerm, allowUser); diff --git a/src/NadekoBot/Modules/Searches/Commands/JokeCommands.cs b/src/NadekoBot/Modules/Searches/Commands/JokeCommands.cs index 4dab9c28..590e5426 100644 --- a/src/NadekoBot/Modules/Searches/Commands/JokeCommands.cs +++ b/src/NadekoBot/Modules/Searches/Commands/JokeCommands.cs @@ -1,14 +1,9 @@ using Discord.Commands; using NadekoBot.Attributes; using NadekoBot.Extensions; -using NadekoBot.Modules.Searches.Models; using NadekoBot.Services; using NadekoBot.Services.Searches; -using Newtonsoft.Json; using Newtonsoft.Json.Linq; -using NLog; -using System.Collections.Generic; -using System.IO; using System.Linq; using System.Net.Http; using System.Threading.Tasks; diff --git a/src/NadekoBot/Modules/Searches/Commands/MemegenCommands.cs b/src/NadekoBot/Modules/Searches/Commands/MemegenCommands.cs index 0b12d343..1425436e 100644 --- a/src/NadekoBot/Modules/Searches/Commands/MemegenCommands.cs +++ b/src/NadekoBot/Modules/Searches/Commands/MemegenCommands.cs @@ -1,5 +1,4 @@ using Newtonsoft.Json; -using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; diff --git a/src/NadekoBot/Modules/Searches/Commands/Models/DefineModel.cs b/src/NadekoBot/Modules/Searches/Commands/Models/DefineModel.cs index 98f0f0bd..f88fd9d3 100644 --- a/src/NadekoBot/Modules/Searches/Commands/Models/DefineModel.cs +++ b/src/NadekoBot/Modules/Searches/Commands/Models/DefineModel.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.Collections.Generic; namespace NadekoBot.Modules.Searches.Commands.Models { diff --git a/src/NadekoBot/Modules/Searches/Commands/Models/GoogleSearchResult.cs b/src/NadekoBot/Modules/Searches/Commands/Models/GoogleSearchResult.cs index 7d21d6f8..72fe4483 100644 --- a/src/NadekoBot/Modules/Searches/Commands/Models/GoogleSearchResult.cs +++ b/src/NadekoBot/Modules/Searches/Commands/Models/GoogleSearchResult.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace NadekoBot.Modules.Searches.Commands.Models +namespace NadekoBot.Modules.Searches.Commands.Models { public struct GoogleSearchResult { diff --git a/src/NadekoBot/Modules/Searches/Commands/Models/OverwatchApiModel.cs b/src/NadekoBot/Modules/Searches/Commands/Models/OverwatchApiModel.cs index 50de3be8..a373e062 100644 --- a/src/NadekoBot/Modules/Searches/Commands/Models/OverwatchApiModel.cs +++ b/src/NadekoBot/Modules/Searches/Commands/Models/OverwatchApiModel.cs @@ -1,6 +1,4 @@ using Newtonsoft.Json; -using System; -using System.Text.RegularExpressions; namespace NadekoBot.Modules.Searches.Models { diff --git a/src/NadekoBot/Modules/Searches/Commands/Models/TimeModels.cs b/src/NadekoBot/Modules/Searches/Commands/Models/TimeModels.cs index e997b78c..f30571fc 100644 --- a/src/NadekoBot/Modules/Searches/Commands/Models/TimeModels.cs +++ b/src/NadekoBot/Modules/Searches/Commands/Models/TimeModels.cs @@ -1,9 +1,4 @@ using Newtonsoft.Json; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace NadekoBot.Modules.Searches.Commands.Models { diff --git a/src/NadekoBot/Modules/Searches/Commands/Models/WeatherModels.cs b/src/NadekoBot/Modules/Searches/Commands/Models/WeatherModels.cs index 371b2065..d9495625 100644 --- a/src/NadekoBot/Modules/Searches/Commands/Models/WeatherModels.cs +++ b/src/NadekoBot/Modules/Searches/Commands/Models/WeatherModels.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.Collections.Generic; namespace NadekoBot.Modules.Searches.Commands.Models { diff --git a/src/NadekoBot/Modules/Searches/Commands/OMDB/OmdbProvider.cs b/src/NadekoBot/Modules/Searches/Commands/OMDB/OmdbProvider.cs index dee47aab..9fb1b602 100644 --- a/src/NadekoBot/Modules/Searches/Commands/OMDB/OmdbProvider.cs +++ b/src/NadekoBot/Modules/Searches/Commands/OMDB/OmdbProvider.cs @@ -1,5 +1,4 @@ using Discord; -using Discord.API; using NadekoBot.Extensions; using NadekoBot.Services; using Newtonsoft.Json; diff --git a/src/NadekoBot/Modules/Searches/Commands/PokemonSearchCommands.cs b/src/NadekoBot/Modules/Searches/Commands/PokemonSearchCommands.cs index 7a24c20f..b457b02b 100644 --- a/src/NadekoBot/Modules/Searches/Commands/PokemonSearchCommands.cs +++ b/src/NadekoBot/Modules/Searches/Commands/PokemonSearchCommands.cs @@ -2,12 +2,8 @@ using Discord.Commands; using NadekoBot.Attributes; using NadekoBot.Extensions; -using NadekoBot.Modules.Searches.Models; using NadekoBot.Services.Searches; -using Newtonsoft.Json; -using NLog; using System.Collections.Generic; -using System.IO; using System.Linq; using System.Threading.Tasks; diff --git a/src/NadekoBot/Modules/Searches/Commands/StreamNotificationCommands.cs b/src/NadekoBot/Modules/Searches/Commands/StreamNotificationCommands.cs index 5ad47ffd..a8c3dec1 100644 --- a/src/NadekoBot/Modules/Searches/Commands/StreamNotificationCommands.cs +++ b/src/NadekoBot/Modules/Searches/Commands/StreamNotificationCommands.cs @@ -3,7 +3,6 @@ using Discord; using System.Linq; using System.Threading.Tasks; using NadekoBot.Services; -using System.Threading; using System.Collections.Generic; using NadekoBot.Services.Database.Models; using NadekoBot.Attributes; diff --git a/src/NadekoBot/Modules/Searches/Commands/Translator.cs b/src/NadekoBot/Modules/Searches/Commands/Translator.cs index 6db98c67..639c9825 100644 --- a/src/NadekoBot/Modules/Searches/Commands/Translator.cs +++ b/src/NadekoBot/Modules/Searches/Commands/Translator.cs @@ -2,11 +2,8 @@ using Discord.Commands; using NadekoBot.Attributes; using NadekoBot.Extensions; -using System; using System.Threading.Tasks; -using System.Collections.Concurrent; using System.Linq; -using Discord.WebSocket; using NadekoBot.Services.Searches; using NadekoBot.Services; diff --git a/src/NadekoBot/Modules/Utility/Commands/CommandMapCommands.cs b/src/NadekoBot/Modules/Utility/Commands/CommandMapCommands.cs index a50bf026..2f019382 100644 --- a/src/NadekoBot/Modules/Utility/Commands/CommandMapCommands.cs +++ b/src/NadekoBot/Modules/Utility/Commands/CommandMapCommands.cs @@ -6,6 +6,7 @@ using NadekoBot.Attributes; using NadekoBot.Extensions; using NadekoBot.Services; using NadekoBot.Services.Database.Models; +using NadekoBot.Services.Utility; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; diff --git a/src/NadekoBot/Modules/Utility/Commands/CrossServerTextChannel.cs b/src/NadekoBot/Modules/Utility/Commands/CrossServerTextChannel.cs index 5e198107..4af2c18d 100644 --- a/src/NadekoBot/Modules/Utility/Commands/CrossServerTextChannel.cs +++ b/src/NadekoBot/Modules/Utility/Commands/CrossServerTextChannel.cs @@ -3,9 +3,8 @@ using Discord.Commands; using NadekoBot.Attributes; using NadekoBot.Extensions; using NadekoBot.Services; -using System; +using NadekoBot.Services.Utility; using System.Collections.Concurrent; -using System.Linq; using System.Threading.Tasks; namespace NadekoBot.Modules.Utility diff --git a/src/NadekoBot/Modules/Utility/Commands/MessageRepeater.cs b/src/NadekoBot/Modules/Utility/Commands/MessageRepeater.cs index 6e0007ce..a2790756 100644 --- a/src/NadekoBot/Modules/Utility/Commands/MessageRepeater.cs +++ b/src/NadekoBot/Modules/Utility/Commands/MessageRepeater.cs @@ -11,7 +11,7 @@ using System.Linq; using System.Text; using System.Threading.Tasks; using Discord.WebSocket; -using NadekoBot.Modules.Utility.Models; +using NadekoBot.Services.Utility; namespace NadekoBot.Modules.Utility { @@ -20,11 +20,11 @@ namespace NadekoBot.Modules.Utility [Group] public class RepeatCommands : NadekoSubmodule { - private readonly UtilityService _service; + private readonly MessageRepeaterService _service; private readonly DiscordShardedClient _client; private readonly DbHandler _db; - public RepeatCommands(UtilityService service, DiscordShardedClient client, DbHandler db) + public RepeatCommands(MessageRepeaterService service, DiscordShardedClient client, DbHandler db) { _service = service; _client = client; diff --git a/src/NadekoBot/Modules/Utility/Commands/Remind.cs b/src/NadekoBot/Modules/Utility/Commands/Remind.cs index eafd5f39..f5781b9f 100644 --- a/src/NadekoBot/Modules/Utility/Commands/Remind.cs +++ b/src/NadekoBot/Modules/Utility/Commands/Remind.cs @@ -4,12 +4,10 @@ using NadekoBot.Attributes; using NadekoBot.Extensions; using NadekoBot.Services; using NadekoBot.Services.Database.Models; -using NLog; +using NadekoBot.Services.Utility; using System; using System.Collections.Generic; -using System.Linq; using System.Text.RegularExpressions; -using System.Threading; using System.Threading.Tasks; namespace NadekoBot.Modules.Utility @@ -19,10 +17,10 @@ namespace NadekoBot.Modules.Utility [Group] public class RemindCommands : NadekoSubmodule { - private readonly UtilityService _service; + private readonly RemindService _service; private readonly DbHandler _db; - public RemindCommands(UtilityService service, DbHandler db) + public RemindCommands(RemindService service, DbHandler db) { _service = service; _db = db; @@ -63,7 +61,7 @@ namespace NadekoBot.Modules.Utility public async Task RemindInternal(ulong targetId, bool isPrivate, string timeStr, [Remainder] string message) { - var m = _service.Remind.Regex.Match(timeStr); + var m = _service.Regex.Match(timeStr); if (m.Length == 0) { @@ -74,7 +72,7 @@ namespace NadekoBot.Modules.Utility string output = ""; var namesAndValues = new Dictionary(); - foreach (var groupName in _service.Remind.Regex.GetGroupNames()) + foreach (var groupName in _service.Regex.GetGroupNames()) { if (groupName == "0") continue; int value; @@ -134,7 +132,7 @@ namespace NadekoBot.Modules.Utility { // ignored } - await _service.Remind.StartReminder(rem); + await _service.StartReminder(rem); } [NadekoCommand, Usage, Description, Aliases] diff --git a/src/NadekoBot/Modules/Utility/Commands/UnitConversion.cs b/src/NadekoBot/Modules/Utility/Commands/UnitConversion.cs index ea16953f..9b9c121c 100644 --- a/src/NadekoBot/Modules/Utility/Commands/UnitConversion.cs +++ b/src/NadekoBot/Modules/Utility/Commands/UnitConversion.cs @@ -2,6 +2,7 @@ using Discord.Commands; using NadekoBot.Attributes; using NadekoBot.Extensions; +using NadekoBot.Services.Utility; using System; using System.Linq; using System.Threading.Tasks; @@ -13,9 +14,9 @@ namespace NadekoBot.Modules.Utility [Group] public class UnitConverterCommands : NadekoSubmodule { - private readonly UtilityService _service; + private readonly ConverterService _service; - public UnitConverterCommands(UtilityService service) + public UnitConverterCommands(ConverterService service) { _service = service; } @@ -23,7 +24,7 @@ namespace NadekoBot.Modules.Utility [NadekoCommand, Usage, Description, Aliases] public async Task ConvertList() { - var res = _service.Converter.Units.GroupBy(x => x.UnitType) + var res = _service.Units.GroupBy(x => x.UnitType) .Aggregate(new EmbedBuilder().WithTitle(GetText("convertlist")) .WithColor(NadekoBot.OkColor), (embed, g) => embed.AddField(efb => @@ -35,8 +36,8 @@ namespace NadekoBot.Modules.Utility [NadekoCommand, Usage, Description, Aliases] public async Task Convert(string origin, string target, decimal value) { - var originUnit = _service.Converter.Units.Find(x => x.Triggers.Select(y => y.ToLowerInvariant()).Contains(origin.ToLowerInvariant())); - var targetUnit = _service.Converter.Units.Find(x => x.Triggers.Select(y => y.ToLowerInvariant()).Contains(target.ToLowerInvariant())); + var originUnit = _service.Units.Find(x => x.Triggers.Select(y => y.ToLowerInvariant()).Contains(origin.ToLowerInvariant())); + var targetUnit = _service.Units.Find(x => x.Triggers.Select(y => y.ToLowerInvariant()).Contains(target.ToLowerInvariant())); if (originUnit == null || targetUnit == null) { await ReplyErrorLocalized("convert_not_found", Format.Bold(origin), Format.Bold(target)).ConfigureAwait(false); diff --git a/src/NadekoBot/Modules/Utility/Models/PatreonData.cs b/src/NadekoBot/Modules/Utility/Models/PatreonData.cs index 87ab3f91..c56a89b1 100644 --- a/src/NadekoBot/Modules/Utility/Models/PatreonData.cs +++ b/src/NadekoBot/Modules/Utility/Models/PatreonData.cs @@ -1,9 +1,4 @@ using Newtonsoft.Json.Linq; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace NadekoBot.Modules.Utility.Models { diff --git a/src/NadekoBot/Modules/Utility/Models/PatreonPledge.cs b/src/NadekoBot/Modules/Utility/Models/PatreonPledge.cs index 1ea3bd3a..e37157e9 100644 --- a/src/NadekoBot/Modules/Utility/Models/PatreonPledge.cs +++ b/src/NadekoBot/Modules/Utility/Models/PatreonPledge.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace NadekoBot.Modules.Utility.Models +namespace NadekoBot.Modules.Utility.Models { public class Attributes { diff --git a/src/NadekoBot/Modules/Utility/Models/PatreonUser.cs b/src/NadekoBot/Modules/Utility/Models/PatreonUser.cs index 353a493a..8f83f1c0 100644 --- a/src/NadekoBot/Modules/Utility/Models/PatreonUser.cs +++ b/src/NadekoBot/Modules/Utility/Models/PatreonUser.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace NadekoBot.Modules.Utility.Models +namespace NadekoBot.Modules.Utility.Models { public class DiscordConnection { diff --git a/src/NadekoBot/Modules/Utility/Utility.cs b/src/NadekoBot/Modules/Utility/Utility.cs index 102f717a..4fb017c0 100644 --- a/src/NadekoBot/Modules/Utility/Utility.cs +++ b/src/NadekoBot/Modules/Utility/Utility.cs @@ -15,10 +15,11 @@ using ImageSharp; using System.Collections.Generic; using Newtonsoft.Json; using Discord.WebSocket; -using NadekoBot.Services; using System.Diagnostics; +using NadekoBot.Modules; +using Color = Discord.Color; -namespace NadekoBot.Modules.Utility +namespace NadekoBot.Services.Utility { public partial class Utility : NadekoTopLevelModule { @@ -164,7 +165,7 @@ namespace NadekoBot.Modules.Utility try { var color = hexColors[i]; - await role.ModifyAsync(r => r.Color = new Discord.Color(color.R, color.G, color.B)).ConfigureAwait(false); + await role.ModifyAsync(r => r.Color = new Color(color.R, color.G, color.B)).ConfigureAwait(false); ++i; if (i >= hexColors.Length) i = 0; diff --git a/src/NadekoBot/Modules/Utility/UtilityService.cs b/src/NadekoBot/Modules/Utility/UtilityService.cs deleted file mode 100644 index 5bb6baa1..00000000 --- a/src/NadekoBot/Modules/Utility/UtilityService.cs +++ /dev/null @@ -1,319 +0,0 @@ -using Discord; -using Discord.WebSocket; -using NadekoBot.Extensions; -using NadekoBot.Modules.Utility.Models; -using NadekoBot.Services; -using NadekoBot.Services.Database.Models; -using Newtonsoft.Json; -using NLog; -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Net.Http; -using System.Text.RegularExpressions; -using System.Threading; -using System.Threading.Tasks; - -namespace NadekoBot.Modules.Utility -{ - public class UtilityService - { - public ConcurrentDictionary> AliasMaps { get; } = new ConcurrentDictionary>(); - - //messagerepeater - //guildid/RepeatRunners - public ConcurrentDictionary> Repeaters { get; set; } - public bool RepeaterReady { get; private set; } - - //remind - public RemindService Remind { get; } - - //unit conversion - public ConverterService Converter { get; } - - public UtilityService(IEnumerable guildConfigs, DiscordShardedClient client, BotConfig config, DbHandler db) - { - //commandmap - AliasMaps = new ConcurrentDictionary>( - guildConfigs.ToDictionary( - x => x.GuildId, - x => new ConcurrentDictionary(x.CommandAliases - .Distinct(new CommandAliasEqualityComparer()) - .ToDictionary(ca => ca.Trigger, ca => ca.Mapping)))); - - //crossesrver - _client = client; - _client.MessageReceived += Client_MessageReceived; - - //messagerepeater - var _ = Task.Run(async () => - { -#if !GLOBAL_NADEKO - await Task.Delay(5000).ConfigureAwait(false); -#else - await Task.Delay(30000).ConfigureAwait(false); -#endif - //todo this is pretty terrible :kms: no time - Repeaters = new ConcurrentDictionary>(guildConfigs - .ToDictionary(gc => gc.GuildId, - gc => new ConcurrentQueue(gc.GuildRepeaters - .Select(gr => new RepeatRunner(client, gr)) - .Where(x => x.Guild != null)))); - RepeaterReady = true; - }); - - //reminder - Remind = new RemindService(client, config, db); - - //unit converter - Converter = new ConverterService(db); - } - - private async Task Client_MessageReceived(Discord.WebSocket.SocketMessage imsg) - { - try - { - if (imsg.Author.IsBot) - return; - var msg = imsg as IUserMessage; - if (msg == null) - return; - var channel = imsg.Channel as ITextChannel; - if (channel == null) - return; - if (msg.Author.Id == _client.CurrentUser.Id) return; - foreach (var subscriber in Subscribers) - { - var set = subscriber.Value; - if (!set.Contains(channel)) - continue; - foreach (var chan in set.Except(new[] { channel })) - { - try - { - await chan.SendMessageAsync(GetMessage(channel, (IGuildUser)msg.Author, - msg)).ConfigureAwait(false); - } - catch - { - // ignored - } - } - } - } - catch - { - // ignored - } - } - - private string GetMessage(ITextChannel channel, IGuildUser user, IUserMessage message) => - $"**{channel.Guild.Name} | {channel.Name}** `{user.Username}`: " + message.Content.SanitizeMentions(); - - public readonly ConcurrentDictionary> Subscribers = - new ConcurrentDictionary>(); - private DiscordShardedClient _client; - } - - public class ConverterService - { - public class MeasurementUnit - { - public List Triggers { get; set; } - public string UnitType { get; set; } - public decimal Modifier { get; set; } - } - - public class Rates - { - public string Base { get; set; } - public DateTime Date { get; set; } - [JsonProperty("rates")] - public Dictionary ConversionRates { get; set; } - } - - public List Units { get; set; } = new List(); - private readonly Logger _log; - private Timer _timer; - private readonly TimeSpan _updateInterval = new TimeSpan(12, 0, 0); - private readonly DbHandler _db; - - public ConverterService(DbHandler db) - { - _log = LogManager.GetCurrentClassLogger(); - _db = db; - try - { - var data = JsonConvert.DeserializeObject>(File.ReadAllText("data/units.json")).Select(u => new ConvertUnit() - { - Modifier = u.Modifier, - UnitType = u.UnitType, - InternalTrigger = string.Join("|", u.Triggers) - }).ToArray(); - - using (var uow = _db.UnitOfWork) - { - if (uow.ConverterUnits.Empty()) - { - uow.ConverterUnits.AddRange(data); - uow.Complete(); - } - } - Units = data.ToList(); - } - catch (Exception ex) - { - _log.Warn("Could not load units: " + ex.Message); - } - - _timer = new Timer(async (obj) => await UpdateCurrency(), null, _updateInterval, _updateInterval); - } - - public static async Task UpdateCurrencyRates() - { - using (var http = new HttpClient()) - { - var res = await http.GetStringAsync("http://api.fixer.io/latest").ConfigureAwait(false); - return JsonConvert.DeserializeObject(res); - } - } - - public async Task UpdateCurrency() - { - try - { - var currencyRates = await UpdateCurrencyRates(); - var unitTypeString = "currency"; - var range = currencyRates.ConversionRates.Select(u => new ConvertUnit() - { - InternalTrigger = u.Key, - Modifier = u.Value, - UnitType = unitTypeString - }).ToArray(); - var baseType = new ConvertUnit() - { - Triggers = new[] { currencyRates.Base }, - Modifier = decimal.One, - UnitType = unitTypeString - }; - var toRemove = Units.Where(u => u.UnitType == unitTypeString); - - using (var uow = _db.UnitOfWork) - { - uow.ConverterUnits.RemoveRange(toRemove.ToArray()); - uow.ConverterUnits.Add(baseType); - uow.ConverterUnits.AddRange(range); - - await uow.CompleteAsync().ConfigureAwait(false); - } - Units.RemoveAll(u => u.UnitType == unitTypeString); - Units.Add(baseType); - Units.AddRange(range); - _log.Info("Updated Currency"); - } - catch - { - _log.Warn("Failed updating currency. Ignore this."); - } - } - - } - - public class RemindService - { - public readonly Regex Regex = new Regex(@"^(?:(?\d)mo)?(?:(?\d)w)?(?:(?\d{1,2})d)?(?:(?\d{1,2})h)?(?:(?\d{1,2})m)?$", - RegexOptions.Compiled | RegexOptions.Multiline); - - public string RemindMessageFormat { get; } - - public readonly IDictionary> _replacements = new Dictionary> - { - { "%message%" , (r) => r.Message }, - { "%user%", (r) => $"<@!{r.UserId}>" }, - { "%target%", (r) => r.IsPrivate ? "Direct Message" : $"<#{r.ChannelId}>"} - }; - - private readonly Logger _log; - private readonly CancellationTokenSource cancelSource; - private readonly CancellationToken cancelAllToken; - private readonly BotConfig _config; - private readonly DiscordShardedClient _client; - private readonly DbHandler _db; - - public RemindService(DiscordShardedClient client, BotConfig config, DbHandler db) - { - _config = config; - _client = client; - _log = LogManager.GetCurrentClassLogger(); - _db = db; - - cancelSource = new CancellationTokenSource(); - cancelAllToken = cancelSource.Token; - List reminders; - using (var uow = _db.UnitOfWork) - { - reminders = uow.Reminders.GetAll().ToList(); - } - RemindMessageFormat = _config.RemindMessageFormat; - - foreach (var r in reminders) - { - Task.Run(() => StartReminder(r)); - } - } - - public async Task StartReminder(Reminder r) - { - var t = cancelAllToken; - var now = DateTime.Now; - - var time = r.When - now; - - if (time.TotalMilliseconds > int.MaxValue) - return; - - await Task.Delay(time, t).ConfigureAwait(false); - try - { - IMessageChannel ch; - if (r.IsPrivate) - { - var user = _client.GetGuild(r.ServerId).GetUser(r.ChannelId); - if (user == null) - return; - ch = await user.CreateDMChannelAsync().ConfigureAwait(false); - } - else - { - ch = _client.GetGuild(r.ServerId)?.GetTextChannel(r.ChannelId); - } - if (ch == null) - return; - - await ch.SendMessageAsync( - _replacements.Aggregate(RemindMessageFormat, - (cur, replace) => cur.Replace(replace.Key, replace.Value(r))) - .SanitizeMentions() - ).ConfigureAwait(false); //it works trust me - } - catch (Exception ex) { _log.Warn(ex); } - finally - { - using (var uow = _db.UnitOfWork) - { - uow.Reminders.Remove(r); - await uow.CompleteAsync(); - } - } - } - } - - public class CommandAliasEqualityComparer : IEqualityComparer - { - public bool Equals(CommandAlias x, CommandAlias y) => x.Trigger == y.Trigger; - - public int GetHashCode(CommandAlias obj) => obj.Trigger.GetHashCode(); - } -} diff --git a/src/NadekoBot/NadekoBot.cs b/src/NadekoBot/NadekoBot.cs index eabdceed..e3c20679 100644 --- a/src/NadekoBot/NadekoBot.cs +++ b/src/NadekoBot/NadekoBot.cs @@ -16,20 +16,21 @@ using System.Collections.Immutable; using System.Diagnostics; using NadekoBot.Services.Database.Models; using System.Threading; -using NadekoBot.Modules.Utility; using NadekoBot.Services.Searches; using NadekoBot.Services.ClashOfClans; using NadekoBot.Services.Music; using NadekoBot.Services.CustomReactions; using NadekoBot.Services.Games; using NadekoBot.Services.Administration; +using NadekoBot.Services.Permissions; +using NadekoBot.Services.Utility; namespace NadekoBot { public class NadekoBot { private Logger _log; - + /* I don't know how to make this not be static * and keep the convenience of .WithOkColor * and .WithErrorColor extensions methods. @@ -38,26 +39,30 @@ namespace NadekoBot * I'll keep this for now */ public static Color OkColor { get; private set; } public static Color ErrorColor { get; private set; } - + //todo placeholder, will be guild-based public static string Prefix { get; } = "."; public ImmutableArray AllGuildConfigs { get; } public BotConfig BotConfig { get; } + public DbHandler Db { get; } + public CommandService CommandService { get; } public DiscordShardedClient Client { get; } public bool Ready { get; private set; } - public INServiceProvider Services { get; } + public INServiceProvider Services { get; private set; } + public BotCredentials Credentials { get; } public NadekoBot() { SetupLogger(); _log = LogManager.GetCurrentClassLogger(); - var credentials = new BotCredentials(); - var db = new DbHandler(credentials); - using (var uow = db.UnitOfWork) + Credentials = new BotCredentials(); + Db = new DbHandler(Credentials); + + using (var uow = Db.UnitOfWork) { AllGuildConfigs = uow.GuildConfigs.GetAllGuildConfigs().ToImmutableArray(); BotConfig = uow.BotConfig.GetOrCreate(); @@ -69,74 +74,88 @@ namespace NadekoBot { MessageCacheSize = 10, LogLevel = LogSeverity.Warning, - TotalShards = credentials.TotalShards, + TotalShards = Credentials.TotalShards, ConnectionTimeout = int.MaxValue, AlwaysDownloadUsers = true, }); - var google = new GoogleApiService(credentials); - var localization = new Localization(BotConfig.Locale, AllGuildConfigs.ToDictionary(x => x.GuildId, x => x.Locale), db); - var strings = new NadekoStrings(localization); - - var greetSettingsService = new GreetSettingsService(Client, AllGuildConfigs, db); - - var commandService = new CommandService(new CommandServiceConfig() + CommandService = new CommandService(new CommandServiceConfig() { CaseSensitiveCommands = false, DefaultRunMode = RunMode.Sync, }); - var commandHandler = new CommandHandler(Client, commandService, credentials, this); - - var stats = new StatsService(Client, commandHandler, credentials); +#if GLOBAL_NADEKO + Client.Log += Client_Log; +#endif + } + private void AddServices() + { + var googleApiService = new GoogleApiService(Credentials); + var soundcloudApiService = new SoundCloudApiService(Credentials); + var localization = new Localization(BotConfig.Locale, AllGuildConfigs.ToDictionary(x => x.GuildId, x => x.Locale), Db); + var strings = new NadekoStrings(localization); + var commandHandler = new CommandHandler(Client, CommandService, Credentials, this); + var stats = new StatsService(Client, commandHandler, Credentials); var images = new ImagesService(); - - var currencyHandler = new CurrencyHandler(BotConfig, db); - - var soundcloud = new SoundCloudApiService(credentials); + var currencyHandler = new CurrencyHandler(BotConfig, Db); //module services - //todo 90 - Make this automatic - var utilityService = new UtilityService(AllGuildConfigs, Client, BotConfig, db); -#region Searches - var searchesService = new SearchesService(Client, google, db); - var streamNotificationService = new StreamNotificationService(db, Client, strings); -#endregion - var clashService = new ClashOfClansService(Client, db, localization, strings); - var musicService = new MusicService(google, strings, localization, db, soundcloud, credentials); - var crService = new CustomReactionsService(db, Client); + //todo 90 - autodiscover, DI, and add instead of manual like this + #region utility + var utilityService = new UtilityService(AllGuildConfigs, Client); + var remindService = new RemindService(Client, BotConfig, Db); + var repeaterService = new MessageRepeaterService(Client, AllGuildConfigs); + var converterService = new ConverterService(Db); + #endregion + #region Searches + var searchesService = new SearchesService(Client, googleApiService, Db); + var streamNotificationService = new StreamNotificationService(Db, Client, strings); + #endregion + var clashService = new ClashOfClansService(Client, Db, localization, strings); + var musicService = new MusicService(googleApiService, strings, localization, Db, soundcloudApiService, Credentials); + var crService = new CustomReactionsService(Db, Client); var gamesService = new GamesService(Client, BotConfig, AllGuildConfigs, strings, images); -#region administration + #region administration var administrationService = new AdministrationService(AllGuildConfigs, commandHandler); - var selfService = new SelfService(this, commandHandler, db, BotConfig); + var greetSettingsService = new GreetSettingsService(Client, AllGuildConfigs, Db); + var selfService = new SelfService(this, commandHandler, Db, BotConfig); var vcRoleService = new VcRoleService(Client, AllGuildConfigs); - var vPlusTService = new VplusTService(Client, AllGuildConfigs, strings, db); - var muteService = new MuteService(Client, AllGuildConfigs, db); + var vPlusTService = new VplusTService(Client, AllGuildConfigs, strings, Db); + var muteService = new MuteService(Client, AllGuildConfigs, Db); var ratelimitService = new RatelimitService(Client, AllGuildConfigs); var protectionService = new ProtectionService(Client, AllGuildConfigs, muteService); var playingRotateService = new PlayingRotateService(Client, BotConfig, musicService); - var gameVcService = new GameVoiceChannelService(Client, db, AllGuildConfigs); + var gameVcService = new GameVoiceChannelService(Client, Db, AllGuildConfigs); var autoAssignRoleService = new AutoAssignRoleService(Client, AllGuildConfigs); -#endregion + var permissionsService = new PermissionsService(Db); + var blacklistService = new BlacklistService(BotConfig); + var cmdcdsService = new CmdCdService(AllGuildConfigs); + var filterService = new FilterService(AllGuildConfigs); + var globalPermsService = new GlobalPermissionService(BotConfig); + #endregion //initialize Services Services = new NServiceProvider.ServiceProviderBuilder() .Add(localization) .Add(stats) .Add(images) - .Add(google) + .Add(googleApiService) .Add(stats) - .Add(credentials) - .Add(commandService) + .Add(Credentials) + .Add(CommandService) .Add(strings) .Add(Client) .Add(BotConfig) .Add(currencyHandler) .Add(commandHandler) - .Add(db) + .Add(Db) //modules .Add(utilityService) + .Add(remindService) + .Add(repeaterService) + .Add(converterService) .Add(searchesService) .Add(streamNotificationService) .Add(clashService) @@ -154,37 +173,30 @@ namespace NadekoBot .Add(gameVcService) .Add(autoAssignRoleService) .Add(protectionService) + .Add(permissionsService) + .Add(blacklistService) + .Add(cmdcdsService) + .Add(filterService) + .Add(globalPermsService) .Build(); commandHandler.AddServices(Services); //setup typereaders - commandService.AddTypeReader(new PermissionActionTypeReader()); - commandService.AddTypeReader(new CommandTypeReader(commandService)); - //commandService.AddTypeReader(new CommandOrCrTypeReader()); - commandService.AddTypeReader(new ModuleTypeReader(commandService)); - commandService.AddTypeReader(new ModuleOrCrTypeReader(commandService)); - commandService.AddTypeReader(new GuildTypeReader(Client)); - -#if GLOBAL_NADEKO - Client.Log += Client_Log; -#endif + CommandService.AddTypeReader(new PermissionActionTypeReader()); + CommandService.AddTypeReader(new CommandTypeReader(CommandService)); + CommandService.AddTypeReader(new CommandOrCrTypeReader(crService, CommandService)); + CommandService.AddTypeReader(new ModuleTypeReader(CommandService)); + CommandService.AddTypeReader(new ModuleOrCrTypeReader(CommandService)); + CommandService.AddTypeReader(new GuildTypeReader(Client)); } - public async Task RunAsync(params string[] args) + private async Task LoginAsync(string token) { - var creds = Services.GetService(); - var stats = Services.GetService(); - var commandHandler = Services.GetService(); - var commandService = Services.GetService(); - - _log.Info("Starting NadekoBot v" + StatsService.BotVersion); - - var sw = Stopwatch.StartNew(); //connect - await Client.LoginAsync(TokenType.Bot, creds.Token).ConfigureAwait(false); + await Client.LoginAsync(TokenType.Bot, token).ConfigureAwait(false); await Client.StartAsync().ConfigureAwait(false); - + // wait for all shards to be ready int readyCount = 0; foreach (var s in Client.Shards) @@ -192,19 +204,33 @@ namespace NadekoBot while (readyCount < Client.Shards.Count) await Task.Delay(100).ConfigureAwait(false); - - stats.Initialize(); + } + + public async Task RunAsync(params string[] args) + { + _log.Info("Starting NadekoBot v" + StatsService.BotVersion); + + var sw = Stopwatch.StartNew(); + + await LoginAsync(Credentials.Token).ConfigureAwait(false); + + AddServices(); sw.Stop(); _log.Info("Connected in " + sw.Elapsed.TotalSeconds.ToString("F2")); + var stats = Services.GetService(); + stats.Initialize(); + var commandHandler = Services.GetService(); + var CommandService = Services.GetService(); + // start handling messages received in commandhandler await commandHandler.StartHandling().ConfigureAwait(false); - var _ = await Task.Run(() => commandService.AddModulesAsync(this.GetType().GetTypeInfo().Assembly)).ConfigureAwait(false); + var _ = await CommandService.AddModulesAsync(this.GetType().GetTypeInfo().Assembly); #if !GLOBAL_NADEKO //todo uncomment this - //await commandService.AddModuleAsync().ConfigureAwait(false); + //await CommandService.AddModuleAsync().ConfigureAwait(false); #endif Ready = true; _log.Info(await stats.Print().ConfigureAwait(false)); diff --git a/src/NadekoBot/NadekoBot.csproj b/src/NadekoBot/NadekoBot.csproj index b0f02199..7cdaca61 100644 --- a/src/NadekoBot/NadekoBot.csproj +++ b/src/NadekoBot/NadekoBot.csproj @@ -30,13 +30,10 @@ - - - diff --git a/src/NadekoBot/Services/Administration/AdministrationService.cs b/src/NadekoBot/Services/Administration/AdministrationService.cs index 69dfaf16..3ead9cc3 100644 --- a/src/NadekoBot/Services/Administration/AdministrationService.cs +++ b/src/NadekoBot/Services/Administration/AdministrationService.cs @@ -7,7 +7,6 @@ using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; -using System.Text; using System.Threading.Tasks; namespace NadekoBot.Services.Administration diff --git a/src/NadekoBot/Services/Administration/PlayingRotateService.cs b/src/NadekoBot/Services/Administration/PlayingRotateService.cs index a63592ff..7662b7ca 100644 --- a/src/NadekoBot/Services/Administration/PlayingRotateService.cs +++ b/src/NadekoBot/Services/Administration/PlayingRotateService.cs @@ -6,9 +6,7 @@ using NLog; using System; using System.Collections.Generic; using System.Linq; -using System.Text; using System.Threading; -using System.Threading.Tasks; namespace NadekoBot.Services.Administration { diff --git a/src/NadekoBot/Services/Administration/ProtectionService.cs b/src/NadekoBot/Services/Administration/ProtectionService.cs index e57f38ef..1737df9a 100644 --- a/src/NadekoBot/Services/Administration/ProtectionService.cs +++ b/src/NadekoBot/Services/Administration/ProtectionService.cs @@ -6,7 +6,6 @@ using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; -using System.Text; using System.Threading.Tasks; namespace NadekoBot.Services.Administration diff --git a/src/NadekoBot/Services/Administration/Ratelimiter.cs b/src/NadekoBot/Services/Administration/Ratelimiter.cs index 168e8f60..6bc65d26 100644 --- a/src/NadekoBot/Services/Administration/Ratelimiter.cs +++ b/src/NadekoBot/Services/Administration/Ratelimiter.cs @@ -3,7 +3,6 @@ using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; -using System.Text; using System.Threading; using System.Threading.Tasks; diff --git a/src/NadekoBot/Services/Administration/SelfService.cs b/src/NadekoBot/Services/Administration/SelfService.cs index 734beab2..c1298f36 100644 --- a/src/NadekoBot/Services/Administration/SelfService.cs +++ b/src/NadekoBot/Services/Administration/SelfService.cs @@ -1,9 +1,4 @@ using NadekoBot.Services.Database.Models; -using NLog; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; using System.Threading.Tasks; namespace NadekoBot.Services.Administration diff --git a/src/NadekoBot/Services/Administration/UserSpamStats.cs b/src/NadekoBot/Services/Administration/UserSpamStats.cs index 401aa180..ad2efcbe 100644 --- a/src/NadekoBot/Services/Administration/UserSpamStats.cs +++ b/src/NadekoBot/Services/Administration/UserSpamStats.cs @@ -1,11 +1,8 @@ using Discord; using System; using System.Collections.Concurrent; -using System.Collections.Generic; using System.Linq; -using System.Text; using System.Threading; -using System.Threading.Tasks; namespace NadekoBot.Services.Administration { diff --git a/src/NadekoBot/Services/Administration/VcRoleService.cs b/src/NadekoBot/Services/Administration/VcRoleService.cs index 057687d9..e04805b8 100644 --- a/src/NadekoBot/Services/Administration/VcRoleService.cs +++ b/src/NadekoBot/Services/Administration/VcRoleService.cs @@ -6,7 +6,6 @@ using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; -using System.Text; using System.Threading.Tasks; namespace NadekoBot.Services.Administration diff --git a/src/NadekoBot/Services/Administration/VplusTService.cs b/src/NadekoBot/Services/Administration/VplusTService.cs index 6d0f8e62..48bccb9c 100644 --- a/src/NadekoBot/Services/Administration/VplusTService.cs +++ b/src/NadekoBot/Services/Administration/VplusTService.cs @@ -7,7 +7,6 @@ using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; -using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; diff --git a/src/NadekoBot/Services/ClashOfClans/ClashOfClansService.cs b/src/NadekoBot/Services/ClashOfClans/ClashOfClansService.cs index 13ea5ba2..6ea1bf41 100644 --- a/src/NadekoBot/Services/ClashOfClans/ClashOfClansService.cs +++ b/src/NadekoBot/Services/ClashOfClans/ClashOfClansService.cs @@ -1,6 +1,5 @@ using Discord; using Discord.WebSocket; -using NadekoBot.DataStructures.ModuleBehaviors; using NadekoBot.Extensions; using NadekoBot.Services.Database.Models; using System; @@ -13,8 +12,8 @@ using System.Threading.Tasks; namespace NadekoBot.Services.ClashOfClans { - // todo, just made this compile, it's a complete mess. A lot of the things here should actually be in the actual module. - // service should just handle the state, module should print out what happened, so everything that has to do with strings + // todo 99 rewrite, just made this compile, it's a complete mess. A lot of the things here should actually be in the actual module. + // service should just handle the state, module should print out what happened, so anything that has to do with strings // shouldn't be here public class ClashOfClansService { diff --git a/src/NadekoBot/Services/CustomReactions/Extensions.cs b/src/NadekoBot/Services/CustomReactions/Extensions.cs index b6a7b12f..9f4444ed 100644 --- a/src/NadekoBot/Services/CustomReactions/Extensions.cs +++ b/src/NadekoBot/Services/CustomReactions/Extensions.cs @@ -2,7 +2,6 @@ using Discord.WebSocket; using NadekoBot.DataStructures; using NadekoBot.Extensions; -using NadekoBot.Services; using NadekoBot.Services.Database.Models; using System; using System.Collections.Generic; diff --git a/src/NadekoBot/Services/Database/Models/AntiProtection.cs b/src/NadekoBot/Services/Database/Models/AntiProtection.cs index a90ee649..160425ea 100644 --- a/src/NadekoBot/Services/Database/Models/AntiProtection.cs +++ b/src/NadekoBot/Services/Database/Models/AntiProtection.cs @@ -1,8 +1,4 @@ -using Discord; -using NadekoBot.Services.Database.Models; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations.Schema; +using System.Collections.Generic; namespace NadekoBot.Services.Database.Models { public class AntiRaidSetting : DbEntity diff --git a/src/NadekoBot/Services/Database/Models/BotConfig.cs b/src/NadekoBot/Services/Database/Models/BotConfig.cs index 81bbb87f..d96df33e 100644 --- a/src/NadekoBot/Services/Database/Models/BotConfig.cs +++ b/src/NadekoBot/Services/Database/Models/BotConfig.cs @@ -104,13 +104,13 @@ Nadeko Support Server: https://discord.gg/nadekobot"; { public ulong ItemId { get; set; } public BlacklistType Type { get; set; } + } - public enum BlacklistType - { - Server, - Channel, - User - } + public enum BlacklistType + { + Server, + Channel, + User } public class EightBallResponse : DbEntity diff --git a/src/NadekoBot/Services/Database/Models/CommandCost.cs b/src/NadekoBot/Services/Database/Models/CommandCost.cs index da5a255e..b3a74745 100644 --- a/src/NadekoBot/Services/Database/Models/CommandCost.cs +++ b/src/NadekoBot/Services/Database/Models/CommandCost.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace NadekoBot.Services.Database.Models +namespace NadekoBot.Services.Database.Models { public class CommandCost : DbEntity { diff --git a/src/NadekoBot/Services/Database/Models/CommandPrice.cs b/src/NadekoBot/Services/Database/Models/CommandPrice.cs index 8c7ea739..62db2067 100644 --- a/src/NadekoBot/Services/Database/Models/CommandPrice.cs +++ b/src/NadekoBot/Services/Database/Models/CommandPrice.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace NadekoBot.Services.Database.Models +namespace NadekoBot.Services.Database.Models { public class CommandPrice : DbEntity { diff --git a/src/NadekoBot/Services/Database/Models/DiscordUser.cs b/src/NadekoBot/Services/Database/Models/DiscordUser.cs index 608daf81..86b84d5b 100644 --- a/src/NadekoBot/Services/Database/Models/DiscordUser.cs +++ b/src/NadekoBot/Services/Database/Models/DiscordUser.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace NadekoBot.Services.Database.Models +namespace NadekoBot.Services.Database.Models { public class DiscordUser : DbEntity { diff --git a/src/NadekoBot/Services/Database/Models/Waifu.cs b/src/NadekoBot/Services/Database/Models/Waifu.cs index 947bf516..88c2778a 100644 --- a/src/NadekoBot/Services/Database/Models/Waifu.cs +++ b/src/NadekoBot/Services/Database/Models/Waifu.cs @@ -1,9 +1,4 @@ using NadekoBot.Extensions; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace NadekoBot.Services.Database.Models { diff --git a/src/NadekoBot/Services/Database/Models/WaifuUpdate.cs b/src/NadekoBot/Services/Database/Models/WaifuUpdate.cs index 1c48826e..2722900a 100644 --- a/src/NadekoBot/Services/Database/Models/WaifuUpdate.cs +++ b/src/NadekoBot/Services/Database/Models/WaifuUpdate.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace NadekoBot.Services.Database.Models +namespace NadekoBot.Services.Database.Models { public class WaifuUpdate : DbEntity { diff --git a/src/NadekoBot/Services/Database/Repositories/IDiscordUserRepository.cs b/src/NadekoBot/Services/Database/Repositories/IDiscordUserRepository.cs index c80608dd..480d0723 100644 --- a/src/NadekoBot/Services/Database/Repositories/IDiscordUserRepository.cs +++ b/src/NadekoBot/Services/Database/Repositories/IDiscordUserRepository.cs @@ -1,10 +1,5 @@ using Discord; using NadekoBot.Services.Database.Models; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace NadekoBot.Services.Database.Repositories { diff --git a/src/NadekoBot/Services/Database/Repositories/IWaifuRepository.cs b/src/NadekoBot/Services/Database/Repositories/IWaifuRepository.cs index 2f2dc0f6..d03c1188 100644 --- a/src/NadekoBot/Services/Database/Repositories/IWaifuRepository.cs +++ b/src/NadekoBot/Services/Database/Repositories/IWaifuRepository.cs @@ -1,5 +1,4 @@ using NadekoBot.Services.Database.Models; -using System; using System.Collections.Generic; namespace NadekoBot.Services.Database.Repositories diff --git a/src/NadekoBot/Services/Database/Repositories/Impl/BotConfigRepository.cs b/src/NadekoBot/Services/Database/Repositories/Impl/BotConfigRepository.cs index c9b7ad7d..dd329796 100644 --- a/src/NadekoBot/Services/Database/Repositories/Impl/BotConfigRepository.cs +++ b/src/NadekoBot/Services/Database/Repositories/Impl/BotConfigRepository.cs @@ -24,6 +24,7 @@ namespace NadekoBot.Services.Database.Repositories.Impl .Include(bc => bc.StartupCommands) .Include(bc => bc.BlockedCommands) .Include(bc => bc.BlockedModules) + .Include(bc => bc.Blacklist) //.Include(bc => bc.CommandCosts) .FirstOrDefault(); else diff --git a/src/NadekoBot/Services/Database/Repositories/Impl/DiscordUserRepository.cs b/src/NadekoBot/Services/Database/Repositories/Impl/DiscordUserRepository.cs index 9425f049..e61c2d0e 100644 --- a/src/NadekoBot/Services/Database/Repositories/Impl/DiscordUserRepository.cs +++ b/src/NadekoBot/Services/Database/Repositories/Impl/DiscordUserRepository.cs @@ -1,9 +1,5 @@ using NadekoBot.Services.Database.Models; -using System; -using System.Collections.Generic; using System.Linq; -using System.Text; -using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Discord; diff --git a/src/NadekoBot/Services/Database/Repositories/Impl/WaifuRepository.cs b/src/NadekoBot/Services/Database/Repositories/Impl/WaifuRepository.cs index 8a973202..de6b96ff 100644 --- a/src/NadekoBot/Services/Database/Repositories/Impl/WaifuRepository.cs +++ b/src/NadekoBot/Services/Database/Repositories/Impl/WaifuRepository.cs @@ -2,8 +2,6 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Text; -using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; namespace NadekoBot.Services.Database.Repositories.Impl diff --git a/src/NadekoBot/Services/Database/Repositories/Impl/WarningsRepository.cs b/src/NadekoBot/Services/Database/Repositories/Impl/WarningsRepository.cs index 4bf4c293..aa5a6d7e 100644 --- a/src/NadekoBot/Services/Database/Repositories/Impl/WarningsRepository.cs +++ b/src/NadekoBot/Services/Database/Repositories/Impl/WarningsRepository.cs @@ -1,6 +1,5 @@ using NadekoBot.Services.Database.Models; using Microsoft.EntityFrameworkCore; -using System; using System.Linq; using System.Threading.Tasks; diff --git a/src/NadekoBot/Services/DbHandler.cs b/src/NadekoBot/Services/DbHandler.cs index 619ccd55..de75a441 100644 --- a/src/NadekoBot/Services/DbHandler.cs +++ b/src/NadekoBot/Services/DbHandler.cs @@ -1,6 +1,4 @@ -using System; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore; using NadekoBot.Services.Database; namespace NadekoBot.Services diff --git a/src/NadekoBot/Services/Discord/SocketMessageEventWrapper.cs b/src/NadekoBot/Services/Discord/SocketMessageEventWrapper.cs index 52c9668f..58b3a1e5 100644 --- a/src/NadekoBot/Services/Discord/SocketMessageEventWrapper.cs +++ b/src/NadekoBot/Services/Discord/SocketMessageEventWrapper.cs @@ -1,9 +1,6 @@ using Discord; using Discord.WebSocket; using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; using System.Threading.Tasks; namespace NadekoBot.Services.Discord diff --git a/src/NadekoBot/Services/Games/ChatterBotSession.cs b/src/NadekoBot/Services/Games/ChatterBotSession.cs index 7c4f152c..8d5e83a7 100644 --- a/src/NadekoBot/Services/Games/ChatterBotSession.cs +++ b/src/NadekoBot/Services/Games/ChatterBotSession.cs @@ -1,6 +1,5 @@ using NadekoBot.Extensions; using Newtonsoft.Json; -using System.Collections.Immutable; using System.Net.Http; using System.Threading.Tasks; diff --git a/src/NadekoBot/Services/GreetSettingsService.cs b/src/NadekoBot/Services/GreetSettingsService.cs index 1e427e65..4ea2df95 100644 --- a/src/NadekoBot/Services/GreetSettingsService.cs +++ b/src/NadekoBot/Services/GreetSettingsService.cs @@ -2,14 +2,12 @@ using Discord.WebSocket; using NadekoBot.DataStructures; using NadekoBot.Extensions; -using NadekoBot.Services; using NadekoBot.Services.Database.Models; using NLog; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; -using System.Text; using System.Threading.Tasks; namespace NadekoBot.Services diff --git a/src/NadekoBot/Services/IBotCredentials.cs b/src/NadekoBot/Services/IBotCredentials.cs index ccc75d27..c6c42f87 100644 --- a/src/NadekoBot/Services/IBotCredentials.cs +++ b/src/NadekoBot/Services/IBotCredentials.cs @@ -1,5 +1,4 @@ using Discord; -using System.Collections.Generic; using System.Collections.Immutable; namespace NadekoBot.Services diff --git a/src/NadekoBot/Services/IImagesService.cs b/src/NadekoBot/Services/IImagesService.cs index 0398c574..eb2ba920 100644 --- a/src/NadekoBot/Services/IImagesService.cs +++ b/src/NadekoBot/Services/IImagesService.cs @@ -1,11 +1,6 @@ -using NadekoBot.DataStructures; -using System; +using System; using System.Collections.Generic; using System.Collections.Immutable; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace NadekoBot.Services { diff --git a/src/NadekoBot/Services/Impl/ImagesService.cs b/src/NadekoBot/Services/Impl/ImagesService.cs index 734178eb..3c28049b 100644 --- a/src/NadekoBot/Services/Impl/ImagesService.cs +++ b/src/NadekoBot/Services/Impl/ImagesService.cs @@ -5,7 +5,6 @@ using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; -using System.Threading.Tasks; namespace NadekoBot.Services.Impl { diff --git a/src/NadekoBot/Services/Impl/Localization.cs b/src/NadekoBot/Services/Impl/Localization.cs index 8f29adb5..8f4e720e 100644 --- a/src/NadekoBot/Services/Impl/Localization.cs +++ b/src/NadekoBot/Services/Impl/Localization.cs @@ -1,13 +1,8 @@ using Discord; -using Discord.Commands; -using NadekoBot.Extensions; using System.Collections.Concurrent; using System.Collections.Generic; using System.Globalization; using System.Linq; -using System.Threading.Tasks; -using System; -using NadekoBot.Services.Database; using NLog; namespace NadekoBot.Services diff --git a/src/NadekoBot/Services/Impl/NadekoStrings.cs b/src/NadekoBot/Services/Impl/NadekoStrings.cs index deff344a..c283f582 100644 --- a/src/NadekoBot/Services/Impl/NadekoStrings.cs +++ b/src/NadekoBot/Services/Impl/NadekoStrings.cs @@ -2,12 +2,10 @@ using System.Collections.Immutable; using System.Globalization; using System.IO; -using System.Xml.Linq; using NLog; using System.Diagnostics; using Newtonsoft.Json; using System; -using Discord; namespace NadekoBot.Services { diff --git a/src/NadekoBot/Services/Impl/StatsService.cs b/src/NadekoBot/Services/Impl/StatsService.cs index 4be17dd0..1b03e2f6 100644 --- a/src/NadekoBot/Services/Impl/StatsService.cs +++ b/src/NadekoBot/Services/Impl/StatsService.cs @@ -6,7 +6,6 @@ using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net.Http; -using System.Reflection; using System.Threading; using System.Threading.Tasks; diff --git a/src/NadekoBot/Services/Music/Song.cs b/src/NadekoBot/Services/Music/Song.cs index ea94508b..20a0af0a 100644 --- a/src/NadekoBot/Services/Music/Song.cs +++ b/src/NadekoBot/Services/Music/Song.cs @@ -3,7 +3,6 @@ using NadekoBot.Extensions; using NLog; using System; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.IO; using System.Text.RegularExpressions; using System.Threading; diff --git a/src/NadekoBot/Services/Permissions/BlacklistService.cs b/src/NadekoBot/Services/Permissions/BlacklistService.cs new file mode 100644 index 00000000..58087a1f --- /dev/null +++ b/src/NadekoBot/Services/Permissions/BlacklistService.cs @@ -0,0 +1,21 @@ +using NadekoBot.Services.Database.Models; +using System.Collections.Concurrent; +using System.Linq; + +namespace NadekoBot.Services.Permissions +{ + public class BlacklistService + { + public ConcurrentHashSet BlacklistedUsers { get; set; } + public ConcurrentHashSet BlacklistedGuilds { get; set; } + public ConcurrentHashSet BlacklistedChannels { get; set; } + + public BlacklistService(BotConfig bc) + { + var blacklist = bc.Blacklist; + BlacklistedUsers = new ConcurrentHashSet(blacklist.Where(bi => bi.Type == BlacklistType.User).Select(c => c.ItemId)); + BlacklistedGuilds = new ConcurrentHashSet(blacklist.Where(bi => bi.Type == BlacklistType.Server).Select(c => c.ItemId)); + BlacklistedChannels = new ConcurrentHashSet(blacklist.Where(bi => bi.Type == BlacklistType.Channel).Select(c => c.ItemId)); + } + } +} diff --git a/src/NadekoBot/Services/Permissions/CmdCdService.cs b/src/NadekoBot/Services/Permissions/CmdCdService.cs new file mode 100644 index 00000000..6c0adf77 --- /dev/null +++ b/src/NadekoBot/Services/Permissions/CmdCdService.cs @@ -0,0 +1,26 @@ +using NadekoBot.Services.Database.Models; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; + +namespace NadekoBot.Services.Permissions +{ + public class CmdCdService + { + public ConcurrentDictionary> CommandCooldowns { get; } + public ConcurrentDictionary> ActiveCooldowns { get; } = new ConcurrentDictionary>(); + + public CmdCdService(IEnumerable gcs) + { + CommandCooldowns = new ConcurrentDictionary>( + gcs.ToDictionary(k => k.GuildId, + v => new ConcurrentHashSet(v.CommandCooldowns))); + } + } + + public class ActiveCooldown + { + public string Command { get; set; } + public ulong UserId { get; set; } + } +} diff --git a/src/NadekoBot/Services/Permissions/FilterService.cs b/src/NadekoBot/Services/Permissions/FilterService.cs new file mode 100644 index 00000000..732d8c41 --- /dev/null +++ b/src/NadekoBot/Services/Permissions/FilterService.cs @@ -0,0 +1,50 @@ +using NadekoBot.Services.Database.Models; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; + +namespace NadekoBot.Services.Permissions +{ + public class FilterService + { + public ConcurrentHashSet InviteFilteringChannels { get; } + public ConcurrentHashSet InviteFilteringServers { get; } + + //serverid, filteredwords + public ConcurrentDictionary> ServerFilteredWords { get; } + + public ConcurrentHashSet WordFilteringChannels { get; } + public ConcurrentHashSet WordFilteringServers { get; } + + public ConcurrentHashSet FilteredWordsForChannel(ulong channelId, ulong guildId) + { + ConcurrentHashSet words = new ConcurrentHashSet(); + if (WordFilteringChannels.Contains(channelId)) + ServerFilteredWords.TryGetValue(guildId, out words); + return words; + } + + public ConcurrentHashSet FilteredWordsForServer(ulong guildId) + { + var words = new ConcurrentHashSet(); + if (WordFilteringServers.Contains(guildId)) + ServerFilteredWords.TryGetValue(guildId, out words); + return words; + } + + public FilterService(IEnumerable gcs) + { + InviteFilteringServers = new ConcurrentHashSet(gcs.Where(gc => gc.FilterInvites).Select(gc => gc.GuildId)); + InviteFilteringChannels = new ConcurrentHashSet(gcs.SelectMany(gc => gc.FilterInvitesChannelIds.Select(fci => fci.ChannelId))); + + var dict = gcs.ToDictionary(gc => gc.GuildId, gc => new ConcurrentHashSet(gc.FilteredWords.Select(fw => fw.Word))); + + ServerFilteredWords = new ConcurrentDictionary>(dict); + + var serverFiltering = gcs.Where(gc => gc.FilterWords); + WordFilteringServers = new ConcurrentHashSet(serverFiltering.Select(gc => gc.GuildId)); + + WordFilteringChannels = new ConcurrentHashSet(gcs.SelectMany(gc => gc.FilterWordsChannelIds.Select(fwci => fwci.ChannelId))); + } + } +} diff --git a/src/NadekoBot/Services/Permissions/GlobalPermissionService.cs b/src/NadekoBot/Services/Permissions/GlobalPermissionService.cs new file mode 100644 index 00000000..c034cdf0 --- /dev/null +++ b/src/NadekoBot/Services/Permissions/GlobalPermissionService.cs @@ -0,0 +1,18 @@ +using NadekoBot.Services.Database.Models; +using System.Collections.Concurrent; +using System.Linq; + +namespace NadekoBot.Services.Permissions +{ + public class GlobalPermissionService + { + public readonly ConcurrentHashSet BlockedModules; + public readonly ConcurrentHashSet BlockedCommands; + + public GlobalPermissionService(BotConfig bc) + { + BlockedModules = new ConcurrentHashSet(bc.BlockedModules.Select(x => x.Name)); + BlockedCommands = new ConcurrentHashSet(bc.BlockedCommands.Select(x => x.Name)); + } + } +} diff --git a/src/NadekoBot/Services/Permissions/PermissionCache.cs b/src/NadekoBot/Services/Permissions/PermissionCache.cs index 9ed7ec8c..5b4dc4b7 100644 --- a/src/NadekoBot/Services/Permissions/PermissionCache.cs +++ b/src/NadekoBot/Services/Permissions/PermissionCache.cs @@ -1,9 +1,4 @@ using NadekoBot.Services.Database.Models; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace NadekoBot.Services.Permissions { diff --git a/src/NadekoBot/Modules/Permissions/PermissionExtensions.cs b/src/NadekoBot/Services/Permissions/PermissionExtensions.cs similarity index 96% rename from src/NadekoBot/Modules/Permissions/PermissionExtensions.cs rename to src/NadekoBot/Services/Permissions/PermissionExtensions.cs index f48dcd16..b90f3e4c 100644 --- a/src/NadekoBot/Modules/Permissions/PermissionExtensions.cs +++ b/src/NadekoBot/Services/Permissions/PermissionExtensions.cs @@ -1,12 +1,10 @@ using Discord; -using Discord.Commands; using Discord.WebSocket; using NadekoBot.Services.Database.Models; -using System; using System.Collections.Generic; using System.Linq; -namespace NadekoBot.Modules.Permissions +namespace NadekoBot.Services.Permissions { public static class PermissionExtensions { @@ -118,7 +116,7 @@ namespace NadekoBot.Modules.Permissions break; } - return NadekoBot.ModulePrefixes[typeof(Permissions).Name] + com; + return NadekoBot.Prefix + com; } public static IEnumerable AsEnumerable(this Permission perm) diff --git a/src/NadekoBot/Services/Permissions/PermissionsCollection.cs b/src/NadekoBot/Services/Permissions/PermissionsCollection.cs index 5709c910..5d37155d 100644 --- a/src/NadekoBot/Services/Permissions/PermissionsCollection.cs +++ b/src/NadekoBot/Services/Permissions/PermissionsCollection.cs @@ -1,7 +1,5 @@ using System; -using System.Collections; using System.Collections.Generic; -using System.Linq; using NadekoBot.Services.Database.Models; using NadekoBot.DataStructures; diff --git a/src/NadekoBot/Services/Permissions/PermissionsService.cs b/src/NadekoBot/Services/Permissions/PermissionsService.cs index b10d8b21..8541b129 100644 --- a/src/NadekoBot/Services/Permissions/PermissionsService.cs +++ b/src/NadekoBot/Services/Permissions/PermissionsService.cs @@ -1,13 +1,155 @@ -using System; -using System.Collections.Generic; +using Microsoft.EntityFrameworkCore; +using NadekoBot.Services.Database.Models; +using NLog; +using System; +using System.Collections.Concurrent; +using System.Diagnostics; using System.Linq; -using System.Text; using System.Threading.Tasks; namespace NadekoBot.Services.Permissions { public class PermissionsService { - + private readonly DbHandler _db; + private readonly Logger _log; + + //guildid, root permission + public ConcurrentDictionary Cache { get; } = + new ConcurrentDictionary(); + + public PermissionsService(DbHandler db) + { + _log = LogManager.GetCurrentClassLogger(); + _db = db; + + var sw = Stopwatch.StartNew(); + TryMigratePermissions(); + using (var uow = _db.UnitOfWork) + { + foreach (var x in uow.GuildConfigs.Permissionsv2ForAll()) + { + Cache.TryAdd(x.GuildId, new PermissionCache() + { + Verbose = x.VerbosePermissions, + PermRole = x.PermissionRole, + Permissions = new PermissionsCollection(x.Permissions) + }); + } + } + + sw.Stop(); + _log.Debug($"Loaded in {sw.Elapsed.TotalSeconds:F2}s"); + } + + public PermissionCache GetCache(ulong guildId) + { + if (!Cache.TryGetValue(guildId, out var pc)) + { + using (var uow = _db.UnitOfWork) + { + var config = uow.GuildConfigs.For(guildId, + set => set.Include(x => x.Permissions)); + UpdateCache(config); + } + Cache.TryGetValue(guildId, out pc); + if (pc == null) + throw new Exception("Cache is null."); + } + return pc; + } + + private void TryMigratePermissions() + { + var log = LogManager.GetCurrentClassLogger(); + using (var uow = _db.UnitOfWork) + { + var oldCache = new ConcurrentDictionary(uow.GuildConfigs + .OldPermissionsForAll() + .Where(x => x.RootPermission != null) // there is a check inside already, but just in case + .ToDictionary(k => k.GuildId, + v => new OldPermissionCache() + { + RootPermission = v.RootPermission, + Verbose = v.VerbosePermissions, + PermRole = v.PermissionRole + })); + + if (oldCache.Any()) + { + log.Info("Old permissions found. Performing one-time migration to v2."); + var i = 0; + foreach (var oc in oldCache) + { + if (i % 3 == 0) + log.Info("Migrating Permissions #" + i + " - GuildId: " + oc.Key); + i++; + var gc = uow.GuildConfigs.GcWithPermissionsv2For(oc.Key); + + var oldPerms = oc.Value.RootPermission.AsEnumerable().Reverse().ToList(); + uow._context.Set().RemoveRange(oldPerms); + gc.RootPermission = null; + if (oldPerms.Count > 2) + { + + var newPerms = oldPerms.Take(oldPerms.Count - 1) + .Select(x => x.Tov2()) + .ToList(); + + var allowPerm = Permissionv2.AllowAllPerm; + var firstPerm = newPerms[0]; + if (allowPerm.State != firstPerm.State || + allowPerm.PrimaryTarget != firstPerm.PrimaryTarget || + allowPerm.SecondaryTarget != firstPerm.SecondaryTarget || + allowPerm.PrimaryTargetId != firstPerm.PrimaryTargetId || + allowPerm.SecondaryTargetName != firstPerm.SecondaryTargetName) + newPerms.Insert(0, Permissionv2.AllowAllPerm); + Cache.TryAdd(oc.Key, new PermissionCache + { + Permissions = new PermissionsCollection(newPerms), + Verbose = gc.VerbosePermissions, + PermRole = gc.PermissionRole, + }); + gc.Permissions = newPerms; + } + } + log.Info("Permission migration to v2 is done."); + uow.Complete(); + } + } + } + + public async Task AddPermissions(ulong guildId, params Permissionv2[] perms) + { + using (var uow = _db.UnitOfWork) + { + var config = uow.GuildConfigs.GcWithPermissionsv2For(guildId); + //var orderedPerms = new PermissionsCollection(config.Permissions); + var max = config.Permissions.Max(x => x.Index); //have to set its index to be the highest + foreach (var perm in perms) + { + perm.Index = ++max; + config.Permissions.Add(perm); + } + await uow.CompleteAsync().ConfigureAwait(false); + UpdateCache(config); + } + } + + public void UpdateCache(GuildConfig config) + { + Cache.AddOrUpdate(config.GuildId, new PermissionCache() + { + Permissions = new PermissionsCollection(config.Permissions), + PermRole = config.PermissionRole, + Verbose = config.VerbosePermissions + }, (id, old) => + { + old.Permissions = new PermissionsCollection(config.Permissions); + old.PermRole = config.PermissionRole; + old.Verbose = config.VerbosePermissions; + return old; + }); + } } } diff --git a/src/NadekoBot/Services/ServiceProvider.cs b/src/NadekoBot/Services/ServiceProvider.cs index 8b28af4d..c3b46ba3 100644 --- a/src/NadekoBot/Services/ServiceProvider.cs +++ b/src/NadekoBot/Services/ServiceProvider.cs @@ -3,9 +3,6 @@ using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace NadekoBot.Services { diff --git a/src/NadekoBot/Services/Utility/ConverterService.cs b/src/NadekoBot/Services/Utility/ConverterService.cs new file mode 100644 index 00000000..081a8d53 --- /dev/null +++ b/src/NadekoBot/Services/Utility/ConverterService.cs @@ -0,0 +1,116 @@ +using NadekoBot.Services.Database.Models; +using Newtonsoft.Json; +using NLog; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; + +namespace NadekoBot.Services.Utility +{ + public class ConverterService + { + public List Units { get; set; } = new List(); + private readonly Logger _log; + private Timer _timer; + private readonly TimeSpan _updateInterval = new TimeSpan(12, 0, 0); + private readonly DbHandler _db; + + public ConverterService(DbHandler db) + { + _log = LogManager.GetCurrentClassLogger(); + _db = db; + try + { + var data = JsonConvert.DeserializeObject>(File.ReadAllText("data/units.json")).Select(u => new ConvertUnit() + { + Modifier = u.Modifier, + UnitType = u.UnitType, + InternalTrigger = string.Join("|", u.Triggers) + }).ToArray(); + + using (var uow = _db.UnitOfWork) + { + if (uow.ConverterUnits.Empty()) + { + uow.ConverterUnits.AddRange(data); + uow.Complete(); + } + } + Units = data.ToList(); + } + catch (Exception ex) + { + _log.Warn("Could not load units: " + ex.Message); + } + + _timer = new Timer(async (obj) => await UpdateCurrency(), null, _updateInterval, _updateInterval); + } + + public static async Task UpdateCurrencyRates() + { + using (var http = new HttpClient()) + { + var res = await http.GetStringAsync("http://api.fixer.io/latest").ConfigureAwait(false); + return JsonConvert.DeserializeObject(res); + } + } + + public async Task UpdateCurrency() + { + try + { + var currencyRates = await UpdateCurrencyRates(); + var unitTypeString = "currency"; + var range = currencyRates.ConversionRates.Select(u => new ConvertUnit() + { + InternalTrigger = u.Key, + Modifier = u.Value, + UnitType = unitTypeString + }).ToArray(); + var baseType = new ConvertUnit() + { + Triggers = new[] { currencyRates.Base }, + Modifier = decimal.One, + UnitType = unitTypeString + }; + var toRemove = Units.Where(u => u.UnitType == unitTypeString); + + using (var uow = _db.UnitOfWork) + { + uow.ConverterUnits.RemoveRange(toRemove.ToArray()); + uow.ConverterUnits.Add(baseType); + uow.ConverterUnits.AddRange(range); + + await uow.CompleteAsync().ConfigureAwait(false); + } + Units.RemoveAll(u => u.UnitType == unitTypeString); + Units.Add(baseType); + Units.AddRange(range); + _log.Info("Updated Currency"); + } + catch + { + _log.Warn("Failed updating currency. Ignore this."); + } + } + } + + public class MeasurementUnit + { + public List Triggers { get; set; } + public string UnitType { get; set; } + public decimal Modifier { get; set; } + } + + public class Rates + { + public string Base { get; set; } + public DateTime Date { get; set; } + [JsonProperty("rates")] + public Dictionary ConversionRates { get; set; } + } +} diff --git a/src/NadekoBot/Services/Utility/MessageRepeaterService.cs b/src/NadekoBot/Services/Utility/MessageRepeaterService.cs new file mode 100644 index 00000000..2997b983 --- /dev/null +++ b/src/NadekoBot/Services/Utility/MessageRepeaterService.cs @@ -0,0 +1,36 @@ +using Discord.WebSocket; +using NadekoBot.Services.Database.Models; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace NadekoBot.Services.Utility +{ + public class MessageRepeaterService + { + //messagerepeater + //guildid/RepeatRunners + public ConcurrentDictionary> Repeaters { get; set; } + public bool RepeaterReady { get; private set; } + + public MessageRepeaterService(DiscordShardedClient client, IEnumerable gcs) + { + var _ = Task.Run(async () => + { +#if !GLOBAL_NADEKO + await Task.Delay(5000).ConfigureAwait(false); +#else + await Task.Delay(30000).ConfigureAwait(false); +#endif + //todo this is pretty terrible :kms: no time + Repeaters = new ConcurrentDictionary>(gcs + .ToDictionary(gc => gc.GuildId, + gc => new ConcurrentQueue(gc.GuildRepeaters + .Select(gr => new RepeatRunner(client, gr)) + .Where(x => x.Guild != null)))); + RepeaterReady = true; + }); + } + } +} diff --git a/src/NadekoBot/Services/Utility/RemindService.cs b/src/NadekoBot/Services/Utility/RemindService.cs new file mode 100644 index 00000000..0ce2ed6c --- /dev/null +++ b/src/NadekoBot/Services/Utility/RemindService.cs @@ -0,0 +1,103 @@ +using Discord; +using Discord.WebSocket; +using NadekoBot.Extensions; +using NadekoBot.Services.Database.Models; +using NLog; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.RegularExpressions; +using System.Threading; +using System.Threading.Tasks; + +namespace NadekoBot.Services.Utility +{ + public class RemindService + { + public readonly Regex Regex = new Regex(@"^(?:(?\d)mo)?(?:(?\d)w)?(?:(?\d{1,2})d)?(?:(?\d{1,2})h)?(?:(?\d{1,2})m)?$", + RegexOptions.Compiled | RegexOptions.Multiline); + + public string RemindMessageFormat { get; } + + public readonly IDictionary> _replacements = new Dictionary> + { + { "%message%" , (r) => r.Message }, + { "%user%", (r) => $"<@!{r.UserId}>" }, + { "%target%", (r) => r.IsPrivate ? "Direct Message" : $"<#{r.ChannelId}>"} + }; + + private readonly Logger _log; + private readonly CancellationTokenSource cancelSource; + private readonly CancellationToken cancelAllToken; + private readonly BotConfig _config; + private readonly DiscordShardedClient _client; + private readonly DbHandler _db; + + public RemindService(DiscordShardedClient client, BotConfig config, DbHandler db) + { + _config = config; + _client = client; + _log = LogManager.GetCurrentClassLogger(); + _db = db; + + cancelSource = new CancellationTokenSource(); + cancelAllToken = cancelSource.Token; + List reminders; + using (var uow = _db.UnitOfWork) + { + reminders = uow.Reminders.GetAll().ToList(); + } + RemindMessageFormat = _config.RemindMessageFormat; + + foreach (var r in reminders) + { + Task.Run(() => StartReminder(r)); + } + } + + public async Task StartReminder(Reminder r) + { + var t = cancelAllToken; + var now = DateTime.Now; + + var time = r.When - now; + + if (time.TotalMilliseconds > int.MaxValue) + return; + + await Task.Delay(time, t).ConfigureAwait(false); + try + { + IMessageChannel ch; + if (r.IsPrivate) + { + var user = _client.GetGuild(r.ServerId).GetUser(r.ChannelId); + if (user == null) + return; + ch = await user.CreateDMChannelAsync().ConfigureAwait(false); + } + else + { + ch = _client.GetGuild(r.ServerId)?.GetTextChannel(r.ChannelId); + } + if (ch == null) + return; + + await ch.SendMessageAsync( + _replacements.Aggregate(RemindMessageFormat, + (cur, replace) => cur.Replace(replace.Key, replace.Value(r))) + .SanitizeMentions() + ).ConfigureAwait(false); //it works trust me + } + catch (Exception ex) { _log.Warn(ex); } + finally + { + using (var uow = _db.UnitOfWork) + { + uow.Reminders.Remove(r); + await uow.CompleteAsync(); + } + } + } + } +} \ No newline at end of file diff --git a/src/NadekoBot/Modules/Utility/Models/RepeatRunner.cs b/src/NadekoBot/Services/Utility/RepeatRunner.cs similarity index 95% rename from src/NadekoBot/Modules/Utility/Models/RepeatRunner.cs rename to src/NadekoBot/Services/Utility/RepeatRunner.cs index c9d7ad15..3a1db8b7 100644 --- a/src/NadekoBot/Modules/Utility/Models/RepeatRunner.cs +++ b/src/NadekoBot/Services/Utility/RepeatRunner.cs @@ -1,18 +1,14 @@ using Discord; using Discord.Net; using Discord.WebSocket; -using Microsoft.Extensions.Logging; using NadekoBot.Extensions; using NadekoBot.Services.Database.Models; using NLog; using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; using System.Threading; using System.Threading.Tasks; -namespace NadekoBot.Modules.Utility.Models +namespace NadekoBot.Services.Utility { public class RepeatRunner { diff --git a/src/NadekoBot/Services/Utility/UtilityService.cs b/src/NadekoBot/Services/Utility/UtilityService.cs new file mode 100644 index 00000000..eca8eaac --- /dev/null +++ b/src/NadekoBot/Services/Utility/UtilityService.cs @@ -0,0 +1,83 @@ +using Discord; +using Discord.WebSocket; +using NadekoBot.Extensions; +using NadekoBot.Services.Database.Models; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace NadekoBot.Services.Utility +{ + public class UtilityService + { + public ConcurrentDictionary> AliasMaps { get; } = new ConcurrentDictionary>(); + + public UtilityService(IEnumerable guildConfigs, DiscordShardedClient client) + { + //commandmap + AliasMaps = new ConcurrentDictionary>( + guildConfigs.ToDictionary( + x => x.GuildId, + x => new ConcurrentDictionary(x.CommandAliases + .Distinct(new CommandAliasEqualityComparer()) + .ToDictionary(ca => ca.Trigger, ca => ca.Mapping)))); + + //cross server + _client = client; + _client.MessageReceived += Client_MessageReceived; + } + + private async Task Client_MessageReceived(SocketMessage imsg) + { + try + { + if (imsg.Author.IsBot) + return; + var msg = imsg as IUserMessage; + if (msg == null) + return; + var channel = imsg.Channel as ITextChannel; + if (channel == null) + return; + if (msg.Author.Id == _client.CurrentUser.Id) return; + foreach (var subscriber in Subscribers) + { + var set = subscriber.Value; + if (!set.Contains(channel)) + continue; + foreach (var chan in set.Except(new[] { channel })) + { + try + { + await chan.SendMessageAsync(GetMessage(channel, (IGuildUser)msg.Author, + msg)).ConfigureAwait(false); + } + catch + { + // ignored + } + } + } + } + catch + { + // ignored + } + } + + private string GetMessage(ITextChannel channel, IGuildUser user, IUserMessage message) => + $"**{channel.Guild.Name} | {channel.Name}** `{user.Username}`: " + message.Content.SanitizeMentions(); + + public readonly ConcurrentDictionary> Subscribers = + new ConcurrentDictionary>(); + private DiscordShardedClient _client; + } + + public class CommandAliasEqualityComparer : IEqualityComparer + { + public bool Equals(CommandAlias x, CommandAlias y) => x.Trigger == y.Trigger; + + public int GetHashCode(CommandAlias obj) => obj.Trigger.GetHashCode(); + } +}