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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -29,8 +29,11 @@ namespace ChaosBot.Discord
|
|||||||
client.Ready += ReadyAsync;
|
client.Ready += ReadyAsync;
|
||||||
services.GetRequiredService<CommandService>().Log += Log;
|
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
|
// 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();
|
await client.StartAsync();
|
||||||
|
|
||||||
// we get the CommandHandler class here and call the InitializeAsync method to start things up for the CommandHandler service
|
// 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())
|
using (ChaosbotContext dbContext = new ChaosbotContext())
|
||||||
{
|
{
|
||||||
Configuration cnfSet = new Configuration();
|
Models.Configuration cnfSet = new Models.Configuration();
|
||||||
|
|
||||||
cnfSet.Key = key;
|
cnfSet.Key = key;
|
||||||
cnfSet.DiscordGuildId = Context.Guild.Id;
|
cnfSet.DiscordGuildId = Context.Guild.Id;
|
||||||
|
|||||||
@ -109,10 +109,9 @@ namespace ChaosBot.Discord.Modules.Admin
|
|||||||
{
|
{
|
||||||
using HttpClient client = new HttpClient();
|
using HttpClient client = new HttpClient();
|
||||||
|
|
||||||
IConfigurationSection configurationSection =
|
Configuration config = new Configuration();
|
||||||
Program.AppSettingsHandler.GetSection("Lodestone:ChaosBotApi");
|
string endpoint =config.GetValue<string>("Lodestone:ChaosBotApi:Url");
|
||||||
string endpoint = configurationSection.GetValue<string>("Url");
|
string apiToken = config.GetValue<string>("Lodestone:ChaosBotApi:ApiToken");
|
||||||
string apiToken = configurationSection.GetValue<string>("ApiToken");
|
|
||||||
|
|
||||||
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiToken);
|
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiToken);
|
||||||
HttpResponseMessage result =
|
HttpResponseMessage result =
|
||||||
|
|||||||
@ -20,10 +20,11 @@ namespace ChaosBot.Discord.Modules.User
|
|||||||
{
|
{
|
||||||
var sb = new StringBuilder();
|
var sb = new StringBuilder();
|
||||||
var embed = new EmbedBuilder();
|
var embed = new EmbedBuilder();
|
||||||
|
Configuration config = new Configuration();
|
||||||
|
|
||||||
embed.WithColor(new Color(255, 255, 0));
|
embed.WithColor(new Color(255, 255, 0));
|
||||||
embed.Title = $"Information {Program.AppSettingsHandler.GetValue<string>("Bot:Name")} v{Program.AppSettingsHandler.GetValue<string>("Bot:Version")}";
|
embed.Title = $"Information {config.GetValue<string>("Bot:Name")} v{config.GetValue<string>("Bot:Version")}";
|
||||||
sb.AppendLine($"Prefix: {ConfigurationRepository.GetValue<string>("Discord:Prefix", Context.Guild.Id)}");
|
sb.AppendLine($"Prefix: {config.GetValue("Discord:Prefix", default(string), Context.Guild.Id)}");
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Add the string to the Embed
|
* Add the string to the Embed
|
||||||
|
|||||||
@ -15,8 +15,9 @@ namespace ChaosBot.Discord.Services
|
|||||||
public static void Initialize(IServiceProvider services)
|
public static void Initialize(IServiceProvider services)
|
||||||
{
|
{
|
||||||
_client = services.GetRequiredService<DiscordSocketClient>();
|
_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);
|
long? lodestoneChannelSloganDescriptionId = serverConfig.GetValue<long?>("Lodestone:SloganDescription:Channel", null);
|
||||||
int refreshMinutes = serverConfig.GetValue("Lodestone:SloganDescription:RefreshMinutes", 60);
|
int refreshMinutes = serverConfig.GetValue("Lodestone:SloganDescription:RefreshMinutes", 60);
|
||||||
|
|||||||
@ -19,17 +19,32 @@ namespace ChaosBot.Models
|
|||||||
{
|
{
|
||||||
if (!optionsBuilder.IsConfigured)
|
if (!optionsBuilder.IsConfigured)
|
||||||
{
|
{
|
||||||
|
string server, user, pass, name;
|
||||||
|
int port;
|
||||||
|
|
||||||
if (Program.AppSettingsHandler == null)
|
if (Program.AppSettingsHandler == null)
|
||||||
{
|
{
|
||||||
Program.AppSettingsHandler = new ConfigurationBuilder()
|
IConfiguration config = Program.AppSettingsHandler = new ConfigurationBuilder()
|
||||||
.SetBasePath(System.IO.Directory.GetCurrentDirectory())
|
.SetBasePath(System.IO.Directory.GetCurrentDirectory())
|
||||||
.AddJsonFile("./appsettings.json", optional: false, reloadOnChange: true).Build();
|
.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");
|
else
|
||||||
int port = Program.AppSettingsHandler.GetValue<int>("Database:Port");
|
{
|
||||||
string user = Program.AppSettingsHandler.GetValue<string>("Database:User");
|
ChaosBot.Configuration config = new ChaosBot.Configuration();
|
||||||
string pass = Program.AppSettingsHandler.GetValue<string>("Database:Pass");
|
|
||||||
string name = Program.AppSettingsHandler.GetValue<string>("Database:Name");
|
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(
|
optionsBuilder.UseMySql(
|
||||||
$"server={server};port={port};user={user};password={pass};database={name}",
|
$"server={server};port={port};user={user};password={pass};database={name}",
|
||||||
x => x.ServerVersion("5.5.64-mariadb"));
|
x => x.ServerVersion("5.5.64-mariadb"));
|
||||||
|
|||||||
@ -42,7 +42,8 @@ namespace ChaosBot
|
|||||||
/*
|
/*
|
||||||
* Initialize the Discord Client and Login
|
* 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
|
try
|
||||||
{
|
{
|
||||||
|
|||||||
@ -17,7 +17,7 @@ namespace ChaosBot.Repositories
|
|||||||
{
|
{
|
||||||
using (ChaosbotContext dbContext = new ChaosbotContext())
|
using (ChaosbotContext dbContext = new ChaosbotContext())
|
||||||
{
|
{
|
||||||
Configuration config = dbContext.Configuration
|
Models.Configuration config = dbContext.Configuration
|
||||||
.SingleOrDefault(c => c.DiscordGuildId == guildId && c.Key == key);
|
.SingleOrDefault(c => c.DiscordGuildId == guildId && c.Key == key);
|
||||||
if (config == null || string.IsNullOrEmpty(config.SerializedValue))
|
if (config == null || string.IsNullOrEmpty(config.SerializedValue))
|
||||||
return GetValueFromAppSettings(key, guildId, defaultValue);
|
return GetValueFromAppSettings(key, guildId, defaultValue);
|
||||||
@ -29,7 +29,7 @@ namespace ChaosBot.Repositories
|
|||||||
{
|
{
|
||||||
using (ChaosbotContext dbContext = new ChaosbotContext())
|
using (ChaosbotContext dbContext = new ChaosbotContext())
|
||||||
{
|
{
|
||||||
Configuration config = dbContext.Configuration
|
Models.Configuration config = dbContext.Configuration
|
||||||
.SingleOrDefault(c => c.DiscordGuildId == guildId && c.Key == key);
|
.SingleOrDefault(c => c.DiscordGuildId == guildId && c.Key == key);
|
||||||
if (config == null) return;
|
if (config == null) return;
|
||||||
dbContext.Remove(config);
|
dbContext.Remove(config);
|
||||||
|
|||||||
@ -36,9 +36,11 @@ namespace ChaosBot.WebServer.App
|
|||||||
[HttpGet]
|
[HttpGet]
|
||||||
public async Task<IActionResult> Index(string code = null)
|
public async Task<IActionResult> Index(string code = null)
|
||||||
{
|
{
|
||||||
string redirectUri = $"{Program.AppSettingsHandler.GetValue<string>("Discord:BaseUri")}/api/discord";
|
Configuration config = new Configuration();
|
||||||
string clientId = Program.AppSettingsHandler.GetValue<string>("Discord:ClientId");
|
|
||||||
string clientSecret = Program.AppSettingsHandler.GetValue<string>("Discord:ClientSecret");
|
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)
|
if (code == null)
|
||||||
return Redirect($"https://discord.com/api/oauth2/authorize?client_id={clientId}&redirect_uri={redirectUri}&response_type=code&scope=identify%20guilds");
|
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()
|
public string Generate()
|
||||||
{
|
{
|
||||||
string clientId = Program.AppSettingsHandler.GetValue<string>("Discord:ClientId");
|
string clientId = new Configuration().GetValue<string>("Discord:ClientId");
|
||||||
const ulong permissions =
|
const ulong permissions =
|
||||||
0x00000020 + // MANAGE_CHANNELS
|
0x00000020 + // MANAGE_CHANNELS
|
||||||
0x04000000 + // CHANGE_NICKNAME
|
0x04000000 + // CHANGE_NICKNAME
|
||||||
|
|||||||
@ -42,7 +42,7 @@ namespace ChaosBot.WebServer
|
|||||||
{
|
{
|
||||||
LoggingFacade.Info("Initializing Kestrel Startup and Configuration");
|
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.UseDeveloperExceptionPage();
|
||||||
|
|
||||||
app.UseForwardedHeaders();
|
app.UseForwardedHeaders();
|
||||||
|
|||||||
@ -22,12 +22,13 @@ namespace ChaosBot.WebServer
|
|||||||
{
|
{
|
||||||
string contentRoot = Directory.GetCurrentDirectory();
|
string contentRoot = Directory.GetCurrentDirectory();
|
||||||
string webRoot = Path.Combine(contentRoot, "wwwroot/dist");
|
string webRoot = Path.Combine(contentRoot, "wwwroot/dist");
|
||||||
|
Configuration config = new Configuration();
|
||||||
|
|
||||||
webBuilder.UseContentRoot(contentRoot);
|
webBuilder.UseContentRoot(contentRoot);
|
||||||
webBuilder.UseWebRoot(webRoot);
|
webBuilder.UseWebRoot(webRoot);
|
||||||
webBuilder.ConfigureKestrel(serverOptions =>
|
webBuilder.ConfigureKestrel(serverOptions =>
|
||||||
{
|
{
|
||||||
serverOptions.Listen(IPAddress.Any, Program.AppSettingsHandler.GetValue<int>("WebServer:Port"),
|
serverOptions.Listen(IPAddress.Any, config.GetValue("WebServer:Port", 80),
|
||||||
listenOptions =>
|
listenOptions =>
|
||||||
{
|
{
|
||||||
listenOptions.UseConnectionLogging();
|
listenOptions.UseConnectionLogging();
|
||||||
@ -37,7 +38,7 @@ namespace ChaosBot.WebServer
|
|||||||
{
|
{
|
||||||
logging.ClearProviders();
|
logging.ClearProviders();
|
||||||
logging.SetMinimumLevel(LogLevel.Trace);
|
logging.SetMinimumLevel(LogLevel.Trace);
|
||||||
logging.AddNLog(new NLogLoggingConfiguration(Program.AppSettingsHandler.GetSection("NLog")));
|
logging.AddNLog(new NLogLoggingConfiguration(config.GetSection("NLog")));
|
||||||
})
|
})
|
||||||
.UseStartup<Startup>();
|
.UseStartup<Startup>();
|
||||||
});
|
});
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user