Revert "rewrote database stuff to be async, hopefuly it works properly."

This reverts commit 11ed1500ba.
This commit is contained in:
Kwoth 2016-07-30 01:21:48 +02:00
parent 11ed1500ba
commit 670a8ddf82
15 changed files with 205 additions and 158 deletions

View File

@ -4,7 +4,6 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Linq.Expressions; using System.Linq.Expressions;
using System.Threading.Tasks;
namespace NadekoBot.Classes namespace NadekoBot.Classes
{ {
@ -14,24 +13,31 @@ namespace NadekoBot.Classes
private string FilePath { get; } = "data/nadekobot.sqlite"; private string FilePath { get; } = "data/nadekobot.sqlite";
public SQLiteAsyncConnection Connection { get; set; } public SQLiteConnection Connection { get; set; }
static DbHandler() { } static DbHandler() { }
public DbHandler() public DbHandler()
{ {
DbHandlerAsync().GetAwaiter().GetResult(); Connection = new SQLiteConnection(FilePath);
} Connection.CreateTable<Stats>();
Connection.CreateTable<Command>();
private async Task DbHandlerAsync() Connection.CreateTable<Announcement>();
{ Connection.CreateTable<Request>();
Connection = new SQLiteAsyncConnection(FilePath); Connection.CreateTable<TypingArticle>();
await Connection.CreateTablesAsync<Stats, Command, Announcement, Request, TypingArticle>(); Connection.CreateTable<CurrencyState>();
await Connection.CreateTablesAsync<CurrencyState, CurrencyTransaction, Donator, UserPokeTypes, UserQuote>(); Connection.CreateTable<CurrencyTransaction>();
await Connection.CreateTablesAsync<Reminder, SongInfo, PlaylistSongInfo, MusicPlaylist, Incident>(); Connection.CreateTable<Donator>();
await Connection.ExecuteAsync(Queries.TransactionTriggerQuery); Connection.CreateTable<UserPokeTypes>();
Connection.CreateTable<UserQuote>();
Connection.CreateTable<Reminder>();
Connection.CreateTable<SongInfo>();
Connection.CreateTable<PlaylistSongInfo>();
Connection.CreateTable<MusicPlaylist>();
Connection.CreateTable<Incident>();
Connection.Execute(Queries.TransactionTriggerQuery);
try try
{ {
await Connection.ExecuteAsync(Queries.DeletePlaylistTriggerQuery); Connection.Execute(Queries.DeletePlaylistTriggerQuery);
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -39,50 +45,78 @@ namespace NadekoBot.Classes
} }
} }
internal async Task DeleteWhere<T>(Expression<Func<T, bool>> p) where T : IDataModel, new() internal T FindOne<T>(Expression<Func<T, bool>> p) where T : IDataModel, new()
{ {
var item = await Connection.Table<T>().Where(p).FirstOrDefaultAsync(); return Connection.Table<T>().Where(p).FirstOrDefault();
if (item != null)
await Connection.DeleteAsync(item);
} }
internal async Task<HashSet<T>> GetAllRows<T>() where T : IDataModel, new() => new HashSet<T>(await Connection.Table<T>().ToListAsync()); internal IList<T> FindAll<T>(Expression<Func<T, bool>> p) where T : IDataModel, new()
internal Task<CurrencyState> GetStateByUserId(long id) => Connection.Table<CurrencyState>().Where(x => x.UserId == id).FirstOrDefaultAsync();
internal async Task<T> Delete<T>(int id) where T : IDataModel, new()
{ {
var found = await Connection.FindAsync<T>(id);
return Connection.Table<T>().Where(p).ToList();
}
internal void DeleteWhere<T>(Expression<Func<T, bool>> p) where T : IDataModel, new()
{
var id = Connection.Table<T>().Where(p).FirstOrDefault()?.Id;
if (id.HasValue)
Connection.Delete<T>(id);
}
internal HashSet<T> GetAllRows<T>() where T : IDataModel, new()
{
return new HashSet<T>(Connection.Table<T>());
}
internal CurrencyState GetStateByUserId(long id)
{
return Connection.Table<CurrencyState>().Where(x => x.UserId == id).FirstOrDefault();
}
internal T Delete<T>(int id) where T : IDataModel, new()
{
var found = Connection.Find<T>(id);
if (found != null) if (found != null)
await Connection.DeleteAsync(found); Connection.Delete<T>(found.Id);
return found; return found;
} }
/// <summary> /// <summary>
/// Updates an existing object or creates a new one /// Updates an existing object or creates a new one
/// </summary> /// </summary>
internal Task<int> Save<T>(T o) where T : IDataModel, new() => Connection.InsertOrReplaceAsync(o); internal void Save<T>(T o) where T : IDataModel, new()
{
var found = Connection.Find<T>(o.Id);
if (found == null)
Connection.Insert(o, typeof(T));
else
Connection.Update(o, typeof(T));
}
/// <summary> /// <summary>
/// Updates an existing object or creates a new one /// Updates an existing object or creates a new one
/// </summary> /// </summary>
internal async Task SaveAll<T>(IEnumerable<T> ocol) where T : IDataModel, new() internal void SaveAll<T>(IEnumerable<T> ocol) where T : IDataModel, new()
{ {
foreach (var o in ocol) foreach (var o in ocol)
await Connection.InsertOrReplaceAsync(o); Connection.InsertOrReplace(o);
} }
internal async Task<T> GetRandom<T>(Expression<Func<T, bool>> p) where T : IDataModel, new() internal T GetRandom<T>(Expression<Func<T, bool>> p) where T : IDataModel, new()
{ {
var r = new Random(); var r = new Random();
return (await Connection.Table<T>().Where(p).ToListAsync()).OrderBy(x => r.Next()).FirstOrDefault(); return Connection.Table<T>().Where(p).ToList().OrderBy(x => r.Next()).FirstOrDefault();
} }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
/// <param name="num">Page number (0+)</param> /// <param name="num">Page number (0+)</param>
/// <returns></returns> /// <returns></returns>
internal Task<List<PlaylistData>> GetPlaylistData(int num) => Connection.QueryAsync<PlaylistData>( internal List<PlaylistData> GetPlaylistData(int num)
{
return Connection.Query<PlaylistData>(
@"SELECT mp.Name as 'Name',mp.Id as 'Id', mp.CreatorName as 'Creator', Count(*) as 'SongCnt' FROM MusicPlaylist as mp @"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 INNER JOIN PlaylistSongInfo as psi
ON mp.Id = psi.PlaylistId ON mp.Id = psi.PlaylistId
@ -90,7 +124,12 @@ Group BY mp.Name
Order By mp.DateAdded desc Order By mp.DateAdded desc
Limit 20 OFFSET ?", num * 20); Limit 20 OFFSET ?", num * 20);
internal async Task<IEnumerable<CurrencyState>> GetTopRichest(int n = 10) => (await Connection.Table<CurrencyState>().OrderByDescending(cs => cs.Value).Take(n).ToListAsync()); }
internal IEnumerable<CurrencyState> GetTopRichest(int n = 10)
{
return Connection.Table<CurrencyState>().OrderByDescending(cs => cs.Value).Take(n).ToList();
}
} }
} }

View File

@ -8,11 +8,14 @@ namespace NadekoBot.Classes
{ {
if (amount <= 0) if (amount <= 0)
return; return;
await DbHandler.Instance.Connection.InsertAsync(new DataModels.CurrencyTransaction await Task.Run(() =>
{
DbHandler.Instance.Connection.Insert(new DataModels.CurrencyTransaction
{ {
Reason = reason, Reason = reason,
UserId = (long)u.Id, UserId = (long)u.Id,
Value = amount, Value = amount,
});
}).ConfigureAwait(false); }).ConfigureAwait(false);
if (silent) if (silent)
@ -28,17 +31,17 @@ namespace NadekoBot.Classes
if (amount <= 0) if (amount <= 0)
return false; return false;
var uid = (long)u.Id; var uid = (long)u.Id;
var state = await DbHandler.Instance.Connection.Table<DataModels.CurrencyState>().Where(cs => cs.UserId == uid).FirstOrDefaultAsync(); var state = DbHandler.Instance.FindOne<DataModels.CurrencyState>(cs => cs.UserId == uid);
if (state.Value < amount) if (state.Value < amount)
return false; return false;
await DbHandler.Instance.Connection.InsertAsync(new DataModels.CurrencyTransaction DbHandler.Instance.Connection.Insert(new DataModels.CurrencyTransaction
{ {
Reason = reason, Reason = reason,
UserId = (long)u.Id, UserId = (long)u.Id,
Value = -amount, Value = -amount,
}).ConfigureAwait(false); });
if (silent) if (silent)
return true; return true;

View File

@ -1,12 +1,11 @@
using NadekoBot.DataModels; using NadekoBot.DataModels;
using System; using System;
using System.Threading.Tasks;
namespace NadekoBot.Classes namespace NadekoBot.Classes
{ {
internal static class IncidentsHandler internal static class IncidentsHandler
{ {
public static Task Add(ulong serverId, ulong channelId, string text) public static void Add(ulong serverId, ulong channelId, string text)
{ {
var def = Console.ForegroundColor; var def = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Red; Console.ForegroundColor = ConsoleColor.Red;
@ -20,7 +19,7 @@ namespace NadekoBot.Classes
Read = false Read = false
}; };
return DbHandler.Instance.Connection.InsertAsync(incident); DbHandler.Instance.Connection.Insert(incident, typeof(Incident));
} }
} }
} }

View File

@ -195,7 +195,7 @@ namespace NadekoBot
.ConfigureAwait(false); .ConfigureAwait(false);
var connectedServers = NadekoBot.Client.Servers.Count(); var connectedServers = NadekoBot.Client.Servers.Count();
await Classes.DbHandler.Instance.Connection.InsertAsync(new DataModels.Stats Classes.DbHandler.Instance.Connection.Insert(new DataModels.Stats
{ {
OnlineUsers = onlineUsers, OnlineUsers = onlineUsers,
RealOnlineUsers = realOnlineUsers, RealOnlineUsers = realOnlineUsers,
@ -255,10 +255,12 @@ namespace NadekoBot
commandTracker.TryAdd(e.Message.Id, DateTime.UtcNow); 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-----"); 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 #if !NADEKO_RELEASE
await Task.Run(() =>
{
try try
{ {
commandsRan++; commandsRan++;
await Classes.DbHandler.Instance.Connection.InsertAsync(new DataModels.Command Classes.DbHandler.Instance.Connection.Insert(new DataModels.Command
{ {
ServerId = (long)(e.Server?.Id ?? 0), ServerId = (long)(e.Server?.Id ?? 0),
ServerName = e.Server?.Name ?? "--Direct Message--", ServerName = e.Server?.Name ?? "--Direct Message--",
@ -268,13 +270,14 @@ namespace NadekoBot
UserName = e.User.Name, UserName = e.User.Name,
CommandName = e.Command.Text, CommandName = e.Command.Text,
DateAdded = DateTime.Now DateAdded = DateTime.Now
}).ConfigureAwait(false); });
} }
catch (Exception ex) catch (Exception ex)
{ {
Console.WriteLine("Probably unimportant error in ran command DB write."); Console.WriteLine("Probably unimportant error in ran command DB write.");
Console.WriteLine(ex); Console.WriteLine(ex);
} }
}).ConfigureAwait(false);
#endif #endif
} }
} }

View File

@ -818,11 +818,14 @@ namespace NadekoBot.Modules.Administration
.Description("List of lovely people who donated to keep this project alive.") .Description("List of lovely people who donated to keep this project alive.")
.Do(async e => .Do(async e =>
{ {
var rows = await DbHandler.Instance.GetAllRows<Donator>().ConfigureAwait(false); await Task.Run(async () =>
{
var rows = DbHandler.Instance.GetAllRows<Donator>();
var donatorsOrdered = rows.OrderByDescending(d => d.Amount); var donatorsOrdered = rows.OrderByDescending(d => d.Amount);
string str = $"**Thanks to the people listed below for making this project happen!**\n"; 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); await e.Channel.SendMessage(str + string.Join("⭐", donatorsOrdered.Select(d => d.UserName))).ConfigureAwait(false);
}).ConfigureAwait(false);
}); });
cgb.CreateCommand(Prefix + "donadd") cgb.CreateCommand(Prefix + "donadd")
@ -831,21 +834,24 @@ namespace NadekoBot.Modules.Administration
.Parameter("amount") .Parameter("amount")
.AddCheck(SimpleCheckers.OwnerOnly()) .AddCheck(SimpleCheckers.OwnerOnly())
.Do(async e => .Do(async e =>
{
await Task.Run(() =>
{ {
var donator = e.Server.FindUsers(e.GetArg("donator")).FirstOrDefault(); var donator = e.Server.FindUsers(e.GetArg("donator")).FirstOrDefault();
var amount = int.Parse(e.GetArg("amount")); var amount = int.Parse(e.GetArg("amount"));
if (donator == null) return; if (donator == null) return;
try try
{ {
await DbHandler.Instance.Connection.InsertAsync(new Donator DbHandler.Instance.Connection.Insert(new Donator
{ {
Amount = amount, Amount = amount,
UserName = donator.Name, UserName = donator.Name,
UserId = (long)donator.Id UserId = (long)donator.Id
}).ConfigureAwait(false); });
await e.Channel.SendMessage("Successfuly added a new donator. 👑").ConfigureAwait(false); e.Channel.SendMessage("Successfuly added a new donator. 👑").ConfigureAwait(false);
} }
catch { } catch { }
}).ConfigureAwait(false);
}); });
cgb.CreateCommand(Prefix + "announce") cgb.CreateCommand(Prefix + "announce")

View File

@ -19,8 +19,8 @@ namespace NadekoBot.Modules.Administration.Commands
.Do(async e => .Do(async e =>
{ {
var sid = (long)e.Server.Id; var sid = (long)e.Server.Id;
var incs = await DbHandler.Instance.Connection.Table<Incident>().Where(i => i.ServerId == sid && i.Read == false).ToListAsync(); var incs = DbHandler.Instance.FindAll<Incident>(i => i.ServerId == sid && i.Read == false);
await DbHandler.Instance.Connection.UpdateAllAsync(incs.Select(i => { i.Read = true; return i; })); DbHandler.Instance.Connection.UpdateAll(incs.Select(i => { i.Read = true; return i; }));
await e.User.SendMessage(string.Join("\n----------------------", incs.Select(i => i.Text))); await e.User.SendMessage(string.Join("\n----------------------", incs.Select(i => i.Text)));
}); });
@ -32,8 +32,8 @@ namespace NadekoBot.Modules.Administration.Commands
.Do(async e => .Do(async e =>
{ {
var sid = (long)e.Server.Id; var sid = (long)e.Server.Id;
var incs = await DbHandler.Instance.Connection.Table<Incident>().Where(i => i.ServerId == sid).ToListAsync(); var incs = DbHandler.Instance.FindAll<Incident>(i => i.ServerId == sid);
await DbHandler.Instance.Connection.UpdateAllAsync(incs.Select(i => { i.Read = true; return i; })); DbHandler.Instance.Connection.UpdateAll(incs.Select(i => { i.Read = true; return i; }));
var data = string.Join("\n----------------------\n", incs.Select(i => i.Text)); var data = string.Join("\n----------------------\n", incs.Select(i => i.Text));
MemoryStream ms = new MemoryStream(); MemoryStream ms = new MemoryStream();
var sw = new StreamWriter(ms); var sw = new StreamWriter(ms);

View File

@ -34,7 +34,7 @@ namespace NadekoBot.Modules.Administration.Commands
NadekoBot.Client.UserJoined += UserJoined; NadekoBot.Client.UserJoined += UserJoined;
NadekoBot.Client.UserLeft += UserLeft; NadekoBot.Client.UserLeft += UserLeft;
var data = Classes.DbHandler.Instance.GetAllRows<DataModels.Announcement>().GetAwaiter().GetResult(); var data = Classes.DbHandler.Instance.GetAllRows<DataModels.Announcement>();
if (!data.Any()) return; if (!data.Any()) return;
foreach (var obj in data) foreach (var obj in data)

View File

@ -40,13 +40,14 @@ namespace NadekoBot.Modules.Conversations
var text = e.GetArg("text"); var text = e.GetArg("text");
if (string.IsNullOrWhiteSpace(text)) if (string.IsNullOrWhiteSpace(text))
return; return;
await Classes.DbHandler.Instance.Connection.InsertAsync(new DataModels.UserQuote() await Task.Run(() =>
Classes.DbHandler.Instance.Connection.Insert(new DataModels.UserQuote()
{ {
DateAdded = DateTime.Now, DateAdded = DateTime.Now,
Keyword = e.GetArg("keyword").ToLowerInvariant(), Keyword = e.GetArg("keyword").ToLowerInvariant(),
Text = text, Text = text,
UserName = e.User.Name, UserName = e.User.Name,
}).ConfigureAwait(false); })).ConfigureAwait(false);
await e.Channel.SendMessage("`New quote added.`").ConfigureAwait(false); await e.Channel.SendMessage("`New quote added.`").ConfigureAwait(false);
}); });
@ -61,7 +62,7 @@ namespace NadekoBot.Modules.Conversations
return; return;
var quote = var quote =
await Classes.DbHandler.Instance.GetRandom<DataModels.UserQuote>( Classes.DbHandler.Instance.GetRandom<DataModels.UserQuote>(
uqm => uqm.Keyword == keyword); uqm => uqm.Keyword == keyword);
if (quote != null) if (quote != null)
@ -79,10 +80,13 @@ namespace NadekoBot.Modules.Conversations
var text = e.GetArg("quote")?.Trim(); var text = e.GetArg("quote")?.Trim();
if (string.IsNullOrWhiteSpace(text)) if (string.IsNullOrWhiteSpace(text))
return; return;
await Task.Run(() =>
{
if (NadekoBot.IsOwner(e.User.Id)) if (NadekoBot.IsOwner(e.User.Id))
await Classes.DbHandler.Instance.DeleteWhere<UserQuote>(uq => uq.Keyword == text); Classes.DbHandler.Instance.DeleteWhere<UserQuote>(uq => uq.Keyword == text);
else else
await Classes.DbHandler.Instance.DeleteWhere<UserQuote>(uq => uq.Keyword == text && uq.UserName == e.User.Name); Classes.DbHandler.Instance.DeleteWhere<UserQuote>(uq => uq.Keyword == text && uq.UserName == e.User.Name);
}).ConfigureAwait(false);
await e.Channel.SendMessage("`Done.`").ConfigureAwait(false); await e.Channel.SendMessage("`Done.`").ConfigureAwait(false);
}); });

View File

@ -44,7 +44,7 @@ namespace NadekoBot.Modules.Gambling.Commands
if (!int.TryParse(e.GetArg("amount"), out amount) || amount < 0) if (!int.TryParse(e.GetArg("amount"), out amount) || amount < 0)
amount = 0; amount = 0;
var userFlowers = await GamblingModule.GetUserFlowers(e.User.Id).ConfigureAwait(false); var userFlowers = GamblingModule.GetUserFlowers(e.User.Id);
if (userFlowers < amount) if (userFlowers < amount)
{ {

View File

@ -43,7 +43,7 @@ namespace NadekoBot.Modules.Gambling
if (!int.TryParse(amountstr, out amount) || amount < 1) if (!int.TryParse(amountstr, out amount) || amount < 1)
return; return;
var userFlowers = await GamblingModule.GetUserFlowers(e.User.Id).ConfigureAwait(false); var userFlowers = GamblingModule.GetUserFlowers(e.User.Id);
if (userFlowers < amount) if (userFlowers < amount)
{ {
@ -57,13 +57,11 @@ namespace NadekoBot.Modules.Gambling
var guess = guessStr == "HEADS" || guessStr == "H"; var guess = guessStr == "HEADS" || guessStr == "H";
bool result = false; 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); await e.Channel.SendFile("heads.png", Properties.Resources.heads.ToStream(System.Drawing.Imaging.ImageFormat.Png)).ConfigureAwait(false);
result = true; result = true;
} }
else else {
{
await e.Channel.SendFile("tails.png", Properties.Resources.tails.ToStream(System.Drawing.Imaging.ImageFormat.Png)).ConfigureAwait(false); await e.Channel.SendFile("tails.png", Properties.Resources.tails.ToStream(System.Drawing.Imaging.ImageFormat.Png)).ConfigureAwait(false);
} }

View File

@ -9,7 +9,6 @@ using NadekoBot.Modules.Permissions.Classes;
using System; using System;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks;
namespace NadekoBot.Modules.Gambling namespace NadekoBot.Modules.Gambling
{ {
@ -58,7 +57,7 @@ namespace NadekoBot.Modules.Gambling
.Do(async e => .Do(async e =>
{ {
var usr = e.Message.MentionedUsers.FirstOrDefault() ?? e.User; var usr = e.Message.MentionedUsers.FirstOrDefault() ?? e.User;
var pts = await GetUserFlowers(usr.Id).ConfigureAwait(false); var pts = GetUserFlowers(usr.Id);
var str = $"{usr.Name} has {pts} {NadekoBot.Config.CurrencySign}"; var str = $"{usr.Name} has {pts} {NadekoBot.Config.CurrencySign}";
await e.Channel.SendMessage(str).ConfigureAwait(false); await e.Channel.SendMessage(str).ConfigureAwait(false);
}); });
@ -80,7 +79,7 @@ namespace NadekoBot.Modules.Gambling
if (mentionedUser == null) if (mentionedUser == null)
return; return;
var userFlowers = await GetUserFlowers(e.User.Id).ConfigureAwait(false); var userFlowers = GetUserFlowers(e.User.Id);
if (userFlowers < amount) if (userFlowers < amount)
{ {
@ -151,7 +150,7 @@ namespace NadekoBot.Modules.Gambling
if (!int.TryParse(amountstr, out amount) || amount < 1) if (!int.TryParse(amountstr, out amount) || amount < 1)
return; return;
var userFlowers = await GetUserFlowers(e.User.Id).ConfigureAwait(false); var userFlowers = GetUserFlowers(e.User.Id);
if (userFlowers < amount) if (userFlowers < amount)
{ {
@ -177,8 +176,7 @@ namespace NadekoBot.Modules.Gambling
str += $"Congratulations! You won {amount * 3}{NadekoBot.Config.CurrencySign} for rolling above 90."; 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); 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**. 👑"; 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 FlowersHandler.AddFlowersAsync(e.User, "Betroll Gamble", amount * 10, true).ConfigureAwait(false);
} }
@ -192,7 +190,7 @@ namespace NadekoBot.Modules.Gambling
.Description($"Displays bot currency leaderboard | {Prefix}lb") .Description($"Displays bot currency leaderboard | {Prefix}lb")
.Do(async e => .Do(async e =>
{ {
var richestTemp = await DbHandler.Instance.GetTopRichest().ConfigureAwait(false); var richestTemp = DbHandler.Instance.GetTopRichest();
var richest = richestTemp as CurrencyState[] ?? richestTemp.ToArray(); var richest = richestTemp as CurrencyState[] ?? richestTemp.ToArray();
if (richest.Length == 0) if (richest.Length == 0)
return; return;
@ -210,7 +208,7 @@ namespace NadekoBot.Modules.Gambling
}); });
} }
public static async Task<long> GetUserFlowers(ulong userId) => public static long GetUserFlowers(ulong userId) =>
(await Classes.DbHandler.Instance.GetStateByUserId((long)userId))?.Value ?? 0; Classes.DbHandler.Instance.GetStateByUserId((long)userId)?.Value ?? 0;
} }
} }

View File

@ -15,9 +15,9 @@ namespace NadekoBot.Modules.Games.Commands
public static class SentencesProvider public static class SentencesProvider
{ {
internal static async Task<string> GetRandomSentence() internal static string GetRandomSentence()
{ {
var data = await DbHandler.Instance.GetAllRows<TypingArticle>(); var data = DbHandler.Instance.GetAllRows<TypingArticle>();
try try
{ {
return data.ToList()[new Random().Next(0, data.Count())].Text; 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 if (IsActive) return; // can't start running game
IsActive = true; IsActive = true;
CurrentSentence = await SentencesProvider.GetRandomSentence().ConfigureAwait(false); CurrentSentence = SentencesProvider.GetRandomSentence();
var i = (int)(CurrentSentence.Length / WORD_VALUE * 1.7f); 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); 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; if (!NadekoBot.IsOwner(e.User.Id) || string.IsNullOrWhiteSpace(e.GetArg("text"))) return;
await DbHandler.Instance.Connection.InsertAsync(new TypingArticle DbHandler.Instance.Connection.Insert(new TypingArticle
{ {
Text = e.GetArg("text"), Text = e.GetArg("text"),
DateAdded = DateTime.Now DateAdded = DateTime.Now
}).ConfigureAwait(false); });
await e.Channel.SendMessage("Added new article for typing game.").ConfigureAwait(false); await e.Channel.SendMessage("Added new article for typing game.").ConfigureAwait(false);
}); });

View File

@ -612,13 +612,13 @@ namespace NadekoBot.Modules.Music
CreatorName = e.User.Name, CreatorName = e.User.Name,
Name = name.ToLowerInvariant(), Name = name.ToLowerInvariant(),
}; };
await DbHandler.Instance.SaveAll(songInfos).ConfigureAwait(false); DbHandler.Instance.SaveAll(songInfos);
await DbHandler.Instance.Save(playlist).ConfigureAwait(false); DbHandler.Instance.Save(playlist);
await DbHandler.Instance.Connection.InsertAllAsync(songInfos.Select(s => new PlaylistSongInfo DbHandler.Instance.Connection.InsertAll(songInfos.Select(s => new PlaylistSongInfo
{ {
PlaylistId = playlist.Id.Value, PlaylistId = playlist.Id.Value,
SongInfoId = s.Id.Value SongInfoId = s.Id.Value
})).ConfigureAwait(false); }), typeof(PlaylistSongInfo));
await e.Channel.SendMessage($"🎵 `Saved playlist as {name}-{playlist.Id}`").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)) if (!int.TryParse(parts[1], out playlistNumber))
return; return;
var playlist = DbHandler.Instance.Connection.FindAsync<MusicPlaylist>( var playlist = DbHandler.Instance.FindOne<MusicPlaylist>(
p => p.Id == playlistNumber); p => p.Id == playlistNumber);
if (playlist == null) if (playlist == null)
@ -659,11 +659,11 @@ namespace NadekoBot.Modules.Music
return; return;
} }
var psis = await DbHandler.Instance.Connection.Table<PlaylistSongInfo>().Where(psi => var psis = DbHandler.Instance.FindAll<PlaylistSongInfo>(psi =>
psi.PlaylistId == playlist.Id).ToListAsync().ConfigureAwait(false); psi.PlaylistId == playlist.Id);
var songInfos = await Task.WhenAll(psis.Select(async psi => await DbHandler.Instance var songInfos = psis.Select(psi => DbHandler.Instance
.Connection.FindAsync<DataModels.SongInfo>(si => si.Id == psi.SongInfoId))).ConfigureAwait(false); .FindOne<DataModels.SongInfo>(si => si.Id == psi.SongInfoId));
await e.Channel.SendMessage($"`Attempting to load {songInfos.Count()} songs`").ConfigureAwait(false); await e.Channel.SendMessage($"`Attempting to load {songInfos.Count()} songs`").ConfigureAwait(false);
foreach (var si in songInfos) foreach (var si in songInfos)
@ -687,17 +687,17 @@ namespace NadekoBot.Modules.Music
.Alias(Prefix + "pls") .Alias(Prefix + "pls")
.Description($"Lists all playlists. Paginated. 20 per page. Default page is 0. |`{Prefix}pls 1`") .Description($"Lists all playlists. Paginated. 20 per page. Default page is 0. |`{Prefix}pls 1`")
.Parameter("num", ParameterType.Optional) .Parameter("num", ParameterType.Optional)
.Do(async e => .Do(e =>
{ {
int num = 0; int num = 0;
int.TryParse(e.GetArg("num"), out num); int.TryParse(e.GetArg("num"), out num);
if (num < 0) if (num < 0)
return; return;
var result = await DbHandler.Instance.GetPlaylistData(num); var result = DbHandler.Instance.GetPlaylistData(num);
if (result.Count == 0) if (result.Count == 0)
await e.Channel.SendMessage($"`No saved playlists found on page {num}`").ConfigureAwait(false); e.Channel.SendMessage($"`No saved playlists found on page {num}`").ConfigureAwait(false);
else else
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); 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") cgb.CreateCommand(Prefix + "deleteplaylist")
@ -711,9 +711,9 @@ namespace NadekoBot.Modules.Music
return; return;
var plnum = int.Parse(pl); var plnum = int.Parse(pl);
if (NadekoBot.IsOwner(e.User.Id)) if (NadekoBot.IsOwner(e.User.Id))
await DbHandler.Instance.Delete<MusicPlaylist>(plnum).ConfigureAwait(false); DbHandler.Instance.Delete<MusicPlaylist>(plnum);
else else
await DbHandler.Instance.DeleteWhere<MusicPlaylist>(mp => mp.Id == plnum && (long)e.User.Id == mp.CreatorId).ConfigureAwait(false); DbHandler.Instance.DeleteWhere<MusicPlaylist>(mp => mp.Id == plnum && (long)e.User.Id == mp.CreatorId);
await e.Channel.SendMessage("`Ok.` :ok:").ConfigureAwait(false); await e.Channel.SendMessage("`Ok.` :ok:").ConfigureAwait(false);
}); });
@ -773,13 +773,11 @@ namespace NadekoBot.Modules.Music
{ {
await e.Channel.SendMessage("Could not select song, likely wrong index"); await e.Channel.SendMessage("Could not select song, likely wrong index");
} } else
else
{ {
await e.Channel.SendMessage($"🎶`Selected song {selSong.SongInfo.Title}:` <{selSong.SongInfo.Query}>").ConfigureAwait(false); await e.Channel.SendMessage($"🎶`Selected song {selSong.SongInfo.Title}:` <{selSong.SongInfo.Query}>").ConfigureAwait(false);
} }
} } else
else
{ {
var curSong = musicPlayer.CurrentSong; var curSong = musicPlayer.CurrentSong;
if (curSong == null) if (curSong == null)

View File

@ -9,7 +9,6 @@ using System;
using System.Collections.Concurrent; using System.Collections.Concurrent;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading.Tasks;
namespace NadekoBot.Modules.Pokemon namespace NadekoBot.Modules.Pokemon
{ {
@ -40,10 +39,10 @@ namespace NadekoBot.Modules.Pokemon
return damage; return damage;
} }
private async Task<PokemonType> GetPokeType(ulong id) private PokemonType GetPokeType(ulong id)
{ {
var db = await DbHandler.Instance.GetAllRows<UserPokeTypes>().ConfigureAwait(false); var db = DbHandler.Instance.GetAllRows<UserPokeTypes>();
Dictionary<long, string> setTypes = db.ToDictionary(x => x.UserId, y => y.type); Dictionary<long, string> setTypes = db.ToDictionary(x => x.UserId, y => y.type);
if (setTypes.ContainsKey((long)id)) if (setTypes.ContainsKey((long)id))
{ {
@ -135,7 +134,7 @@ namespace NadekoBot.Modules.Pokemon
} }
//Check whether move can be used //Check whether move can be used
PokemonType userType = await GetPokeType(e.User.Id).ConfigureAwait(false); PokemonType userType = GetPokeType(e.User.Id);
var enabledMoves = userType.Moves; var enabledMoves = userType.Moves;
if (!enabledMoves.Contains(move.ToLowerInvariant())) if (!enabledMoves.Contains(move.ToLowerInvariant()))
@ -145,7 +144,7 @@ namespace NadekoBot.Modules.Pokemon
} }
//get target type //get target type
PokemonType targetType = await GetPokeType(target.Id).ConfigureAwait(false); PokemonType targetType = GetPokeType(target.Id);
//generate damage //generate damage
int damage = GetDamage(userType, targetType); int damage = GetDamage(userType, targetType);
//apply damage to target //apply damage to target
@ -200,7 +199,7 @@ namespace NadekoBot.Modules.Pokemon
.Description($"Lists the moves you are able to use | `{Prefix}ml`") .Description($"Lists the moves you are able to use | `{Prefix}ml`")
.Do(async e => .Do(async e =>
{ {
var userType = await GetPokeType(e.User.Id).ConfigureAwait(false); var userType = GetPokeType(e.User.Id);
var movesList = userType.Moves; var movesList = userType.Moves;
var str = $"**Moves for `{userType.Name}` type.**"; var str = $"**Moves for `{userType.Name}` type.**";
foreach (string m in movesList) foreach (string m in movesList)
@ -236,7 +235,7 @@ namespace NadekoBot.Modules.Pokemon
} }
//Payment~ //Payment~
var amount = 1; var amount = 1;
var pts = (await Classes.DbHandler.Instance.GetStateByUserId((long)e.User.Id).ConfigureAwait(false))?.Value ?? 0; var pts = Classes.DbHandler.Instance.GetStateByUserId((long)e.User.Id)?.Value ?? 0;
if (pts < amount) 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); 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);
@ -277,7 +276,7 @@ namespace NadekoBot.Modules.Pokemon
await e.Channel.SendMessage("No such person.").ConfigureAwait(false); await e.Channel.SendMessage("No such person.").ConfigureAwait(false);
return; return;
} }
var pType = await GetPokeType(usr.Id).ConfigureAwait(false); var pType = GetPokeType(usr.Id);
await e.Channel.SendMessage($"Type of {usr.Name} is **{pType.Name.ToLowerInvariant()}**{pType.Icon}").ConfigureAwait(false); await e.Channel.SendMessage($"Type of {usr.Name} is **{pType.Name.ToLowerInvariant()}**{pType.Icon}").ConfigureAwait(false);
}); });
@ -296,7 +295,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); 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; return;
} }
if (targetType == await GetPokeType(e.User.Id).ConfigureAwait(false)) if (targetType == GetPokeType(e.User.Id))
{ {
await e.Channel.SendMessage($"Your type is already {targetType.Name.ToLowerInvariant()}{targetType.Icon}").ConfigureAwait(false); await e.Channel.SendMessage($"Your type is already {targetType.Name.ToLowerInvariant()}{targetType.Icon}").ConfigureAwait(false);
return; return;
@ -304,7 +303,7 @@ namespace NadekoBot.Modules.Pokemon
//Payment~ //Payment~
var amount = 1; var amount = 1;
var pts = (await DbHandler.Instance.GetStateByUserId((long)e.User.Id).ConfigureAwait(false))?.Value ?? 0; var pts = DbHandler.Instance.GetStateByUserId((long)e.User.Id)?.Value ?? 0;
if (pts < amount) 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); 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);
@ -312,19 +311,19 @@ namespace NadekoBot.Modules.Pokemon
} }
await FlowersHandler.RemoveFlowers(e.User, $"set usertype to {targetTypeStr}", amount).ConfigureAwait(false); await FlowersHandler.RemoveFlowers(e.User, $"set usertype to {targetTypeStr}", amount).ConfigureAwait(false);
//Actually changing the type here //Actually changing the type here
var preTypes = await DbHandler.Instance.GetAllRows<UserPokeTypes>().ConfigureAwait(false); var preTypes = DbHandler.Instance.GetAllRows<UserPokeTypes>();
Dictionary<long, int> Dict = preTypes.ToDictionary(x => x.UserId, y => y.Id.Value); Dictionary<long, int> Dict = preTypes.ToDictionary(x => x.UserId, y => y.Id.Value);
if (Dict.ContainsKey((long)e.User.Id)) if (Dict.ContainsKey((long)e.User.Id))
{ {
//delete previous type //delete previous type
await DbHandler.Instance.Delete<UserPokeTypes>(Dict[(long)e.User.Id]).ConfigureAwait(false); DbHandler.Instance.Delete<UserPokeTypes>(Dict[(long)e.User.Id]);
} }
await DbHandler.Instance.Connection.InsertAsync(new UserPokeTypes DbHandler.Instance.Connection.Insert(new UserPokeTypes
{ {
UserId = (long)e.User.Id, UserId = (long)e.User.Id,
type = targetType.Name type = targetType.Name
}).ConfigureAwait(false); }, typeof(UserPokeTypes));
//Now for the response //Now for the response

View File

@ -28,7 +28,7 @@ namespace NadekoBot.Modules.Utility.Commands
public Remind(DiscordModule module) : base(module) public Remind(DiscordModule module) : base(module)
{ {
var remList = DbHandler.Instance.GetAllRows<Reminder>().GetAwaiter().GetResult(); var remList = DbHandler.Instance.GetAllRows<Reminder>();
reminders = remList.Select(StartNewReminder).ToList(); reminders = remList.Select(StartNewReminder).ToList();
} }
@ -73,7 +73,7 @@ namespace NadekoBot.Modules.Utility.Commands
} }
finally finally
{ {
await DbHandler.Instance.Delete<Reminder>(r.Id.Value).ConfigureAwait(false); DbHandler.Instance.Delete<Reminder>(r.Id.Value);
t.Stop(); t.Stop();
t.Dispose(); t.Dispose();
} }
@ -171,7 +171,7 @@ namespace NadekoBot.Modules.Utility.Commands
UserId = (long)e.User.Id, UserId = (long)e.User.Id,
ServerId = (long)e.Server.Id ServerId = (long)e.Server.Id
}; };
await DbHandler.Instance.Connection.InsertAsync(rem).ConfigureAwait(false); DbHandler.Instance.Connection.Insert(rem);
reminders.Add(StartNewReminder(rem)); reminders.Add(StartNewReminder(rem));