Rework configuration through a root level helper
This commit is contained in:
parent
062dd56767
commit
194d025660
65
ChaosBot/Configuration.cs
Normal file
65
ChaosBot/Configuration.cs
Normal file
@ -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<string, Type> ConfigurationFlags = new Dictionary<string, Type>
|
||||
{
|
||||
{"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
|
||||
* <exception cref="ArgumentException">Configuration key does not exist</exception>
|
||||
* <exception cref="ArgumentException">Configuration key does not have the provided type</exception>
|
||||
* <returns>Configuration value</returns>
|
||||
*/
|
||||
public T GetValue<T>(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<T>(string key)
|
||||
{
|
||||
return GetValue<T>(key, default);
|
||||
}
|
||||
|
||||
public IConfigurationSection GetSection(string key)
|
||||
{
|
||||
return _appSettingsWrapper.GetSection(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the available configuration flags
|
||||
* <returns>Immutable dictionary of config-key/type pairs</returns>
|
||||
*/
|
||||
public ImmutableDictionary<string, Type> GetConfigurationFlags()
|
||||
{
|
||||
return ConfigurationFlags.ToImmutableDictionary();
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -28,9 +28,12 @@ namespace ChaosBot.Discord
|
||||
client.Log += Log;
|
||||
client.Ready += ReadyAsync;
|
||||
services.GetRequiredService<CommandService>().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<string>("Discord:Token"));
|
||||
await client.LoginAsync(TokenType.Bot, config.GetValue<string>("Discord:Token"));
|
||||
await client.StartAsync();
|
||||
|
||||
// we get the CommandHandler class here and call the InitializeAsync method to start things up for the CommandHandler service
|
||||
|
||||
@ -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;
|
||||
|
||||
@ -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<string>("Url");
|
||||
string apiToken = configurationSection.GetValue<string>("ApiToken");
|
||||
Configuration config = new Configuration();
|
||||
string endpoint =config.GetValue<string>("Lodestone:ChaosBotApi:Url");
|
||||
string apiToken = config.GetValue<string>("Lodestone:ChaosBotApi:ApiToken");
|
||||
|
||||
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiToken);
|
||||
HttpResponseMessage result =
|
||||
|
||||
@ -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<string>("Bot:Name")} v{Program.AppSettingsHandler.GetValue<string>("Bot:Version")}";
|
||||
sb.AppendLine($"Prefix: {ConfigurationRepository.GetValue<string>("Discord:Prefix", Context.Guild.Id)}");
|
||||
embed.Title = $"Information {config.GetValue<string>("Bot:Name")} v{config.GetValue<string>("Bot:Version")}";
|
||||
sb.AppendLine($"Prefix: {config.GetValue("Discord:Prefix", default(string), Context.Guild.Id)}");
|
||||
|
||||
/*
|
||||
* Add the string to the Embed
|
||||
|
||||
@ -15,8 +15,9 @@ namespace ChaosBot.Discord.Services
|
||||
public static void Initialize(IServiceProvider services)
|
||||
{
|
||||
_client = services.GetRequiredService<DiscordSocketClient>();
|
||||
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<long?>("Lodestone:SloganDescription:Channel", null);
|
||||
int refreshMinutes = serverConfig.GetValue("Lodestone:SloganDescription:RefreshMinutes", 60);
|
||||
|
||||
@ -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<string>("Database:Host");
|
||||
port = config.GetValue<int>("Database:Port");
|
||||
user = config.GetValue<string>("Database:User");
|
||||
pass = config.GetValue<string>("Database:Pass");
|
||||
name = config.GetValue<string>("Database:Name");
|
||||
}
|
||||
string server = Program.AppSettingsHandler.GetValue<string>("Database:Host");
|
||||
int port = Program.AppSettingsHandler.GetValue<int>("Database:Port");
|
||||
string user = Program.AppSettingsHandler.GetValue<string>("Database:User");
|
||||
string pass = Program.AppSettingsHandler.GetValue<string>("Database:Pass");
|
||||
string name = Program.AppSettingsHandler.GetValue<string>("Database:Name");
|
||||
else
|
||||
{
|
||||
ChaosBot.Configuration config = new ChaosBot.Configuration();
|
||||
|
||||
server = config.GetValue<string>("Database:Host");
|
||||
port = config.GetValue<int>("Database:Port");
|
||||
user = config.GetValue<string>("Database:User");
|
||||
pass = config.GetValue<string>("Database:Pass");
|
||||
name = config.GetValue<string>("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});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -42,7 +42,8 @@ namespace ChaosBot
|
||||
/*
|
||||
* Initialize the Discord Client and Login
|
||||
*/
|
||||
_logger.Info($"Starting Up {AppSettingsHandler.GetValue<string>("Bot:Name")} v{AppSettingsHandler.GetValue<string>("Bot:Version")}");
|
||||
Configuration config = new Configuration();
|
||||
_logger.Info($"Starting Up {config.GetValue<string>("Bot:Name")} v{config.GetValue<string>("Bot:Version")}");
|
||||
|
||||
try
|
||||
{
|
||||
|
||||
@ -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));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -36,9 +36,11 @@ namespace ChaosBot.WebServer.App
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> Index(string code = null)
|
||||
{
|
||||
string redirectUri = $"{Program.AppSettingsHandler.GetValue<string>("Discord:BaseUri")}/api/discord";
|
||||
string clientId = Program.AppSettingsHandler.GetValue<string>("Discord:ClientId");
|
||||
string clientSecret = Program.AppSettingsHandler.GetValue<string>("Discord:ClientSecret");
|
||||
Configuration config = new Configuration();
|
||||
|
||||
string redirectUri = $"{config.GetValue<string>("Discord:BaseUri")}/api/discord";
|
||||
string clientId = config.GetValue<string>("Discord:ClientId");
|
||||
string clientSecret = config.GetValue<string>("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");
|
||||
|
||||
@ -6,7 +6,7 @@ namespace ChaosBot.WebServer.Services
|
||||
{
|
||||
public string Generate()
|
||||
{
|
||||
string clientId = Program.AppSettingsHandler.GetValue<string>("Discord:ClientId");
|
||||
string clientId = new Configuration().GetValue<string>("Discord:ClientId");
|
||||
const ulong permissions =
|
||||
0x00000020 + // MANAGE_CHANNELS
|
||||
0x04000000 + // CHANGE_NICKNAME
|
||||
|
||||
@ -42,7 +42,7 @@ namespace ChaosBot.WebServer
|
||||
{
|
||||
LoggingFacade.Info("Initializing Kestrel Startup and Configuration");
|
||||
|
||||
if (Program.AppSettingsHandler.GetValue<bool>("WebServer:Debug", false))
|
||||
if (new Configuration().GetValue("WebServer:Debug", false))
|
||||
app.UseDeveloperExceptionPage();
|
||||
|
||||
app.UseForwardedHeaders();
|
||||
|
||||
@ -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<int>("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<Startup>();
|
||||
});
|
||||
|
||||
Loading…
Reference in New Issue
Block a user