diff --git a/NadekoBot/Classes/DBHandler.cs b/NadekoBot/Classes/DBHandler.cs index db8dee81..31634696 100644 --- a/NadekoBot/Classes/DBHandler.cs +++ b/NadekoBot/Classes/DBHandler.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; +using System.Threading.Tasks; namespace NadekoBot.Classes { @@ -13,31 +14,24 @@ namespace NadekoBot.Classes private string FilePath { get; } = "data/nadekobot.sqlite"; - public SQLiteConnection Connection { get; set; } + public SQLiteAsyncConnection Connection { get; set; } static DbHandler() { } public DbHandler() { - Connection = new SQLiteConnection(FilePath); - Connection.CreateTable(); - Connection.CreateTable(); - Connection.CreateTable(); - Connection.CreateTable(); - Connection.CreateTable(); - Connection.CreateTable(); - Connection.CreateTable(); - Connection.CreateTable(); - Connection.CreateTable(); - Connection.CreateTable(); - Connection.CreateTable(); - Connection.CreateTable(); - Connection.CreateTable(); - Connection.CreateTable(); - Connection.CreateTable(); - Connection.Execute(Queries.TransactionTriggerQuery); + DbHandlerAsync().GetAwaiter().GetResult(); + } + + private async Task DbHandlerAsync() + { + Connection = new SQLiteAsyncConnection(FilePath); + await Connection.CreateTablesAsync(); + await Connection.CreateTablesAsync(); + await Connection.CreateTablesAsync(); + await Connection.ExecuteAsync(Queries.TransactionTriggerQuery); try { - Connection.Execute(Queries.DeletePlaylistTriggerQuery); + await Connection.ExecuteAsync(Queries.DeletePlaylistTriggerQuery); } catch (Exception ex) { @@ -45,78 +39,50 @@ namespace NadekoBot.Classes } } - internal T FindOne(Expression> p) where T : IDataModel, new() + internal async Task DeleteWhere(Expression> p) where T : IDataModel, new() { - return Connection.Table().Where(p).FirstOrDefault(); - + var item = await Connection.Table().Where(p).FirstOrDefaultAsync(); + if (item != null) + await Connection.DeleteAsync(item); } - internal IList FindAll(Expression> p) where T : IDataModel, new() + internal async Task> GetAllRows() where T : IDataModel, new() => new HashSet(await Connection.Table().ToListAsync()); + + internal Task GetStateByUserId(long id) => Connection.Table().Where(x => x.UserId == id).FirstOrDefaultAsync(); + + internal async Task Delete(int id) where T : IDataModel, new() { - - return Connection.Table().Where(p).ToList(); - - } - - internal void DeleteWhere(Expression> p) where T : IDataModel, new() - { - var id = Connection.Table().Where(p).FirstOrDefault()?.Id; - if (id.HasValue) - Connection.Delete(id); - } - - internal HashSet GetAllRows() where T : IDataModel, new() - { - return new HashSet(Connection.Table()); - } - - internal CurrencyState GetStateByUserId(long id) - { - return Connection.Table().Where(x => x.UserId == id).FirstOrDefault(); - } - - internal T Delete(int id) where T : IDataModel, new() - { - var found = Connection.Find(id); + var found = await Connection.FindAsync(id); if (found != null) - Connection.Delete(found.Id); + await Connection.DeleteAsync(found); return found; } /// /// Updates an existing object or creates a new one /// - internal void Save(T o) where T : IDataModel, new() - { - var found = Connection.Find(o.Id); - if (found == null) - Connection.Insert(o, typeof(T)); - else - Connection.Update(o, typeof(T)); - } + internal Task Save(T o) where T : IDataModel, new() => Connection.InsertOrReplaceAsync(o); /// /// Updates an existing object or creates a new one /// - internal void SaveAll(IEnumerable ocol) where T : IDataModel, new() + internal async Task SaveAll(IEnumerable ocol) where T : IDataModel, new() { foreach (var o in ocol) - Connection.InsertOrReplace(o); + await Connection.InsertOrReplaceAsync(o); } - internal T GetRandom(Expression> p) where T : IDataModel, new() + internal async Task GetRandom(Expression> p) where T : IDataModel, new() { var r = new Random(); - return Connection.Table().Where(p).ToList().OrderBy(x => r.Next()).FirstOrDefault(); + return (await Connection.Table().Where(p).ToListAsync()).OrderBy(x => r.Next()).FirstOrDefault(); } /// /// /// /// Page number (0+) /// - internal List GetPlaylistData(int num) - { - return Connection.Query( + internal Task> GetPlaylistData(int num) => Connection.QueryAsync( @"SELECT mp.Name as 'Name',mp.Id as 'Id', mp.CreatorName as 'Creator', Count(*) as 'SongCnt' FROM MusicPlaylist as mp INNER JOIN PlaylistSongInfo as psi ON mp.Id = psi.PlaylistId @@ -124,12 +90,7 @@ Group BY mp.Name Order By mp.DateAdded desc Limit 20 OFFSET ?", num * 20); - } - - internal IEnumerable GetTopRichest(int n = 10) - { - return Connection.Table().OrderByDescending(cs => cs.Value).Take(n).ToList(); - } + internal async Task> GetTopRichest(int n = 10) => (await Connection.Table().OrderByDescending(cs => cs.Value).Take(n).ToListAsync()); } } diff --git a/NadekoBot/Classes/FlowersHandler.cs b/NadekoBot/Classes/FlowersHandler.cs index 57191c63..f787c0ab 100644 --- a/NadekoBot/Classes/FlowersHandler.cs +++ b/NadekoBot/Classes/FlowersHandler.cs @@ -8,14 +8,11 @@ namespace NadekoBot.Classes { if (amount <= 0) return; - await Task.Run(() => + await DbHandler.Instance.Connection.InsertAsync(new DataModels.CurrencyTransaction { - DbHandler.Instance.Connection.Insert(new DataModels.CurrencyTransaction - { - Reason = reason, - UserId = (long)u.Id, - Value = amount, - }); + Reason = reason, + UserId = (long)u.Id, + Value = amount, }).ConfigureAwait(false); if (silent) @@ -26,27 +23,27 @@ namespace NadekoBot.Classes await u.SendMessage("๐Ÿ‘‘Congratulations!๐Ÿ‘‘\nYou received: " + flows).ConfigureAwait(false); } - public static async Task RemoveFlowers(Discord.User u, string reason, int amount, bool silent=false, string message="๐Ÿ‘Ž`Bot owner has taken {0}{1} from you.`") + public static async Task RemoveFlowers(Discord.User u, string reason, int amount, bool silent = false, string message = "๐Ÿ‘Ž`Bot owner has taken {0}{1} from you.`") { if (amount <= 0) return false; var uid = (long)u.Id; - var state = DbHandler.Instance.FindOne(cs => cs.UserId == uid); + var state = await DbHandler.Instance.Connection.Table().Where(cs => cs.UserId == uid).FirstOrDefaultAsync(); if (state.Value < amount) return false; - DbHandler.Instance.Connection.Insert(new DataModels.CurrencyTransaction + await DbHandler.Instance.Connection.InsertAsync(new DataModels.CurrencyTransaction { Reason = reason, UserId = (long)u.Id, Value = -amount, - }); + }).ConfigureAwait(false); if (silent) return true; - await u.SendMessage(string.Format(message,amount,NadekoBot.Config.CurrencySign)).ConfigureAwait(false); + await u.SendMessage(string.Format(message, amount, NadekoBot.Config.CurrencySign)).ConfigureAwait(false); return true; } } diff --git a/NadekoBot/Classes/IncidentsHandler.cs b/NadekoBot/Classes/IncidentsHandler.cs index 3042f824..79495697 100644 --- a/NadekoBot/Classes/IncidentsHandler.cs +++ b/NadekoBot/Classes/IncidentsHandler.cs @@ -1,11 +1,12 @@ ๏ปฟusing NadekoBot.DataModels; using System; +using System.Threading.Tasks; namespace NadekoBot.Classes { internal static class IncidentsHandler { - public static void Add(ulong serverId, ulong channelId, string text) + public static Task Add(ulong serverId, ulong channelId, string text) { var def = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Red; @@ -19,7 +20,7 @@ namespace NadekoBot.Classes Read = false }; - DbHandler.Instance.Connection.Insert(incident, typeof(Incident)); + return DbHandler.Instance.Connection.InsertAsync(incident); } } } diff --git a/NadekoBot/Classes/NadekoStats.cs b/NadekoBot/Classes/NadekoStats.cs index 8161348a..0cf1772f 100644 --- a/NadekoBot/Classes/NadekoStats.cs +++ b/NadekoBot/Classes/NadekoStats.cs @@ -195,7 +195,7 @@ namespace NadekoBot .ConfigureAwait(false); var connectedServers = NadekoBot.Client.Servers.Count(); - Classes.DbHandler.Instance.Connection.Insert(new DataModels.Stats + await Classes.DbHandler.Instance.Connection.InsertAsync(new DataModels.Stats { OnlineUsers = onlineUsers, RealOnlineUsers = realOnlineUsers, @@ -255,29 +255,26 @@ namespace NadekoBot commandTracker.TryAdd(e.Message.Id, DateTime.UtcNow); Console.WriteLine($">>COMMAND STARTED\nCmd: {e.Command.Text}\nMsg: {e.Message.Text}\nUsr: {e.User.Name} [{e.User.Id}]\nSrvr: {e.Server?.Name ?? "PRIVATE"} [{e.Server?.Id}]\n-----"); #if !NADEKO_RELEASE - await Task.Run(() => + try { - try + commandsRan++; + await Classes.DbHandler.Instance.Connection.InsertAsync(new DataModels.Command { - commandsRan++; - Classes.DbHandler.Instance.Connection.Insert(new DataModels.Command - { - ServerId = (long)(e.Server?.Id ?? 0), - ServerName = e.Server?.Name ?? "--Direct Message--", - ChannelId = (long)e.Channel.Id, - ChannelName = e.Channel.IsPrivate ? "--Direct Message" : e.Channel.Name, - UserId = (long)e.User.Id, - UserName = e.User.Name, - CommandName = e.Command.Text, - DateAdded = DateTime.Now - }); - } - catch (Exception ex) - { - Console.WriteLine("Probably unimportant error in ran command DB write."); - Console.WriteLine(ex); - } - }).ConfigureAwait(false); + ServerId = (long)(e.Server?.Id ?? 0), + ServerName = e.Server?.Name ?? "--Direct Message--", + ChannelId = (long)e.Channel.Id, + ChannelName = e.Channel.IsPrivate ? "--Direct Message" : e.Channel.Name, + UserId = (long)e.User.Id, + UserName = e.User.Name, + CommandName = e.Command.Text, + DateAdded = DateTime.Now + }).ConfigureAwait(false); + } + catch (Exception ex) + { + Console.WriteLine("Probably unimportant error in ran command DB write."); + Console.WriteLine(ex); + } #endif } } diff --git a/NadekoBot/Modules/Administration/AdministrationModule.cs b/NadekoBot/Modules/Administration/AdministrationModule.cs index 670d2513..b3573807 100644 --- a/NadekoBot/Modules/Administration/AdministrationModule.cs +++ b/NadekoBot/Modules/Administration/AdministrationModule.cs @@ -818,14 +818,11 @@ namespace NadekoBot.Modules.Administration .Description("List of lovely people who donated to keep this project alive.") .Do(async e => { - await Task.Run(async () => - { - var rows = DbHandler.Instance.GetAllRows(); - var donatorsOrdered = rows.OrderByDescending(d => d.Amount); - string str = $"**Thanks to the people listed below for making this project happen!**\n"; + var rows = await DbHandler.Instance.GetAllRows().ConfigureAwait(false); + var donatorsOrdered = rows.OrderByDescending(d => d.Amount); + string str = $"**Thanks to the people listed below for making this project happen!**\n"; - await e.Channel.SendMessage(str + string.Join("โญ", donatorsOrdered.Select(d => d.UserName))).ConfigureAwait(false); - }).ConfigureAwait(false); + await e.Channel.SendMessage(str + string.Join("โญ", donatorsOrdered.Select(d => d.UserName))).ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "donadd") @@ -835,23 +832,20 @@ namespace NadekoBot.Modules.Administration .AddCheck(SimpleCheckers.OwnerOnly()) .Do(async e => { - await Task.Run(() => + var donator = e.Server.FindUsers(e.GetArg("donator")).FirstOrDefault(); + var amount = int.Parse(e.GetArg("amount")); + if (donator == null) return; + try { - var donator = e.Server.FindUsers(e.GetArg("donator")).FirstOrDefault(); - var amount = int.Parse(e.GetArg("amount")); - if (donator == null) return; - try + await DbHandler.Instance.Connection.InsertAsync(new Donator { - DbHandler.Instance.Connection.Insert(new Donator - { - Amount = amount, - UserName = donator.Name, - UserId = (long)donator.Id - }); - e.Channel.SendMessage("Successfuly added a new donator. ๐Ÿ‘‘").ConfigureAwait(false); - } - catch { } - }).ConfigureAwait(false); + Amount = amount, + UserName = donator.Name, + UserId = (long)donator.Id + }).ConfigureAwait(false); + await e.Channel.SendMessage("Successfuly added a new donator. ๐Ÿ‘‘").ConfigureAwait(false); + } + catch { } }); cgb.CreateCommand(Prefix + "announce") diff --git a/NadekoBot/Modules/Administration/Commands/IncidentsCommands.cs b/NadekoBot/Modules/Administration/Commands/IncidentsCommands.cs index d7915bb2..cd8ff95c 100644 --- a/NadekoBot/Modules/Administration/Commands/IncidentsCommands.cs +++ b/NadekoBot/Modules/Administration/Commands/IncidentsCommands.cs @@ -19,8 +19,8 @@ namespace NadekoBot.Modules.Administration.Commands .Do(async e => { var sid = (long)e.Server.Id; - var incs = DbHandler.Instance.FindAll(i => i.ServerId == sid && i.Read == false); - DbHandler.Instance.Connection.UpdateAll(incs.Select(i => { i.Read = true; return i; })); + var incs = await DbHandler.Instance.Connection.Table().Where(i => i.ServerId == sid && i.Read == false).ToListAsync(); + await DbHandler.Instance.Connection.UpdateAllAsync(incs.Select(i => { i.Read = true; return i; })); await e.User.SendMessage(string.Join("\n----------------------", incs.Select(i => i.Text))); }); @@ -32,8 +32,8 @@ namespace NadekoBot.Modules.Administration.Commands .Do(async e => { var sid = (long)e.Server.Id; - var incs = DbHandler.Instance.FindAll(i => i.ServerId == sid); - DbHandler.Instance.Connection.UpdateAll(incs.Select(i => { i.Read = true; return i; })); + var incs = await DbHandler.Instance.Connection.Table().Where(i => i.ServerId == sid).ToListAsync(); + await DbHandler.Instance.Connection.UpdateAllAsync(incs.Select(i => { i.Read = true; return i; })); var data = string.Join("\n----------------------\n", incs.Select(i => i.Text)); MemoryStream ms = new MemoryStream(); var sw = new StreamWriter(ms); diff --git a/NadekoBot/Modules/Administration/Commands/ServerGreetCommand.cs b/NadekoBot/Modules/Administration/Commands/ServerGreetCommand.cs index 5281f9df..6b36d634 100644 --- a/NadekoBot/Modules/Administration/Commands/ServerGreetCommand.cs +++ b/NadekoBot/Modules/Administration/Commands/ServerGreetCommand.cs @@ -34,7 +34,7 @@ namespace NadekoBot.Modules.Administration.Commands NadekoBot.Client.UserJoined += UserJoined; NadekoBot.Client.UserLeft += UserLeft; - var data = Classes.DbHandler.Instance.GetAllRows(); + var data = Classes.DbHandler.Instance.GetAllRows().GetAwaiter().GetResult(); if (!data.Any()) return; foreach (var obj in data) diff --git a/NadekoBot/Modules/Conversations/Conversations.cs b/NadekoBot/Modules/Conversations/Conversations.cs index a3611d0e..ae23b109 100644 --- a/NadekoBot/Modules/Conversations/Conversations.cs +++ b/NadekoBot/Modules/Conversations/Conversations.cs @@ -40,14 +40,13 @@ namespace NadekoBot.Modules.Conversations var text = e.GetArg("text"); if (string.IsNullOrWhiteSpace(text)) return; - await Task.Run(() => - Classes.DbHandler.Instance.Connection.Insert(new DataModels.UserQuote() - { - DateAdded = DateTime.Now, - Keyword = e.GetArg("keyword").ToLowerInvariant(), - Text = text, - UserName = e.User.Name, - })).ConfigureAwait(false); + await Classes.DbHandler.Instance.Connection.InsertAsync(new DataModels.UserQuote() + { + DateAdded = DateTime.Now, + Keyword = e.GetArg("keyword").ToLowerInvariant(), + Text = text, + UserName = e.User.Name, + }).ConfigureAwait(false); await e.Channel.SendMessage("`New quote added.`").ConfigureAwait(false); }); @@ -62,7 +61,7 @@ namespace NadekoBot.Modules.Conversations return; var quote = - Classes.DbHandler.Instance.GetRandom( + await Classes.DbHandler.Instance.GetRandom( uqm => uqm.Keyword == keyword); if (quote != null) @@ -80,13 +79,10 @@ namespace NadekoBot.Modules.Conversations var text = e.GetArg("quote")?.Trim(); if (string.IsNullOrWhiteSpace(text)) return; - await Task.Run(() => - { - if (NadekoBot.IsOwner(e.User.Id)) - Classes.DbHandler.Instance.DeleteWhere(uq => uq.Keyword == text); - else - Classes.DbHandler.Instance.DeleteWhere(uq => uq.Keyword == text && uq.UserName == e.User.Name); - }).ConfigureAwait(false); + if (NadekoBot.IsOwner(e.User.Id)) + await Classes.DbHandler.Instance.DeleteWhere(uq => uq.Keyword == text); + else + await Classes.DbHandler.Instance.DeleteWhere(uq => uq.Keyword == text && uq.UserName == e.User.Name); await e.Channel.SendMessage("`Done.`").ConfigureAwait(false); }); diff --git a/NadekoBot/Modules/Gambling/Commands/AnimalRacing.cs b/NadekoBot/Modules/Gambling/Commands/AnimalRacing.cs index a908128c..cb9a6b77 100644 --- a/NadekoBot/Modules/Gambling/Commands/AnimalRacing.cs +++ b/NadekoBot/Modules/Gambling/Commands/AnimalRacing.cs @@ -44,7 +44,7 @@ namespace NadekoBot.Modules.Gambling.Commands if (!int.TryParse(e.GetArg("amount"), out amount) || amount < 0) amount = 0; - var userFlowers = GamblingModule.GetUserFlowers(e.User.Id); + var userFlowers = await GamblingModule.GetUserFlowers(e.User.Id).ConfigureAwait(false); if (userFlowers < amount) { diff --git a/NadekoBot/Modules/Gambling/FlipCoinCommand.cs b/NadekoBot/Modules/Gambling/FlipCoinCommand.cs index d0b79919..8ec9f8d1 100644 --- a/NadekoBot/Modules/Gambling/FlipCoinCommand.cs +++ b/NadekoBot/Modules/Gambling/FlipCoinCommand.cs @@ -20,7 +20,7 @@ namespace NadekoBot.Modules.Gambling .Do(FlipCoinFunc()); cgb.CreateCommand(Module.Prefix + "betflip") - .Alias(Prefix+"bf") + .Alias(Prefix + "bf") .Description($"Bet to guess will the result be heads or tails. Guessing award you double flowers you've bet. | `{Prefix}bf 5 heads` or `{Prefix}bf 3 t`") .Parameter("amount", ParameterType.Required) .Parameter("guess", ParameterType.Required) @@ -43,7 +43,7 @@ namespace NadekoBot.Modules.Gambling if (!int.TryParse(amountstr, out amount) || amount < 1) return; - var userFlowers = GamblingModule.GetUserFlowers(e.User.Id); + var userFlowers = await GamblingModule.GetUserFlowers(e.User.Id).ConfigureAwait(false); if (userFlowers < amount) { @@ -57,11 +57,13 @@ namespace NadekoBot.Modules.Gambling var guess = guessStr == "HEADS" || guessStr == "H"; bool result = false; - if (rng.Next(0, 2) == 1) { + if (rng.Next(0, 2) == 1) + { await e.Channel.SendFile("heads.png", Properties.Resources.heads.ToStream(System.Drawing.Imaging.ImageFormat.Png)).ConfigureAwait(false); result = true; } - else { + else + { await e.Channel.SendFile("tails.png", Properties.Resources.tails.ToStream(System.Drawing.Imaging.ImageFormat.Png)).ConfigureAwait(false); } diff --git a/NadekoBot/Modules/Gambling/GamblingModule.cs b/NadekoBot/Modules/Gambling/GamblingModule.cs index efa3a553..9b3899aa 100644 --- a/NadekoBot/Modules/Gambling/GamblingModule.cs +++ b/NadekoBot/Modules/Gambling/GamblingModule.cs @@ -9,6 +9,7 @@ using NadekoBot.Modules.Permissions.Classes; using System; using System.Linq; using System.Text; +using System.Threading.Tasks; namespace NadekoBot.Modules.Gambling { @@ -57,13 +58,13 @@ namespace NadekoBot.Modules.Gambling .Do(async e => { var usr = e.Message.MentionedUsers.FirstOrDefault() ?? e.User; - var pts = GetUserFlowers(usr.Id); + var pts = await GetUserFlowers(usr.Id).ConfigureAwait(false); var str = $"{usr.Name} has {pts} {NadekoBot.Config.CurrencySign}"; await e.Channel.SendMessage(str).ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "give") - .Description(string.Format("Give someone a certain amount of {0}s", NadekoBot.Config.CurrencyName)+ $"|`{Prefix}give 1 \"@SomeGuy\"`") + .Description(string.Format("Give someone a certain amount of {0}s", NadekoBot.Config.CurrencyName) + $"|`{Prefix}give 1 \"@SomeGuy\"`") .Parameter("amount", ParameterType.Required) .Parameter("receiver", ParameterType.Unparsed) .Do(async e => @@ -79,7 +80,7 @@ namespace NadekoBot.Modules.Gambling if (mentionedUser == null) return; - var userFlowers = GetUserFlowers(e.User.Id); + var userFlowers = await GetUserFlowers(e.User.Id).ConfigureAwait(false); if (userFlowers < amount) { @@ -141,7 +142,7 @@ namespace NadekoBot.Modules.Gambling cgb.CreateCommand(Prefix + "betroll") .Alias(Prefix + "br") .Description($"Bets a certain amount of {NadekoBot.Config.CurrencyName}s and rolls a dice. Rolling over 66 yields x2 flowers, over 90 - x3 and 100 x10. | `{Prefix}br 5`") - .Parameter("amount",ParameterType.Required) + .Parameter("amount", ParameterType.Required) .Do(async e => { var amountstr = e.GetArg("amount").Trim(); @@ -150,7 +151,7 @@ namespace NadekoBot.Modules.Gambling if (!int.TryParse(amountstr, out amount) || amount < 1) return; - var userFlowers = GetUserFlowers(e.User.Id); + var userFlowers = await GetUserFlowers(e.User.Id).ConfigureAwait(false); if (userFlowers < amount) { @@ -176,13 +177,14 @@ namespace NadekoBot.Modules.Gambling str += $"Congratulations! You won {amount * 3}{NadekoBot.Config.CurrencySign} for rolling above 90."; await FlowersHandler.AddFlowersAsync(e.User, "Betroll Gamble", amount * 3, true).ConfigureAwait(false); } - else { + else + { str += $"๐Ÿ‘‘ Congratulations! You won {amount * 10}{NadekoBot.Config.CurrencySign} for rolling **100**. ๐Ÿ‘‘"; await FlowersHandler.AddFlowersAsync(e.User, "Betroll Gamble", amount * 10, true).ConfigureAwait(false); } await e.Channel.SendMessage(str).ConfigureAwait(false); - + }); cgb.CreateCommand(Prefix + "leaderboard") @@ -190,7 +192,7 @@ namespace NadekoBot.Modules.Gambling .Description($"Displays bot currency leaderboard | {Prefix}lb") .Do(async e => { - var richestTemp = DbHandler.Instance.GetTopRichest(); + var richestTemp = await DbHandler.Instance.GetTopRichest().ConfigureAwait(false); var richest = richestTemp as CurrencyState[] ?? richestTemp.ToArray(); if (richest.Length == 0) return; @@ -208,7 +210,7 @@ namespace NadekoBot.Modules.Gambling }); } - public static long GetUserFlowers(ulong userId) => - Classes.DbHandler.Instance.GetStateByUserId((long)userId)?.Value ?? 0; + public static async Task GetUserFlowers(ulong userId) => + (await Classes.DbHandler.Instance.GetStateByUserId((long)userId))?.Value ?? 0; } } diff --git a/NadekoBot/Modules/Games/Commands/SpeedTyping.cs b/NadekoBot/Modules/Games/Commands/SpeedTyping.cs index 07100820..ebcecead 100644 --- a/NadekoBot/Modules/Games/Commands/SpeedTyping.cs +++ b/NadekoBot/Modules/Games/Commands/SpeedTyping.cs @@ -15,9 +15,9 @@ namespace NadekoBot.Modules.Games.Commands public static class SentencesProvider { - internal static string GetRandomSentence() + internal static async Task GetRandomSentence() { - var data = DbHandler.Instance.GetAllRows(); + var data = await DbHandler.Instance.GetAllRows(); try { return data.ToList()[new Random().Next(0, data.Count())].Text; @@ -66,7 +66,7 @@ namespace NadekoBot.Modules.Games.Commands { if (IsActive) return; // can't start running game IsActive = true; - CurrentSentence = SentencesProvider.GetRandomSentence(); + CurrentSentence = await SentencesProvider.GetRandomSentence().ConfigureAwait(false); var i = (int)(CurrentSentence.Length / WORD_VALUE * 1.7f); await channel.SendMessage($":clock2: Next contest will last for {i} seconds. Type the bolded text as fast as you can.").ConfigureAwait(false); @@ -182,11 +182,11 @@ namespace NadekoBot.Modules.Games.Commands { if (!NadekoBot.IsOwner(e.User.Id) || string.IsNullOrWhiteSpace(e.GetArg("text"))) return; - DbHandler.Instance.Connection.Insert(new TypingArticle + await DbHandler.Instance.Connection.InsertAsync(new TypingArticle { Text = e.GetArg("text"), DateAdded = DateTime.Now - }); + }).ConfigureAwait(false); await e.Channel.SendMessage("Added new article for typing game.").ConfigureAwait(false); }); diff --git a/NadekoBot/Modules/Music/MusicModule.cs b/NadekoBot/Modules/Music/MusicModule.cs index 77630fd7..e198df3e 100644 --- a/NadekoBot/Modules/Music/MusicModule.cs +++ b/NadekoBot/Modules/Music/MusicModule.cs @@ -612,13 +612,13 @@ namespace NadekoBot.Modules.Music CreatorName = e.User.Name, Name = name.ToLowerInvariant(), }; - DbHandler.Instance.SaveAll(songInfos); - DbHandler.Instance.Save(playlist); - DbHandler.Instance.Connection.InsertAll(songInfos.Select(s => new PlaylistSongInfo + await DbHandler.Instance.SaveAll(songInfos).ConfigureAwait(false); + await DbHandler.Instance.Save(playlist).ConfigureAwait(false); + await DbHandler.Instance.Connection.InsertAllAsync(songInfos.Select(s => new PlaylistSongInfo { PlaylistId = playlist.Id.Value, SongInfoId = s.Id.Value - }), typeof(PlaylistSongInfo)); + })).ConfigureAwait(false); await e.Channel.SendMessage($"๐ŸŽต `Saved playlist as {name}-{playlist.Id}`").ConfigureAwait(false); @@ -650,7 +650,7 @@ namespace NadekoBot.Modules.Music if (!int.TryParse(parts[1], out playlistNumber)) return; - var playlist = DbHandler.Instance.FindOne( + var playlist = DbHandler.Instance.Connection.FindAsync( p => p.Id == playlistNumber); if (playlist == null) @@ -659,11 +659,11 @@ namespace NadekoBot.Modules.Music return; } - var psis = DbHandler.Instance.FindAll(psi => - psi.PlaylistId == playlist.Id); + var psis = await DbHandler.Instance.Connection.Table().Where(psi => + psi.PlaylistId == playlist.Id).ToListAsync().ConfigureAwait(false); - var songInfos = psis.Select(psi => DbHandler.Instance - .FindOne(si => si.Id == psi.SongInfoId)); + var songInfos = await Task.WhenAll(psis.Select(async psi => await DbHandler.Instance + .Connection.FindAsync(si => si.Id == psi.SongInfoId))).ConfigureAwait(false); await e.Channel.SendMessage($"`Attempting to load {songInfos.Count()} songs`").ConfigureAwait(false); foreach (var si in songInfos) @@ -687,17 +687,17 @@ namespace NadekoBot.Modules.Music .Alias(Prefix + "pls") .Description($"Lists all playlists. Paginated. 20 per page. Default page is 0. |`{Prefix}pls 1`") .Parameter("num", ParameterType.Optional) - .Do(e => + .Do(async e => { int num = 0; int.TryParse(e.GetArg("num"), out num); if (num < 0) return; - var result = DbHandler.Instance.GetPlaylistData(num); + var result = await DbHandler.Instance.GetPlaylistData(num); if (result.Count == 0) - e.Channel.SendMessage($"`No saved playlists found on page {num}`").ConfigureAwait(false); + await e.Channel.SendMessage($"`No saved playlists found on page {num}`").ConfigureAwait(false); else - e.Channel.SendMessage($"```js\n--- List of saved playlists ---\n\n" + string.Join("\n", result.Select(r => $"'{r.Name}-{r.Id}' by {r.Creator} ({r.SongCnt} songs)")) + $"\n\n --- Page {num} ---```").ConfigureAwait(false); + await e.Channel.SendMessage($"```js\n--- List of saved playlists ---\n\n" + string.Join("\n", result.Select(r => $"'{r.Name}-{r.Id}' by {r.Creator} ({r.SongCnt} songs)")) + $"\n\n --- Page {num} ---```").ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "deleteplaylist") @@ -711,9 +711,9 @@ namespace NadekoBot.Modules.Music return; var plnum = int.Parse(pl); if (NadekoBot.IsOwner(e.User.Id)) - DbHandler.Instance.Delete(plnum); + await DbHandler.Instance.Delete(plnum).ConfigureAwait(false); else - DbHandler.Instance.DeleteWhere(mp => mp.Id == plnum && (long)e.User.Id == mp.CreatorId); + await DbHandler.Instance.DeleteWhere(mp => mp.Id == plnum && (long)e.User.Id == mp.CreatorId).ConfigureAwait(false); await e.Channel.SendMessage("`Ok.` :ok:").ConfigureAwait(false); }); @@ -771,20 +771,22 @@ namespace NadekoBot.Modules.Music var selSong = musicPlayer.Playlist.DefaultIfEmpty(null).ElementAtOrDefault(index - 1); if (selSong == null) { - await e.Channel.SendMessage("Could not select song, likely wrong index"); - - } else + await e.Channel.SendMessage("Could not select song, likely wrong index"); + + } + else { await e.Channel.SendMessage($"๐ŸŽถ`Selected song {selSong.SongInfo.Title}:` <{selSong.SongInfo.Query}>").ConfigureAwait(false); } - } else + } + else { var curSong = musicPlayer.CurrentSong; if (curSong == null) return; await e.Channel.SendMessage($"๐ŸŽถ`Current song:` <{curSong.SongInfo.Query}>").ConfigureAwait(false); } - + }); cgb.CreateCommand(Prefix + "autoplay") diff --git a/NadekoBot/Modules/Pokemon/PokemonModule.cs b/NadekoBot/Modules/Pokemon/PokemonModule.cs index d494fffa..abc290b1 100644 --- a/NadekoBot/Modules/Pokemon/PokemonModule.cs +++ b/NadekoBot/Modules/Pokemon/PokemonModule.cs @@ -9,6 +9,7 @@ using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; +using System.Threading.Tasks; namespace NadekoBot.Modules.Pokemon { @@ -39,10 +40,10 @@ namespace NadekoBot.Modules.Pokemon return damage; } - private PokemonType GetPokeType(ulong id) + private async Task GetPokeType(ulong id) { - var db = DbHandler.Instance.GetAllRows(); + var db = await DbHandler.Instance.GetAllRows().ConfigureAwait(false); Dictionary setTypes = db.ToDictionary(x => x.UserId, y => y.type); if (setTypes.ContainsKey((long)id)) { @@ -134,7 +135,7 @@ namespace NadekoBot.Modules.Pokemon } //Check whether move can be used - PokemonType userType = GetPokeType(e.User.Id); + PokemonType userType = await GetPokeType(e.User.Id).ConfigureAwait(false); var enabledMoves = userType.Moves; if (!enabledMoves.Contains(move.ToLowerInvariant())) @@ -144,7 +145,7 @@ namespace NadekoBot.Modules.Pokemon } //get target type - PokemonType targetType = GetPokeType(target.Id); + PokemonType targetType = await GetPokeType(target.Id).ConfigureAwait(false); //generate damage int damage = GetDamage(userType, targetType); //apply damage to target @@ -199,7 +200,7 @@ namespace NadekoBot.Modules.Pokemon .Description($"Lists the moves you are able to use | `{Prefix}ml`") .Do(async e => { - var userType = GetPokeType(e.User.Id); + var userType = await GetPokeType(e.User.Id).ConfigureAwait(false); var movesList = userType.Moves; var str = $"**Moves for `{userType.Name}` type.**"; foreach (string m in movesList) @@ -235,7 +236,7 @@ namespace NadekoBot.Modules.Pokemon } //Payment~ var amount = 1; - var pts = Classes.DbHandler.Instance.GetStateByUserId((long)e.User.Id)?.Value ?? 0; + var pts = (await Classes.DbHandler.Instance.GetStateByUserId((long)e.User.Id).ConfigureAwait(false))?.Value ?? 0; if (pts < amount) { await e.Channel.SendMessage($"{e.User.Mention} you don't have enough {NadekoBot.Config.CurrencyName}s! \nYou still need {amount - pts} {NadekoBot.Config.CurrencySign} to be able to do this!").ConfigureAwait(false); @@ -276,7 +277,7 @@ namespace NadekoBot.Modules.Pokemon await e.Channel.SendMessage("No such person.").ConfigureAwait(false); return; } - var pType = GetPokeType(usr.Id); + var pType = await GetPokeType(usr.Id).ConfigureAwait(false); await e.Channel.SendMessage($"Type of {usr.Name} is **{pType.Name.ToLowerInvariant()}**{pType.Icon}").ConfigureAwait(false); }); @@ -295,7 +296,7 @@ namespace NadekoBot.Modules.Pokemon await e.Channel.SendMessage("Invalid type specified. Type must be one of:\n" + string.Join(", ", NadekoBot.Config.PokemonTypes.Select(t => t.Name.ToUpperInvariant()))).ConfigureAwait(false); return; } - if (targetType == GetPokeType(e.User.Id)) + if (targetType == await GetPokeType(e.User.Id).ConfigureAwait(false)) { await e.Channel.SendMessage($"Your type is already {targetType.Name.ToLowerInvariant()}{targetType.Icon}").ConfigureAwait(false); return; @@ -303,7 +304,7 @@ namespace NadekoBot.Modules.Pokemon //Payment~ var amount = 1; - var pts = DbHandler.Instance.GetStateByUserId((long)e.User.Id)?.Value ?? 0; + var pts = (await DbHandler.Instance.GetStateByUserId((long)e.User.Id).ConfigureAwait(false))?.Value ?? 0; if (pts < amount) { await e.Channel.SendMessage($"{e.User.Mention} you don't have enough {NadekoBot.Config.CurrencyName}s! \nYou still need {amount - pts} {NadekoBot.Config.CurrencySign} to be able to do this!").ConfigureAwait(false); @@ -311,19 +312,19 @@ namespace NadekoBot.Modules.Pokemon } await FlowersHandler.RemoveFlowers(e.User, $"set usertype to {targetTypeStr}", amount).ConfigureAwait(false); //Actually changing the type here - var preTypes = DbHandler.Instance.GetAllRows(); + var preTypes = await DbHandler.Instance.GetAllRows().ConfigureAwait(false); Dictionary Dict = preTypes.ToDictionary(x => x.UserId, y => y.Id.Value); if (Dict.ContainsKey((long)e.User.Id)) { //delete previous type - DbHandler.Instance.Delete(Dict[(long)e.User.Id]); + await DbHandler.Instance.Delete(Dict[(long)e.User.Id]).ConfigureAwait(false); } - DbHandler.Instance.Connection.Insert(new UserPokeTypes + await DbHandler.Instance.Connection.InsertAsync(new UserPokeTypes { UserId = (long)e.User.Id, type = targetType.Name - }, typeof(UserPokeTypes)); + }).ConfigureAwait(false); //Now for the response diff --git a/NadekoBot/Modules/Utility/Commands/Remind.cs b/NadekoBot/Modules/Utility/Commands/Remind.cs index 808f4b11..a742c033 100644 --- a/NadekoBot/Modules/Utility/Commands/Remind.cs +++ b/NadekoBot/Modules/Utility/Commands/Remind.cs @@ -28,7 +28,7 @@ namespace NadekoBot.Modules.Utility.Commands public Remind(DiscordModule module) : base(module) { - var remList = DbHandler.Instance.GetAllRows(); + var remList = DbHandler.Instance.GetAllRows().GetAwaiter().GetResult(); reminders = remList.Select(StartNewReminder).ToList(); } @@ -73,7 +73,7 @@ namespace NadekoBot.Modules.Utility.Commands } finally { - DbHandler.Instance.Delete(r.Id.Value); + await DbHandler.Instance.Delete(r.Id.Value).ConfigureAwait(false); t.Stop(); t.Dispose(); } @@ -171,7 +171,7 @@ namespace NadekoBot.Modules.Utility.Commands UserId = (long)e.User.Id, ServerId = (long)e.Server.Id }; - DbHandler.Instance.Connection.Insert(rem); + await DbHandler.Instance.Connection.InsertAsync(rem).ConfigureAwait(false); reminders.Add(StartNewReminder(rem));