Added database configuration

This commit is contained in:
Noikoio 2017-11-01 13:56:06 -07:00
parent 5c972997c0
commit 2568b11c8e
2 changed files with 73 additions and 0 deletions

View file

@ -0,0 +1,68 @@
using Newtonsoft.Json.Linq;
using Npgsql;
using System.Threading.Tasks;
namespace Noikoio.RegexBot.ConfigItem
{
class DatabaseConfig
{
private readonly bool _enabled;
private readonly string _host;
private readonly string _user;
private readonly string _pass;
private readonly string _dbname;
private readonly string _parsemsg;
/// <summary>
/// Gets whether database features are enabled.
/// </summary>
public bool Enabled => _enabled;
/// <summary>
/// Constructor error message (only if not enabled)
/// </summary>
public string ParseMsg => _parsemsg;
public DatabaseConfig(JToken ctok)
{
if (ctok == null || ctok.Type != JTokenType.Object)
{
_enabled = false;
_parsemsg = "Database configuration not defined.";
return;
}
var conf = (JObject)ctok;
_host = conf["hostname"]?.Value<string>() ?? "localhost"; // default to localhost
_user = conf["username"]?.Value<string>();
_pass = conf["password"]?.Value<string>();
_dbname = conf["database"]?.Value<string>();
if (string.IsNullOrWhiteSpace(_user) || string.IsNullOrWhiteSpace(_pass) || string.IsNullOrWhiteSpace(_dbname))
{
_parsemsg = "One or more required values are invalid or not defined.";
_enabled = false;
}
_parsemsg = null;
_enabled = true;
}
public async Task<NpgsqlConnection> OpenConnectionAsync(ulong? guildId)
{
if (!Enabled) return null;
var cs = new NpgsqlConnectionStringBuilder()
{
Host = _host,
Username = _user,
Password = _pass,
Database = _dbname
};
if (guildId.HasValue) cs.SearchPath = "g_" + guildId.Value.ToString();
var db = new NpgsqlConnection(cs.ToString());
await db.OpenAsync();
return db;
}
}
}

View file

@ -20,6 +20,7 @@ namespace Noikoio.RegexBot
private readonly RegexBot _bot;
private readonly string _configPath;
private DatabaseConfig _dbConfig;
private ServerConfig[] _servers;
// The following values do not change on reload:
@ -28,6 +29,8 @@ namespace Noikoio.RegexBot
public string BotUserToken => _botToken;
public string CurrentGame => _currentGame;
public DatabaseConfig Database => _dbConfig;
public ServerConfig[] Servers => _servers;
public Configuration(RegexBot bot)
@ -84,6 +87,8 @@ namespace Noikoio.RegexBot
}
_currentGame = conf["playing"]?.Value<string>();
_dbConfig = new DatabaseConfig(conf["database"]);
return true;
}