diff --git a/ChaosBot/ConfigHelpers/Configuration.cs b/ChaosBot/ConfigHelpers/Configuration.cs new file mode 100644 index 0000000..d65d0b8 --- /dev/null +++ b/ChaosBot/ConfigHelpers/Configuration.cs @@ -0,0 +1,166 @@ +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 +{ + public class Configuration + { + private readonly IConfiguration _appSettingsWrapper; + + private static readonly Dictionary ConfigurationFlags = new Dictionary + { + {"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, true)}, + {"WebServer:Debug", new ConfigurationDetails("WebServer:Debug", false, true, false)}, + + {"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, true)}, + {"Lodestone:ChaosBotApi:Url", new ConfigurationDetails("Lodestone:ChaosBotApi:Url", "http://locahost:8000", true, 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, false)}, + {"LevelUp:Channel", new ConfigurationDetails("LevelUp:Channel", null, false, false)}, + {"LevelUp:MentionUser", new ConfigurationDetails("LevelUp:MentionUser", true, false, false)}, + }; + + public Configuration() + { + _appSettingsWrapper = GetAppSettingsWrapper(); + } + + 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"); + + return Program.AppSettingsHandler; + } + + public ImmutableDictionary GetConfigurationFlags() + { + return ConfigurationFlags.ToImmutableDictionary(); + } + + public IConfigurationSection GetSection(string key) + { + return _appSettingsWrapper.GetSection(key); + } + } + + public interface IConfigurationDetails + { + string Key { get; } + bool WriteRestricted { get; } + bool ReadRestricted { 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 readValueEvenIfRestricted = false); + void SetValue(T value, ulong guildId); + } + + public class ConfigurationDetails : IConfigurationDetails + { + public string Key { 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 writeRestricted, bool readRestricted) + { + Key = key; + DefaultValue = defaultValue; + WriteRestricted = writeRestricted; + ReadRestricted = readRestricted; + } + + public T GetValue(ulong? guildId = null, bool readRestricted = false) + { + return GetValue(DefaultValue, guildId, readRestricted); + } + + public T GetValue(T defaultValue, ulong? guildId = null, bool readValueEvenIfRestricted = false) + { + if (!readValueEvenIfRestricted && ReadRestricted) + throw new UnauthorizedAccessException($"Configuration key '{Key}' is restricted"); + + if (guildId.HasValue) + { + return ConfigurationRepository.GetValue(Key, guildId.Value, defaultValue); + } + + return Configuration.GetAppSettingsWrapper().GetValue(Key, defaultValue); + } + + public string GetStringValue(ulong guildId) + { + return GetValue(guildId: guildId).ToString(); + } + + public void SetValue(T value, ulong guildId) + { + if (WriteRestricted) + 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 (WriteRestricted) + throw new UnauthorizedAccessException($"Configuration key '{Key}' is restricted"); + ConfigurationRepository.DeleteValue(Key, guildId); + } + } +} diff --git a/ChaosBot/ConfigHelpers/ConfigurationRepository.cs b/ChaosBot/ConfigHelpers/ConfigurationRepository.cs new file mode 100644 index 0000000..f5d1d1b --- /dev/null +++ b/ChaosBot/ConfigHelpers/ConfigurationRepository.cs @@ -0,0 +1,57 @@ +using System.Linq; +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 +{ + internal static class ConfigurationRepository + { + public static T GetValue(string key, ulong guildId) + { + return GetValue(key, guildId, default); + } + + 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); + } + + 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(); + } + + private static T GetValueFromAppSettings(string key, ulong guildId, T defaultValue) + { + return Program.AppSettingsHandler.GetValue($"Servers:{guildId}:{key}", Program.AppSettingsHandler.GetValue(key, defaultValue)); + } + } +} diff --git a/ChaosBot/Discord/DiscordConnect.cs b/ChaosBot/Discord/DiscordConnect.cs index c94424e..878db02 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; @@ -28,9 +29,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.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 c4ba8e7..29935f6 100644 --- a/ChaosBot/Discord/Modules/Admin/Config.cs +++ b/ChaosBot/Discord/Modules/Admin/Config.cs @@ -1,14 +1,16 @@ using System; +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; using Newtonsoft.Json; +using Configuration = ChaosBot.ConfigHelpers.Configuration; namespace ChaosBot.Discord.Modules.Admin { @@ -43,19 +45,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.GetByKey("Discord:Prefix").GetValue(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.GetByKey("Discord:Prefix").GetValue(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.GetByKey("Discord:Prefix").GetValue(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.GetByKey("Discord:Prefix").GetValue(Context.Guild.Id)}config help"); /* * Add the string to the Embed @@ -79,22 +82,8 @@ namespace ChaosBot.Discord.Modules.Admin { if ((key != null) && (value != null) ) { - if(RestrictedConfig.IsAllowed(key)) - { - using (ChaosbotContext dbContext = new ChaosbotContext()) - { - Configuration cnfSet = new 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 { @@ -112,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(); @@ -124,7 +113,22 @@ 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 IConfigurationDetails configFlagValue)) + { + configValue = new Configuration().GetByKey(key).GetStringValue(Context.Guild.Id); + } + else + { + configValue = "Not a valid key"; + } + + sb.AppendLine($"Value: {configValue}"); /* * Add the string to the Embed @@ -152,12 +156,13 @@ namespace ChaosBot.Discord.Modules.Admin { try { - if ((key != null) && (RestrictedConfig.IsAllowed(key))) + if ((key != null)) { StringBuilder sb = new StringBuilder(); EmbedBuilder embed = new EmbedBuilder(); + Configuration config = new Configuration(); - ConfigurationRepository.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 e71bdd6..ca4a380 100644 --- a/ChaosBot/Discord/Modules/Admin/RankCheck.cs +++ b/ChaosBot/Discord/Modules/Admin/RankCheck.cs @@ -11,9 +11,9 @@ 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; namespace ChaosBot.Discord.Modules.Admin { @@ -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.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/Discord/Modules/Admin/Role.cs b/ChaosBot/Discord/Modules/Admin/Role.cs index 95bd044..3e91f7f 100644 --- a/ChaosBot/Discord/Modules/Admin/Role.cs +++ b/ChaosBot/Discord/Modules/Admin/Role.cs @@ -7,8 +7,8 @@ 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; namespace ChaosBot.Discord.Modules.Admin { @@ -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.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($"{ConfigurationRepository.GetValue("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($"{ConfigurationRepository.GetValue("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($"{ConfigurationRepository.GetValue("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 553d79e..0f760b2 100644 --- a/ChaosBot/Discord/Modules/User/Info.cs +++ b/ChaosBot/Discord/Modules/User/Info.cs @@ -1,8 +1,8 @@ using System; 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; @@ -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.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 f44c4db..c1ca9c3 100644 --- a/ChaosBot/Discord/Modules/User/Lodestone.cs +++ b/ChaosBot/Discord/Modules/User/Lodestone.cs @@ -8,9 +8,9 @@ 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; namespace ChaosBot.Discord.Modules.User { @@ -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.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: {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.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: {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.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($"{ConfigurationRepository.GetValue("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 e3bc9a7..264e958 100644 --- a/ChaosBot/Discord/Modules/User/Points.cs +++ b/ChaosBot/Discord/Modules/User/Points.cs @@ -4,12 +4,12 @@ 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; using Discord.WebSocket; using Microsoft.EntityFrameworkCore; +using Configuration = ChaosBot.ConfigHelpers.Configuration; namespace ChaosBot.Discord.Modules.User { @@ -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.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($"{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.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 0da4467..a8b398c 100644 --- a/ChaosBot/Discord/Modules/User/RaffleCmd.cs +++ b/ChaosBot/Discord/Modules/User/RaffleCmd.cs @@ -4,11 +4,11 @@ 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; using Discord.WebSocket; +using Configuration = ChaosBot.ConfigHelpers.Configuration; namespace ChaosBot.Discord.Modules.User { @@ -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.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($"{ConfigurationRepository.GetValue("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($"{ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}raffle remove "); - sb.AppendLine($"{ConfigurationRepository.GetValue("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 @@ -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().GetByKey("Discord:Prefix").GetValue(Context.Guild.Id)}raffle clear confirm```"); } } catch (Exception ex) diff --git a/ChaosBot/Discord/PreConditions/CheckCommandPerm.cs b/ChaosBot/Discord/PreConditions/CheckCommandPerm.cs index 2c9fa75..14a1ac7 100644 --- a/ChaosBot/Discord/PreConditions/CheckCommandPerm.cs +++ b/ChaosBot/Discord/PreConditions/CheckCommandPerm.cs @@ -3,7 +3,7 @@ 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; @@ -16,70 +16,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")); } } } diff --git a/ChaosBot/Discord/PreConditions/CheckModuleEnabled.cs b/ChaosBot/Discord/PreConditions/CheckModuleEnabled.cs index 502c7c5..1ae3d64 100644 --- a/ChaosBot/Discord/PreConditions/CheckModuleEnabled.cs +++ b/ChaosBot/Discord/PreConditions/CheckModuleEnabled.cs @@ -1,6 +1,6 @@ using System; using System.Threading.Tasks; -using ChaosBot.Repositories; +using ChaosBot.ConfigHelpers; using Discord.Commands; namespace ChaosBot.Discord.PreConditions @@ -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().GetByKey($"Module:{moduleName}:Enabled").GetValue(true, context.Guild.Id); } } } diff --git a/ChaosBot/Discord/Services/CommandHandler.cs b/ChaosBot/Discord/Services/CommandHandler.cs index 1c370ea..893677c 100644 --- a/ChaosBot/Discord/Services/CommandHandler.cs +++ b/ChaosBot/Discord/Services/CommandHandler.cs @@ -3,12 +3,12 @@ using System.Linq; using System.Reflection; using System.Threading.Tasks; using ChaosBot.Models; -using ChaosBot.Repositories; using Discord; using Discord.Commands; using Discord.WebSocket; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; +using Configuration = ChaosBot.ConfigHelpers.Configuration; namespace ChaosBot.Discord.Services { @@ -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.GetByKey("Discord:Prefix").GetValue(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.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 ade1678..dd85c52 100644 --- a/ChaosBot/Discord/Services/ExperienceHandler.cs +++ b/ChaosBot/Discord/Services/ExperienceHandler.cs @@ -2,11 +2,11 @@ using System; using System.Linq; using ChaosBot.Discord.PreConditions; using ChaosBot.Models; -using ChaosBot.Repositories; using Discord; using Discord.Commands; using Discord.WebSocket; using Microsoft.EntityFrameworkCore; +using Configuration = ChaosBot.ConfigHelpers.Configuration; namespace ChaosBot.Discord.Services { @@ -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.GetByKey("LevelUp:Channel").GetValue(null, context.Guild.Id); string mentionString = $"<@{context.User.Id}>"; - if (!Convert.ToBoolean(ConfigurationRepository.GetValue("LevelUp:MentionUser", context.Guild.Id, "true"))) + if (!config.GetByKey("LevelUp:MentionUser").GetValue(context.Guild.Id)) { mentionString = context.User.Username; if (context.User is IGuildUser guildUser) diff --git a/ChaosBot/Discord/Services/TimerHandler.cs b/ChaosBot/Discord/Services/TimerHandler.cs index fe5850b..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; @@ -15,8 +16,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..4eb3543 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 + { + ConfigHelpers.Configuration config = new ConfigHelpers.Configuration(); + + 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( $"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..f735594 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")] @@ -42,7 +43,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.GetByKey("Bot:Name").GetValue()} v{config.GetByKey("Bot:Version").GetValue()}"); try { diff --git a/ChaosBot/Repositories/ConfigurationRepository.cs b/ChaosBot/Repositories/ConfigurationRepository.cs deleted file mode 100644 index e85c9de..0000000 --- a/ChaosBot/Repositories/ConfigurationRepository.cs +++ /dev/null @@ -1,45 +0,0 @@ -using System; -using System.Linq; -using ChaosBot.Models; -using System.Text.Json; -using Microsoft.Extensions.Configuration; - -namespace ChaosBot.Repositories -{ - public static class ConfigurationRepository - { - public static T GetValue(string key, ulong guildId) - { - return GetValue(key, guildId, default); - } - - public static T GetValue(string key, ulong guildId, T defaultValue) - { - using (ChaosbotContext dbContext = new ChaosbotContext()) - { - 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 DeleteValue(string key, ulong guildId) - { - using (ChaosbotContext dbContext = new ChaosbotContext()) - { - 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) - { - return Program.AppSettingsHandler.GetValue($"Servers:{guildId}:{key}", Program.AppSettingsHandler.GetValue(key, defaultValue)); - } - } -} \ No newline at end of file diff --git a/ChaosBot/Services/CheckPermissions.cs b/ChaosBot/Services/CheckPermissions.cs index 21a7ef7..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; @@ -14,7 +13,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 +32,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 +61,9 @@ namespace ChaosBot.Services return true; } else + { LoggingFacade.Info("CheckCommandperm.CheckPermissionsAsync|commandPermissions: No Default"); + } } // Permission denied diff --git a/ChaosBot/Services/RestrictedConfig.cs b/ChaosBot/Services/RestrictedConfig.cs deleted file mode 100644 index 88fc681..0000000 --- a/ChaosBot/Services/RestrictedConfig.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace ChaosBot.Services -{ - public class RestrictedConfig - { - 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"}; - - if (restrictedCfg.Contains(key)) - return false; - - return true; - } - } -} diff --git a/ChaosBot/WebServer/App/DiscordController.cs b/ChaosBot/WebServer/App/DiscordController.cs index 48e6247..7991957 100644 --- a/ChaosBot/WebServer/App/DiscordController.cs +++ b/ChaosBot/WebServer/App/DiscordController.cs @@ -4,8 +4,8 @@ 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; using Discord; using Microsoft.AspNetCore.Mvc; @@ -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.GetByKey("Discord:BaseUri").GetValue()}/api/discord"; + string clientId = config.GetByKey("Discord:ClientId").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/Services/DiscordInviteGenerator.cs b/ChaosBot/WebServer/Services/DiscordInviteGenerator.cs index 088c616..2c7bb8d 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 @@ -6,7 +7,7 @@ namespace ChaosBot.WebServer.Services { public string Generate() { - string clientId = Program.AppSettingsHandler.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/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; + } } } diff --git a/ChaosBot/WebServer/Startup.cs b/ChaosBot/WebServer/Startup.cs index 90607ff..b71f352 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; @@ -42,7 +43,7 @@ namespace ChaosBot.WebServer { LoggingFacade.Info("Initializing Kestrel Startup and Configuration"); - if (Program.AppSettingsHandler.GetValue("WebServer:Debug", false)) + if (new Configuration().GetByKey("WebServer:Debug").GetValue()) app.UseDeveloperExceptionPage(); app.UseForwardedHeaders(); diff --git a/ChaosBot/WebServer/WebServer.cs b/ChaosBot/WebServer/WebServer.cs index 2d7d8dd..21c6c1c 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; @@ -22,12 +23,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.GetByKey("WebServer:Port").GetValue(readRestricted: true), listenOptions => { listenOptions.UseConnectionLogging(); @@ -37,7 +39,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(); });