From 062dd56767bbc69444e4283151963fd8e309c6e6 Mon Sep 17 00:00:00 2001 From: Daniel-I-Am Date: Wed, 14 Oct 2020 22:21:29 +0200 Subject: [PATCH 01/18] Add optional validation rule --- .../WebServer/Services/ValidationService.cs | 26 ++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/ChaosBot/WebServer/Services/ValidationService.cs b/ChaosBot/WebServer/Services/ValidationService.cs index c90f040..80b0599 100644 --- a/ChaosBot/WebServer/Services/ValidationService.cs +++ b/ChaosBot/WebServer/Services/ValidationService.cs @@ -29,6 +29,7 @@ namespace ChaosBot.WebServer.Services ValidationResult result = ruleType switch { + "optional" => CheckOptional(key, value), "required" => CheckRequired(key, value), "type" => CheckType(key, value, ruleParts), "min" => CheckMin(key, value, ruleParts), @@ -36,6 +37,9 @@ namespace ChaosBot.WebServer.Services _ => new ValidationResult.Unknown() }; + if (result.DoesForceSuccess()) + break; + if (result.GetError() != null) { errorBuilder.AppendLine($"[{result.GetKey()}] {result.GetError()}"); @@ -48,6 +52,13 @@ namespace ChaosBot.WebServer.Services return error.Length == 0; } + private ValidationResult CheckOptional(string key, dynamic value) + { + if (value == null) + return new ValidationResult.SuperSuccess(); + return new ValidationResult.Success(); + } + private ValidationResult CheckRequired(string key, dynamic value) { if (value != null) @@ -154,7 +165,15 @@ namespace ChaosBot.WebServer.Services _errorMessage = errorMessage; _key = key; } - + + internal class SuperSuccess : ValidationResult + { + public override bool DoesForceSuccess() + { + return true; + } + } + internal class Success : ValidationResult {} internal class Failure : ValidationResult @@ -172,5 +191,10 @@ namespace ChaosBot.WebServer.Services { return this._key; } + + public virtual bool DoesForceSuccess() + { + return false; + } } } From 194d025660a24643fdc816f40470e9dd6f9d8121 Mon Sep 17 00:00:00 2001 From: Daniel-I-Am Date: Fri, 16 Oct 2020 16:43:54 +0200 Subject: [PATCH 02/18] Rework configuration through a root level helper --- ChaosBot/Configuration.cs | 65 +++++++++++++++++++ ChaosBot/Discord/DiscordConnect.cs | 5 +- ChaosBot/Discord/Modules/Admin/Config.cs | 2 +- ChaosBot/Discord/Modules/Admin/RankCheck.cs | 7 +- ChaosBot/Discord/Modules/User/Info.cs | 5 +- ChaosBot/Discord/Services/TimerHandler.cs | 3 +- ChaosBot/Models/ChaosbotContext.cs | 29 +++++++-- ChaosBot/Program.cs | 3 +- .../Repositories/ConfigurationRepository.cs | 6 +- ChaosBot/WebServer/App/DiscordController.cs | 8 ++- .../Services/DiscordInviteGenerator.cs | 2 +- ChaosBot/WebServer/Startup.cs | 2 +- ChaosBot/WebServer/WebServer.cs | 5 +- 13 files changed, 115 insertions(+), 27 deletions(-) create mode 100644 ChaosBot/Configuration.cs diff --git a/ChaosBot/Configuration.cs b/ChaosBot/Configuration.cs new file mode 100644 index 0000000..1573f95 --- /dev/null +++ b/ChaosBot/Configuration.cs @@ -0,0 +1,65 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using ChaosBot.Repositories; +using Microsoft.Extensions.Configuration; + +namespace ChaosBot +{ + public class Configuration + { + private readonly IConfiguration _appSettingsWrapper; + + private static readonly Dictionary ConfigurationFlags = new Dictionary + { + {"LevelUp:Enabled", typeof(bool)}, + }; + + public Configuration() + { + _appSettingsWrapper = Program.AppSettingsHandler; + + if (_appSettingsWrapper == null) + throw new NullReferenceException("Program.AppSettingsHandler is unset"); + } + + /** + * Gets the configuration value associated with a key in an optional guild + * Configuration key does not exist + * Configuration key does not have the provided type + * Configuration value + */ + public T GetValue(string key, T defaultValue, ulong? guildId = null) + { + if (!ConfigurationFlags.ContainsKey(key)) + throw new ArgumentException($"Configuration does not contain key '{key}'"); + + if (!(ConfigurationFlags[key] == typeof(T))) + throw new ArgumentException($"Configuration flag '{key}<{ConfigurationFlags[key]}>' does not have type '{typeof(T)}'"); + + if (guildId.HasValue) + return ConfigurationRepository.GetValue(key, guildId.Value, defaultValue); + + return _appSettingsWrapper.GetValue(key, defaultValue); + } + + public T GetValue(string key) + { + return GetValue(key, default); + } + + public IConfigurationSection GetSection(string key) + { + return _appSettingsWrapper.GetSection(key); + } + + /** + * Get the available configuration flags + * Immutable dictionary of config-key/type pairs + */ + public ImmutableDictionary GetConfigurationFlags() + { + return ConfigurationFlags.ToImmutableDictionary(); + } + } +} diff --git a/ChaosBot/Discord/DiscordConnect.cs b/ChaosBot/Discord/DiscordConnect.cs index c94424e..05ee3d3 100644 --- a/ChaosBot/Discord/DiscordConnect.cs +++ b/ChaosBot/Discord/DiscordConnect.cs @@ -28,9 +28,12 @@ namespace ChaosBot.Discord client.Log += Log; client.Ready += ReadyAsync; services.GetRequiredService().Log += Log; + + // Get the configuration handler + Configuration config = new Configuration(); // this is where we get the Token value from the configuration file, and start the bot - await client.LoginAsync(TokenType.Bot, Program.AppSettingsHandler.GetValue("Discord:Token")); + await client.LoginAsync(TokenType.Bot, config.GetValue("Discord:Token")); await client.StartAsync(); // we get the CommandHandler class here and call the InitializeAsync method to start things up for the CommandHandler service diff --git a/ChaosBot/Discord/Modules/Admin/Config.cs b/ChaosBot/Discord/Modules/Admin/Config.cs index c4ba8e7..f305aa4 100644 --- a/ChaosBot/Discord/Modules/Admin/Config.cs +++ b/ChaosBot/Discord/Modules/Admin/Config.cs @@ -83,7 +83,7 @@ namespace ChaosBot.Discord.Modules.Admin { using (ChaosbotContext dbContext = new ChaosbotContext()) { - Configuration cnfSet = new Configuration(); + Models.Configuration cnfSet = new Models.Configuration(); cnfSet.Key = key; cnfSet.DiscordGuildId = Context.Guild.Id; diff --git a/ChaosBot/Discord/Modules/Admin/RankCheck.cs b/ChaosBot/Discord/Modules/Admin/RankCheck.cs index e71bdd6..ca65164 100644 --- a/ChaosBot/Discord/Modules/Admin/RankCheck.cs +++ b/ChaosBot/Discord/Modules/Admin/RankCheck.cs @@ -109,10 +109,9 @@ namespace ChaosBot.Discord.Modules.Admin { using HttpClient client = new HttpClient(); - IConfigurationSection configurationSection = - Program.AppSettingsHandler.GetSection("Lodestone:ChaosBotApi"); - string endpoint = configurationSection.GetValue("Url"); - string apiToken = configurationSection.GetValue("ApiToken"); + Configuration config = new Configuration(); + string endpoint =config.GetValue("Lodestone:ChaosBotApi:Url"); + string apiToken = config.GetValue("Lodestone:ChaosBotApi:ApiToken"); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiToken); HttpResponseMessage result = diff --git a/ChaosBot/Discord/Modules/User/Info.cs b/ChaosBot/Discord/Modules/User/Info.cs index 553d79e..60af2c0 100644 --- a/ChaosBot/Discord/Modules/User/Info.cs +++ b/ChaosBot/Discord/Modules/User/Info.cs @@ -20,10 +20,11 @@ namespace ChaosBot.Discord.Modules.User { var sb = new StringBuilder(); var embed = new EmbedBuilder(); + Configuration config = new Configuration(); embed.WithColor(new Color(255, 255, 0)); - embed.Title = $"Information {Program.AppSettingsHandler.GetValue("Bot:Name")} v{Program.AppSettingsHandler.GetValue("Bot:Version")}"; - sb.AppendLine($"Prefix: {ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id)}"); + embed.Title = $"Information {config.GetValue("Bot:Name")} v{config.GetValue("Bot:Version")}"; + sb.AppendLine($"Prefix: {config.GetValue("Discord:Prefix", default(string), Context.Guild.Id)}"); /* * Add the string to the Embed diff --git a/ChaosBot/Discord/Services/TimerHandler.cs b/ChaosBot/Discord/Services/TimerHandler.cs index fe5850b..480d5ed 100644 --- a/ChaosBot/Discord/Services/TimerHandler.cs +++ b/ChaosBot/Discord/Services/TimerHandler.cs @@ -15,8 +15,9 @@ namespace ChaosBot.Discord.Services public static void Initialize(IServiceProvider services) { _client = services.GetRequiredService(); + Configuration config = new Configuration(); - foreach (IConfigurationSection serverConfig in Program.AppSettingsHandler.GetSection("Servers").GetChildren()) + foreach (IConfigurationSection serverConfig in config.GetSection("Servers").GetChildren()) { long? lodestoneChannelSloganDescriptionId = serverConfig.GetValue("Lodestone:SloganDescription:Channel", null); int refreshMinutes = serverConfig.GetValue("Lodestone:SloganDescription:RefreshMinutes", 60); diff --git a/ChaosBot/Models/ChaosbotContext.cs b/ChaosBot/Models/ChaosbotContext.cs index ced2e6f..b307f66 100644 --- a/ChaosBot/Models/ChaosbotContext.cs +++ b/ChaosBot/Models/ChaosbotContext.cs @@ -19,17 +19,32 @@ namespace ChaosBot.Models { if (!optionsBuilder.IsConfigured) { + string server, user, pass, name; + int port; + if (Program.AppSettingsHandler == null) { - Program.AppSettingsHandler = new ConfigurationBuilder() + IConfiguration config = Program.AppSettingsHandler = new ConfigurationBuilder() .SetBasePath(System.IO.Directory.GetCurrentDirectory()) .AddJsonFile("./appsettings.json", optional: false, reloadOnChange: true).Build(); + + server = config.GetValue("Database:Host"); + port = config.GetValue("Database:Port"); + user = config.GetValue("Database:User"); + pass = config.GetValue("Database:Pass"); + name = config.GetValue("Database:Name"); } - string server = Program.AppSettingsHandler.GetValue("Database:Host"); - int port = Program.AppSettingsHandler.GetValue("Database:Port"); - string user = Program.AppSettingsHandler.GetValue("Database:User"); - string pass = Program.AppSettingsHandler.GetValue("Database:Pass"); - string name = Program.AppSettingsHandler.GetValue("Database:Name"); + else + { + ChaosBot.Configuration config = new ChaosBot.Configuration(); + + server = config.GetValue("Database:Host"); + port = config.GetValue("Database:Port"); + user = config.GetValue("Database:User"); + pass = config.GetValue("Database:Pass"); + name = config.GetValue("Database:Name"); + } + optionsBuilder.UseMySql( $"server={server};port={port};user={user};password={pass};database={name}", x => x.ServerVersion("5.5.64-mariadb")); @@ -54,4 +69,4 @@ namespace ChaosBot.Models .HasKey(x => new {x.DiscordGuildId, x.Command}); } } -} \ No newline at end of file +} diff --git a/ChaosBot/Program.cs b/ChaosBot/Program.cs index 500e4d1..9fe2151 100644 --- a/ChaosBot/Program.cs +++ b/ChaosBot/Program.cs @@ -42,7 +42,8 @@ namespace ChaosBot /* * Initialize the Discord Client and Login */ - _logger.Info($"Starting Up {AppSettingsHandler.GetValue("Bot:Name")} v{AppSettingsHandler.GetValue("Bot:Version")}"); + Configuration config = new Configuration(); + _logger.Info($"Starting Up {config.GetValue("Bot:Name")} v{config.GetValue("Bot:Version")}"); try { diff --git a/ChaosBot/Repositories/ConfigurationRepository.cs b/ChaosBot/Repositories/ConfigurationRepository.cs index e85c9de..ca21996 100644 --- a/ChaosBot/Repositories/ConfigurationRepository.cs +++ b/ChaosBot/Repositories/ConfigurationRepository.cs @@ -17,7 +17,7 @@ namespace ChaosBot.Repositories { using (ChaosbotContext dbContext = new ChaosbotContext()) { - Configuration config = dbContext.Configuration + Models.Configuration config = dbContext.Configuration .SingleOrDefault(c => c.DiscordGuildId == guildId && c.Key == key); if (config == null || string.IsNullOrEmpty(config.SerializedValue)) return GetValueFromAppSettings(key, guildId, defaultValue); @@ -29,7 +29,7 @@ namespace ChaosBot.Repositories { using (ChaosbotContext dbContext = new ChaosbotContext()) { - Configuration config = dbContext.Configuration + Models.Configuration config = dbContext.Configuration .SingleOrDefault(c => c.DiscordGuildId == guildId && c.Key == key); if (config == null) return; dbContext.Remove(config); @@ -42,4 +42,4 @@ namespace ChaosBot.Repositories return Program.AppSettingsHandler.GetValue($"Servers:{guildId}:{key}", Program.AppSettingsHandler.GetValue(key, defaultValue)); } } -} \ No newline at end of file +} diff --git a/ChaosBot/WebServer/App/DiscordController.cs b/ChaosBot/WebServer/App/DiscordController.cs index 48e6247..b568e41 100644 --- a/ChaosBot/WebServer/App/DiscordController.cs +++ b/ChaosBot/WebServer/App/DiscordController.cs @@ -36,9 +36,11 @@ namespace ChaosBot.WebServer.App [HttpGet] public async Task Index(string code = null) { - string redirectUri = $"{Program.AppSettingsHandler.GetValue("Discord:BaseUri")}/api/discord"; - string clientId = Program.AppSettingsHandler.GetValue("Discord:ClientId"); - string clientSecret = Program.AppSettingsHandler.GetValue("Discord:ClientSecret"); + Configuration config = new Configuration(); + + string redirectUri = $"{config.GetValue("Discord:BaseUri")}/api/discord"; + string clientId = config.GetValue("Discord:ClientId"); + string clientSecret = config.GetValue("Discord:ClientSecret"); if (code == null) return Redirect($"https://discord.com/api/oauth2/authorize?client_id={clientId}&redirect_uri={redirectUri}&response_type=code&scope=identify%20guilds"); diff --git a/ChaosBot/WebServer/Services/DiscordInviteGenerator.cs b/ChaosBot/WebServer/Services/DiscordInviteGenerator.cs index 088c616..0c3684a 100644 --- a/ChaosBot/WebServer/Services/DiscordInviteGenerator.cs +++ b/ChaosBot/WebServer/Services/DiscordInviteGenerator.cs @@ -6,7 +6,7 @@ namespace ChaosBot.WebServer.Services { public string Generate() { - string clientId = Program.AppSettingsHandler.GetValue("Discord:ClientId"); + string clientId = new Configuration().GetValue("Discord:ClientId"); const ulong permissions = 0x00000020 + // MANAGE_CHANNELS 0x04000000 + // CHANGE_NICKNAME diff --git a/ChaosBot/WebServer/Startup.cs b/ChaosBot/WebServer/Startup.cs index 90607ff..a35b965 100644 --- a/ChaosBot/WebServer/Startup.cs +++ b/ChaosBot/WebServer/Startup.cs @@ -42,7 +42,7 @@ namespace ChaosBot.WebServer { LoggingFacade.Info("Initializing Kestrel Startup and Configuration"); - if (Program.AppSettingsHandler.GetValue("WebServer:Debug", false)) + if (new Configuration().GetValue("WebServer:Debug", false)) app.UseDeveloperExceptionPage(); app.UseForwardedHeaders(); diff --git a/ChaosBot/WebServer/WebServer.cs b/ChaosBot/WebServer/WebServer.cs index 2d7d8dd..71a3a13 100644 --- a/ChaosBot/WebServer/WebServer.cs +++ b/ChaosBot/WebServer/WebServer.cs @@ -22,12 +22,13 @@ namespace ChaosBot.WebServer { string contentRoot = Directory.GetCurrentDirectory(); string webRoot = Path.Combine(contentRoot, "wwwroot/dist"); + Configuration config = new Configuration(); webBuilder.UseContentRoot(contentRoot); webBuilder.UseWebRoot(webRoot); webBuilder.ConfigureKestrel(serverOptions => { - serverOptions.Listen(IPAddress.Any, Program.AppSettingsHandler.GetValue("WebServer:Port"), + serverOptions.Listen(IPAddress.Any, config.GetValue("WebServer:Port", 80), listenOptions => { listenOptions.UseConnectionLogging(); @@ -37,7 +38,7 @@ namespace ChaosBot.WebServer { logging.ClearProviders(); logging.SetMinimumLevel(LogLevel.Trace); - logging.AddNLog(new NLogLoggingConfiguration(Program.AppSettingsHandler.GetSection("NLog"))); + logging.AddNLog(new NLogLoggingConfiguration(config.GetSection("NLog"))); }) .UseStartup(); }); From 2a468f1a9575fa6eeb42f3be781da6362111e469 Mon Sep 17 00:00:00 2001 From: Daniel-I-Am Date: Fri, 16 Oct 2020 16:50:21 +0200 Subject: [PATCH 03/18] Implement everything that now requires the typed fields --- ChaosBot/Configuration.cs | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/ChaosBot/Configuration.cs b/ChaosBot/Configuration.cs index 1573f95..7f6037d 100644 --- a/ChaosBot/Configuration.cs +++ b/ChaosBot/Configuration.cs @@ -12,7 +12,26 @@ namespace ChaosBot private static readonly Dictionary ConfigurationFlags = new Dictionary { - {"LevelUp:Enabled", typeof(bool)}, + {"Bot:Name", typeof(string)}, + {"Bot:Version", typeof(string)}, + + {"WebServer:Port", typeof(int)}, + {"WebServer:Debug", typeof(bool)}, + + {"Discord:Prefix", typeof(string)}, + {"Discord:Token", typeof(string)}, + {"Discord:BaseUri", typeof(string)}, + {"Discord:ClientId", typeof(string)}, + {"Discord:ClientSecret", typeof(string)}, + + {"Lodestone:ChaosBotApi:ApiToken", typeof(string)}, + {"Lodestone:ChaosBotApi:Url", typeof(string)}, + + {"Database:Host", typeof(string)}, + {"Database:Port", typeof(int)}, + {"Database:User", typeof(string)}, + {"Database:Pass", typeof(string)}, + {"Database:Name", typeof(string)}, }; public Configuration() From 29c5a0a1028f48310c7cf9d6977226d929edd8f3 Mon Sep 17 00:00:00 2001 From: Daniel-I-Am Date: Fri, 16 Oct 2020 17:04:54 +0200 Subject: [PATCH 04/18] Allow regex in keys --- ChaosBot/Configuration.cs | 36 ++++++++++++++++++++++++++++++------ 1 file changed, 30 insertions(+), 6 deletions(-) diff --git a/ChaosBot/Configuration.cs b/ChaosBot/Configuration.cs index 7f6037d..2246f2e 100644 --- a/ChaosBot/Configuration.cs +++ b/ChaosBot/Configuration.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Collections.Immutable; +using System.Text.RegularExpressions; using ChaosBot.Repositories; using Microsoft.Extensions.Configuration; @@ -37,7 +38,7 @@ namespace ChaosBot public Configuration() { _appSettingsWrapper = Program.AppSettingsHandler; - + if (_appSettingsWrapper == null) throw new NullReferenceException("Program.AppSettingsHandler is unset"); } @@ -50,16 +51,18 @@ namespace ChaosBot */ public T GetValue(string key, T defaultValue, ulong? guildId = null) { - if (!ConfigurationFlags.ContainsKey(key)) + bool keyExists = TryGetKeyFromRegexMatch(key, out string realKey); + + if (!keyExists) throw new ArgumentException($"Configuration does not contain key '{key}'"); - if (!(ConfigurationFlags[key] == typeof(T))) - throw new ArgumentException($"Configuration flag '{key}<{ConfigurationFlags[key]}>' does not have type '{typeof(T)}'"); + if (!(ConfigurationFlags[realKey] == typeof(T))) + throw new ArgumentException($"Configuration flag '{realKey}<{ConfigurationFlags[realKey]}>' does not have type '{typeof(T)}'"); if (guildId.HasValue) - return ConfigurationRepository.GetValue(key, guildId.Value, defaultValue); + return ConfigurationRepository.GetValue(realKey, guildId.Value, defaultValue); - return _appSettingsWrapper.GetValue(key, defaultValue); + return _appSettingsWrapper.GetValue(realKey, defaultValue); } public T GetValue(string key) @@ -80,5 +83,26 @@ namespace ChaosBot { return ConfigurationFlags.ToImmutableDictionary(); } + + private bool TryGetKeyFromRegexMatch(string key, out string realKey) + { + if (ConfigurationFlags.ContainsKey(key)) + { + realKey = key; + return true; + } + + foreach (string configurationFlagsKey in ConfigurationFlags.Keys) + { + if (new Regex(configurationFlagsKey).IsMatch(key)) + { + realKey = key; + return true; + } + } + + realKey = null; + return false; + } } } From 9b604b67a7428d75e35eac6771ea37c7aebef2e0 Mon Sep 17 00:00:00 2001 From: Daniel-I-Am Date: Fri, 16 Oct 2020 17:21:42 +0200 Subject: [PATCH 05/18] Rework PermissionChecker to not be dumb... --- ChaosBot/Services/CheckPermissions.cs | 29 ++++++++++----------------- 1 file changed, 11 insertions(+), 18 deletions(-) diff --git a/ChaosBot/Services/CheckPermissions.cs b/ChaosBot/Services/CheckPermissions.cs index 21a7ef7..1d4b59d 100644 --- a/ChaosBot/Services/CheckPermissions.cs +++ b/ChaosBot/Services/CheckPermissions.cs @@ -14,7 +14,7 @@ namespace ChaosBot.Services // Debug information LoggingFacade.Trace($"CheckCommandPerm.CheckPermissionsAsync|Checking permissions for command: {command}"); - // If user is not SocketGuildUser, then return error + // If user is not SocketGuildUser, then do not grant permission if (!(context.User is SocketGuildUser gUser)) return false; // Get the possible permissions @@ -33,29 +33,20 @@ namespace ChaosBot.Services // Loop through all permissions foreach (CommandPermission perm in commandPermissions) { - ulong requiredGroup; - // Check if it's a role or group permission and fetch the right type - if (perm.TargetType == (int)PermissionTarget.Role) - { - // If it's a role, check the configuration for the role otherwise return the permission value - requiredGroup = ConfigurationRepository.GetValue($"Role:{perm.TargetId}", context.Guild.Id, perm.TargetId); - } - else if (perm.TargetType == (int) PermissionTarget.User) + // TODO: fix {CommandPermission} model to not be int, but to be PermissionTarget, so we can remove the int casts + if (perm.TargetType == (int) PermissionTarget.User) { if (context.User.Id == perm.TargetId) return true; + } - return false; - } - else + // TODO: fix {CommandPermission} model to not be int, but to be PermissionTarget, so we can remove the int casts + if (perm.TargetType == (int) PermissionTarget.Role) { - // Return the permission value - requiredGroup = perm.TargetId; + // Check if any of the users roles are of the required group, if so, permission granted + if (gUser.Roles.Any(r => r.Id == perm.TargetId)) + return true; } - - // Check if any of the users roles are of the required group, if so, permission granted - if (gUser.Roles.Any(r => r.Id == requiredGroup)) - return true; } } else @@ -71,7 +62,9 @@ namespace ChaosBot.Services return true; } else + { LoggingFacade.Info("CheckCommandperm.CheckPermissionsAsync|commandPermissions: No Default"); + } } // Permission denied From 5019ea3d3e5a0ca717d071a53b0a92a1fe3d0a59 Mon Sep 17 00:00:00 2001 From: Daniel-I-Am Date: Fri, 16 Oct 2020 17:25:34 +0200 Subject: [PATCH 06/18] Remove *some* duplicate code --- .../Discord/PreConditions/CheckCommandPerm.cs | 67 ++----------------- 1 file changed, 4 insertions(+), 63 deletions(-) diff --git a/ChaosBot/Discord/PreConditions/CheckCommandPerm.cs b/ChaosBot/Discord/PreConditions/CheckCommandPerm.cs index 2c9fa75..46dba74 100644 --- a/ChaosBot/Discord/PreConditions/CheckCommandPerm.cs +++ b/ChaosBot/Discord/PreConditions/CheckCommandPerm.cs @@ -4,6 +4,7 @@ using System.Linq; using System.Threading.Tasks; using ChaosBot.Models; using ChaosBot.Repositories; +using ChaosBot.Services; using Discord.Commands; using Discord.WebSocket; @@ -16,70 +17,10 @@ namespace ChaosBot.Discord.PreConditions public override Task CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services) { - // Debug information - LoggingFacade.Trace($"CheckCommandPerm.CheckPermissionsAsync|Checking permissions for command: {command.Name}"); + if (CheckPermissions.CheckPerms(context, command.Name, _defaultRole)) + return Task.FromResult(PreconditionResult.FromSuccess()); - // If user is not SocketGuildUser, then return error - if (!(context.User is SocketGuildUser gUser)) return Task.FromResult(PreconditionResult.FromError("You must be in a guild to run this command.")); - - // Get the possible permissions - List commandPermissions; - using (ChaosbotContext dbContext = new ChaosbotContext()) - { - IQueryable permissions = dbContext.CommandPermissions; - commandPermissions = permissions.Where(p => p.Command.Equals(command.Name)) - .Where(p => p.DiscordGuildId == context.Guild.Id) - .ToList(); - } - - // If we can find a permission - if(commandPermissions.Count >= 1) - { - // Loop through all permissions - foreach (CommandPermission perm in commandPermissions) - { - ulong requiredGroup; - // Check if it's a role or group permission and fetch the right type - if (perm.TargetType == (int)PermissionTarget.Role) - { - // If it's a role, check the configuration for the role otherwise return the permission value - requiredGroup = ConfigurationRepository.GetValue($"Role:{perm.TargetId}", context.Guild.Id, perm.TargetId); - } - else if (perm.TargetType == (int) PermissionTarget.User) - { - if(context.User.Id == perm.TargetId) - return Task.FromResult(PreconditionResult.FromSuccess()); - continue; - } - else - { - // Return the permission value - requiredGroup = perm.TargetId; - } - - // Check if any of the users roles are of the required group, if so, permission granted - if (gUser.Roles.Any(r => r.Id == requiredGroup)) - return Task.FromResult(PreconditionResult.FromSuccess()); - } - } - else - { - if (_defaultRole == "Admin") - { - if(gUser.GuildPermissions.Administrator) - return Task.FromResult(PreconditionResult.FromSuccess()); - } - else if ( _defaultRole == "User") - { - if(gUser.GuildPermissions.SendMessages) - return Task.FromResult(PreconditionResult.FromSuccess()); - } - else - LoggingFacade.Info($"CheckCommandperm.CheckPermissionsAsync|commandPermissions: No Default"); - } - - // Permission denied - return Task.FromResult(PreconditionResult.FromError($"You do not have access to this command.")); + return Task.FromResult(PreconditionResult.FromError("No permission has been granted to your user or your role")); } } } From afbb92b1e9721f3384b0574c0fccf2947d4a80a4 Mon Sep 17 00:00:00 2001 From: Daniel-I-Am Date: Fri, 16 Oct 2020 17:55:00 +0200 Subject: [PATCH 07/18] Rework all usages of configuration --- ChaosBot/Configuration.cs | 54 ++++++++++++------- ChaosBot/Discord/Modules/Admin/Config.cs | 23 ++++++-- ChaosBot/Discord/Modules/Admin/Role.cs | 9 ++-- ChaosBot/Discord/Modules/User/Info.cs | 2 +- ChaosBot/Discord/Modules/User/Lodestone.cs | 15 +++--- ChaosBot/Discord/Modules/User/Points.cs | 11 ++-- ChaosBot/Discord/Modules/User/RaffleCmd.cs | 15 +++--- .../PreConditions/CheckModuleEnabled.cs | 3 +- ChaosBot/Discord/Services/CommandHandler.cs | 5 +- .../Discord/Services/ExperienceHandler.cs | 5 +- ChaosBot/WebServer/Startup.cs | 2 +- ChaosBot/WebServer/WebServer.cs | 2 +- 12 files changed, 90 insertions(+), 56 deletions(-) diff --git a/ChaosBot/Configuration.cs b/ChaosBot/Configuration.cs index 2246f2e..b79031a 100644 --- a/ChaosBot/Configuration.cs +++ b/ChaosBot/Configuration.cs @@ -11,28 +11,32 @@ namespace ChaosBot { private readonly IConfiguration _appSettingsWrapper; - private static readonly Dictionary ConfigurationFlags = new Dictionary + private static readonly Dictionary ConfigurationFlags = new Dictionary { - {"Bot:Name", typeof(string)}, - {"Bot:Version", typeof(string)}, + {"Bot:Name", (typeof(string), "ChaosBot")}, + {"Bot:Version", (typeof(string), "1.0.0")}, - {"WebServer:Port", typeof(int)}, - {"WebServer:Debug", typeof(bool)}, + {"WebServer:Port", (typeof(int), 8080)}, + {"WebServer:Debug", (typeof(bool), false)}, - {"Discord:Prefix", typeof(string)}, - {"Discord:Token", typeof(string)}, - {"Discord:BaseUri", typeof(string)}, - {"Discord:ClientId", typeof(string)}, - {"Discord:ClientSecret", typeof(string)}, + {"Discord:Prefix", (typeof(string), "!")}, + {"Discord:Token", (typeof(string), "SECRET_TOKEN")}, + {"Discord:BaseUri", (typeof(string), "http://localhost:8080/")}, + {"Discord:ClientId", (typeof(string), "1234567890")}, + {"Discord:ClientSecret", (typeof(string), "1234567890_SECRET_TOKEN")}, - {"Lodestone:ChaosBotApi:ApiToken", typeof(string)}, - {"Lodestone:ChaosBotApi:Url", typeof(string)}, + {"Lodestone:ChaosBotApi:ApiToken", (typeof(string), "SECRET_TOKEN")}, + {"Lodestone:ChaosBotApi:Url", (typeof(string), "http://locahost:8000")}, - {"Database:Host", typeof(string)}, - {"Database:Port", typeof(int)}, - {"Database:User", typeof(string)}, - {"Database:Pass", typeof(string)}, - {"Database:Name", typeof(string)}, + {"Database:Host", (typeof(string), "localhost")}, + {"Database:Port", (typeof(int), 3306)}, + {"Database:User", (typeof(string), "root")}, + {"Database:Pass", (typeof(string), "password")}, + {"Database:Name", (typeof(string), "chaosbot")}, + + {"Module:Experience:Enabled", (typeof(bool), true)}, + {"LevelUp:Channel", (typeof(string), null)}, + {"LevelUp:MentionUser", (typeof(bool), true)}, }; public Configuration() @@ -56,7 +60,7 @@ namespace ChaosBot if (!keyExists) throw new ArgumentException($"Configuration does not contain key '{key}'"); - if (!(ConfigurationFlags[realKey] == typeof(T))) + if (!(ConfigurationFlags[realKey].type == typeof(T))) throw new ArgumentException($"Configuration flag '{realKey}<{ConfigurationFlags[realKey]}>' does not have type '{typeof(T)}'"); if (guildId.HasValue) @@ -65,6 +69,18 @@ namespace ChaosBot return _appSettingsWrapper.GetValue(realKey, defaultValue); } + public T GetValueGlobalDefault(string key, ulong? guildId = null) + { + bool keyExists = TryGetKeyFromRegexMatch(key, out string realKey); + object defaultObject = keyExists ? ConfigurationFlags[realKey].defaultValue : null; + + T defaultValue = default; + if (defaultObject != null) + defaultValue = (T)Convert.ChangeType(defaultObject, typeof(T)); + + return GetValue(key, defaultValue); + } + public T GetValue(string key) { return GetValue(key, default); @@ -79,7 +95,7 @@ namespace ChaosBot * Get the available configuration flags * Immutable dictionary of config-key/type pairs */ - public ImmutableDictionary GetConfigurationFlags() + public ImmutableDictionary GetConfigurationFlags() { return ConfigurationFlags.ToImmutableDictionary(); } diff --git a/ChaosBot/Discord/Modules/Admin/Config.cs b/ChaosBot/Discord/Modules/Admin/Config.cs index f305aa4..4b4ad9c 100644 --- a/ChaosBot/Discord/Modules/Admin/Config.cs +++ b/ChaosBot/Discord/Modules/Admin/Config.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Immutable; using Discord.Commands; using System.Threading.Tasks; using System.Text; @@ -43,19 +44,20 @@ namespace ChaosBot.Discord.Modules.Admin { var sb = new StringBuilder(); var embed = new EmbedBuilder(); + Configuration config = new Configuration(); embed.WithColor(new Color(255, 255, 0)); embed.Title = $"Configuration Management Help"; sb.AppendLine(); sb.AppendLine("To set a configuration value:"); - sb.AppendLine($"{ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}config set "); + sb.AppendLine($"{config.GetValueGlobalDefault("Discord:Prefix", Context.Guild.Id)}config set "); sb.AppendLine("To get a configuration value:"); - sb.AppendLine($"{ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}config get "); + sb.AppendLine($"{config.GetValueGlobalDefault("Discord:Prefix", Context.Guild.Id)}config get "); sb.AppendLine("To reset a configuration value to default:"); - sb.AppendLine($"{ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}config reset "); + sb.AppendLine($"{config.GetValueGlobalDefault("Discord:Prefix", Context.Guild.Id)}config reset "); sb.AppendLine(); sb.AppendLine("To view this help:"); - sb.AppendLine($"{ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}config help"); + sb.AppendLine($"{config.GetValueGlobalDefault("Discord:Prefix", Context.Guild.Id)}config help"); /* * Add the string to the Embed @@ -124,7 +126,18 @@ namespace ChaosBot.Discord.Modules.Admin embed.Title = $"Configuration Retrieval"; sb.AppendLine(); sb.AppendLine($" Flag: {key}"); - sb.AppendLine($"Value: {ConfigurationRepository.GetValue(key, Context.Guild.Id, "NotSet")}"); + + Configuration config = new Configuration(); + ImmutableDictionary configFlags = + config.GetConfigurationFlags(); + + dynamic configValue; + if (configFlags.TryGetValue(key, out (Type type, object defaultvalue) configFlagValue)) + configValue = new Configuration().GetValue(key, configFlagValue.defaultvalue, Context.Guild.Id); + else + configValue = "Not a valid key"; + + sb.AppendLine($"Value: {configValue}"); /* * Add the string to the Embed diff --git a/ChaosBot/Discord/Modules/Admin/Role.cs b/ChaosBot/Discord/Modules/Admin/Role.cs index 95bd044..98f7b43 100644 --- a/ChaosBot/Discord/Modules/Admin/Role.cs +++ b/ChaosBot/Discord/Modules/Admin/Role.cs @@ -23,19 +23,20 @@ namespace ChaosBot.Discord.Modules.Admin { var sb = new StringBuilder(); var embed = new EmbedBuilder(); + Configuration config = new Configuration(); embed.WithColor(new Color(255, 255, 0)); embed.Title = $"Role Management Help"; sb.AppendLine(); sb.AppendLine("To add a role-reaction to a message:"); - sb.AppendLine($"{ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}role add "); + sb.AppendLine($"{config.GetValueGlobalDefault("Discord:Prefix", Context.Guild.Id)}role add "); sb.AppendLine("To add many role-reactions to a message add more sets of emote and role:"); - sb.AppendLine($"{ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}role add "); + sb.AppendLine($"{config.GetValueGlobalDefault("Discord:Prefix", Context.Guild.Id)}role add "); sb.AppendLine("To remove a role-reaction from a message:"); - sb.AppendLine($"{ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}role remove "); + sb.AppendLine($"{config.GetValueGlobalDefault("Discord:Prefix", Context.Guild.Id)}role remove "); sb.AppendLine(); sb.AppendLine("To view this help:"); - sb.AppendLine($"{ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}role help"); + sb.AppendLine($"{config.GetValueGlobalDefault("Discord:Prefix", Context.Guild.Id)}role help"); /* * Add the string to the Embed diff --git a/ChaosBot/Discord/Modules/User/Info.cs b/ChaosBot/Discord/Modules/User/Info.cs index 60af2c0..e4a4d57 100644 --- a/ChaosBot/Discord/Modules/User/Info.cs +++ b/ChaosBot/Discord/Modules/User/Info.cs @@ -24,7 +24,7 @@ namespace ChaosBot.Discord.Modules.User embed.WithColor(new Color(255, 255, 0)); embed.Title = $"Information {config.GetValue("Bot:Name")} v{config.GetValue("Bot:Version")}"; - sb.AppendLine($"Prefix: {config.GetValue("Discord:Prefix", default(string), Context.Guild.Id)}"); + sb.AppendLine($"Prefix: {config.GetValueGlobalDefault("Discord:Prefix", Context.Guild.Id)}"); /* * Add the string to the Embed diff --git a/ChaosBot/Discord/Modules/User/Lodestone.cs b/ChaosBot/Discord/Modules/User/Lodestone.cs index f44c4db..c9f5cde 100644 --- a/ChaosBot/Discord/Modules/User/Lodestone.cs +++ b/ChaosBot/Discord/Modules/User/Lodestone.cs @@ -73,28 +73,29 @@ namespace ChaosBot.Discord.Modules.User { var sb = new StringBuilder(); var embed = new EmbedBuilder(); + Configuration config = new Configuration(); embed.WithColor(new Color(255, 255, 0)); embed.Title = "Lodestone API Help"; sb.AppendLine(); sb.AppendLine(); sb.AppendLine("To get FreeCompany Info:"); - sb.AppendLine($"By Id: {ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}lodestone freecompany 9231394073691143535"); - sb.AppendLine($"By Name: {ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}lodestone freecompany Siren Helix"); + sb.AppendLine($"By Id: {config.GetValueGlobalDefault("Discord:Prefix", Context.Guild.Id)}lodestone freecompany 9231394073691143535"); + sb.AppendLine($"By Name: {config.GetValueGlobalDefault("Discord:Prefix", Context.Guild.Id)}lodestone freecompany Siren Helix"); sb.AppendLine(); sb.AppendLine("To get Character Info:"); - sb.AppendLine($"By Id: {ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}lodestone character 9231394073691143535"); - sb.AppendLine($"By Name: {ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}lodestone character Siren Luna Kaisar"); + sb.AppendLine($"By Id: {config.GetValueGlobalDefault("Discord:Prefix", Context.Guild.Id)}lodestone character 9231394073691143535"); + sb.AppendLine($"By Name: {config.GetValueGlobalDefault("Discord:Prefix", Context.Guild.Id)}lodestone character Siren Luna Kaisar"); if (CheckPermissions.CheckPerms(Context, "lodestone.link")) { sb.AppendLine("To Link your Character:"); - sb.AppendLine($"By Id: {ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}lodestone link 9231394073691143535"); - sb.AppendLine($"By Name: {ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}lodestone link Siren Luna Kaisar"); + sb.AppendLine($"By Id: {config.GetValueGlobalDefault("Discord:Prefix", Context.Guild.Id)}lodestone link 9231394073691143535"); + sb.AppendLine($"By Name: {config.GetValueGlobalDefault("Discord:Prefix", Context.Guild.Id)}lodestone link Siren Luna Kaisar"); } sb.AppendLine(); sb.AppendLine(); sb.AppendLine("To view this help:"); - sb.AppendLine($"{ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}config help"); + sb.AppendLine($"{config.GetValueGlobalDefault("Discord:Prefix", Context.Guild.Id)}config help"); /* * Add the string to the Embed diff --git a/ChaosBot/Discord/Modules/User/Points.cs b/ChaosBot/Discord/Modules/User/Points.cs index e3bc9a7..8ecfa3f 100644 --- a/ChaosBot/Discord/Modules/User/Points.cs +++ b/ChaosBot/Discord/Modules/User/Points.cs @@ -76,19 +76,20 @@ namespace ChaosBot.Discord.Modules.User { var sb = new StringBuilder(); var embed = new EmbedBuilder(); + Configuration config = new Configuration(); embed.WithColor(new Color(255, 255, 0)); embed.Title = "Points system"; sb.AppendLine($"{Context.User.Mention} has requested points information."); sb.AppendLine(); sb.AppendLine("Usage:"); - sb.AppendLine($"{ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}points info"); - sb.AppendLine($"{ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}points help"); + sb.AppendLine($"{config.GetValueGlobalDefault("Discord:Prefix", Context.Guild.Id)}points info"); + sb.AppendLine($"{config.GetValueGlobalDefault("Discord:Prefix", Context.Guild.Id)}points help"); sb.AppendLine(); sb.AppendLine("Moderation commands:"); - sb.AppendLine($"{ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}points add "); - sb.AppendLine($"{ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}point remove "); - sb.AppendLine($"{ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}point delete "); + sb.AppendLine($"{config.GetValueGlobalDefault("Discord:Prefix", Context.Guild.Id)}points add "); + sb.AppendLine($"{config.GetValueGlobalDefault("Discord:Prefix", Context.Guild.Id)}point remove "); + sb.AppendLine($"{config.GetValueGlobalDefault("Discord:Prefix", Context.Guild.Id)}point delete "); /* * Add the string to the Embed diff --git a/ChaosBot/Discord/Modules/User/RaffleCmd.cs b/ChaosBot/Discord/Modules/User/RaffleCmd.cs index 0da4467..7ced268 100644 --- a/ChaosBot/Discord/Modules/User/RaffleCmd.cs +++ b/ChaosBot/Discord/Modules/User/RaffleCmd.cs @@ -85,23 +85,24 @@ namespace ChaosBot.Discord.Modules.User { var sb = new StringBuilder(); var embed = new EmbedBuilder(); + Configuration config = new Configuration(); embed.WithColor(new Color(255, 255, 0)); embed.Title = "Raffle system"; sb.AppendLine($"{Context.User.Mention} has requested Raffle information."); sb.AppendLine(); sb.AppendLine("Usage:"); - sb.AppendLine($"{ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}raffle info"); - sb.AppendLine($"{ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}raffle help"); - sb.AppendLine($"{ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}raffle buy "); + sb.AppendLine($"{config.GetValueGlobalDefault("Discord:Prefix", Context.Guild.Id)}raffle info"); + sb.AppendLine($"{config.GetValueGlobalDefault("Discord:Prefix", Context.Guild.Id)}raffle help"); + sb.AppendLine($"{config.GetValueGlobalDefault("Discord:Prefix", Context.Guild.Id)}raffle buy "); sb.AppendLine(); sb.AppendLine("Moderation commands:"); if(CheckPermissions.CheckPerms(Context, "raffle.add", "Admin")) - sb.AppendLine($"{ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}raffle add "); + sb.AppendLine($"{config.GetValueGlobalDefault("Discord:Prefix", Context.Guild.Id)}raffle add "); if(CheckPermissions.CheckPerms(Context, "raffle.remove", "Admin")) { - sb.AppendLine($"{ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}raffle remove "); - sb.AppendLine($"{ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}raffle delete "); + sb.AppendLine($"{config.GetValueGlobalDefault("Discord:Prefix", Context.Guild.Id)}raffle remove "); + sb.AppendLine($"{config.GetValueGlobalDefault("Discord:Prefix", Context.Guild.Id)}raffle delete "); } /* * Add the string to the Embed @@ -279,7 +280,7 @@ namespace ChaosBot.Discord.Modules.User else { await ReplyAsync( - $"{Context.User.Mention}, if you wish to clear ALL tickets, please send the below command.```{ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}raffle clear confirm```"); + $"{Context.User.Mention}, if you wish to clear ALL tickets, please send the below command.```{new Configuration().GetValueGlobalDefault("Discord:Prefix", Context.Guild.Id)}raffle clear confirm```"); } } catch (Exception ex) diff --git a/ChaosBot/Discord/PreConditions/CheckModuleEnabled.cs b/ChaosBot/Discord/PreConditions/CheckModuleEnabled.cs index 502c7c5..dbd1d24 100644 --- a/ChaosBot/Discord/PreConditions/CheckModuleEnabled.cs +++ b/ChaosBot/Discord/PreConditions/CheckModuleEnabled.cs @@ -32,8 +32,7 @@ namespace ChaosBot.Discord.PreConditions if (context.Guild == null) throw new Exception("This must be run in a guild"); // Check if module enabled in database - return Convert.ToBoolean(ConfigurationRepository.GetValue($"Module:{moduleName}:Enabled", - context.Guild.Id, "true")); + return new Configuration().GetValue($"Module:{moduleName}:Enabled", true, context.Guild.Id); } } } diff --git a/ChaosBot/Discord/Services/CommandHandler.cs b/ChaosBot/Discord/Services/CommandHandler.cs index 1c370ea..25593e3 100644 --- a/ChaosBot/Discord/Services/CommandHandler.cs +++ b/ChaosBot/Discord/Services/CommandHandler.cs @@ -66,13 +66,14 @@ namespace ChaosBot.Discord.Services SocketCommandContext context = new SocketCommandContext(_client, message); + Configuration config = new Configuration(); int argPos = 0; - string prefix = ConfigurationRepository.GetValue("Discord:Prefix", context.Guild.Id, "!"); + string prefix = config.GetValueGlobalDefault("Discord:Prefix", context.Guild.Id); if (!(message.HasMentionPrefix(_client.CurrentUser, ref argPos) || message.HasStringPrefix(prefix, ref argPos))) { - if(Convert.ToBoolean(ConfigurationRepository.GetValue("Experience:Commands", context.Guild.Id, "false"))) + if(config.GetValue("Module:Experience:Enabled", false, context.Guild.Id)) ExperienceHandler.AddXp(context); return; } diff --git a/ChaosBot/Discord/Services/ExperienceHandler.cs b/ChaosBot/Discord/Services/ExperienceHandler.cs index ade1678..cc59850 100644 --- a/ChaosBot/Discord/Services/ExperienceHandler.cs +++ b/ChaosBot/Discord/Services/ExperienceHandler.cs @@ -66,12 +66,13 @@ namespace ChaosBot.Discord.Services { // The user has leveled up, we can send a message LoggingFacade.Info($"User leveled up [{context.User.Username}#{context.User.Discriminator} -> Level {newLevel}]"); + Configuration config = new Configuration(); string channelToSendIn = - ConfigurationRepository.GetValue("LevelUp:Channel", context.Guild.Id, "false"); + config.GetValue("LevelUp:Channel", null, context.Guild.Id); string mentionString = $"<@{context.User.Id}>"; - if (!Convert.ToBoolean(ConfigurationRepository.GetValue("LevelUp:MentionUser", context.Guild.Id, "true"))) + if (!config.GetValueGlobalDefault("LevelUp:MentionUser", context.Guild.Id)) { mentionString = context.User.Username; if (context.User is IGuildUser guildUser) diff --git a/ChaosBot/WebServer/Startup.cs b/ChaosBot/WebServer/Startup.cs index a35b965..1914204 100644 --- a/ChaosBot/WebServer/Startup.cs +++ b/ChaosBot/WebServer/Startup.cs @@ -42,7 +42,7 @@ namespace ChaosBot.WebServer { LoggingFacade.Info("Initializing Kestrel Startup and Configuration"); - if (new Configuration().GetValue("WebServer:Debug", false)) + if (new Configuration().GetValueGlobalDefault("WebServer:Debug")) app.UseDeveloperExceptionPage(); app.UseForwardedHeaders(); diff --git a/ChaosBot/WebServer/WebServer.cs b/ChaosBot/WebServer/WebServer.cs index 71a3a13..22d24f7 100644 --- a/ChaosBot/WebServer/WebServer.cs +++ b/ChaosBot/WebServer/WebServer.cs @@ -28,7 +28,7 @@ namespace ChaosBot.WebServer webBuilder.UseWebRoot(webRoot); webBuilder.ConfigureKestrel(serverOptions => { - serverOptions.Listen(IPAddress.Any, config.GetValue("WebServer:Port", 80), + serverOptions.Listen(IPAddress.Any, config.GetValueGlobalDefault("WebServer:Port"), listenOptions => { listenOptions.UseConnectionLogging(); From 47e6d2bed566b20bc4e91f96fd0fb3b7f1c39be3 Mon Sep 17 00:00:00 2001 From: Daniel-I-Am Date: Fri, 16 Oct 2020 17:57:57 +0200 Subject: [PATCH 08/18] Move Configuration wrapper class to separate namespace --- ChaosBot/{ => ConfigHelpers}/Configuration.cs | 2 +- ChaosBot/Discord/DiscordConnect.cs | 1 + ChaosBot/Discord/Modules/Admin/Config.cs | 1 + ChaosBot/Discord/Modules/Admin/RankCheck.cs | 1 + ChaosBot/Discord/Modules/Admin/Role.cs | 1 + ChaosBot/Discord/Modules/User/Info.cs | 1 + ChaosBot/Discord/Modules/User/Lodestone.cs | 1 + ChaosBot/Discord/Modules/User/Points.cs | 1 + ChaosBot/Discord/Modules/User/RaffleCmd.cs | 1 + ChaosBot/Discord/PreConditions/CheckModuleEnabled.cs | 1 + ChaosBot/Discord/Services/CommandHandler.cs | 1 + ChaosBot/Discord/Services/ExperienceHandler.cs | 1 + ChaosBot/Discord/Services/TimerHandler.cs | 1 + ChaosBot/Models/ChaosbotContext.cs | 2 +- ChaosBot/Program.cs | 1 + ChaosBot/WebServer/App/DiscordController.cs | 1 + ChaosBot/WebServer/Services/DiscordInviteGenerator.cs | 1 + ChaosBot/WebServer/Startup.cs | 1 + ChaosBot/WebServer/WebServer.cs | 1 + 19 files changed, 19 insertions(+), 2 deletions(-) rename ChaosBot/{ => ConfigHelpers}/Configuration.cs (99%) diff --git a/ChaosBot/Configuration.cs b/ChaosBot/ConfigHelpers/Configuration.cs similarity index 99% rename from ChaosBot/Configuration.cs rename to ChaosBot/ConfigHelpers/Configuration.cs index b79031a..437c58d 100644 --- a/ChaosBot/Configuration.cs +++ b/ChaosBot/ConfigHelpers/Configuration.cs @@ -5,7 +5,7 @@ using System.Text.RegularExpressions; using ChaosBot.Repositories; using Microsoft.Extensions.Configuration; -namespace ChaosBot +namespace ChaosBot.ConfigHelpers { public class Configuration { diff --git a/ChaosBot/Discord/DiscordConnect.cs b/ChaosBot/Discord/DiscordConnect.cs index 05ee3d3..8d73ba5 100644 --- a/ChaosBot/Discord/DiscordConnect.cs +++ b/ChaosBot/Discord/DiscordConnect.cs @@ -3,6 +3,7 @@ using Discord; using Discord.Commands; using Discord.WebSocket; using System.Threading.Tasks; +using ChaosBot.ConfigHelpers; using ChaosBot.Discord.Services; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; diff --git a/ChaosBot/Discord/Modules/Admin/Config.cs b/ChaosBot/Discord/Modules/Admin/Config.cs index 4b4ad9c..ed26ce4 100644 --- a/ChaosBot/Discord/Modules/Admin/Config.cs +++ b/ChaosBot/Discord/Modules/Admin/Config.cs @@ -10,6 +10,7 @@ using ChaosBot.Services; using Discord; using Microsoft.EntityFrameworkCore; using Newtonsoft.Json; +using Configuration = ChaosBot.ConfigHelpers.Configuration; namespace ChaosBot.Discord.Modules.Admin { diff --git a/ChaosBot/Discord/Modules/Admin/RankCheck.cs b/ChaosBot/Discord/Modules/Admin/RankCheck.cs index ca65164..73572f7 100644 --- a/ChaosBot/Discord/Modules/Admin/RankCheck.cs +++ b/ChaosBot/Discord/Modules/Admin/RankCheck.cs @@ -14,6 +14,7 @@ using ChaosBot.Models; using ChaosBot.Repositories; using Microsoft.Extensions.Configuration; using Newtonsoft.Json; +using Configuration = ChaosBot.ConfigHelpers.Configuration; namespace ChaosBot.Discord.Modules.Admin { diff --git a/ChaosBot/Discord/Modules/Admin/Role.cs b/ChaosBot/Discord/Modules/Admin/Role.cs index 98f7b43..15015fc 100644 --- a/ChaosBot/Discord/Modules/Admin/Role.cs +++ b/ChaosBot/Discord/Modules/Admin/Role.cs @@ -9,6 +9,7 @@ using ChaosBot.Discord.PreConditions; using ChaosBot.Models; using ChaosBot.Repositories; using Microsoft.EntityFrameworkCore; +using Configuration = ChaosBot.ConfigHelpers.Configuration; namespace ChaosBot.Discord.Modules.Admin { diff --git a/ChaosBot/Discord/Modules/User/Info.cs b/ChaosBot/Discord/Modules/User/Info.cs index e4a4d57..c5c4c60 100644 --- a/ChaosBot/Discord/Modules/User/Info.cs +++ b/ChaosBot/Discord/Modules/User/Info.cs @@ -1,6 +1,7 @@ using System; using System.Text; using System.Threading.Tasks; +using ChaosBot.ConfigHelpers; using ChaosBot.Discord.PreConditions; using ChaosBot.Repositories; using Discord; diff --git a/ChaosBot/Discord/Modules/User/Lodestone.cs b/ChaosBot/Discord/Modules/User/Lodestone.cs index c9f5cde..1c947df 100644 --- a/ChaosBot/Discord/Modules/User/Lodestone.cs +++ b/ChaosBot/Discord/Modules/User/Lodestone.cs @@ -11,6 +11,7 @@ using ChaosBot.Models; using ChaosBot.Repositories; using ChaosBot.Services; using Microsoft.EntityFrameworkCore; +using Configuration = ChaosBot.ConfigHelpers.Configuration; namespace ChaosBot.Discord.Modules.User { diff --git a/ChaosBot/Discord/Modules/User/Points.cs b/ChaosBot/Discord/Modules/User/Points.cs index 8ecfa3f..3d8d032 100644 --- a/ChaosBot/Discord/Modules/User/Points.cs +++ b/ChaosBot/Discord/Modules/User/Points.cs @@ -10,6 +10,7 @@ using Discord; using Discord.Commands; using Discord.WebSocket; using Microsoft.EntityFrameworkCore; +using Configuration = ChaosBot.ConfigHelpers.Configuration; namespace ChaosBot.Discord.Modules.User { diff --git a/ChaosBot/Discord/Modules/User/RaffleCmd.cs b/ChaosBot/Discord/Modules/User/RaffleCmd.cs index 7ced268..ad0261d 100644 --- a/ChaosBot/Discord/Modules/User/RaffleCmd.cs +++ b/ChaosBot/Discord/Modules/User/RaffleCmd.cs @@ -9,6 +9,7 @@ using ChaosBot.Services; using Discord; using Discord.Commands; using Discord.WebSocket; +using Configuration = ChaosBot.ConfigHelpers.Configuration; namespace ChaosBot.Discord.Modules.User { diff --git a/ChaosBot/Discord/PreConditions/CheckModuleEnabled.cs b/ChaosBot/Discord/PreConditions/CheckModuleEnabled.cs index dbd1d24..967eac8 100644 --- a/ChaosBot/Discord/PreConditions/CheckModuleEnabled.cs +++ b/ChaosBot/Discord/PreConditions/CheckModuleEnabled.cs @@ -1,5 +1,6 @@ using System; using System.Threading.Tasks; +using ChaosBot.ConfigHelpers; using ChaosBot.Repositories; using Discord.Commands; diff --git a/ChaosBot/Discord/Services/CommandHandler.cs b/ChaosBot/Discord/Services/CommandHandler.cs index 25593e3..6a6cf1e 100644 --- a/ChaosBot/Discord/Services/CommandHandler.cs +++ b/ChaosBot/Discord/Services/CommandHandler.cs @@ -9,6 +9,7 @@ using Discord.Commands; using Discord.WebSocket; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; +using Configuration = ChaosBot.ConfigHelpers.Configuration; namespace ChaosBot.Discord.Services { diff --git a/ChaosBot/Discord/Services/ExperienceHandler.cs b/ChaosBot/Discord/Services/ExperienceHandler.cs index cc59850..b5fef2a 100644 --- a/ChaosBot/Discord/Services/ExperienceHandler.cs +++ b/ChaosBot/Discord/Services/ExperienceHandler.cs @@ -7,6 +7,7 @@ using Discord; using Discord.Commands; using Discord.WebSocket; using Microsoft.EntityFrameworkCore; +using Configuration = ChaosBot.ConfigHelpers.Configuration; namespace ChaosBot.Discord.Services { diff --git a/ChaosBot/Discord/Services/TimerHandler.cs b/ChaosBot/Discord/Services/TimerHandler.cs index 480d5ed..cc1875c 100644 --- a/ChaosBot/Discord/Services/TimerHandler.cs +++ b/ChaosBot/Discord/Services/TimerHandler.cs @@ -1,4 +1,5 @@ using System; +using ChaosBot.ConfigHelpers; using ChaosBot.Services; using Discord; using Discord.WebSocket; diff --git a/ChaosBot/Models/ChaosbotContext.cs b/ChaosBot/Models/ChaosbotContext.cs index b307f66..d0d3f7b 100644 --- a/ChaosBot/Models/ChaosbotContext.cs +++ b/ChaosBot/Models/ChaosbotContext.cs @@ -36,7 +36,7 @@ namespace ChaosBot.Models } else { - ChaosBot.Configuration config = new ChaosBot.Configuration(); + ConfigHelpers.Configuration config = new ConfigHelpers.Configuration(); server = config.GetValue("Database:Host"); port = config.GetValue("Database:Port"); diff --git a/ChaosBot/Program.cs b/ChaosBot/Program.cs index 9fe2151..1a0e23c 100644 --- a/ChaosBot/Program.cs +++ b/ChaosBot/Program.cs @@ -4,6 +4,7 @@ using System.Reflection; using System.Runtime.CompilerServices; using ChaosBot.Discord; using System.Threading.Tasks; +using ChaosBot.ConfigHelpers; using Microsoft.Extensions.Configuration; [assembly: InternalsVisibleTo("ChaosBot.UnitTests")] diff --git a/ChaosBot/WebServer/App/DiscordController.cs b/ChaosBot/WebServer/App/DiscordController.cs index b568e41..e8b7029 100644 --- a/ChaosBot/WebServer/App/DiscordController.cs +++ b/ChaosBot/WebServer/App/DiscordController.cs @@ -4,6 +4,7 @@ using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; +using ChaosBot.ConfigHelpers; using ChaosBot.Discord; using ChaosBot.Repositories; using ChaosBot.WebServer.Services; diff --git a/ChaosBot/WebServer/Services/DiscordInviteGenerator.cs b/ChaosBot/WebServer/Services/DiscordInviteGenerator.cs index 0c3684a..b689851 100644 --- a/ChaosBot/WebServer/Services/DiscordInviteGenerator.cs +++ b/ChaosBot/WebServer/Services/DiscordInviteGenerator.cs @@ -1,3 +1,4 @@ +using ChaosBot.ConfigHelpers; using Microsoft.Extensions.Configuration; namespace ChaosBot.WebServer.Services diff --git a/ChaosBot/WebServer/Startup.cs b/ChaosBot/WebServer/Startup.cs index 1914204..8c6ec5a 100644 --- a/ChaosBot/WebServer/Startup.cs +++ b/ChaosBot/WebServer/Startup.cs @@ -1,4 +1,5 @@ using System.Net.Http; +using ChaosBot.ConfigHelpers; using ChaosBot.WebServer.Services; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Builder; diff --git a/ChaosBot/WebServer/WebServer.cs b/ChaosBot/WebServer/WebServer.cs index 22d24f7..7e37f66 100644 --- a/ChaosBot/WebServer/WebServer.cs +++ b/ChaosBot/WebServer/WebServer.cs @@ -1,5 +1,6 @@ using System.IO; using System.Net; +using ChaosBot.ConfigHelpers; using NLog.Extensions.Logging; using Microsoft.AspNetCore.Hosting; From fe59799e1fa781a867c865fc0196570094133f28 Mon Sep 17 00:00:00 2001 From: Daniel-I-Am Date: Fri, 16 Oct 2020 17:59:49 +0200 Subject: [PATCH 09/18] Move ConfigurationRepository to ConfigHelpers namespace --- ChaosBot/ConfigHelpers/Configuration.cs | 1 - .../ConfigurationRepository.cs | 5 ++--- ChaosBot/Discord/Modules/Admin/Config.cs | 2 +- ChaosBot/Discord/Modules/Admin/RankCheck.cs | 1 - ChaosBot/Discord/Modules/Admin/Role.cs | 1 - ChaosBot/Discord/Modules/User/Info.cs | 1 - ChaosBot/Discord/Modules/User/Lodestone.cs | 1 - ChaosBot/Discord/Modules/User/Points.cs | 1 - ChaosBot/Discord/Modules/User/RaffleCmd.cs | 1 - ChaosBot/Discord/PreConditions/CheckCommandPerm.cs | 1 - ChaosBot/Discord/PreConditions/CheckModuleEnabled.cs | 1 - ChaosBot/Discord/Services/CommandHandler.cs | 1 - ChaosBot/Discord/Services/ExperienceHandler.cs | 1 - ChaosBot/Services/CheckPermissions.cs | 1 - ChaosBot/WebServer/App/DiscordController.cs | 1 - 15 files changed, 3 insertions(+), 17 deletions(-) rename ChaosBot/{Repositories => ConfigHelpers}/ConfigurationRepository.cs (97%) diff --git a/ChaosBot/ConfigHelpers/Configuration.cs b/ChaosBot/ConfigHelpers/Configuration.cs index 437c58d..2260457 100644 --- a/ChaosBot/ConfigHelpers/Configuration.cs +++ b/ChaosBot/ConfigHelpers/Configuration.cs @@ -2,7 +2,6 @@ using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Text.RegularExpressions; -using ChaosBot.Repositories; using Microsoft.Extensions.Configuration; namespace ChaosBot.ConfigHelpers diff --git a/ChaosBot/Repositories/ConfigurationRepository.cs b/ChaosBot/ConfigHelpers/ConfigurationRepository.cs similarity index 97% rename from ChaosBot/Repositories/ConfigurationRepository.cs rename to ChaosBot/ConfigHelpers/ConfigurationRepository.cs index ca21996..0f12efc 100644 --- a/ChaosBot/Repositories/ConfigurationRepository.cs +++ b/ChaosBot/ConfigHelpers/ConfigurationRepository.cs @@ -1,10 +1,9 @@ -using System; using System.Linq; -using ChaosBot.Models; using System.Text.Json; +using ChaosBot.Models; using Microsoft.Extensions.Configuration; -namespace ChaosBot.Repositories +namespace ChaosBot.ConfigHelpers { public static class ConfigurationRepository { diff --git a/ChaosBot/Discord/Modules/Admin/Config.cs b/ChaosBot/Discord/Modules/Admin/Config.cs index ed26ce4..2785bac 100644 --- a/ChaosBot/Discord/Modules/Admin/Config.cs +++ b/ChaosBot/Discord/Modules/Admin/Config.cs @@ -3,9 +3,9 @@ using System.Collections.Immutable; using Discord.Commands; using System.Threading.Tasks; using System.Text; +using ChaosBot.ConfigHelpers; using ChaosBot.Discord.PreConditions; using ChaosBot.Models; -using ChaosBot.Repositories; using ChaosBot.Services; using Discord; using Microsoft.EntityFrameworkCore; diff --git a/ChaosBot/Discord/Modules/Admin/RankCheck.cs b/ChaosBot/Discord/Modules/Admin/RankCheck.cs index 73572f7..ec233a5 100644 --- a/ChaosBot/Discord/Modules/Admin/RankCheck.cs +++ b/ChaosBot/Discord/Modules/Admin/RankCheck.cs @@ -11,7 +11,6 @@ using System.Text; using ChaosBot.Discord.PreConditions; using ChaosBot.Lodestone; using ChaosBot.Models; -using ChaosBot.Repositories; using Microsoft.Extensions.Configuration; using Newtonsoft.Json; using Configuration = ChaosBot.ConfigHelpers.Configuration; diff --git a/ChaosBot/Discord/Modules/Admin/Role.cs b/ChaosBot/Discord/Modules/Admin/Role.cs index 15015fc..73f848d 100644 --- a/ChaosBot/Discord/Modules/Admin/Role.cs +++ b/ChaosBot/Discord/Modules/Admin/Role.cs @@ -7,7 +7,6 @@ using System.Text; using System.Text.RegularExpressions; using ChaosBot.Discord.PreConditions; using ChaosBot.Models; -using ChaosBot.Repositories; using Microsoft.EntityFrameworkCore; using Configuration = ChaosBot.ConfigHelpers.Configuration; diff --git a/ChaosBot/Discord/Modules/User/Info.cs b/ChaosBot/Discord/Modules/User/Info.cs index c5c4c60..0a639ea 100644 --- a/ChaosBot/Discord/Modules/User/Info.cs +++ b/ChaosBot/Discord/Modules/User/Info.cs @@ -3,7 +3,6 @@ using System.Text; using System.Threading.Tasks; using ChaosBot.ConfigHelpers; using ChaosBot.Discord.PreConditions; -using ChaosBot.Repositories; using Discord; using Discord.Commands; using Microsoft.Extensions.Configuration; diff --git a/ChaosBot/Discord/Modules/User/Lodestone.cs b/ChaosBot/Discord/Modules/User/Lodestone.cs index 1c947df..5b3ffed 100644 --- a/ChaosBot/Discord/Modules/User/Lodestone.cs +++ b/ChaosBot/Discord/Modules/User/Lodestone.cs @@ -8,7 +8,6 @@ using System.Linq; using ChaosBot.Discord.PreConditions; using ChaosBot.Lodestone; using ChaosBot.Models; -using ChaosBot.Repositories; using ChaosBot.Services; using Microsoft.EntityFrameworkCore; using Configuration = ChaosBot.ConfigHelpers.Configuration; diff --git a/ChaosBot/Discord/Modules/User/Points.cs b/ChaosBot/Discord/Modules/User/Points.cs index 3d8d032..0b2e7fd 100644 --- a/ChaosBot/Discord/Modules/User/Points.cs +++ b/ChaosBot/Discord/Modules/User/Points.cs @@ -4,7 +4,6 @@ using System.Text; using System.Threading.Tasks; using ChaosBot.Discord.PreConditions; using ChaosBot.Models; -using ChaosBot.Repositories; using ChaosBot.Services; using Discord; using Discord.Commands; diff --git a/ChaosBot/Discord/Modules/User/RaffleCmd.cs b/ChaosBot/Discord/Modules/User/RaffleCmd.cs index ad0261d..fefaa55 100644 --- a/ChaosBot/Discord/Modules/User/RaffleCmd.cs +++ b/ChaosBot/Discord/Modules/User/RaffleCmd.cs @@ -4,7 +4,6 @@ using System.Text; using System.Threading.Tasks; using ChaosBot.Discord.PreConditions; using ChaosBot.Models; -using ChaosBot.Repositories; using ChaosBot.Services; using Discord; using Discord.Commands; diff --git a/ChaosBot/Discord/PreConditions/CheckCommandPerm.cs b/ChaosBot/Discord/PreConditions/CheckCommandPerm.cs index 46dba74..14a1ac7 100644 --- a/ChaosBot/Discord/PreConditions/CheckCommandPerm.cs +++ b/ChaosBot/Discord/PreConditions/CheckCommandPerm.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using ChaosBot.Models; -using ChaosBot.Repositories; using ChaosBot.Services; using Discord.Commands; using Discord.WebSocket; diff --git a/ChaosBot/Discord/PreConditions/CheckModuleEnabled.cs b/ChaosBot/Discord/PreConditions/CheckModuleEnabled.cs index 967eac8..6452326 100644 --- a/ChaosBot/Discord/PreConditions/CheckModuleEnabled.cs +++ b/ChaosBot/Discord/PreConditions/CheckModuleEnabled.cs @@ -1,7 +1,6 @@ using System; using System.Threading.Tasks; using ChaosBot.ConfigHelpers; -using ChaosBot.Repositories; using Discord.Commands; namespace ChaosBot.Discord.PreConditions diff --git a/ChaosBot/Discord/Services/CommandHandler.cs b/ChaosBot/Discord/Services/CommandHandler.cs index 6a6cf1e..1e89cc6 100644 --- a/ChaosBot/Discord/Services/CommandHandler.cs +++ b/ChaosBot/Discord/Services/CommandHandler.cs @@ -3,7 +3,6 @@ using System.Linq; using System.Reflection; using System.Threading.Tasks; using ChaosBot.Models; -using ChaosBot.Repositories; using Discord; using Discord.Commands; using Discord.WebSocket; diff --git a/ChaosBot/Discord/Services/ExperienceHandler.cs b/ChaosBot/Discord/Services/ExperienceHandler.cs index b5fef2a..7da9f06 100644 --- a/ChaosBot/Discord/Services/ExperienceHandler.cs +++ b/ChaosBot/Discord/Services/ExperienceHandler.cs @@ -2,7 +2,6 @@ using System; using System.Linq; using ChaosBot.Discord.PreConditions; using ChaosBot.Models; -using ChaosBot.Repositories; using Discord; using Discord.Commands; using Discord.WebSocket; diff --git a/ChaosBot/Services/CheckPermissions.cs b/ChaosBot/Services/CheckPermissions.cs index 1d4b59d..31f8575 100644 --- a/ChaosBot/Services/CheckPermissions.cs +++ b/ChaosBot/Services/CheckPermissions.cs @@ -1,7 +1,6 @@ using System.Collections.Generic; using System.Linq; using ChaosBot.Models; -using ChaosBot.Repositories; using Discord.Commands; using Discord.WebSocket; diff --git a/ChaosBot/WebServer/App/DiscordController.cs b/ChaosBot/WebServer/App/DiscordController.cs index e8b7029..2e6939b 100644 --- a/ChaosBot/WebServer/App/DiscordController.cs +++ b/ChaosBot/WebServer/App/DiscordController.cs @@ -6,7 +6,6 @@ using System.Net.Http.Headers; using System.Threading.Tasks; using ChaosBot.ConfigHelpers; using ChaosBot.Discord; -using ChaosBot.Repositories; using ChaosBot.WebServer.Services; using Discord; using Microsoft.AspNetCore.Mvc; From f0d01f1a653d6db7802bc70f8cbbeec23e56b453 Mon Sep 17 00:00:00 2001 From: Daniel-I-Am Date: Fri, 16 Oct 2020 18:02:38 +0200 Subject: [PATCH 10/18] Refactor out checking logic --- ChaosBot/ConfigHelpers/Configuration.cs | 31 +++++++++++++++---------- 1 file changed, 19 insertions(+), 12 deletions(-) diff --git a/ChaosBot/ConfigHelpers/Configuration.cs b/ChaosBot/ConfigHelpers/Configuration.cs index 2260457..fb17914 100644 --- a/ChaosBot/ConfigHelpers/Configuration.cs +++ b/ChaosBot/ConfigHelpers/Configuration.cs @@ -54,20 +54,19 @@ namespace ChaosBot.ConfigHelpers */ public T GetValue(string key, T defaultValue, ulong? guildId = null) { - bool keyExists = TryGetKeyFromRegexMatch(key, out string realKey); + string realKey = EnsureKeyExistsAndTypeCorrect(key); - if (!keyExists) - throw new ArgumentException($"Configuration does not contain key '{key}'"); - - if (!(ConfigurationFlags[realKey].type == typeof(T))) - throw new ArgumentException($"Configuration flag '{realKey}<{ConfigurationFlags[realKey]}>' does not have type '{typeof(T)}'"); - if (guildId.HasValue) return ConfigurationRepository.GetValue(realKey, guildId.Value, defaultValue); return _appSettingsWrapper.GetValue(realKey, defaultValue); } + public T GetValue(string key) + { + return GetValue(key, default); + } + public T GetValueGlobalDefault(string key, ulong? guildId = null) { bool keyExists = TryGetKeyFromRegexMatch(key, out string realKey); @@ -80,11 +79,6 @@ namespace ChaosBot.ConfigHelpers return GetValue(key, defaultValue); } - public T GetValue(string key) - { - return GetValue(key, default); - } - public IConfigurationSection GetSection(string key) { return _appSettingsWrapper.GetSection(key); @@ -99,6 +93,19 @@ namespace ChaosBot.ConfigHelpers return ConfigurationFlags.ToImmutableDictionary(); } + private string EnsureKeyExistsAndTypeCorrect(string key) + { + bool keyExists = TryGetKeyFromRegexMatch(key, out string realKey); + + if (!keyExists) + throw new ArgumentException($"Configuration does not contain key '{key}'"); + + if (!(ConfigurationFlags[realKey].type == typeof(T))) + throw new ArgumentException( + $"Configuration flag '{realKey}<{ConfigurationFlags[realKey]}>' does not have type '{typeof(T)}'"); + return realKey; + } + private bool TryGetKeyFromRegexMatch(string key, out string realKey) { if (ConfigurationFlags.ContainsKey(key)) From 80a8a5f6dbb68387b228cf87e732162af63b30f2 Mon Sep 17 00:00:00 2001 From: Daniel-I-Am Date: Fri, 16 Oct 2020 18:04:04 +0200 Subject: [PATCH 11/18] Add wrapper for DeleteValue --- ChaosBot/ConfigHelpers/Configuration.cs | 6 ++++++ ChaosBot/Discord/Modules/Admin/Config.cs | 3 ++- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/ChaosBot/ConfigHelpers/Configuration.cs b/ChaosBot/ConfigHelpers/Configuration.cs index fb17914..bd298af 100644 --- a/ChaosBot/ConfigHelpers/Configuration.cs +++ b/ChaosBot/ConfigHelpers/Configuration.cs @@ -84,6 +84,12 @@ namespace ChaosBot.ConfigHelpers return _appSettingsWrapper.GetSection(key); } + public void DeleteValue(string key, ulong guildId) + { + ConfigurationRepository.DeleteValue(key, guildId); + } + + /** * Get the available configuration flags * Immutable dictionary of config-key/type pairs diff --git a/ChaosBot/Discord/Modules/Admin/Config.cs b/ChaosBot/Discord/Modules/Admin/Config.cs index 2785bac..4658b51 100644 --- a/ChaosBot/Discord/Modules/Admin/Config.cs +++ b/ChaosBot/Discord/Modules/Admin/Config.cs @@ -170,8 +170,9 @@ namespace ChaosBot.Discord.Modules.Admin { StringBuilder sb = new StringBuilder(); EmbedBuilder embed = new EmbedBuilder(); + Configuration config = new Configuration(); - ConfigurationRepository.DeleteValue(key, Context.Guild.Id); + config.DeleteValue(key, Context.Guild.Id); embed.WithColor(new Color(255, 255, 0)); embed.Title = $"Configuration Reset"; From 7f1bb9668f4db5ddc61da0daed72e021b6c4e5d3 Mon Sep 17 00:00:00 2001 From: Daniel-I-Am Date: Fri, 16 Oct 2020 18:04:52 +0200 Subject: [PATCH 12/18] Make ConfigurationRepository internal to ConfigHelpers --- ChaosBot/ConfigHelpers/ConfigurationRepository.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ChaosBot/ConfigHelpers/ConfigurationRepository.cs b/ChaosBot/ConfigHelpers/ConfigurationRepository.cs index 0f12efc..93f0b8b 100644 --- a/ChaosBot/ConfigHelpers/ConfigurationRepository.cs +++ b/ChaosBot/ConfigHelpers/ConfigurationRepository.cs @@ -5,7 +5,7 @@ using Microsoft.Extensions.Configuration; namespace ChaosBot.ConfigHelpers { - public static class ConfigurationRepository + internal static class ConfigurationRepository { public static T GetValue(string key, ulong guildId) { From dd00a6edeb6c386c9ad0335c0fbf97c28119b62c Mon Sep 17 00:00:00 2001 From: Daniel-I-Am Date: Fri, 16 Oct 2020 18:57:50 +0200 Subject: [PATCH 13/18] Fix config get command --- ChaosBot/ConfigHelpers/Configuration.cs | 24 +++++++++++++++++++----- ChaosBot/Discord/Modules/Admin/Config.cs | 6 +++++- 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/ChaosBot/ConfigHelpers/Configuration.cs b/ChaosBot/ConfigHelpers/Configuration.cs index bd298af..f1f7caa 100644 --- a/ChaosBot/ConfigHelpers/Configuration.cs +++ b/ChaosBot/ConfigHelpers/Configuration.cs @@ -54,7 +54,8 @@ namespace ChaosBot.ConfigHelpers */ public T GetValue(string key, T defaultValue, ulong? guildId = null) { - string realKey = EnsureKeyExistsAndTypeCorrect(key); + string realKey = EnsureKeyExists(key); + EnsureTypeCorrect(realKey); if (guildId.HasValue) return ConfigurationRepository.GetValue(realKey, guildId.Value, defaultValue); @@ -79,6 +80,16 @@ namespace ChaosBot.ConfigHelpers return GetValue(key, defaultValue); } + public object GetStringValue(string key, ulong? guildId = null) + { + string realKey = EnsureKeyExists(key); + + if (guildId.HasValue) + return ConfigurationRepository.GetValue(realKey, guildId.Value, ConfigurationFlags[realKey].defaultValue); + + return _appSettingsWrapper.GetValue(realKey, ConfigurationFlags[realKey].defaultValue); + } + public IConfigurationSection GetSection(string key) { return _appSettingsWrapper.GetSection(key); @@ -99,19 +110,22 @@ namespace ChaosBot.ConfigHelpers return ConfigurationFlags.ToImmutableDictionary(); } - private string EnsureKeyExistsAndTypeCorrect(string key) + private string EnsureKeyExists(string key) { bool keyExists = TryGetKeyFromRegexMatch(key, out string realKey); if (!keyExists) throw new ArgumentException($"Configuration does not contain key '{key}'"); - if (!(ConfigurationFlags[realKey].type == typeof(T))) - throw new ArgumentException( - $"Configuration flag '{realKey}<{ConfigurationFlags[realKey]}>' does not have type '{typeof(T)}'"); return realKey; } + private void EnsureTypeCorrect(string realKey) + { + if (!(ConfigurationFlags[realKey].type == typeof(T))) + throw new ArgumentException($"Configuration flag '{realKey}<{ConfigurationFlags[realKey]}>' does not have type '{typeof(T)}'"); + } + private bool TryGetKeyFromRegexMatch(string key, out string realKey) { if (ConfigurationFlags.ContainsKey(key)) diff --git a/ChaosBot/Discord/Modules/Admin/Config.cs b/ChaosBot/Discord/Modules/Admin/Config.cs index 4658b51..e19224a 100644 --- a/ChaosBot/Discord/Modules/Admin/Config.cs +++ b/ChaosBot/Discord/Modules/Admin/Config.cs @@ -134,9 +134,13 @@ namespace ChaosBot.Discord.Modules.Admin dynamic configValue; if (configFlags.TryGetValue(key, out (Type type, object defaultvalue) configFlagValue)) - configValue = new Configuration().GetValue(key, configFlagValue.defaultvalue, Context.Guild.Id); + { + configValue = new Configuration().GetStringValue(key, Context.Guild.Id); + } else + { configValue = "Not a valid key"; + } sb.AppendLine($"Value: {configValue}"); From 49de2320331b860d30441b6513951635d3658a14 Mon Sep 17 00:00:00 2001 From: Daniel-I-Am Date: Fri, 16 Oct 2020 18:59:44 +0200 Subject: [PATCH 14/18] Add everything to restrictedconfig --- ChaosBot/Services/RestrictedConfig.cs | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/ChaosBot/Services/RestrictedConfig.cs b/ChaosBot/Services/RestrictedConfig.cs index 88fc681..21aa5e6 100644 --- a/ChaosBot/Services/RestrictedConfig.cs +++ b/ChaosBot/Services/RestrictedConfig.cs @@ -8,7 +8,29 @@ namespace ChaosBot.Services public static Boolean IsAllowed(string key) { // TODO: List populated from DB - List restrictedCfg = new List {"Database:Host", "Database:Port", "Database:Name", "Database:User", "Database:Pass", "Bot:Version", "NLog", "WebServer", "Discord:Token"}; + List restrictedCfg = new List + { + "Bot:Name", + "Bot:Version", + + "WebServer:Port", + "WebServer:Debug", + + "Discord:Prefix", + "Discord:Token", + "Discord:BaseUri", + "Discord:ClientId", + "Discord:ClientSecret", + + "Lodestone:ChaosBotApi:ApiToken", + "Lodestone:ChaosBotApi:Url", + + "Database:Host", + "Database:Port", + "Database:User", + "Database:Pass", + "Database:Name", + }; if (restrictedCfg.Contains(key)) return false; From a1461855c6eb59ab3563284fcf9e2263d1cab0ce Mon Sep 17 00:00:00 2001 From: Daniel-I-Am Date: Fri, 16 Oct 2020 19:00:22 +0200 Subject: [PATCH 15/18] Fix return type of RestrictedConfig.IsAllowed --- ChaosBot/Services/RestrictedConfig.cs | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/ChaosBot/Services/RestrictedConfig.cs b/ChaosBot/Services/RestrictedConfig.cs index 21aa5e6..f535a7a 100644 --- a/ChaosBot/Services/RestrictedConfig.cs +++ b/ChaosBot/Services/RestrictedConfig.cs @@ -5,7 +5,7 @@ namespace ChaosBot.Services { public class RestrictedConfig { - public static Boolean IsAllowed(string key) + public static bool IsAllowed(string key) { // TODO: List populated from DB List restrictedCfg = new List @@ -32,10 +32,7 @@ namespace ChaosBot.Services "Database:Name", }; - if (restrictedCfg.Contains(key)) - return false; - - return true; + return !restrictedCfg.Contains(key); } } } From 21514746cec25f95a3340ec7be85fdcdbcc2c57b Mon Sep 17 00:00:00 2001 From: Daniel-I-Am Date: Fri, 16 Oct 2020 19:01:24 +0200 Subject: [PATCH 16/18] Make RestrictedConfig static --- ChaosBot/Services/RestrictedConfig.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ChaosBot/Services/RestrictedConfig.cs b/ChaosBot/Services/RestrictedConfig.cs index f535a7a..e21e90f 100644 --- a/ChaosBot/Services/RestrictedConfig.cs +++ b/ChaosBot/Services/RestrictedConfig.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; namespace ChaosBot.Services { - public class RestrictedConfig + public static class RestrictedConfig { public static bool IsAllowed(string key) { From 951692e5fb225279c7656568a6e213e88bc3be6c Mon Sep 17 00:00:00 2001 From: Daniel-I-Am Date: Fri, 16 Oct 2020 21:01:04 +0200 Subject: [PATCH 17/18] Rework all config controllers again --- ChaosBot/ConfigHelpers/Configuration.cs | 219 ++++++++++-------- .../ConfigHelpers/ConfigurationRepository.cs | 47 ++-- ChaosBot/Discord/DiscordConnect.cs | 2 +- ChaosBot/Discord/Modules/Admin/Config.cs | 31 +-- ChaosBot/Discord/Modules/Admin/RankCheck.cs | 4 +- ChaosBot/Discord/Modules/Admin/Role.cs | 8 +- ChaosBot/Discord/Modules/User/Info.cs | 4 +- ChaosBot/Discord/Modules/User/Lodestone.cs | 14 +- ChaosBot/Discord/Modules/User/Points.cs | 10 +- ChaosBot/Discord/Modules/User/RaffleCmd.cs | 14 +- .../PreConditions/CheckModuleEnabled.cs | 2 +- ChaosBot/Discord/Services/CommandHandler.cs | 4 +- .../Discord/Services/ExperienceHandler.cs | 4 +- ChaosBot/Models/ChaosbotContext.cs | 10 +- ChaosBot/Program.cs | 2 +- ChaosBot/WebServer/App/DiscordController.cs | 6 +- .../Services/DiscordInviteGenerator.cs | 2 +- ChaosBot/WebServer/Startup.cs | 2 +- ChaosBot/WebServer/WebServer.cs | 2 +- 19 files changed, 201 insertions(+), 186 deletions(-) diff --git a/ChaosBot/ConfigHelpers/Configuration.cs b/ChaosBot/ConfigHelpers/Configuration.cs index f1f7caa..de6cd76 100644 --- a/ChaosBot/ConfigHelpers/Configuration.cs +++ b/ChaosBot/ConfigHelpers/Configuration.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Text.RegularExpressions; +using System.Threading.Tasks; using Microsoft.Extensions.Configuration; namespace ChaosBot.ConfigHelpers @@ -10,141 +11,153 @@ namespace ChaosBot.ConfigHelpers { private readonly IConfiguration _appSettingsWrapper; - private static readonly Dictionary ConfigurationFlags = new Dictionary + private static readonly Dictionary ConfigurationFlags = new Dictionary { - {"Bot:Name", (typeof(string), "ChaosBot")}, - {"Bot:Version", (typeof(string), "1.0.0")}, + {"Bot:Name", new ConfigurationDetails("Bot:Name", "ChaosBot", true)}, + {"Bot:Version", new ConfigurationDetails("Bot:Version", "1.0.0", true)}, - {"WebServer:Port", (typeof(int), 8080)}, - {"WebServer:Debug", (typeof(bool), false)}, + {"WebServer:Port", new ConfigurationDetails("WebServer:Port", 8080, true)}, + {"WebServer:Debug", new ConfigurationDetails("WebServer:Debug", false, true)}, - {"Discord:Prefix", (typeof(string), "!")}, - {"Discord:Token", (typeof(string), "SECRET_TOKEN")}, - {"Discord:BaseUri", (typeof(string), "http://localhost:8080/")}, - {"Discord:ClientId", (typeof(string), "1234567890")}, - {"Discord:ClientSecret", (typeof(string), "1234567890_SECRET_TOKEN")}, + {"Discord:Prefix", new ConfigurationDetails("Discord:Prefix", "!", true)}, + {"Discord:Token", new ConfigurationDetails("Discord:Token", "SECRET_TOKEN", true)}, + {"Discord:BaseUri", new ConfigurationDetails("Discord:BaseUri", "http://localhost:8080/", true)}, + {"Discord:ClientId", new ConfigurationDetails("Discord:ClientId", "1234567890", true)}, + {"Discord:ClientSecret", new ConfigurationDetails("Discord:ClientSecret", "1234567890_SECRET_TOKEN", true)}, - {"Lodestone:ChaosBotApi:ApiToken", (typeof(string), "SECRET_TOKEN")}, - {"Lodestone:ChaosBotApi:Url", (typeof(string), "http://locahost:8000")}, + {"Lodestone:ChaosBotApi:ApiToken", new ConfigurationDetails("Lodestone:ChaosBotApi:ApiToken", "SECRET_TOKEN", true)}, + {"Lodestone:ChaosBotApi:Url", new ConfigurationDetails("Lodestone:ChaosBotApi:Url", "http://locahost:8000", true)}, - {"Database:Host", (typeof(string), "localhost")}, - {"Database:Port", (typeof(int), 3306)}, - {"Database:User", (typeof(string), "root")}, - {"Database:Pass", (typeof(string), "password")}, - {"Database:Name", (typeof(string), "chaosbot")}, + {"Database:Host", new ConfigurationDetails("Database:Host", "localhost", true)}, + {"Database:Port", new ConfigurationDetails("Database:Port", 3306, true)}, + {"Database:User", new ConfigurationDetails("Database:User", "root", true)}, + {"Database:Pass", new ConfigurationDetails("Database:Pass", "password", true)}, + {"Database:Name", new ConfigurationDetails("Database:Name", "chaosbot", true)}, - {"Module:Experience:Enabled", (typeof(bool), true)}, - {"LevelUp:Channel", (typeof(string), null)}, - {"LevelUp:MentionUser", (typeof(bool), true)}, + {"Module:Experience:Enabled", new ConfigurationDetails("Module:Experience:Enabled", true, false)}, + {"LevelUp:Channel", new ConfigurationDetails("LevelUp:Channel", null, false)}, + {"LevelUp:MentionUser", new ConfigurationDetails("LevelUp:MentionUser", true, false)}, }; public Configuration() { - _appSettingsWrapper = Program.AppSettingsHandler; + _appSettingsWrapper = GetAppSettingsWrapper(); + } - if (_appSettingsWrapper == null) + public IConfigurationDetails GetByKey(string key) + { + if (ConfigurationFlags.TryGetValue(key, out IConfigurationDetails details)) + { + return details; + } + + throw new ArgumentException($"Configuration '{key}' is not available"); + } + + public IConfigurationDetails GetByKey(string key) + { + IConfigurationDetails configurationDetails = GetByKey(key); + + if (configurationDetails.Type != typeof(T)) + throw new ArgumentException($"Configuration flag '{key}' is not of type '{typeof(T)}'"); + + return (IConfigurationDetails) configurationDetails; + } + + internal static IConfiguration GetAppSettingsWrapper() + { + if (Program.AppSettingsHandler == null) throw new NullReferenceException("Program.AppSettingsHandler is unset"); - } - /** - * Gets the configuration value associated with a key in an optional guild - * Configuration key does not exist - * Configuration key does not have the provided type - * Configuration value - */ - public T GetValue(string key, T defaultValue, ulong? guildId = null) + return Program.AppSettingsHandler; + } + + public ImmutableDictionary GetConfigurationFlags() { - string realKey = EnsureKeyExists(key); - EnsureTypeCorrect(realKey); - - if (guildId.HasValue) - return ConfigurationRepository.GetValue(realKey, guildId.Value, defaultValue); - - return _appSettingsWrapper.GetValue(realKey, defaultValue); + return ConfigurationFlags.ToImmutableDictionary(); } - - public T GetValue(string key) - { - return GetValue(key, default); - } - - public T GetValueGlobalDefault(string key, ulong? guildId = null) - { - bool keyExists = TryGetKeyFromRegexMatch(key, out string realKey); - object defaultObject = keyExists ? ConfigurationFlags[realKey].defaultValue : null; - - T defaultValue = default; - if (defaultObject != null) - defaultValue = (T)Convert.ChangeType(defaultObject, typeof(T)); - - return GetValue(key, defaultValue); - } - - public object GetStringValue(string key, ulong? guildId = null) - { - string realKey = EnsureKeyExists(key); - - if (guildId.HasValue) - return ConfigurationRepository.GetValue(realKey, guildId.Value, ConfigurationFlags[realKey].defaultValue); - - return _appSettingsWrapper.GetValue(realKey, ConfigurationFlags[realKey].defaultValue); - } - + public IConfigurationSection GetSection(string key) { return _appSettingsWrapper.GetSection(key); } + } - public void DeleteValue(string key, ulong guildId) + public interface IConfigurationDetails + { + string Key { get; } + bool Restricted { get; } + Type Type { get; } + object DefaultValue { get; } + string GetStringValue(ulong guildId); + void SetValueFromString(string value, ulong guildId); + void DeleteValue(ulong guildId); + } + + public interface IConfigurationDetails : IConfigurationDetails + { + new T DefaultValue { get; } + T GetValue(ulong? guildId = null, bool readRestricted = false); + T GetValue(T defaultValue, ulong? guildId = null, bool readRestricted = false); + void SetValue(T value, ulong guildId); + } + + public class ConfigurationDetails : IConfigurationDetails + { + public string Key { get; } + public bool Restricted { get; } + public T DefaultValue { get; } + + object IConfigurationDetails.DefaultValue => DefaultValue; + public Type Type => typeof(T); + + public ConfigurationDetails(string key, T defaultValue, bool restricted) { - ConfigurationRepository.DeleteValue(key, guildId); + Key = key; + DefaultValue = defaultValue; + Restricted = restricted; } - - /** - * Get the available configuration flags - * Immutable dictionary of config-key/type pairs - */ - public ImmutableDictionary GetConfigurationFlags() + public T GetValue(ulong? guildId = null, bool readRestricted = false) { - return ConfigurationFlags.ToImmutableDictionary(); + return GetValue(DefaultValue, guildId, readRestricted); } - private string EnsureKeyExists(string key) + public T GetValue(T defaultValue, ulong? guildId = null, bool readRestricted = false) { - bool keyExists = TryGetKeyFromRegexMatch(key, out string realKey); + if (!readRestricted && Restricted) + throw new UnauthorizedAccessException($"Configuration key '{Key}' is restricted"); - if (!keyExists) - throw new ArgumentException($"Configuration does not contain key '{key}'"); - - return realKey; - } - - private void EnsureTypeCorrect(string realKey) - { - if (!(ConfigurationFlags[realKey].type == typeof(T))) - throw new ArgumentException($"Configuration flag '{realKey}<{ConfigurationFlags[realKey]}>' does not have type '{typeof(T)}'"); - } - - private bool TryGetKeyFromRegexMatch(string key, out string realKey) - { - if (ConfigurationFlags.ContainsKey(key)) + if (guildId.HasValue) { - realKey = key; - return true; + return ConfigurationRepository.GetValue(Key, guildId.Value, defaultValue); } - foreach (string configurationFlagsKey in ConfigurationFlags.Keys) - { - if (new Regex(configurationFlagsKey).IsMatch(key)) - { - realKey = key; - return true; - } - } + return Configuration.GetAppSettingsWrapper().GetValue(Key, defaultValue); + } - realKey = null; - return false; + public string GetStringValue(ulong guildId) + { + return GetValue(guildId: guildId).ToString(); + } + + public void SetValue(T value, ulong guildId) + { + if (Restricted) + throw new UnauthorizedAccessException($"Configuration key '{Key}' is restricted"); + ConfigurationRepository.SetValue(Key, value, guildId); + } + + public void SetValueFromString(string value, ulong guildId) + { + SetValue((T)Convert.ChangeType(value, typeof(T)), guildId); + } + + public void DeleteValue(ulong guildId) + { + if (Restricted) + throw new UnauthorizedAccessException($"Configuration key '{Key}' is restricted"); + ConfigurationRepository.DeleteValue(Key, guildId); } } } diff --git a/ChaosBot/ConfigHelpers/ConfigurationRepository.cs b/ChaosBot/ConfigHelpers/ConfigurationRepository.cs index 93f0b8b..f5d1d1b 100644 --- a/ChaosBot/ConfigHelpers/ConfigurationRepository.cs +++ b/ChaosBot/ConfigHelpers/ConfigurationRepository.cs @@ -1,7 +1,10 @@ using System.Linq; -using System.Text.Json; +using System.Threading.Tasks; using ChaosBot.Models; +using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; +using Newtonsoft.Json; +using JsonSerializer = System.Text.Json.JsonSerializer; namespace ChaosBot.ConfigHelpers { @@ -14,26 +17,36 @@ namespace ChaosBot.ConfigHelpers public static T GetValue(string key, ulong guildId, T defaultValue) { - using (ChaosbotContext dbContext = new ChaosbotContext()) - { - Models.Configuration config = dbContext.Configuration - .SingleOrDefault(c => c.DiscordGuildId == guildId && c.Key == key); - if (config == null || string.IsNullOrEmpty(config.SerializedValue)) - return GetValueFromAppSettings(key, guildId, defaultValue); - return JsonSerializer.Deserialize(config.SerializedValue); - } + using ChaosbotContext dbContext = new ChaosbotContext(); + Models.Configuration config = dbContext.Configuration + .SingleOrDefault(c => c.DiscordGuildId == guildId && c.Key == key); + if (config == null || string.IsNullOrEmpty(config.SerializedValue)) + return GetValueFromAppSettings(key, guildId, defaultValue); + return JsonSerializer.Deserialize(config.SerializedValue); + } + + public static void SetValue(string key, T value, ulong guildId) + { + using ChaosbotContext dbContext = new ChaosbotContext(); + Models.Configuration cnfSet = new Models.Configuration(); + + cnfSet.Key = key; + cnfSet.DiscordGuildId = guildId; + cnfSet.SerializedValue = JsonConvert.SerializeObject(value); + + dbContext.Configuration.Upsert(cnfSet) + .On(x => new {x.Key, x.DiscordGuildId}) + .Run(); } public static void DeleteValue(string key, ulong guildId) { - using (ChaosbotContext dbContext = new ChaosbotContext()) - { - Models.Configuration config = dbContext.Configuration - .SingleOrDefault(c => c.DiscordGuildId == guildId && c.Key == key); - if (config == null) return; - dbContext.Remove(config); - dbContext.SaveChanges(); - } + using ChaosbotContext dbContext = new ChaosbotContext(); + Models.Configuration config = dbContext.Configuration + .SingleOrDefault(c => c.DiscordGuildId == guildId && c.Key == key); + if (config == null) return; + dbContext.Remove(config); + dbContext.SaveChanges(); } private static T GetValueFromAppSettings(string key, ulong guildId, T defaultValue) diff --git a/ChaosBot/Discord/DiscordConnect.cs b/ChaosBot/Discord/DiscordConnect.cs index 8d73ba5..86914d5 100644 --- a/ChaosBot/Discord/DiscordConnect.cs +++ b/ChaosBot/Discord/DiscordConnect.cs @@ -34,7 +34,7 @@ namespace ChaosBot.Discord Configuration config = new Configuration(); // this is where we get the Token value from the configuration file, and start the bot - await client.LoginAsync(TokenType.Bot, config.GetValue("Discord:Token")); + await client.LoginAsync(TokenType.Bot, config.GetByKey("Discord:Token").GetValue()); await client.StartAsync(); // we get the CommandHandler class here and call the InitializeAsync method to start things up for the CommandHandler service diff --git a/ChaosBot/Discord/Modules/Admin/Config.cs b/ChaosBot/Discord/Modules/Admin/Config.cs index e19224a..e5d2089 100644 --- a/ChaosBot/Discord/Modules/Admin/Config.cs +++ b/ChaosBot/Discord/Modules/Admin/Config.cs @@ -51,14 +51,14 @@ namespace ChaosBot.Discord.Modules.Admin embed.Title = $"Configuration Management Help"; sb.AppendLine(); sb.AppendLine("To set a configuration value:"); - sb.AppendLine($"{config.GetValueGlobalDefault("Discord:Prefix", Context.Guild.Id)}config set "); + sb.AppendLine($"{config.GetByKey("Discord:Prefix").GetValue(Context.Guild.Id)}config set "); sb.AppendLine("To get a configuration value:"); - sb.AppendLine($"{config.GetValueGlobalDefault("Discord:Prefix", Context.Guild.Id)}config get "); + sb.AppendLine($"{config.GetByKey("Discord:Prefix").GetValue(Context.Guild.Id)}config get "); sb.AppendLine("To reset a configuration value to default:"); - sb.AppendLine($"{config.GetValueGlobalDefault("Discord:Prefix", Context.Guild.Id)}config reset "); + sb.AppendLine($"{config.GetByKey("Discord:Prefix").GetValue(Context.Guild.Id)}config reset "); sb.AppendLine(); sb.AppendLine("To view this help:"); - sb.AppendLine($"{config.GetValueGlobalDefault("Discord:Prefix", Context.Guild.Id)}config help"); + sb.AppendLine($"{config.GetByKey("Discord:Prefix").GetValue(Context.Guild.Id)}config help"); /* * Add the string to the Embed @@ -84,19 +84,8 @@ namespace ChaosBot.Discord.Modules.Admin { if(RestrictedConfig.IsAllowed(key)) { - using (ChaosbotContext dbContext = new ChaosbotContext()) - { - Models.Configuration cnfSet = new Models.Configuration(); - - cnfSet.Key = key; - cnfSet.DiscordGuildId = Context.Guild.Id; - cnfSet.SerializedValue = JsonConvert.SerializeObject(value); - - await dbContext.Configuration.Upsert(cnfSet) - .On(x => new {x.Key, x.DiscordGuildId}).RunAsync(); - - await ConfigGet(key, true); - } + new Configuration().GetByKey(key).SetValueFromString(value, Context.Guild.Id); + await ConfigGet(key, true); } } else @@ -129,13 +118,13 @@ namespace ChaosBot.Discord.Modules.Admin sb.AppendLine($" Flag: {key}"); Configuration config = new Configuration(); - ImmutableDictionary configFlags = + ImmutableDictionary configFlags = config.GetConfigurationFlags(); dynamic configValue; - if (configFlags.TryGetValue(key, out (Type type, object defaultvalue) configFlagValue)) + if (configFlags.TryGetValue(key, out IConfigurationDetails configFlagValue)) { - configValue = new Configuration().GetStringValue(key, Context.Guild.Id); + configValue = new Configuration().GetByKey(key).GetStringValue(Context.Guild.Id); } else { @@ -176,7 +165,7 @@ namespace ChaosBot.Discord.Modules.Admin EmbedBuilder embed = new EmbedBuilder(); Configuration config = new Configuration(); - config.DeleteValue(key, Context.Guild.Id); + config.GetByKey(key).DeleteValue(Context.Guild.Id); embed.WithColor(new Color(255, 255, 0)); embed.Title = $"Configuration Reset"; diff --git a/ChaosBot/Discord/Modules/Admin/RankCheck.cs b/ChaosBot/Discord/Modules/Admin/RankCheck.cs index ec233a5..8c9a402 100644 --- a/ChaosBot/Discord/Modules/Admin/RankCheck.cs +++ b/ChaosBot/Discord/Modules/Admin/RankCheck.cs @@ -110,8 +110,8 @@ namespace ChaosBot.Discord.Modules.Admin using HttpClient client = new HttpClient(); Configuration config = new Configuration(); - string endpoint =config.GetValue("Lodestone:ChaosBotApi:Url"); - string apiToken = config.GetValue("Lodestone:ChaosBotApi:ApiToken"); + string endpoint =config.GetByKey("Lodestone:ChaosBotApi:Url").GetValue(); + string apiToken = config.GetByKey("Lodestone:ChaosBotApi:ApiToken").GetValue(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiToken); HttpResponseMessage result = diff --git a/ChaosBot/Discord/Modules/Admin/Role.cs b/ChaosBot/Discord/Modules/Admin/Role.cs index 73f848d..3e91f7f 100644 --- a/ChaosBot/Discord/Modules/Admin/Role.cs +++ b/ChaosBot/Discord/Modules/Admin/Role.cs @@ -29,14 +29,14 @@ namespace ChaosBot.Discord.Modules.Admin embed.Title = $"Role Management Help"; sb.AppendLine(); sb.AppendLine("To add a role-reaction to a message:"); - sb.AppendLine($"{config.GetValueGlobalDefault("Discord:Prefix", Context.Guild.Id)}role add "); + sb.AppendLine($"{config.GetByKey("Discord:Prefix").GetValue(Context.Guild.Id)}role add "); sb.AppendLine("To add many role-reactions to a message add more sets of emote and role:"); - sb.AppendLine($"{config.GetValueGlobalDefault("Discord:Prefix", Context.Guild.Id)}role add "); + sb.AppendLine($"{config.GetByKey("Discord:Prefix").GetValue(Context.Guild.Id)}role add "); sb.AppendLine("To remove a role-reaction from a message:"); - sb.AppendLine($"{config.GetValueGlobalDefault("Discord:Prefix", Context.Guild.Id)}role remove "); + sb.AppendLine($"{config.GetByKey("Discord:Prefix").GetValue(Context.Guild.Id)}role remove "); sb.AppendLine(); sb.AppendLine("To view this help:"); - sb.AppendLine($"{config.GetValueGlobalDefault("Discord:Prefix", Context.Guild.Id)}role help"); + sb.AppendLine($"{config.GetByKey("Discord:Prefix").GetValue(Context.Guild.Id)}role help"); /* * Add the string to the Embed diff --git a/ChaosBot/Discord/Modules/User/Info.cs b/ChaosBot/Discord/Modules/User/Info.cs index 0a639ea..0f760b2 100644 --- a/ChaosBot/Discord/Modules/User/Info.cs +++ b/ChaosBot/Discord/Modules/User/Info.cs @@ -23,8 +23,8 @@ namespace ChaosBot.Discord.Modules.User Configuration config = new Configuration(); embed.WithColor(new Color(255, 255, 0)); - embed.Title = $"Information {config.GetValue("Bot:Name")} v{config.GetValue("Bot:Version")}"; - sb.AppendLine($"Prefix: {config.GetValueGlobalDefault("Discord:Prefix", Context.Guild.Id)}"); + embed.Title = $"Information {config.GetByKey("Bot:Name").GetValue()} v{config.GetByKey("Bot:Version").GetValue()}"; + sb.AppendLine($"Prefix: {config.GetByKey("Discord:Prefix").GetValue(Context.Guild.Id)}"); /* * Add the string to the Embed diff --git a/ChaosBot/Discord/Modules/User/Lodestone.cs b/ChaosBot/Discord/Modules/User/Lodestone.cs index 5b3ffed..c1ca9c3 100644 --- a/ChaosBot/Discord/Modules/User/Lodestone.cs +++ b/ChaosBot/Discord/Modules/User/Lodestone.cs @@ -80,22 +80,22 @@ namespace ChaosBot.Discord.Modules.User sb.AppendLine(); sb.AppendLine(); sb.AppendLine("To get FreeCompany Info:"); - sb.AppendLine($"By Id: {config.GetValueGlobalDefault("Discord:Prefix", Context.Guild.Id)}lodestone freecompany 9231394073691143535"); - sb.AppendLine($"By Name: {config.GetValueGlobalDefault("Discord:Prefix", Context.Guild.Id)}lodestone freecompany Siren Helix"); + sb.AppendLine($"By Id: {config.GetByKey("Discord:Prefix").GetValue(Context.Guild.Id)}lodestone freecompany 9231394073691143535"); + sb.AppendLine($"By Name: {config.GetByKey("Discord:Prefix").GetValue(Context.Guild.Id)}lodestone freecompany Siren Helix"); sb.AppendLine(); sb.AppendLine("To get Character Info:"); - sb.AppendLine($"By Id: {config.GetValueGlobalDefault("Discord:Prefix", Context.Guild.Id)}lodestone character 9231394073691143535"); - sb.AppendLine($"By Name: {config.GetValueGlobalDefault("Discord:Prefix", Context.Guild.Id)}lodestone character Siren Luna Kaisar"); + sb.AppendLine($"By Id: {config.GetByKey("Discord:Prefix").GetValue(Context.Guild.Id)}lodestone character 9231394073691143535"); + sb.AppendLine($"By Name: {config.GetByKey("Discord:Prefix").GetValue(Context.Guild.Id)}lodestone character Siren Luna Kaisar"); if (CheckPermissions.CheckPerms(Context, "lodestone.link")) { sb.AppendLine("To Link your Character:"); - sb.AppendLine($"By Id: {config.GetValueGlobalDefault("Discord:Prefix", Context.Guild.Id)}lodestone link 9231394073691143535"); - sb.AppendLine($"By Name: {config.GetValueGlobalDefault("Discord:Prefix", Context.Guild.Id)}lodestone link Siren Luna Kaisar"); + sb.AppendLine($"By Id: {config.GetByKey("Discord:Prefix").GetValue(Context.Guild.Id)}lodestone link 9231394073691143535"); + sb.AppendLine($"By Name: {config.GetByKey("Discord:Prefix").GetValue(Context.Guild.Id)}lodestone link Siren Luna Kaisar"); } sb.AppendLine(); sb.AppendLine(); sb.AppendLine("To view this help:"); - sb.AppendLine($"{config.GetValueGlobalDefault("Discord:Prefix", Context.Guild.Id)}config help"); + sb.AppendLine($"{config.GetByKey("Discord:Prefix").GetValue(Context.Guild.Id)}config help"); /* * Add the string to the Embed diff --git a/ChaosBot/Discord/Modules/User/Points.cs b/ChaosBot/Discord/Modules/User/Points.cs index 0b2e7fd..264e958 100644 --- a/ChaosBot/Discord/Modules/User/Points.cs +++ b/ChaosBot/Discord/Modules/User/Points.cs @@ -83,13 +83,13 @@ namespace ChaosBot.Discord.Modules.User sb.AppendLine($"{Context.User.Mention} has requested points information."); sb.AppendLine(); sb.AppendLine("Usage:"); - sb.AppendLine($"{config.GetValueGlobalDefault("Discord:Prefix", Context.Guild.Id)}points info"); - sb.AppendLine($"{config.GetValueGlobalDefault("Discord:Prefix", Context.Guild.Id)}points help"); + sb.AppendLine($"{config.GetByKey("Discord:Prefix").GetValue(Context.Guild.Id)}points info"); + sb.AppendLine($"{config.GetByKey("Discord:Prefix").GetValue(Context.Guild.Id)}points help"); sb.AppendLine(); sb.AppendLine("Moderation commands:"); - sb.AppendLine($"{config.GetValueGlobalDefault("Discord:Prefix", Context.Guild.Id)}points add "); - sb.AppendLine($"{config.GetValueGlobalDefault("Discord:Prefix", Context.Guild.Id)}point remove "); - sb.AppendLine($"{config.GetValueGlobalDefault("Discord:Prefix", Context.Guild.Id)}point delete "); + sb.AppendLine($"{config.GetByKey("Discord:Prefix").GetValue(Context.Guild.Id)}points add "); + sb.AppendLine($"{config.GetByKey("Discord:Prefix").GetValue(Context.Guild.Id)}point remove "); + sb.AppendLine($"{config.GetByKey("Discord:Prefix").GetValue(Context.Guild.Id)}point delete "); /* * Add the string to the Embed diff --git a/ChaosBot/Discord/Modules/User/RaffleCmd.cs b/ChaosBot/Discord/Modules/User/RaffleCmd.cs index fefaa55..a8b398c 100644 --- a/ChaosBot/Discord/Modules/User/RaffleCmd.cs +++ b/ChaosBot/Discord/Modules/User/RaffleCmd.cs @@ -92,17 +92,17 @@ namespace ChaosBot.Discord.Modules.User sb.AppendLine($"{Context.User.Mention} has requested Raffle information."); sb.AppendLine(); sb.AppendLine("Usage:"); - sb.AppendLine($"{config.GetValueGlobalDefault("Discord:Prefix", Context.Guild.Id)}raffle info"); - sb.AppendLine($"{config.GetValueGlobalDefault("Discord:Prefix", Context.Guild.Id)}raffle help"); - sb.AppendLine($"{config.GetValueGlobalDefault("Discord:Prefix", Context.Guild.Id)}raffle buy "); + sb.AppendLine($"{config.GetByKey("Discord:Prefix").GetValue(Context.Guild.Id)}raffle info"); + sb.AppendLine($"{config.GetByKey("Discord:Prefix").GetValue(Context.Guild.Id)}raffle help"); + sb.AppendLine($"{config.GetByKey("Discord:Prefix").GetValue(Context.Guild.Id)}raffle buy "); sb.AppendLine(); sb.AppendLine("Moderation commands:"); if(CheckPermissions.CheckPerms(Context, "raffle.add", "Admin")) - sb.AppendLine($"{config.GetValueGlobalDefault("Discord:Prefix", Context.Guild.Id)}raffle add "); + sb.AppendLine($"{config.GetByKey("Discord:Prefix").GetValue(Context.Guild.Id)}raffle add "); if(CheckPermissions.CheckPerms(Context, "raffle.remove", "Admin")) { - sb.AppendLine($"{config.GetValueGlobalDefault("Discord:Prefix", Context.Guild.Id)}raffle remove "); - sb.AppendLine($"{config.GetValueGlobalDefault("Discord:Prefix", Context.Guild.Id)}raffle delete "); + sb.AppendLine($"{config.GetByKey("Discord:Prefix").GetValue(Context.Guild.Id)}raffle remove "); + sb.AppendLine($"{config.GetByKey("Discord:Prefix").GetValue(Context.Guild.Id)}raffle delete "); } /* * Add the string to the Embed @@ -280,7 +280,7 @@ namespace ChaosBot.Discord.Modules.User else { await ReplyAsync( - $"{Context.User.Mention}, if you wish to clear ALL tickets, please send the below command.```{new Configuration().GetValueGlobalDefault("Discord:Prefix", Context.Guild.Id)}raffle clear confirm```"); + $"{Context.User.Mention}, if you wish to clear ALL tickets, please send the below command.```{new Configuration().GetByKey("Discord:Prefix").GetValue(Context.Guild.Id)}raffle clear confirm```"); } } catch (Exception ex) diff --git a/ChaosBot/Discord/PreConditions/CheckModuleEnabled.cs b/ChaosBot/Discord/PreConditions/CheckModuleEnabled.cs index 6452326..1ae3d64 100644 --- a/ChaosBot/Discord/PreConditions/CheckModuleEnabled.cs +++ b/ChaosBot/Discord/PreConditions/CheckModuleEnabled.cs @@ -32,7 +32,7 @@ namespace ChaosBot.Discord.PreConditions if (context.Guild == null) throw new Exception("This must be run in a guild"); // Check if module enabled in database - return new Configuration().GetValue($"Module:{moduleName}:Enabled", true, context.Guild.Id); + return new Configuration().GetByKey($"Module:{moduleName}:Enabled").GetValue(true, context.Guild.Id); } } } diff --git a/ChaosBot/Discord/Services/CommandHandler.cs b/ChaosBot/Discord/Services/CommandHandler.cs index 1e89cc6..893677c 100644 --- a/ChaosBot/Discord/Services/CommandHandler.cs +++ b/ChaosBot/Discord/Services/CommandHandler.cs @@ -69,11 +69,11 @@ namespace ChaosBot.Discord.Services Configuration config = new Configuration(); int argPos = 0; - string prefix = config.GetValueGlobalDefault("Discord:Prefix", context.Guild.Id); + string prefix = config.GetByKey("Discord:Prefix").GetValue(context.Guild.Id); if (!(message.HasMentionPrefix(_client.CurrentUser, ref argPos) || message.HasStringPrefix(prefix, ref argPos))) { - if(config.GetValue("Module:Experience:Enabled", false, context.Guild.Id)) + if(config.GetByKey("Module:Experience:Enabled").GetValue(false, context.Guild.Id)) ExperienceHandler.AddXp(context); return; } diff --git a/ChaosBot/Discord/Services/ExperienceHandler.cs b/ChaosBot/Discord/Services/ExperienceHandler.cs index 7da9f06..dd85c52 100644 --- a/ChaosBot/Discord/Services/ExperienceHandler.cs +++ b/ChaosBot/Discord/Services/ExperienceHandler.cs @@ -69,10 +69,10 @@ namespace ChaosBot.Discord.Services Configuration config = new Configuration(); string channelToSendIn = - config.GetValue("LevelUp:Channel", null, context.Guild.Id); + config.GetByKey("LevelUp:Channel").GetValue(null, context.Guild.Id); string mentionString = $"<@{context.User.Id}>"; - if (!config.GetValueGlobalDefault("LevelUp:MentionUser", context.Guild.Id)) + if (!config.GetByKey("LevelUp:MentionUser").GetValue(context.Guild.Id)) { mentionString = context.User.Username; if (context.User is IGuildUser guildUser) diff --git a/ChaosBot/Models/ChaosbotContext.cs b/ChaosBot/Models/ChaosbotContext.cs index d0d3f7b..64ee36b 100644 --- a/ChaosBot/Models/ChaosbotContext.cs +++ b/ChaosBot/Models/ChaosbotContext.cs @@ -38,11 +38,11 @@ namespace ChaosBot.Models { ConfigHelpers.Configuration config = new ConfigHelpers.Configuration(); - server = config.GetValue("Database:Host"); - port = config.GetValue("Database:Port"); - user = config.GetValue("Database:User"); - pass = config.GetValue("Database:Pass"); - name = config.GetValue("Database:Name"); + server = config.GetByKey("Database:Host").GetValue(); + port = config.GetByKey("Database:Port").GetValue(); + user = config.GetByKey("Database:User").GetValue(); + pass = config.GetByKey("Database:Pass").GetValue(); + name = config.GetByKey("Database:Name").GetValue(); } optionsBuilder.UseMySql( diff --git a/ChaosBot/Program.cs b/ChaosBot/Program.cs index 1a0e23c..f735594 100644 --- a/ChaosBot/Program.cs +++ b/ChaosBot/Program.cs @@ -44,7 +44,7 @@ namespace ChaosBot * Initialize the Discord Client and Login */ Configuration config = new Configuration(); - _logger.Info($"Starting Up {config.GetValue("Bot:Name")} v{config.GetValue("Bot:Version")}"); + _logger.Info($"Starting Up {config.GetByKey("Bot:Name").GetValue()} v{config.GetByKey("Bot:Version").GetValue()}"); try { diff --git a/ChaosBot/WebServer/App/DiscordController.cs b/ChaosBot/WebServer/App/DiscordController.cs index 2e6939b..97fa6cf 100644 --- a/ChaosBot/WebServer/App/DiscordController.cs +++ b/ChaosBot/WebServer/App/DiscordController.cs @@ -38,9 +38,9 @@ namespace ChaosBot.WebServer.App { Configuration config = new Configuration(); - string redirectUri = $"{config.GetValue("Discord:BaseUri")}/api/discord"; - string clientId = config.GetValue("Discord:ClientId"); - string clientSecret = config.GetValue("Discord:ClientSecret"); + string redirectUri = $"{config.GetByKey("Discord:BaseUri").GetValue()}/api/discord"; + string clientId = config.GetByKey("Discord:ClientId").GetValue(); + string clientSecret = config.GetByKey("Discord:ClientSecret").GetValue(); if (code == null) return Redirect($"https://discord.com/api/oauth2/authorize?client_id={clientId}&redirect_uri={redirectUri}&response_type=code&scope=identify%20guilds"); diff --git a/ChaosBot/WebServer/Services/DiscordInviteGenerator.cs b/ChaosBot/WebServer/Services/DiscordInviteGenerator.cs index b689851..2c7bb8d 100644 --- a/ChaosBot/WebServer/Services/DiscordInviteGenerator.cs +++ b/ChaosBot/WebServer/Services/DiscordInviteGenerator.cs @@ -7,7 +7,7 @@ namespace ChaosBot.WebServer.Services { public string Generate() { - string clientId = new Configuration().GetValue("Discord:ClientId"); + string clientId = new Configuration().GetByKey("Discord:ClientId").GetValue(); const ulong permissions = 0x00000020 + // MANAGE_CHANNELS 0x04000000 + // CHANGE_NICKNAME diff --git a/ChaosBot/WebServer/Startup.cs b/ChaosBot/WebServer/Startup.cs index 8c6ec5a..b71f352 100644 --- a/ChaosBot/WebServer/Startup.cs +++ b/ChaosBot/WebServer/Startup.cs @@ -43,7 +43,7 @@ namespace ChaosBot.WebServer { LoggingFacade.Info("Initializing Kestrel Startup and Configuration"); - if (new Configuration().GetValueGlobalDefault("WebServer:Debug")) + if (new Configuration().GetByKey("WebServer:Debug").GetValue()) app.UseDeveloperExceptionPage(); app.UseForwardedHeaders(); diff --git a/ChaosBot/WebServer/WebServer.cs b/ChaosBot/WebServer/WebServer.cs index 7e37f66..503e97c 100644 --- a/ChaosBot/WebServer/WebServer.cs +++ b/ChaosBot/WebServer/WebServer.cs @@ -29,7 +29,7 @@ namespace ChaosBot.WebServer webBuilder.UseWebRoot(webRoot); webBuilder.ConfigureKestrel(serverOptions => { - serverOptions.Listen(IPAddress.Any, config.GetValueGlobalDefault("WebServer:Port"), + serverOptions.Listen(IPAddress.Any, config.GetByKey("WebServer:Port").GetValue(), listenOptions => { listenOptions.UseConnectionLogging(); From 858edf685151c6b1148b6152c6bad5bfa7a5c51a Mon Sep 17 00:00:00 2001 From: Daniel-I-Am Date: Fri, 16 Oct 2020 21:12:25 +0200 Subject: [PATCH 18/18] Fix core classes not being able to read configuration --- ChaosBot/ConfigHelpers/Configuration.cs | 59 +++++++++++---------- ChaosBot/Discord/DiscordConnect.cs | 2 +- ChaosBot/Discord/Modules/Admin/Config.cs | 11 ++-- ChaosBot/Discord/Modules/Admin/RankCheck.cs | 4 +- ChaosBot/Models/ChaosbotContext.cs | 10 ++-- ChaosBot/Services/RestrictedConfig.cs | 38 ------------- ChaosBot/WebServer/App/DiscordController.cs | 2 +- ChaosBot/WebServer/WebServer.cs | 2 +- 8 files changed, 45 insertions(+), 83 deletions(-) delete mode 100644 ChaosBot/Services/RestrictedConfig.cs diff --git a/ChaosBot/ConfigHelpers/Configuration.cs b/ChaosBot/ConfigHelpers/Configuration.cs index de6cd76..d65d0b8 100644 --- a/ChaosBot/ConfigHelpers/Configuration.cs +++ b/ChaosBot/ConfigHelpers/Configuration.cs @@ -13,30 +13,30 @@ namespace ChaosBot.ConfigHelpers private static readonly Dictionary ConfigurationFlags = new Dictionary { - {"Bot:Name", new ConfigurationDetails("Bot:Name", "ChaosBot", true)}, - {"Bot:Version", new ConfigurationDetails("Bot:Version", "1.0.0", true)}, + {"Bot:Name", new ConfigurationDetails("Bot:Name", "ChaosBot", true, false)}, + {"Bot:Version", new ConfigurationDetails("Bot:Version", "1.0.0", true, false)}, - {"WebServer:Port", new ConfigurationDetails("WebServer:Port", 8080, true)}, - {"WebServer:Debug", new ConfigurationDetails("WebServer:Debug", false, true)}, + {"WebServer:Port", new ConfigurationDetails("WebServer:Port", 8080, true, true)}, + {"WebServer:Debug", new ConfigurationDetails("WebServer:Debug", false, true, false)}, - {"Discord:Prefix", new ConfigurationDetails("Discord:Prefix", "!", true)}, - {"Discord:Token", new ConfigurationDetails("Discord:Token", "SECRET_TOKEN", true)}, - {"Discord:BaseUri", new ConfigurationDetails("Discord:BaseUri", "http://localhost:8080/", true)}, - {"Discord:ClientId", new ConfigurationDetails("Discord:ClientId", "1234567890", true)}, - {"Discord:ClientSecret", new ConfigurationDetails("Discord:ClientSecret", "1234567890_SECRET_TOKEN", true)}, + {"Discord:Prefix", new ConfigurationDetails("Discord:Prefix", "!", true, false)}, + {"Discord:Token", new ConfigurationDetails("Discord:Token", "SECRET_TOKEN", true, true)}, + {"Discord:BaseUri", new ConfigurationDetails("Discord:BaseUri", "http://localhost:8080/", true, false)}, + {"Discord:ClientId", new ConfigurationDetails("Discord:ClientId", "1234567890", true, false)}, + {"Discord:ClientSecret", new ConfigurationDetails("Discord:ClientSecret", "1234567890_SECRET_TOKEN", true, true)}, - {"Lodestone:ChaosBotApi:ApiToken", new ConfigurationDetails("Lodestone:ChaosBotApi:ApiToken", "SECRET_TOKEN", true)}, - {"Lodestone:ChaosBotApi:Url", new ConfigurationDetails("Lodestone:ChaosBotApi:Url", "http://locahost:8000", true)}, + {"Lodestone:ChaosBotApi:ApiToken", new ConfigurationDetails("Lodestone:ChaosBotApi:ApiToken", "SECRET_TOKEN", true, true)}, + {"Lodestone:ChaosBotApi:Url", new ConfigurationDetails("Lodestone:ChaosBotApi:Url", "http://locahost:8000", true, true)}, - {"Database:Host", new ConfigurationDetails("Database:Host", "localhost", true)}, - {"Database:Port", new ConfigurationDetails("Database:Port", 3306, true)}, - {"Database:User", new ConfigurationDetails("Database:User", "root", true)}, - {"Database:Pass", new ConfigurationDetails("Database:Pass", "password", true)}, - {"Database:Name", new ConfigurationDetails("Database:Name", "chaosbot", true)}, + {"Database:Host", new ConfigurationDetails("Database:Host", "localhost", true, true)}, + {"Database:Port", new ConfigurationDetails("Database:Port", 3306, true, true)}, + {"Database:User", new ConfigurationDetails("Database:User", "root", true, true)}, + {"Database:Pass", new ConfigurationDetails("Database:Pass", "password", true, true)}, + {"Database:Name", new ConfigurationDetails("Database:Name", "chaosbot", true, true)}, - {"Module:Experience:Enabled", new ConfigurationDetails("Module:Experience:Enabled", true, false)}, - {"LevelUp:Channel", new ConfigurationDetails("LevelUp:Channel", null, false)}, - {"LevelUp:MentionUser", new ConfigurationDetails("LevelUp:MentionUser", true, false)}, + {"Module:Experience:Enabled", new ConfigurationDetails("Module:Experience:Enabled", true, false, false)}, + {"LevelUp:Channel", new ConfigurationDetails("LevelUp:Channel", null, false, false)}, + {"LevelUp:MentionUser", new ConfigurationDetails("LevelUp:MentionUser", true, false, false)}, }; public Configuration() @@ -86,7 +86,8 @@ namespace ChaosBot.ConfigHelpers public interface IConfigurationDetails { string Key { get; } - bool Restricted { get; } + bool WriteRestricted { get; } + bool ReadRestricted { get; } Type Type { get; } object DefaultValue { get; } string GetStringValue(ulong guildId); @@ -98,24 +99,26 @@ namespace ChaosBot.ConfigHelpers { new T DefaultValue { get; } T GetValue(ulong? guildId = null, bool readRestricted = false); - T GetValue(T defaultValue, ulong? guildId = null, bool readRestricted = false); + T GetValue(T defaultValue, ulong? guildId = null, bool readValueEvenIfRestricted = false); void SetValue(T value, ulong guildId); } public class ConfigurationDetails : IConfigurationDetails { public string Key { get; } - public bool Restricted { get; } + public bool WriteRestricted { get; } + public bool ReadRestricted { get; } public T DefaultValue { get; } object IConfigurationDetails.DefaultValue => DefaultValue; public Type Type => typeof(T); - public ConfigurationDetails(string key, T defaultValue, bool restricted) + public ConfigurationDetails(string key, T defaultValue, bool writeRestricted, bool readRestricted) { Key = key; DefaultValue = defaultValue; - Restricted = restricted; + WriteRestricted = writeRestricted; + ReadRestricted = readRestricted; } public T GetValue(ulong? guildId = null, bool readRestricted = false) @@ -123,9 +126,9 @@ namespace ChaosBot.ConfigHelpers return GetValue(DefaultValue, guildId, readRestricted); } - public T GetValue(T defaultValue, ulong? guildId = null, bool readRestricted = false) + public T GetValue(T defaultValue, ulong? guildId = null, bool readValueEvenIfRestricted = false) { - if (!readRestricted && Restricted) + if (!readValueEvenIfRestricted && ReadRestricted) throw new UnauthorizedAccessException($"Configuration key '{Key}' is restricted"); if (guildId.HasValue) @@ -143,7 +146,7 @@ namespace ChaosBot.ConfigHelpers public void SetValue(T value, ulong guildId) { - if (Restricted) + if (WriteRestricted) throw new UnauthorizedAccessException($"Configuration key '{Key}' is restricted"); ConfigurationRepository.SetValue(Key, value, guildId); } @@ -155,7 +158,7 @@ namespace ChaosBot.ConfigHelpers public void DeleteValue(ulong guildId) { - if (Restricted) + if (WriteRestricted) throw new UnauthorizedAccessException($"Configuration key '{Key}' is restricted"); ConfigurationRepository.DeleteValue(Key, guildId); } diff --git a/ChaosBot/Discord/DiscordConnect.cs b/ChaosBot/Discord/DiscordConnect.cs index 86914d5..878db02 100644 --- a/ChaosBot/Discord/DiscordConnect.cs +++ b/ChaosBot/Discord/DiscordConnect.cs @@ -34,7 +34,7 @@ namespace ChaosBot.Discord Configuration config = new Configuration(); // this is where we get the Token value from the configuration file, and start the bot - await client.LoginAsync(TokenType.Bot, config.GetByKey("Discord:Token").GetValue()); + await client.LoginAsync(TokenType.Bot, config.GetByKey("Discord:Token").GetValue(readRestricted: true)); await client.StartAsync(); // we get the CommandHandler class here and call the InitializeAsync method to start things up for the CommandHandler service diff --git a/ChaosBot/Discord/Modules/Admin/Config.cs b/ChaosBot/Discord/Modules/Admin/Config.cs index e5d2089..29935f6 100644 --- a/ChaosBot/Discord/Modules/Admin/Config.cs +++ b/ChaosBot/Discord/Modules/Admin/Config.cs @@ -82,11 +82,8 @@ namespace ChaosBot.Discord.Modules.Admin { if ((key != null) && (value != null) ) { - if(RestrictedConfig.IsAllowed(key)) - { - new Configuration().GetByKey(key).SetValueFromString(value, Context.Guild.Id); - await ConfigGet(key, true); - } + new Configuration().GetByKey(key).SetValueFromString(value, Context.Guild.Id); + await ConfigGet(key, true); } else { @@ -104,7 +101,7 @@ namespace ChaosBot.Discord.Modules.Admin { try { - if ((key != null) && (RestrictedConfig.IsAllowed(key))) + if ((key != null)) { StringBuilder sb = new StringBuilder(); EmbedBuilder embed = new EmbedBuilder(); @@ -159,7 +156,7 @@ namespace ChaosBot.Discord.Modules.Admin { try { - if ((key != null) && (RestrictedConfig.IsAllowed(key))) + if ((key != null)) { StringBuilder sb = new StringBuilder(); EmbedBuilder embed = new EmbedBuilder(); diff --git a/ChaosBot/Discord/Modules/Admin/RankCheck.cs b/ChaosBot/Discord/Modules/Admin/RankCheck.cs index 8c9a402..ca4a380 100644 --- a/ChaosBot/Discord/Modules/Admin/RankCheck.cs +++ b/ChaosBot/Discord/Modules/Admin/RankCheck.cs @@ -110,8 +110,8 @@ namespace ChaosBot.Discord.Modules.Admin using HttpClient client = new HttpClient(); Configuration config = new Configuration(); - string endpoint =config.GetByKey("Lodestone:ChaosBotApi:Url").GetValue(); - string apiToken = config.GetByKey("Lodestone:ChaosBotApi:ApiToken").GetValue(); + string endpoint =config.GetByKey("Lodestone:ChaosBotApi:Url").GetValue(readRestricted: true); + string apiToken = config.GetByKey("Lodestone:ChaosBotApi:ApiToken").GetValue(readRestricted: true); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiToken); HttpResponseMessage result = diff --git a/ChaosBot/Models/ChaosbotContext.cs b/ChaosBot/Models/ChaosbotContext.cs index 64ee36b..4eb3543 100644 --- a/ChaosBot/Models/ChaosbotContext.cs +++ b/ChaosBot/Models/ChaosbotContext.cs @@ -38,11 +38,11 @@ namespace ChaosBot.Models { ConfigHelpers.Configuration config = new ConfigHelpers.Configuration(); - server = config.GetByKey("Database:Host").GetValue(); - port = config.GetByKey("Database:Port").GetValue(); - user = config.GetByKey("Database:User").GetValue(); - pass = config.GetByKey("Database:Pass").GetValue(); - name = config.GetByKey("Database:Name").GetValue(); + server = config.GetByKey("Database:Host").GetValue(readRestricted: true); + port = config.GetByKey("Database:Port").GetValue(readRestricted: true); + user = config.GetByKey("Database:User").GetValue(readRestricted: true); + pass = config.GetByKey("Database:Pass").GetValue(readRestricted: true); + name = config.GetByKey("Database:Name").GetValue(readRestricted: true); } optionsBuilder.UseMySql( diff --git a/ChaosBot/Services/RestrictedConfig.cs b/ChaosBot/Services/RestrictedConfig.cs deleted file mode 100644 index e21e90f..0000000 --- a/ChaosBot/Services/RestrictedConfig.cs +++ /dev/null @@ -1,38 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace ChaosBot.Services -{ - public static class RestrictedConfig - { - public static bool IsAllowed(string key) - { - // TODO: List populated from DB - List restrictedCfg = new List - { - "Bot:Name", - "Bot:Version", - - "WebServer:Port", - "WebServer:Debug", - - "Discord:Prefix", - "Discord:Token", - "Discord:BaseUri", - "Discord:ClientId", - "Discord:ClientSecret", - - "Lodestone:ChaosBotApi:ApiToken", - "Lodestone:ChaosBotApi:Url", - - "Database:Host", - "Database:Port", - "Database:User", - "Database:Pass", - "Database:Name", - }; - - return !restrictedCfg.Contains(key); - } - } -} diff --git a/ChaosBot/WebServer/App/DiscordController.cs b/ChaosBot/WebServer/App/DiscordController.cs index 97fa6cf..7991957 100644 --- a/ChaosBot/WebServer/App/DiscordController.cs +++ b/ChaosBot/WebServer/App/DiscordController.cs @@ -40,7 +40,7 @@ namespace ChaosBot.WebServer.App string redirectUri = $"{config.GetByKey("Discord:BaseUri").GetValue()}/api/discord"; string clientId = config.GetByKey("Discord:ClientId").GetValue(); - string clientSecret = config.GetByKey("Discord:ClientSecret").GetValue(); + string clientSecret = config.GetByKey("Discord:ClientSecret").GetValue(readRestricted: true); if (code == null) return Redirect($"https://discord.com/api/oauth2/authorize?client_id={clientId}&redirect_uri={redirectUri}&response_type=code&scope=identify%20guilds"); diff --git a/ChaosBot/WebServer/WebServer.cs b/ChaosBot/WebServer/WebServer.cs index 503e97c..21c6c1c 100644 --- a/ChaosBot/WebServer/WebServer.cs +++ b/ChaosBot/WebServer/WebServer.cs @@ -29,7 +29,7 @@ namespace ChaosBot.WebServer webBuilder.UseWebRoot(webRoot); webBuilder.ConfigureKestrel(serverOptions => { - serverOptions.Listen(IPAddress.Any, config.GetByKey("WebServer:Port").GetValue(), + serverOptions.Listen(IPAddress.Any, config.GetByKey("WebServer:Port").GetValue(readRestricted: true), listenOptions => { listenOptions.UseConnectionLogging();