diff --git a/ChaosBot/Attribute/AssemblyController.cs b/ChaosBot/Attribute/AssemblyController.cs deleted file mode 100644 index 3565c69..0000000 --- a/ChaosBot/Attribute/AssemblyController.cs +++ /dev/null @@ -1,124 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using System.Text; -using ChaosBot.Database; -using NLog; - -namespace ChaosBot.Attribute -{ - public static class AssemblyController - { - private static ILogger _logger = Program.Logger; - public static void RegisterAll() - { - Assembly dbEntityAssembly = Assembly.GetAssembly(typeof(DBEntity)); - if (dbEntityAssembly != null) - { - foreach (Type type in dbEntityAssembly.GetTypes()) - { - RegisterDBEntityType(type); - } - } - } - - public static void RegisterDBEntityType(Type type) - { - try - { - if (type.GetCustomAttributes(typeof(DBEntity), true).Length > 0) - { - // Get a reference to the attribute - DBEntity dbEntity = type.GetCustomAttributes(typeof(DBEntity)).Cast().First(); - - // Generate columns - // name, type, constraintName, constraints, - List> columnList = new List>(); - - // Get the table as an easy variable - string table = dbEntity.Table; - - // Loop through all fields - foreach (PropertyInfo prop in type.GetProperties()) - { - string columnName = prop.Name; - string columnType = null; - if (prop.PropertyType.IsGenericType && - prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>)) - { - Type[] typeArguments = prop.PropertyType.GetGenericArguments(); - if (typeArguments.Length == 1) - columnType = DBEntity.DataTypes.GetValueOrDefault(typeArguments[0]).ToString(); - } - else - { - columnType = DBEntity.DataTypes.GetValueOrDefault(prop.PropertyType).ToString(); - } - - StringBuilder constraintNameBuilder = new StringBuilder($"{table}_{columnName}"); - List constraintsList = new List(); - - // Go through every attribute - foreach (object fieldAttribute in prop.GetCustomAttributes(true)) - { - if (fieldAttribute is DBFieldAttribute dBFieldAttribute) - { - string constraintSuffix = - DBEntity.ConstrainNames.GetValueOrDefault(dBFieldAttribute.GetType(), null); - if (constraintSuffix != null) - { - constraintNameBuilder.Append($"_{constraintSuffix}"); - constraintsList.Add($"{dBFieldAttribute.GetSQLiteQuery()}"); - } - } - } - - string constraintName = constraintNameBuilder.ToString(); - if (constraintsList.Count > 0) - { - constraintsList.Insert(0, "CONSTRAINT"); - constraintsList.Insert(1, constraintName); - } - - string constraints = String.Join(" ", constraintsList); - columnList.Add( - new Tuple(columnName, columnType, constraintName, constraints)); - } - - // Check table exists - bool tableExists = - Controller.RawQuery($"SELECT name FROM sqlite_master WHERE type='table' AND name='{table}'") - .Rows.Count > 0; - - if (!tableExists) - { - string columnDefs = String.Join(", ", columnList.Select(c => $"{c.Item1} {c.Item2} {c.Item4}")); - string query = $"CREATE TABLE {table} ({columnDefs})"; - Controller.RawQuery(query, readOutput: false); - } - else - { - foreach (Tuple column in columnList) - { - try - { - string query = - $"ALTER TABLE {table} ADD COLUMN {column.Item1} {column.Item2} {column.Item4}"; - Controller.RawQuery(query, readOutput: false, throwError: true); - } - catch - { - // ignored - } - } - } - } - } - catch (Exception ex) - { - _logger.Error($"AssemblyController.Register: Exception [{ex}] thrown, <[{ex.Message}]>."); - } - } - } -} \ No newline at end of file diff --git a/ChaosBot/Attribute/DBAutoIncrement.cs b/ChaosBot/Attribute/DBAutoIncrement.cs deleted file mode 100644 index 0ede23d..0000000 --- a/ChaosBot/Attribute/DBAutoIncrement.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System; - -namespace ChaosBot.Attribute -{ - [AttributeUsage(AttributeTargets.Property)] - public class DBAutoIncrement : DBFieldAttribute - { - public override string GetSQLiteQuery() - { - return "AUTOINCREMENT"; - } - } -} \ No newline at end of file diff --git a/ChaosBot/Attribute/DBEntity.cs b/ChaosBot/Attribute/DBEntity.cs deleted file mode 100644 index da812b2..0000000 --- a/ChaosBot/Attribute/DBEntity.cs +++ /dev/null @@ -1,49 +0,0 @@ -using System; -using System.Collections.Generic; -using Microsoft.Data.Sqlite; - -namespace ChaosBot.Attribute -{ - [AttributeUsage(AttributeTargets.Class)] - public class DBEntity : System.Attribute - { - public readonly string Table; - - // Yeah... this table does not exist elsewhere except human-readable documentation - public static readonly Dictionary DataTypes = new Dictionary - { - {typeof(bool), SqliteType.Integer}, - {typeof(byte), SqliteType.Integer}, - {typeof(byte[]), SqliteType.Blob}, - {typeof(char), SqliteType.Text}, - {typeof(DateTime), SqliteType.Text}, - {typeof(DateTimeOffset), SqliteType.Text}, - {typeof(Decimal), SqliteType.Text}, - {typeof(Double), SqliteType.Real}, - {typeof(Guid), SqliteType.Text}, - {typeof(Int16), SqliteType.Integer}, - {typeof(Int32), SqliteType.Integer}, - {typeof(Int64), SqliteType.Integer}, - {typeof(SByte), SqliteType.Integer}, - {typeof(Single), SqliteType.Real}, - {typeof(String), SqliteType.Text}, - {typeof(TimeSpan), SqliteType.Text}, - {typeof(UInt16), SqliteType.Integer}, - {typeof(UInt32), SqliteType.Integer}, - {typeof(UInt64), SqliteType.Integer} - }; - - public static readonly Dictionary ConstrainNames = new Dictionary - { - {typeof(DBNotNull), "nn"}, - {typeof(DBUnique), "uq"}, - {typeof(DBPrimaryKey), "pk"}, - {typeof(DBAutoIncrement), "ai"}, - }; - - public DBEntity(string table) - { - this.Table = table; - } - } -} \ No newline at end of file diff --git a/ChaosBot/Attribute/DBFieldAttribute.cs b/ChaosBot/Attribute/DBFieldAttribute.cs deleted file mode 100644 index b0a0c1f..0000000 --- a/ChaosBot/Attribute/DBFieldAttribute.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace ChaosBot.Attribute -{ - public abstract class DBFieldAttribute : System.Attribute - { - public abstract string GetSQLiteQuery(); - } -} \ No newline at end of file diff --git a/ChaosBot/Attribute/DBNotNull.cs b/ChaosBot/Attribute/DBNotNull.cs deleted file mode 100644 index 201bd7b..0000000 --- a/ChaosBot/Attribute/DBNotNull.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System; - -namespace ChaosBot.Attribute -{ - [AttributeUsage(AttributeTargets.Property)] - public class DBNotNull : DBFieldAttribute - { - public override string GetSQLiteQuery() - { - return "NOT NULL"; - } - } -} \ No newline at end of file diff --git a/ChaosBot/Attribute/DBPrimaryKey.cs b/ChaosBot/Attribute/DBPrimaryKey.cs deleted file mode 100644 index 3a3bd31..0000000 --- a/ChaosBot/Attribute/DBPrimaryKey.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System; - -namespace ChaosBot.Attribute -{ - [AttributeUsage(AttributeTargets.Property)] - public class DBPrimaryKey : DBFieldAttribute - { - public override string GetSQLiteQuery() - { - return "PRIMARY KEY"; - } - } -} \ No newline at end of file diff --git a/ChaosBot/Attribute/DBUnique.cs b/ChaosBot/Attribute/DBUnique.cs deleted file mode 100644 index 30529c0..0000000 --- a/ChaosBot/Attribute/DBUnique.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System; - -namespace ChaosBot.Attribute -{ - [AttributeUsage(AttributeTargets.Property)] - public class DBUnique : DBFieldAttribute - { - public override string GetSQLiteQuery() - { - return "UNIQUE"; - } - } -} \ No newline at end of file diff --git a/ChaosBot/ChaosBot.csproj b/ChaosBot/ChaosBot.csproj index 23db4ed..90a46e7 100644 --- a/ChaosBot/ChaosBot.csproj +++ b/ChaosBot/ChaosBot.csproj @@ -27,4 +27,8 @@ + + + + diff --git a/ChaosBot/Database/Controller.cs b/ChaosBot/Database/Controller.cs deleted file mode 100644 index 1a8c9ed..0000000 --- a/ChaosBot/Database/Controller.cs +++ /dev/null @@ -1,88 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Data; -using System.Text; -using ChaosBot.Database.Repository; -using Microsoft.Data.Sqlite; -using Microsoft.Extensions.Configuration; -using Microsoft.VisualBasic; -using NLog; - -namespace ChaosBot.Database -{ - public static class Controller - { - static SqliteConnection _conn = new SqliteConnection($"Data Source={System.IO.Directory.GetCurrentDirectory()}/{ConfigurationRepository.GetValue("Bot:Database")}"); - private static ILogger _logger = Program.Logger; - - /// - /// Run a raw query on the database - /// - /// - /// string query = "TRUNCATE SomeTable"; - /// Controller.RawQuery(query); - /// - /// Raw query to execute - /// Whether to read the output and return it as a DataFrame - /// Whether to throw any exceptions or to log and shrug. - /// - public static DataTable RawQuery(string query, Dictionary parameters = null, bool readOutput = true, bool throwError = false) - { - DataTable dt = new DataTable(); - - try - { - using (_conn) - { - // Open the SQLite connection - _conn.Open(); - - // Start creating the command and assign the query given - SqliteCommand cmd = _conn.CreateCommand(); - cmd.CommandText = query; - - // Add parameters if they exist - if (parameters != null) - { - foreach (var parameter in parameters) - { - cmd.Parameters.AddWithValue(parameter.Key, parameter.Value); - } - } - - // Prepare the statement - _logger.Trace($"Database.Controller.RawQuery: Running query {cmd.CommandText}"); - cmd.Prepare(); - - if (readOutput) - { - // output needs to be read, make a reader and fill the datatable with the data - SqliteDataReader executeReader = cmd.ExecuteReader(); - dt.Load(executeReader); - } - else - { - // output does not need to be read, just run the query without reading - cmd.ExecuteNonQuery(); - } - - // Clean up after ourselves - _conn.Close(); - } - } - catch (Exception ex) - { - if (throwError) - { - // If we throw any exception, just throw it so other code can handle it - throw; - } - - // We handle the exception, log it and be done - _logger.Fatal($"Database.Controller.RawQuery: Exception [{ex}] thrown, <[{ex.Message}]>."); - } - - return dt; - } - } -} \ No newline at end of file diff --git a/ChaosBot/Database/Entity/BaseEntity.cs b/ChaosBot/Database/Entity/BaseEntity.cs deleted file mode 100644 index 8451e7b..0000000 --- a/ChaosBot/Database/Entity/BaseEntity.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System; -using System.Data; -using System.Linq; -using ChaosBot.Attribute; -using ChaosBot.Database; - -namespace ChaosBot.Database.Entity -{ - public abstract class BaseEntity - { - protected BaseEntity() {} - - public abstract void SetFromRow(DataRow row); - - - protected static QueryBuilder Query() where T : BaseEntity, new() - { - var dbEntityAttribute = typeof(T).GetCustomAttributes( - typeof(DBEntity), - true - ).FirstOrDefault() as DBEntity; - if (dbEntityAttribute != null) - { - return new QueryBuilder(dbEntityAttribute.Table); - } - - throw new SystemException($"Class {typeof(T)} does not have an attribute of {typeof(DBEntity)} set"); - } - } -} \ No newline at end of file diff --git a/ChaosBot/Database/Entity/CommandPermission.cs b/ChaosBot/Database/Entity/CommandPermission.cs deleted file mode 100644 index a85eb65..0000000 --- a/ChaosBot/Database/Entity/CommandPermission.cs +++ /dev/null @@ -1,53 +0,0 @@ -using System; -using System.Data; -using ChaosBot.Attribute; - -namespace ChaosBot.Database.Entity -{ - [DBEntity("CommandPermissions")] - public class CommandPermission : BaseEntity - { - [DBPrimaryKey] - [DBAutoIncrement] - [DBNotNull] - [DBUnique] - public Nullable id { get; private set; } - public string type { get; private set; } - public string value { get; private set; } - public string cmd { get; private set; } - public long guildId { get; private set; } - - public CommandPermission() {} - - public CommandPermission(int id, string type, string value, string cmd, long guildId) - { - this.id = id; - this.type = type; - this.value = value; - this.cmd = cmd; - this.guildId = guildId; - } - - public CommandPermission(string type, string value, string cmd, long guildId) - { - this.type = type; - this.value = value; - this.cmd = cmd; - this.guildId = guildId; - } - - public static QueryBuilder Query() - { - return BaseEntity.Query(); - } - - public override void SetFromRow(DataRow row) - { - id = (long)row["id"]; - type = (string)row["type"]; - value = (string)row["value"]; - cmd = (string)row["cmd"]; - guildId = (long) row["guildid"]; - } - } -} \ No newline at end of file diff --git a/ChaosBot/Database/Entity/LodestoneCharacters.cs b/ChaosBot/Database/Entity/LodestoneCharacters.cs deleted file mode 100644 index 993bf67..0000000 --- a/ChaosBot/Database/Entity/LodestoneCharacters.cs +++ /dev/null @@ -1,29 +0,0 @@ -using ChaosBot.Attribute; -using ChaosBot.Lodestone; - -namespace ChaosBot.Database.Entity -{ - [DBEntity("LodestoneCharacter")] - public class LodestoneCharacter - { - [DBUnique] - [DBPrimaryKey] - public int id { get; } - public string name { get; } - public string avatar { get; } - - public LodestoneCharacter(int id, string name, string avatar) - { - this.id = id; - this.name = name; - this.avatar = avatar; - } - - public LodestoneCharacter(Character character) - { - this.id = (int)character.ID; - this.name = character.Name; - this.avatar = character.Avatar; - } - } -} \ No newline at end of file diff --git a/ChaosBot/Database/Entity/LodestoneFreeCompany.cs b/ChaosBot/Database/Entity/LodestoneFreeCompany.cs deleted file mode 100644 index 88d193e..0000000 --- a/ChaosBot/Database/Entity/LodestoneFreeCompany.cs +++ /dev/null @@ -1,18 +0,0 @@ -using ChaosBot.Attribute; - -namespace ChaosBot.Database.Entity -{ - [DBEntity("LodestoneFreeCompany")] - public class LodestoneFreeCompany - { - [DBUnique] - public string id { get; } - public string name { get; } - - public LodestoneFreeCompany(string id, string name) - { - this.id = id; - this.name = name; - } - } -} \ No newline at end of file diff --git a/ChaosBot/Database/Entity/Points.cs b/ChaosBot/Database/Entity/Points.cs deleted file mode 100644 index 81869ba..0000000 --- a/ChaosBot/Database/Entity/Points.cs +++ /dev/null @@ -1,49 +0,0 @@ -using System; -using System.Data; -using ChaosBot.Attribute; - -namespace ChaosBot.Database.Entity -{ - [DBEntity("PointsTable")] - public class Points : BaseEntity - { - [DBPrimaryKey] - [DBAutoIncrement] - [DBNotNull] - [DBUnique] - public Nullable id { get; private set; } - public long points { get; private set; } - public long userId { get; private set; } - public long guildId { get; private set; } - - public Points() {} - - public Points(long id, long userId, long guildId, int points) - { - this.id = id; - this.userId = userId; - this.guildId = guildId; - this.points = points; - } - - public Points(long userId, long guildId, long points) - { - this.points = points; - this.userId = userId; - this.guildId = guildId; - } - - public static QueryBuilder Query() - { - return BaseEntity.Query(); - } - - public override void SetFromRow(DataRow row) - { - id = (long)row["id"]; - userId = (long)row["userId"]; - guildId = (long)row["guildId"]; - points = (long)row["points"]; - } - } -} \ No newline at end of file diff --git a/ChaosBot/Database/Entity/Raffle.cs b/ChaosBot/Database/Entity/Raffle.cs deleted file mode 100644 index c61e338..0000000 --- a/ChaosBot/Database/Entity/Raffle.cs +++ /dev/null @@ -1,45 +0,0 @@ -using System; -using System.Data; -using ChaosBot.Attribute; - -namespace ChaosBot.Database.Entity -{ - [DBEntity("RaffleTable")] - public class Raffle : BaseEntity - { - [DBPrimaryKey] - [DBAutoIncrement] - [DBNotNull] - [DBUnique] - public Nullable id { get; private set; } - public long userId { get; private set; } - public long guildId { get; private set; } - - public Raffle() {} - - public Raffle(int id, long userId, long guildId) - { - this.id = id; - this.userId = userId; - this.guildId = guildId; - } - - public Raffle(long userId, long guildId) - { - this.userId = userId; - this.guildId = guildId; - } - - public static QueryBuilder Query() - { - return BaseEntity.Query(); - } - - public override void SetFromRow(DataRow row) - { - id = (long)row["id"]; - userId = (long)row["userid"]; - guildId = (long) row["guildid"]; - } - } -} \ No newline at end of file diff --git a/ChaosBot/Database/Entity/ServerConfigurationFlag.cs b/ChaosBot/Database/Entity/ServerConfigurationFlag.cs deleted file mode 100644 index 01f79e0..0000000 --- a/ChaosBot/Database/Entity/ServerConfigurationFlag.cs +++ /dev/null @@ -1,67 +0,0 @@ -using System; -using System.Data; -using System.IO; -using System.Text; -using System.Text.Json; -using System.Xml.Serialization; -using ChaosBot.Attribute; - -namespace ChaosBot.Database.Entity -{ - [DBEntity("ServerConfigurationFlags")] - public class ServerConfigurationFlag : BaseEntity - { - public string key { get; private set; } - - public string serializedValue { get; set; } - - public long guildId { get; private set; } - - public ServerConfigurationFlag() {} - - public ServerConfigurationFlag(string key, T value, ulong guildId) - { - this.serializedValue = Serialize(value); - this.key = key; - this.guildId = Convert.ToInt64(guildId); - } - public ServerConfigurationFlag(string key, T value, long guildId) - { - this.serializedValue = Serialize(value); - this.key = key; - this.guildId = guildId; - } - public ServerConfigurationFlag(string key, long guildId) - { - this.key = key; - this.guildId = guildId; - } - - public static QueryBuilder> Query() - { - return BaseEntity.Query>(); - } - - public override void SetFromRow(DataRow row) - { - key = (string)row["key"]; - serializedValue = (string)row["serializedValue"]; - guildId = (long)row["guildId"]; - } - - public T GetValue() - { - return Deserialize(serializedValue); - } - - public static string Serialize(T value) - { - return JsonSerializer.Serialize(value); - } - - public static T Deserialize(string serializedValue) - { - return JsonSerializer.Deserialize(serializedValue); - } - } -} \ No newline at end of file diff --git a/ChaosBot/Database/FilterValue.cs b/ChaosBot/Database/FilterValue.cs deleted file mode 100644 index 23968af..0000000 --- a/ChaosBot/Database/FilterValue.cs +++ /dev/null @@ -1,16 +0,0 @@ -using NLog.Filters; - -namespace ChaosBot.Database -{ - public struct FilterValue - { - public object Value; - public string Comparison; - - public FilterValue(object value, string comparison = null) - { - this.Value = value; - this.Comparison = comparison; - } - } -} \ No newline at end of file diff --git a/ChaosBot/Database/QueryBuilder.cs b/ChaosBot/Database/QueryBuilder.cs deleted file mode 100644 index b023eed..0000000 --- a/ChaosBot/Database/QueryBuilder.cs +++ /dev/null @@ -1,290 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Data; -using System.Reflection; -using System.Text; -using ChaosBot.Attribute; -using ChaosBot.Database.Entity; - -namespace ChaosBot.Database -{ - public class QueryBuilder where T : BaseEntity, new() - { - private string _table; - private bool _distinct; - private Dictionary _whereConditions; - private Dictionary _setList; - private List _orderKeys; - private List _groupByList; - private int _limit; - private int _offset; - public QueryBuilder(string table) - { - _table = table; - _distinct = false; - _whereConditions = new Dictionary(); - _setList = new Dictionary(); - _orderKeys = new List(); - _groupByList = new List(); - _limit = -1; - _offset = -1; - } - - /* - * Fetch all records from a database - */ - public List All() - { - QueryBuilderRaw query = new QueryBuilderRaw(); - DataTable dt = query - .Select() - .Append("*") - .FromTable(_table) - .Run(); - - List returnList = new List(); - foreach (DataRow row in dt.Rows) - { - T newObject = new T(); - newObject.SetFromRow(row); - returnList.Add(newObject); - } - - return returnList; - } - - /* - * Set a where condition - */ - public QueryBuilder Where(string key, object value, string comparison = null) - { - _whereConditions.Add(key, new FilterValue(value, comparison)); - return this; - } - - /* - * Set distinct - */ - public QueryBuilder Distinct() - { - _distinct = true; - return this; - } - - /* - * Set SET field - */ - public QueryBuilder Set(string key, object value) - { - _setList.Add(key, value); - return this; - } - - /* - * Set an order key - */ - public QueryBuilder OrderBy(string key) - { - _orderKeys.Add(key); - return this; - } - - /* - * Set a groupBy key - */ - public QueryBuilder GroupBy(string key) - { - _groupByList.Add(key); - return this; - } - - /* - * Limit amount of responses - */ - public QueryBuilder Limit(int amount) - { - _limit = amount; - return this; - } - - public QueryBuilder Offset(int amount) - { - _offset = amount; - return this; - } - - public QueryBuilder Limit(int limit, int offset) - { - Limit(limit); - return Offset(offset); - } - - /* - * Basic mathematical operations - */ - public int Count() - { - QueryBuilderRaw query = new QueryBuilderRaw(); - query - .Select() - .Append("COUNT(*) as count") - .FromTable(_table); - - if (_whereConditions.Count > 0) - query.Where(_whereConditions); - - long amount = (long)query.Run().Rows[0]["count"]; - return Convert.ToInt32(amount); - } - - /* - * Basic logical operations - */ - public bool Exists() - { - QueryBuilderRaw query = new QueryBuilderRaw(); - query - .Select() - .Append("COUNT(*)>0 as present") - .FromTable(_table); - - if (_whereConditions.Count > 0) - query.Where(_whereConditions); - - return (bool)query.Run().Rows[0]["present"]; - } - - public bool DoesNotExist() - { - QueryBuilderRaw query = new QueryBuilderRaw(); - query - .Select() - .Append("COUNT(*)=0 as notPresent") - .FromTable(_table); - - if (_whereConditions.Count > 0) - query.Where(_whereConditions); - - return (bool)query.Run().Rows[0]["notPresent"]; - } - - /* - * Actions - */ - public List Get() - { - List returnList = new List(); - - QueryBuilderRaw query = new QueryBuilderRaw(); - query - .Select(); - - if (_distinct) - query.Distinct(); - - query - .Append("*") - .FromTable(_table); - - if (_whereConditions.Keys.Count > 0) - query.Where(_whereConditions); - - if (_groupByList.Count > 0) - query.GroupBy(_groupByList); - - if (_orderKeys.Count > 0) - query.OrderBy(_orderKeys); - - if (_limit >= 0) - { - if (_offset >= 0) - { - query.Limit(_limit, _offset); - } - else - { - query.Limit(_limit); - } - } - - DataTable dt = query.Run(); - foreach (DataRow row in dt.Rows) - { - T newObject = new T(); - newObject.SetFromRow(row); - returnList.Add(newObject); - } - - return returnList; - } - - public T First() - { - Limit(1); - List list = Get(); - - if (list.Count > 0) - return list[0]; - return null; - } - - public void Insert(T obj) - { - Dictionary objectKeysAndValues = GetObjectKeysAndValues(obj); - QueryBuilderRaw query = new QueryBuilderRaw(); - query - .Insert() - .IntoTable(_table) - .Columns(new List(objectKeysAndValues.Keys)) - .Values(objectKeysAndValues); - - query.Run(); - } - - public void Update() - { - QueryBuilderRaw query = new QueryBuilderRaw(); - query - .Update() - .Table(_table) - .Set(_setList); - - if (_whereConditions.Keys.Count > 0) - query.Where(_whereConditions); - - query.Run(); - } - - public void Delete() - { - QueryBuilderRaw query = new QueryBuilderRaw(); - query - .Delete() - .FromTable(_table); - - if (_whereConditions.Keys.Count > 0) - query.Where(_whereConditions); - - query.Run(); - } - - /* - * Helpers - */ - private Dictionary GetObjectKeysAndValues(T obj) - { - var returnValue = new Dictionary(); - - foreach (PropertyInfo prop in typeof(T).GetProperties()) - { - string columnName = prop.Name; - object value = prop.GetValue(obj); - - if (value != null) - returnValue.Add(columnName, value); - } - - return returnValue; - } - } -} \ No newline at end of file diff --git a/ChaosBot/Database/QueryBuilderRaw.cs b/ChaosBot/Database/QueryBuilderRaw.cs deleted file mode 100644 index 2300a87..0000000 --- a/ChaosBot/Database/QueryBuilderRaw.cs +++ /dev/null @@ -1,175 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Data; -using System.Linq; -using System.Text; - -namespace ChaosBot.Database -{ - public class QueryBuilderRaw - { - private StringBuilder _query; - private Dictionary _parameters; - private int keyIndex = 0; - - public QueryBuilderRaw() - { - _query = new StringBuilder(); - _parameters = new Dictionary(); - } - - public QueryBuilderRaw Append(string text) - { - _query.Append(text); - if (!text.EndsWith(" ")) - _query.Append(" "); - return this; - } - - public DataTable Run() - { - return Controller.RawQuery(_query.ToString(), _parameters); - } - - public QueryBuilderRaw Select() - { - return Append("SELECT"); - } - - public QueryBuilderRaw Insert(string alternativeAction = null) - { - Append("INSERT"); - if (alternativeAction != null) - Append(alternativeAction); - return this; - } - - public QueryBuilderRaw Update(string alternativeAction = null) - { - Append("UPDATE"); - if (alternativeAction != null) - Append(alternativeAction); - return this; - } - - public QueryBuilderRaw Delete() - { - return Append("DELETE"); - } - - public QueryBuilderRaw Distinct() - { - return Append("DISTINCT"); - } - - public QueryBuilderRaw Table(string table) - { - return Append(table); - } - - public QueryBuilderRaw FromTable(string table) - { - Append("FROM"); - return Table(table); - } - - public QueryBuilderRaw IntoTable(string table) - { - Append("INTO"); - return Table(table); - } - - public QueryBuilderRaw Columns(List columnList) - { - Append("("); - Append(String.Join(", ", columnList)); - Append(")"); - return this; - } - - public QueryBuilderRaw Values(Dictionary keyValueList) - { - Append("VALUES ("); - List parameterKeys = new List(); - foreach (KeyValuePair pair in keyValueList) - { - string parameterName = AddParameterAndReturnKey(pair.Key, pair.Value); - parameterKeys.Add(parameterName); - } - Append(string.Join(", ", parameterKeys)); - Append(")"); - return this; - } - - public QueryBuilderRaw Set(Dictionary keyValueList) - { - Append("SET"); - List parameterKeys = new List(); - foreach (KeyValuePair pair in keyValueList) - { - string parameterName = AddParameterAndReturnKey(pair.Key, pair.Value); - parameterKeys.Add($"{pair.Key} = {parameterName}"); - } - Append(string.Join(", ", parameterKeys)); - return this; - } - - public QueryBuilderRaw Where(Dictionary whereCondition) - { - Append("WHERE"); - List whereConditionList = new List(); - foreach (string key in whereCondition.Keys) - { - FilterValue value = whereCondition.GetValueOrDefault(key); - string parameterName = AddParameterAndReturnKey(key, value.Value); - whereConditionList.Add($"{key} {value.Comparison ?? "="} {parameterName}"); - } - Append(string.Join(" AND ", whereConditionList)); - return this; - } - - public QueryBuilderRaw GroupBy(List groupByList) - { - Append("GROUP BY"); - return Append(string.Join(", ", groupByList)); - } - - public QueryBuilderRaw OrderBy(List orderKeys) - { - Append("ORDER BY"); - return Append(string.Join(", ", orderKeys)); - } - - public QueryBuilderRaw Limit(int limit) - { - return Append($"LIMIT {limit}"); - } - - public QueryBuilderRaw Limit(int limit, int offset) - { - return Append($"LIMIT {limit} OFFSET {offset}"); - } - - private void AddParameter(string parameterName, object value) - { - _parameters.Add(parameterName, value); - } - - private string AddParameterAndReturnKey(string key, object value) - { - string parameterKey = GetUniqueParameterName(key); - AddParameter(parameterKey, value); - return parameterKey; - } - - private string GetStaticParameterName(string key) - { - return $"@databasevalue{key}"; - } - - private string GetUniqueParameterName(string key) - { - return $"{GetStaticParameterName(key)}_{keyIndex++}"; - } - } -} \ No newline at end of file diff --git a/ChaosBot/Database/Repository/CommandPermissionRepository.cs b/ChaosBot/Database/Repository/CommandPermissionRepository.cs deleted file mode 100644 index 59f68e9..0000000 --- a/ChaosBot/Database/Repository/CommandPermissionRepository.cs +++ /dev/null @@ -1,41 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Data; -using System.Linq; -using ChaosBot.Database.Entity; -using Microsoft.Data.Sqlite; - -namespace ChaosBot.Database.Repository -{ - public static class CommandPermissionRepository - { - private static readonly string Table = "CommandPermissions"; - - /// - /// Fetch all CommandPermissions filtered by guildId - /// - /// - /// List of Commands and Permissions - public static CommandPermission[] All(long guildId) - { - var cmds = CommandPermission.Query().Where("guildId", guildId).All(); - - return cmds.ToArray(); - } - - /// - /// Get all CommandPermissions for a command filtered by guild - /// - /// - /// - /// List of raffles - public static CommandPermission[] getPerm(string cmd, long guildId) - { - List cmds = CommandPermission.Query().Where("cmd", cmd).Where("guildId", guildId).Get(); - - if(cmds.Count != 0) return cmds.ToArray(); - - return null; - } - } -} \ No newline at end of file diff --git a/ChaosBot/Database/Repository/ConfigurationRepository.cs b/ChaosBot/Database/Repository/ConfigurationRepository.cs deleted file mode 100644 index 3560549..0000000 --- a/ChaosBot/Database/Repository/ConfigurationRepository.cs +++ /dev/null @@ -1,98 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Data; -using ChaosBot.Database.Entity; -using Microsoft.Extensions.Configuration; -using NLog; - -namespace ChaosBot.Database.Repository -{ - public static class ConfigurationRepository - { - private static ILogger _logger = Program.Logger; - public static IConfiguration AppSettingsHandler { get; set; } - - private static readonly string ServersTable = "ServerConfigurationFlags"; - - /// - /// Get global configuration option - /// - /// - /// - /// - public static T GetValue(string configurationFlag) - { - return AppSettingsHandler.GetValue(configurationFlag); - } - - /// - /// Get guild specific configuration option - /// - /// - /// - /// - /// - public static T GetValue(string configurationFlag, ulong guildId) - { - if (_logger == null) return AppSettingsHandler.GetValue($"Servers:{guildId}:{configurationFlag}"); - - string valueSerialized = GetValueRaw(configurationFlag, Convert.ToInt64(guildId)); - if (valueSerialized != null) - return ServerConfigurationFlag.Deserialize(valueSerialized); - return AppSettingsHandler.GetValue($"Servers:{guildId}:{configurationFlag}"); - } - - public static string GetValueRaw(string configurationFlag, long guildId) - { - Dictionary filterColumns = new Dictionary(); - filterColumns.Add("key", new FilterValue(configurationFlag)); - filterColumns.Add("guildId", new FilterValue(guildId)); - ServerConfigurationFlag serverConfigurationFlag = ServerConfigurationFlag.Query().Where("key", configurationFlag).Where("guildId", guildId).First(); - if (serverConfigurationFlag != null) - { - return serverConfigurationFlag.serializedValue; - } - - return null; - } - - /// - /// Get guild specific configuration option - /// - /// - /// - /// - /// - public static void SetValue(string configurationFlag, ulong guildId, T value) - { - SetValueRaw(configurationFlag, Convert.ToInt64(guildId), ServerConfigurationFlag.Serialize(value)); - } - - public static void SetValueRaw(string configurationFlag, long guildId, string serializedValue) - { - try - { - int matchCount = ServerConfigurationFlag.Query().Where("key", configurationFlag).Where("guildId", guildId).Count(); - if (matchCount > 0) - { - ServerConfigurationFlag.Query() - .Where("key", configurationFlag) - .Where("guildId", guildId) - .Set("key", configurationFlag) - .Set("guildId", guildId) - .Set("serializedValue", serializedValue) - .Update(); - return; - } - - ServerConfigurationFlag newValue = new ServerConfigurationFlag(configurationFlag, guildId); - newValue.serializedValue = serializedValue; - ServerConfigurationFlag.Query().Insert(newValue); - } - catch (Exception ex) - { - _logger.Fatal($"ConfigurationRepository.SetValueRaw: Exception [{ex}] thrown, <[{ex.Message}]>."); - } - } - } -} \ No newline at end of file diff --git a/ChaosBot/Database/Repository/PointsRepository.cs b/ChaosBot/Database/Repository/PointsRepository.cs deleted file mode 100644 index a664b4b..0000000 --- a/ChaosBot/Database/Repository/PointsRepository.cs +++ /dev/null @@ -1,75 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Data; -using ChaosBot.Database.Entity; - -namespace ChaosBot.Database.Repository -{ - public static class PointsRepository - { - private static readonly string Table = "PointsTable"; - - public static Points[] All() - { - List pointsList = Points.Query().All(); - - return pointsList.ToArray(); - } - - public static Points[] All(long guildId) - { - List pointsList = Points.Query().Where("guildId", guildId).All(); - - return pointsList.ToArray(); - } - - - public static long Total(long userId, long guildId) - { - Points userPoints = Points.Query().Where("userId", userId).Where("guildId", guildId).First(); - - if (userPoints != null) - return userPoints.points; - - Points emptyUserPoints = new Points(userId, guildId, 0); - Points.Query().Insert(emptyUserPoints); - return 0; - } - - - public static int Count(long userId, long guildId) - { - return Points.Query().Where("userId", userId).Where("guildId", guildId).Count(); - } - - - public static long Add(long userId, long points, long guildId) - { - Points userPoints = Points.Query().Where("userId", userId).Where("guildId", guildId).First(); - if (userPoints != null) - { - Points.Query().Where("userId", userId).Where("guildId", guildId).Set("points", userPoints.points + points).Update(); - return userPoints.points + points; - } - - Points newUserPoints = new Points(userId, guildId, points); - - Points.Query().Insert(newUserPoints); - return points; - } - - public static long Remove(long userId, long points, long guildId) - { - Points userPoints = Points.Query().Where("userId", userId).Where("guildId", guildId).First(); - - Points.Query().Where("userId", userId).Where("guildId", guildId).Set("points", userPoints.points - points).Update(); - - return userPoints.points - points; - } - - public static void Delete(int userId) - { - Points.Query().Where("userId", userId).Delete(); - } - } -} diff --git a/ChaosBot/Database/Repository/RaffleRepository.cs b/ChaosBot/Database/Repository/RaffleRepository.cs deleted file mode 100644 index 348b5e1..0000000 --- a/ChaosBot/Database/Repository/RaffleRepository.cs +++ /dev/null @@ -1,141 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Data; -using System.Linq; -using ChaosBot.Database.Entity; -using Microsoft.Data.Sqlite; - -namespace ChaosBot.Database.Repository -{ - public static class RaffleRepository - { - private static readonly string Table = "RaffleTable"; - - /// - /// Fetch all Raffles - /// - /// List of raffles - public static Raffle[] All() - { - var raffles = Raffle.Query().All(); - - return raffles.ToArray(); - } - - /// - /// Fetch all Raffles filtered by guildId - /// - /// - /// List of raffles - public static Raffle[] All(long guildId) - { - var raffles = Raffle.Query().Where("guildId", guildId).All(); - - return raffles.ToArray(); - } - - /// - /// Count amount of Raffles - /// - /// Amount of raffles - public static int Count() - { - return Raffle.Query().Count(); - } - - /// - /// Count amount of Raffles filtered by guildId - /// - /// - /// Amount of raffles - public static int Count(long guildId) - { - return Raffle.Query().Where("guildId", guildId).Count(); - } - - /// - /// Count amount of Raffles filtered by guildId - /// - /// - /// - /// Amount of raffles - public static int Count(long userId, long guildId) - { - return Raffle.Query().Where("userId", userId).Where("guildId", guildId).Count(); - } - - /// - /// Get all Raffles from a user - /// - /// - /// List of raffles - public static Raffle[] SelectUser(long userId) - { - List raffles = Raffle.Query().Where("userId", userId).Get(); - - return raffles.ToArray(); - } - - /// - /// Get all Raffles from a user filtered by guild - /// - /// - /// - /// List of raffles - public static Raffle[] SelectUser(long userId, long guildId) - { - List raffles = Raffle.Query().Where("userId", userId).Where("guildId", guildId).Get(); - - return raffles.ToArray(); - } - - /// - /// Insert a Raffle into the database - /// - /// - public static void Insert(Raffle raffle) - { - Raffle.Query().Insert(raffle); - } - - /// - /// Insert a List of Raffles into the database - /// - /// - public static void MassInsert(List raffles) - { - foreach (var raf in raffles) - { - Raffle.Query().Insert(raf); - } - } - - /// - /// Pick a random raffle from the database filtered to a guild - /// - /// - /// Random raffle - public static Raffle PickRandom(long guildId) - { - return Raffle.Query().Where("guildId", guildId).OrderBy("RANDOM()").First(); - } - - /// - /// Clear all Raffles for a given guild - /// - /// - public static void ClearRaffle(long guildId) - { - Raffle.Query().Where("guildId", guildId).Delete(); - } - - /// - /// Delete a Raffle by id - /// - /// - public static void Delete(long id) - { - Raffle.Query().Where("id", id).Delete(); - } - } -} \ No newline at end of file diff --git a/ChaosBot/Discord/DiscordConnect.cs b/ChaosBot/Discord/DiscordConnect.cs index 91ef6da..03f5bb3 100644 --- a/ChaosBot/Discord/DiscordConnect.cs +++ b/ChaosBot/Discord/DiscordConnect.cs @@ -4,7 +4,6 @@ using Discord; using Discord.Commands; using Discord.WebSocket; using System.Threading.Tasks; -using ChaosBot.Database.Repository; using ChaosBot.Discord.Services; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; @@ -34,7 +33,7 @@ namespace ChaosBot.Discord services.GetRequiredService().Log += Log; // this is where we get the Token value from the configuration file, and start the bot - await client.LoginAsync(TokenType.Bot, ConfigurationRepository.GetValue("Discord:Token")); + await client.LoginAsync(TokenType.Bot, Program.AppSettingsHandler.GetValue("Discord:Token")); 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/ConfigCommands.cs b/ChaosBot/Discord/Modules/ConfigCommands.cs index 4c1c4e1..fe7c769 100644 --- a/ChaosBot/Discord/Modules/ConfigCommands.cs +++ b/ChaosBot/Discord/Modules/ConfigCommands.cs @@ -1,18 +1,20 @@ using System; +using System.Linq; using Discord; using Discord.Commands; using System.Threading.Tasks; using NLog; using System.Text; -using ChaosBot.Database.Repository; +using System.Text.Json; using ChaosBot.Discord.PreConditions; +using ChaosBot.Models; +using ChaosBot.Repositories; namespace ChaosBot.Discord.Modules { public class ConfigCommands : ModuleBase { - private static readonly ILogger _logger = Program.Logger; - private static readonly string _prefix = ConfigurationRepository.GetValue("Discord:Prefix"); + private static readonly ILogger _logger = Program.Logger; [Command("config")] [CheckCommandPerm] @@ -25,10 +27,19 @@ namespace ChaosBot.Discord.Modules { if (configFlag == null || value == null) { - await ReplyAsync($"Syntax Wrong. Please see {_prefix}config help"); + string prefix = ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!"); + await ReplyAsync($"Syntax Wrong. Please see {prefix}config help"); return; } - ConfigurationRepository.SetValue(configFlag, Context.Guild.Id, value); + using (ChaosbotContext dbContext = new ChaosbotContext()) + { + // ConfigurationRepository.SetValue(configFlag, Context.Guild.Id, value); + Configuration config = dbContext.Configuration + .FirstOrDefault(c => c.DiscordGuildId == Context.Guild.Id && c.Key == configFlag); + // TODO: Is this warning valid? + config.SerializedValue = JsonSerializer.Serialize(value); + dbContext.SaveChanges(); + } embed.WithColor(new Color(255, 255, 0)); embed.Title = $"Configuration Management"; sb.AppendLine($"{Context.User.Mention} has changed the Configuration."); @@ -56,13 +67,15 @@ namespace ChaosBot.Discord.Modules [RequireUserPermission(GuildPermission.ManageGuild)] public async Task helpConfig(string configFlag = null, string value = null) { + string prefix = ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!"); + var sb = new StringBuilder(); var embed = new EmbedBuilder(); embed.WithColor(new Color(255, 255, 0)); embed.Title = $"Configuration Management Help"; sb.AppendLine(); - sb.AppendLine($"{_prefix}config "); + sb.AppendLine($"{prefix}config "); /* * Add the string to the Embed diff --git a/ChaosBot/Discord/Modules/InfoCommands.cs b/ChaosBot/Discord/Modules/InfoCommands.cs index 71989a2..0f0eecb 100644 --- a/ChaosBot/Discord/Modules/InfoCommands.cs +++ b/ChaosBot/Discord/Modules/InfoCommands.cs @@ -3,8 +3,6 @@ using Discord; using System.Text; using Discord.Commands; using System.Threading.Tasks; -using ChaosBot.Database; -using ChaosBot.Database.Repository; using Microsoft.Extensions.Configuration; using NLog; @@ -26,11 +24,11 @@ namespace ChaosBot.Discord.Modules embed.WithColor(new Color(255, 255,0)); embed.Title = $"General Information"; - sb.AppendLine($"{Context.User.Mention} has requested information from {ConfigurationRepository.GetValue("Bot:Name")}."); + // TODO: pull bot nickname + sb.AppendLine($"{Context.User.Mention} has requested information from {Program.AppSettingsHandler.GetValue("Bot:Name")}."); sb.AppendLine(); - sb.AppendLine($"Bot Version: {ConfigurationRepository.GetValue("Bot:Version")}"); - sb.AppendLine($"Bot Prefix: {ConfigurationRepository.GetValue("Discord:Prefix")}"); - sb.AppendLine($"{Controller.RawQuery("select * from RaffleTable where Id = (abs(random()) % (select (select max(Id) from RaffleTable)+1)) or rowid = (select min(Id) from RaffleTable) order by Id DESC limit 1;").Rows[0]["userId"]}"); + sb.AppendLine($"Bot Version: {Program.AppSettingsHandler.GetValue("Bot:Version")}"); + sb.AppendLine($"Bot Prefix: {Program.AppSettingsHandler.GetValue("Discord:Prefix")}"); /* * Add the string to the Embed diff --git a/ChaosBot/Discord/Modules/LodestoneCommands.cs b/ChaosBot/Discord/Modules/LodestoneCommands.cs index db83863..be29b85 100644 --- a/ChaosBot/Discord/Modules/LodestoneCommands.cs +++ b/ChaosBot/Discord/Modules/LodestoneCommands.cs @@ -5,11 +5,9 @@ using Discord.Commands; using System.Threading.Tasks; using System.Collections.Generic; using System.Linq; -using ChaosBot.Database; using ChaosBot.Lodestone; using ChaosBot.Services; using Discord.Net; -using Microsoft.Extensions.Configuration; using NLog; diff --git a/ChaosBot/Discord/Modules/PointsCommands.cs b/ChaosBot/Discord/Modules/PointsCommands.cs index 707e250..f6bb74a 100644 --- a/ChaosBot/Discord/Modules/PointsCommands.cs +++ b/ChaosBot/Discord/Modules/PointsCommands.cs @@ -1,15 +1,10 @@ using System; -using System.Collections.Generic; using System.Text; using System.Threading.Tasks; -using ChaosBot.Database.Entity; using Discord; using Discord.Commands; -using Microsoft.Extensions.Configuration; using NLog; -using ChaosBot.Database.Repository; -using ChaosBot.Database; -using System.Data; +using ChaosBot.Repositories; namespace ChaosBot.Discord.Modules { @@ -24,7 +19,7 @@ namespace ChaosBot.Discord.Modules { var sb = new StringBuilder(); var embed = new EmbedBuilder(); - string prefix = ConfigurationRepository.GetValue("Discord:Prefix"); + string prefix = ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!"); embed.WithColor(new Color(255, 255, 0)); embed.Title = $"Points system"; diff --git a/ChaosBot/Discord/Modules/RaffleSystem.cs b/ChaosBot/Discord/Modules/RaffleSystem.cs index 86d1dcc..d135632 100644 --- a/ChaosBot/Discord/Modules/RaffleSystem.cs +++ b/ChaosBot/Discord/Modules/RaffleSystem.cs @@ -1,12 +1,13 @@ using System; using System.Collections.Generic; +using System.Linq; using System.Text; using System.Threading.Tasks; -using ChaosBot.Database.Entity; using Discord; using Discord.Commands; using NLog; -using ChaosBot.Database.Repository; +using ChaosBot.Models; +using ChaosBot.Repositories; namespace ChaosBot.Discord.Modules { @@ -39,7 +40,7 @@ namespace ChaosBot.Discord.Modules { var eb = new EmbedBuilder(); var sb = new StringBuilder(); - string prefix = ConfigurationRepository.GetValue("Discord.Prefix", Context.Guild.Id); + string prefix = ConfigurationRepository.GetValue("Discord.Prefix", Context.Guild.Id, "!"); sb.AppendLine($"{Context.User.Mention} has requested raffle information."); sb.AppendLine(); diff --git a/ChaosBot/Discord/PreConditions/CheckCommandPerm.cs b/ChaosBot/Discord/PreConditions/CheckCommandPerm.cs index 0b29203..f7a3f32 100644 --- a/ChaosBot/Discord/PreConditions/CheckCommandPerm.cs +++ b/ChaosBot/Discord/PreConditions/CheckCommandPerm.cs @@ -1,7 +1,9 @@ using System; +using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -using ChaosBot.Database.Repository; +using ChaosBot.Models; +using ChaosBot.Repositories; using Discord.Commands; using Discord.WebSocket; using NLog; @@ -21,29 +23,36 @@ namespace ChaosBot.Discord.PreConditions 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 - var commandPermissions = CommandPermissionRepository.getPerm(command.Name, Convert.ToInt64(context.Guild.Id)); + 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 != null) { // Loop through all permissions - foreach (var perm in commandPermissions) + foreach (CommandPermission perm in commandPermissions) { - string requiredGroup; + ulong requiredGroup; // Check if it's a role or group permission and fetch the right type - if (perm.type.ToLower() == "role") + 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.value}", context.Guild.Id) ?? perm.value; + requiredGroup = ConfigurationRepository.GetValue($"Role:{perm.TargetId}", context.Guild.Id, perm.TargetId); } else { // Return the permission value - requiredGroup = perm.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.Name == requiredGroup)) + if (gUser.Roles.Any(r => r.Id == requiredGroup)) return Task.FromResult(PreconditionResult.FromSuccess()); } } diff --git a/ChaosBot/Discord/Services/CommandHandler.cs b/ChaosBot/Discord/Services/CommandHandler.cs index 761418c..106b3fd 100644 --- a/ChaosBot/Discord/Services/CommandHandler.cs +++ b/ChaosBot/Discord/Services/CommandHandler.cs @@ -1,7 +1,7 @@ using System; using System.Reflection; using System.Threading.Tasks; -using ChaosBot.Database.Repository; +using ChaosBot.Repositories; using Microsoft.Extensions.DependencyInjection; using Discord; using Discord.Commands; @@ -51,14 +51,13 @@ namespace ChaosBot.Discord.Services if (message.Source != MessageSource.User) return; - var argPos = 0; + SocketCommandContext context = new SocketCommandContext(_client, message); - char prefix = Char.Parse(ConfigurationRepository.GetValue("Discord:Prefix")); - - if (!(message.HasMentionPrefix(_client.CurrentUser, ref argPos) || message.HasCharPrefix(prefix, ref argPos))) + int argPos = 0; + + string prefix = ConfigurationRepository.GetValue("Discord:Prefix", context.Guild.Id, "!"); + if (!(message.HasMentionPrefix(_client.CurrentUser, ref argPos) || message.HasStringPrefix(prefix, ref argPos))) return; - - var context = new SocketCommandContext(_client, message); await _commands.ExecuteAsync(context, argPos, _services); } diff --git a/ChaosBot/Discord/Services/TimerHandler.cs b/ChaosBot/Discord/Services/TimerHandler.cs index f16ee99..4ccb18f 100644 --- a/ChaosBot/Discord/Services/TimerHandler.cs +++ b/ChaosBot/Discord/Services/TimerHandler.cs @@ -1,6 +1,4 @@ using System; -using System.Threading.Tasks; -using ChaosBot.Database.Repository; using ChaosBot.Services; using Discord; using Discord.WebSocket; @@ -19,7 +17,7 @@ namespace ChaosBot.Discord.Services { _client = services.GetRequiredService(); - foreach (IConfigurationSection serverConfig in ConfigurationRepository.AppSettingsHandler.GetSection("Servers").GetChildren()) + foreach (IConfigurationSection serverConfig in Program.AppSettingsHandler.GetSection("Servers").GetChildren()) { long? lodestoneChannelSloganDescriptionId = serverConfig.GetValue("Lodestone:SloganDescription:Channel", null); int refreshMinutes = serverConfig.GetValue("Lodestone:SloganDescription:RefreshMinutes", 60); diff --git a/ChaosBot/Logging.cs b/ChaosBot/Logging.cs index 5bc6f1b..8bd4a1e 100644 --- a/ChaosBot/Logging.cs +++ b/ChaosBot/Logging.cs @@ -1,5 +1,4 @@ using System; -using ChaosBot.Database.Repository; using Microsoft.Extensions.Configuration; using NLog; using NLog.Extensions.Logging; diff --git a/ChaosBot/Migrations/20200804204734_CommandPermissions.cs b/ChaosBot/Migrations/20200804204734_CommandPermissions.cs index 2081ca3..f58ca69 100644 --- a/ChaosBot/Migrations/20200804204734_CommandPermissions.cs +++ b/ChaosBot/Migrations/20200804204734_CommandPermissions.cs @@ -1,4 +1,5 @@ -using Microsoft.EntityFrameworkCore.Metadata; +using ChaosBot.Models; +using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; namespace ChaosBot.Migrations @@ -32,10 +33,4 @@ namespace ChaosBot.Migrations migrationBuilder.DropTable(Table); } } - - public enum PermissionTarget - { - User, - Role - } } diff --git a/ChaosBot/Models/ChaosbotContext.cs b/ChaosBot/Models/ChaosbotContext.cs index ad60227..4f74541 100644 --- a/ChaosBot/Models/ChaosbotContext.cs +++ b/ChaosBot/Models/ChaosbotContext.cs @@ -1,4 +1,3 @@ -using ChaosBot.Database.Repository; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; @@ -17,17 +16,17 @@ namespace ChaosBot.Models { if (!optionsBuilder.IsConfigured) { - if (ConfigurationRepository.AppSettingsHandler == null) + if (Program.AppSettingsHandler == null) { - ConfigurationRepository.AppSettingsHandler = new ConfigurationBuilder() + Program.AppSettingsHandler = new ConfigurationBuilder() .SetBasePath(System.IO.Directory.GetCurrentDirectory()) .AddJsonFile("./appsettings.json", optional: false, reloadOnChange: true).Build(); } - string server = ConfigurationRepository.GetValue("Database:Host"); - int port = ConfigurationRepository.GetValue("Database:Port"); - string user = ConfigurationRepository.GetValue("Database:User"); - string pass = ConfigurationRepository.GetValue("Database:Pass"); - string name = ConfigurationRepository.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"); optionsBuilder.UseMySql( $"server={server};port={port};user={user};password={pass};database={name}", x => x.ServerVersion("5.5.64-mariadb")); diff --git a/ChaosBot/Models/CommandPermission.cs b/ChaosBot/Models/CommandPermission.cs index 3301d34..d42a0f1 100644 --- a/ChaosBot/Models/CommandPermission.cs +++ b/ChaosBot/Models/CommandPermission.cs @@ -18,4 +18,10 @@ namespace ChaosBot.Models public string Command { get; set; } } #endregion + + public enum PermissionTarget + { + User, + Role + } } \ No newline at end of file diff --git a/ChaosBot/Program.cs b/ChaosBot/Program.cs index 9cc7e48..0860718 100644 --- a/ChaosBot/Program.cs +++ b/ChaosBot/Program.cs @@ -3,8 +3,6 @@ using System; using System.Runtime.CompilerServices; using ChaosBot.Discord; using System.Threading.Tasks; -using ChaosBot.Attribute; -using ChaosBot.Database.Repository; using Microsoft.Extensions.Configuration; [assembly: InternalsVisibleTo("ChaosBot.UnitTests")] @@ -13,6 +11,8 @@ namespace ChaosBot internal class Program { public static ILogger Logger; + public static IConfiguration AppSettingsHandler; + private static string _appsettingsPath; private static void Main(string[] args) @@ -38,17 +38,12 @@ namespace ChaosBot /* * Set AppSettingsHandler on ConfigurationRepository */ - ConfigurationRepository.AppSettingsHandler = configurationHandler; - - /* - * Attempt to load our custom assemblies - */ - RegisterAssemblyController(); + AppSettingsHandler = configurationHandler; /* * Initialize the Discord Client and Login */ - Logger.Info($"Starting Up {ConfigurationRepository.GetValue("Bot:Name")} v{ConfigurationRepository.GetValue("Bot:Version")}"); + Logger.Info($"Starting Up {AppSettingsHandler.GetValue("Bot:Name")} v{AppSettingsHandler.GetValue("Bot:Version")}"); var discordBot = LoadDiscord(); @@ -68,11 +63,6 @@ namespace ChaosBot .AddJsonFile(appsettingsPath, optional: false, reloadOnChange: true).Build(); } - public static void RegisterAssemblyController() - { - AssemblyController.RegisterAll(); - } - public static void LoadWebServer() { WebServer.WebServer.Start(new string[]{}); diff --git a/ChaosBot/Repositories/ConfigurationRepository.cs b/ChaosBot/Repositories/ConfigurationRepository.cs new file mode 100644 index 0000000..abab954 --- /dev/null +++ b/ChaosBot/Repositories/ConfigurationRepository.cs @@ -0,0 +1,27 @@ +using System; +using System.Linq; +using ChaosBot.Models; +using System.Text.Json; + +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 (String.IsNullOrEmpty(config.SerializedValue)) + return defaultValue; + return JsonSerializer.Deserialize(config.SerializedValue); + } + } + } +} \ No newline at end of file diff --git a/ChaosBot/WebServer/App/Controller/ConfigurationController.cs b/ChaosBot/WebServer/App/Controller/ConfigurationController.cs deleted file mode 100644 index 26271b2..0000000 --- a/ChaosBot/WebServer/App/Controller/ConfigurationController.cs +++ /dev/null @@ -1,26 +0,0 @@ -using System; -using ChaosBot.Database.Repository; -using Microsoft.AspNetCore.Mvc; -using NLog; - -namespace ChaosBot.WebServer.App.Controller -{ - [ApiController] - [Route("/config/{guildId}/{flag}")] - public class ConfigurationController - { - private readonly ILogger _logger = Program.Logger; - - [HttpGet] - public string GetConfigurationFlag(long guildId, string flag) - { - return ConfigurationRepository.GetValueRaw(flag, guildId); - } - - [HttpPost] - public void SetConfigurationFlag(long guildId, string flag, [FromBody] string serializedValue) - { - ConfigurationRepository.SetValueRaw(flag, guildId, serializedValue); - } - } -} \ No newline at end of file diff --git a/ChaosBot/WebServer/WebServer.cs b/ChaosBot/WebServer/WebServer.cs index 613a64d..c3a3970 100644 --- a/ChaosBot/WebServer/WebServer.cs +++ b/ChaosBot/WebServer/WebServer.cs @@ -1,8 +1,8 @@ using System.Net; -using ChaosBot.Database.Repository; using NLog.Extensions.Logging; using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; @@ -21,7 +21,7 @@ namespace ChaosBot.WebServer { webBuilder.ConfigureKestrel(serverOptions => { - serverOptions.Listen(IPAddress.Any, ConfigurationRepository.GetValue("WebServer:Port"), + serverOptions.Listen(IPAddress.Any, Program.AppSettingsHandler.GetValue("WebServer:Port"), listenOptions => { listenOptions.UseConnectionLogging(); @@ -31,7 +31,7 @@ namespace ChaosBot.WebServer { logging.ClearProviders(); logging.SetMinimumLevel(LogLevel.Trace); - logging.AddNLog(new NLogLoggingConfiguration(ConfigurationRepository.AppSettingsHandler.GetSection("NLog"))); + logging.AddNLog(new NLogLoggingConfiguration(Program.AppSettingsHandler.GetSection("NLog"))); }) .UseStartup(); });