diff --git a/ConfigItem/DatabaseConfig.cs b/ConfigItem/DatabaseConfig.cs new file mode 100644 index 0000000..7f858d6 --- /dev/null +++ b/ConfigItem/DatabaseConfig.cs @@ -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; + + /// + /// Gets whether database features are enabled. + /// + public bool Enabled => _enabled; + /// + /// Constructor error message (only if not enabled) + /// + 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() ?? "localhost"; // default to localhost + _user = conf["username"]?.Value(); + _pass = conf["password"]?.Value(); + _dbname = conf["database"]?.Value(); + + 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 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; + } + } +} diff --git a/Configuration.cs b/Configuration.cs index ab3fa5b..ac799f0 100644 --- a/Configuration.cs +++ b/Configuration.cs @@ -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(); + _dbConfig = new DatabaseConfig(conf["database"]); + return true; }