diff --git a/src/NadekoBot/Modules/Searches/Commands/UnitConversion.cs b/src/NadekoBot/Modules/Searches/Commands/UnitConversion.cs index 2a859061..8f503ff8 100644 --- a/src/NadekoBot/Modules/Searches/Commands/UnitConversion.cs +++ b/src/NadekoBot/Modules/Searches/Commands/UnitConversion.cs @@ -2,6 +2,8 @@ using Discord.Commands; using NadekoBot.Attributes; using NadekoBot.Extensions; +using NadekoBot.Services; +using NadekoBot.Services.Database.Models; using Newtonsoft.Json; using NLog; using System; @@ -28,19 +30,31 @@ namespace NadekoBot.Modules.Searches try { - Units = JsonConvert.DeserializeObject>(File.ReadAllText("units.json")); + using (var uow = DbHandler.UnitOfWork()) + { + //need to do this the first time + if (uow.ConverterUnits.Empty()) + { + var content = JsonConvert.DeserializeObject>(File.ReadAllText("units.json")).Select(u => new ConvertUnit() + { + Modifier = u.Modifier, + UnitType = u.UnitType, + InternalTrigger = string.Join("|", u.Triggers) + }); + + uow.ConverterUnits.AddRange(content.ToArray()); + uow.Complete(); + } + Units = uow.ConverterUnits.GetAll().ToList(); + } } catch (Exception e) { _log.Warn("Could not load units: " + e.Message); - } - } - public List Units { get; set; } - - + public List Units { get; set; } [Command("updatecur")] [RequireContext(ContextType.Guild)] @@ -49,9 +63,9 @@ namespace NadekoBot.Modules.Searches var channel = msg.Channel as IGuildChannel; var currencyRates = await UpdateCurrencyRates(); var unitTypeString = "currency"; - var baseType = new JsonUnit() + var baseType = new ConvertUnit() { - Triggers = new List() { currencyRates.Base }, + Triggers = new[] { currencyRates.Base }, Modifier = decimal.One, UnitType = unitTypeString }; @@ -60,22 +74,31 @@ namespace NadekoBot.Modules.Searches Units.Add(baseType); else Units[baseIndex] = baseType; - foreach (var rate in currencyRates.ConversionRates) + using (var uow = DbHandler.UnitOfWork()) { - var u = new JsonUnit() + foreach (var rate in currencyRates.ConversionRates) { - Triggers = new List() { rate.Key }, - UnitType = unitTypeString, - Modifier = rate.Value - }; - var lower = u.Triggers.First().ToLowerInvariant(); - var toUpdate = Units.FindIndex(x => x.UnitType == "currency" && x.Triggers.First().ToLowerInvariant() == lower); - if (toUpdate == -1) - Units.Add(u); - else - Units[toUpdate] = u; + var u = new ConvertUnit() + { + Triggers = new[] { rate.Key }, + UnitType = unitTypeString, + Modifier = rate.Value + }; + var lower = u.Triggers.First().ToLowerInvariant(); + var toUpdate = Units.FindIndex(x => x.UnitType == "currency" && x.Triggers.First().ToLowerInvariant() == lower); + if (toUpdate == -1) + { + Units.Add(u); + uow.ConverterUnits.Add(u); + } + else + { + Units[toUpdate] = u; + uow.ConverterUnits.Update(u); + } + uow.Complete(); + } } - File.WriteAllText("units.json", JsonConvert.SerializeObject(Units, Formatting.Indented)); await msg.Reply("done"); } [LocalizedCommand, LocalizedDescription, LocalizedSummary] @@ -162,8 +185,9 @@ namespace NadekoBot.Modules.Searches if (originUnit.UnitType == "currency") { res = (value * targetUnit.Modifier) / originUnit.Modifier; - } else - res = (value * originUnit.Modifier) / targetUnit.Modifier; + } + else + res = (value * originUnit.Modifier) / targetUnit.Modifier; } res = Math.Round(res, 2); await msg.Reply(string.Format("{0} {1} is equal to {2} {3}", value, originUnit.Triggers.First(), res, targetUnit.Triggers.First())); @@ -190,89 +214,11 @@ namespace NadekoBot.Modules.Searches public Dictionary ConversionRates { get; set; } } - - public class JsonUnit + public class MeasurementUnit { public List Triggers { get; set; } public string UnitType { get; set; } public decimal Modifier { get; set; } } - - - #region GetXML - /* - public class UnitCollection - { - public List UnitTypes; - - public UnitCollection(string content) - { - using (var xmlReader = XmlReader.Create(File.OpenRead("units.xml"), new XmlReaderSettings() { IgnoreComments = true, IgnoreWhitespace = true })) - { - XmlDocument doc = new XmlDocument(); - doc.Load(xmlReader); - - UnitTypes = new List(); - foreach (XmlNode node in doc.LastChild.ChildNodes) - { //units/ - UnitType type = new UnitType() - { - Name = node.Name - }; - var units = new List(); - foreach (XmlNode unitNode in node.ChildNodes) - { - var curNode = unitNode.FirstChild; - Unit u = new Unit() - { - Key = curNode.InnerText, - Singular = (curNode = curNode.NextSibling).InnerText, - Plural = (curNode = curNode.NextSibling).InnerText, - Symbol = (curNode = curNode.NextSibling).InnerText, - Source = curNode.NextSibling.NextSibling.InnerText - }; - List factors = new List(); - foreach (XmlNode factorNode in curNode.NextSibling.ChildNodes) - { - Factor f = new Factor() - { - Modifier = factorNode.FirstChild.InnerText.Replace(" ", "") - }; - f.From = factorNode.Attributes.GetNamedItem("from").InnerText; - factors.Add(f); - } - u.Factors = factors; - units.Add(u); - } - type.Units = units; - UnitTypes.Add(type); - } - } - } - - public class UnitType - { - public string Name { get; set; } - public List Units { get; set; } - } - - public class Unit - { - public string Key { get; set; } - public string Plural { get; set; } - public string Singular { get; set; } - public string Symbol { get; set; } - public List Factors { get; set; } - public string Source { get; set; } - } - - public class Factor - { - public string From { get; set; } - public string Modifier { get; set; } - } - } - */ - #endregion } } \ No newline at end of file diff --git a/src/NadekoBot/Services/Database/IUnitOfWork.cs b/src/NadekoBot/Services/Database/IUnitOfWork.cs index 905af9af..14719461 100644 --- a/src/NadekoBot/Services/Database/IUnitOfWork.cs +++ b/src/NadekoBot/Services/Database/IUnitOfWork.cs @@ -17,6 +17,7 @@ namespace NadekoBot.Services.Database ISelfAssignedRolesRepository SelfAssignedRoles { get; } IBotConfigRepository BotConfig { get; } IRepeaterRepository Repeaters { get; } + IUnitConverterRepository ConverterUnits { get; } int Complete(); Task CompleteAsync(); diff --git a/src/NadekoBot/Services/Database/Models/ConvertUnit.cs b/src/NadekoBot/Services/Database/Models/ConvertUnit.cs new file mode 100644 index 00000000..3a487218 --- /dev/null +++ b/src/NadekoBot/Services/Database/Models/ConvertUnit.cs @@ -0,0 +1,38 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations.Schema; +using System.Linq; +using System.Threading.Tasks; + +namespace NadekoBot.Services.Database.Models +{ + public class ConvertUnit : DbEntity + { + public ConvertUnit() { } + [NotMapped] + private string[] _triggersValue; + [NotMapped] + public string[] Triggers + { + get + { + return _triggersValue ?? (_triggersValue = InternalTrigger.Split('|')); + } + set + { + _triggersValue = value; + InternalTrigger = string.Join("|", _triggersValue); + } + } + //protected or private? + /// + /// DO NOT CALL THIS + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public string InternalTrigger { get; set; } + public string UnitType { get; set; } + public decimal Modifier { get; set; } + } + +} diff --git a/src/NadekoBot/Services/Database/NadekoContext.cs b/src/NadekoBot/Services/Database/NadekoContext.cs index ae32be4a..da725a30 100644 --- a/src/NadekoBot/Services/Database/NadekoContext.cs +++ b/src/NadekoBot/Services/Database/NadekoContext.cs @@ -20,6 +20,7 @@ namespace NadekoBot.Services.Database public DbSet BotConfig { get; set; } public DbSet Repeaters { get; set; } public DbSet Currency { get; set; } + public DbSet ConversionUnits { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { @@ -83,6 +84,7 @@ namespace NadekoBot.Services.Database .HasIndex(c => c.UserId) .IsUnique(); #endregion + } protected abstract override void OnConfiguring(DbContextOptionsBuilder optionsBuilder); } diff --git a/src/NadekoBot/Services/Database/Repositories/IUnitConverterRepository.cs b/src/NadekoBot/Services/Database/Repositories/IUnitConverterRepository.cs new file mode 100644 index 00000000..147f38d8 --- /dev/null +++ b/src/NadekoBot/Services/Database/Repositories/IUnitConverterRepository.cs @@ -0,0 +1,14 @@ +using NadekoBot.Services.Database.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace NadekoBot.Services.Database.Repositories +{ + public interface IUnitConverterRepository : IRepository + { + void AddOrUpdate(Func check, ConvertUnit toAdd, Func toUpdate); + bool Empty(); + } +} diff --git a/src/NadekoBot/Services/Database/Repositories/Impl/UnitCOnverterRepository.cs b/src/NadekoBot/Services/Database/Repositories/Impl/UnitCOnverterRepository.cs new file mode 100644 index 00000000..846fe524 --- /dev/null +++ b/src/NadekoBot/Services/Database/Repositories/Impl/UnitCOnverterRepository.cs @@ -0,0 +1,28 @@ +using NadekoBot.Services.Database.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; + +namespace NadekoBot.Services.Database.Repositories.Impl +{ + public class UnitConverterRepository : Repository, IUnitConverterRepository + { + public UnitConverterRepository(DbContext context) : base(context) + { + } + + public void AddOrUpdate(Func check, ConvertUnit toAdd, Func toUpdate) + { + var existing = _set.FirstOrDefault(check); + if (existing != null) + { + existing = toUpdate.Invoke(existing); + } + else _set.Add(toAdd); + } + + public bool Empty() => !_set.Any(); + } +} diff --git a/src/NadekoBot/Services/Database/UnitOfWork.cs b/src/NadekoBot/Services/Database/UnitOfWork.cs index f8e42e64..58def7dd 100644 --- a/src/NadekoBot/Services/Database/UnitOfWork.cs +++ b/src/NadekoBot/Services/Database/UnitOfWork.cs @@ -38,6 +38,8 @@ namespace NadekoBot.Services.Database private ICurrencyRepository _currency; public ICurrencyRepository Currency => _currency ?? (_currency = new CurrencyRepository(_context)); + private IUnitConverterRepository _conUnits; + public IUnitConverterRepository ConverterUnits => _conUnits ?? (_conUnits = new UnitConverterRepository(_context)); public UnitOfWork(NadekoContext context) {