From 9354e5f83e62cdf18c7f6578f608ecba84551f60 Mon Sep 17 00:00:00 2001 From: runebaas Date: Sat, 19 May 2018 10:49:01 +0200 Subject: [PATCH] Change User Model and Add poll model, port !poll but ended up disabling it --- Geekbot.net/Commands/Admin/Mod.cs | 2 +- Geekbot.net/Commands/Utils/{Poll => }/Poll.cs | 103 +++++++++++------- .../Commands/Utils/Poll/PollDataDto.cs | 13 --- .../Commands/Utils/Poll/PollResultDto.cs | 8 -- Geekbot.net/Database/DatabaseContext.cs | 3 +- Geekbot.net/Database/DatabaseInitializer.cs | 2 +- Geekbot.net/Database/Models/PollModel.cs | 27 +++++ .../Database/Models/PollQuestionModel.cs | 16 +++ Geekbot.net/Database/Models/UserModel.cs | 3 +- .../Database/Models/UserSettingsModel.cs | 15 --- .../Database/Models/UserUsedNamesModel.cs | 15 +++ Geekbot.net/Database/RedisMigration.cs | 16 +-- .../Lib/UserRepository/UserRepository.cs | 7 +- 13 files changed, 138 insertions(+), 92 deletions(-) rename Geekbot.net/Commands/Utils/{Poll => }/Poll.cs (63%) delete mode 100644 Geekbot.net/Commands/Utils/Poll/PollDataDto.cs delete mode 100644 Geekbot.net/Commands/Utils/Poll/PollResultDto.cs create mode 100644 Geekbot.net/Database/Models/PollModel.cs create mode 100644 Geekbot.net/Database/Models/PollQuestionModel.cs delete mode 100644 Geekbot.net/Database/Models/UserSettingsModel.cs create mode 100644 Geekbot.net/Database/Models/UserUsedNamesModel.cs diff --git a/Geekbot.net/Commands/Admin/Mod.cs b/Geekbot.net/Commands/Admin/Mod.cs index 2e4ad24..a200cac 100644 --- a/Geekbot.net/Commands/Admin/Mod.cs +++ b/Geekbot.net/Commands/Admin/Mod.cs @@ -35,7 +35,7 @@ namespace Geekbot.net.Commands.Admin var userRepo = _userRepository.Get(user.Id); var sb = new StringBuilder(); sb.AppendLine($":bust_in_silhouette: {user.Username} has been known as:"); - foreach (var name in userRepo.UsedNames) sb.AppendLine($"- `{name}`"); + foreach (var name in userRepo.UsedNames) sb.AppendLine($"- `{name.Name}`"); await ReplyAsync(sb.ToString()); } catch (Exception e) diff --git a/Geekbot.net/Commands/Utils/Poll/Poll.cs b/Geekbot.net/Commands/Utils/Poll.cs similarity index 63% rename from Geekbot.net/Commands/Utils/Poll/Poll.cs rename to Geekbot.net/Commands/Utils/Poll.cs index aad6eee..585c1fb 100644 --- a/Geekbot.net/Commands/Utils/Poll/Poll.cs +++ b/Geekbot.net/Commands/Utils/Poll.cs @@ -5,28 +5,27 @@ using System.Text; using System.Threading.Tasks; using Discord; using Discord.Commands; +using Geekbot.net.Database; +using Geekbot.net.Database.Models; using Geekbot.net.Lib.Converters; using Geekbot.net.Lib.ErrorHandling; using Geekbot.net.Lib.Extensions; using Geekbot.net.Lib.UserRepository; -using Newtonsoft.Json; -using StackExchange.Redis; -namespace Geekbot.net.Commands.Utils.Poll +namespace Geekbot.net.Commands.Utils { [Group("poll")] public class Poll : ModuleBase { private readonly IEmojiConverter _emojiConverter; private readonly IErrorHandler _errorHandler; - private readonly IDatabase _redis; + private readonly DatabaseContext _database; private readonly IUserRepository _userRepository; - public Poll(IErrorHandler errorHandler, IDatabase redis, IEmojiConverter emojiConverter, - IUserRepository userRepository) + public Poll(IErrorHandler errorHandler, DatabaseContext database, IEmojiConverter emojiConverter, IUserRepository userRepository) { _errorHandler = errorHandler; - _redis = redis; + _database = database; _emojiConverter = emojiConverter; _userRepository = userRepository; } @@ -38,7 +37,7 @@ namespace Geekbot.net.Commands.Utils.Poll try { var currentPoll = GetCurrentPoll(); - if (currentPoll.Question == null || currentPoll.IsFinshed) + if (currentPoll.Question == null) { await ReplyAsync( "There is no poll in this channel ongoing at the moment\r\nYou can create one with `!poll create question;option1;option2;option3`"); @@ -60,6 +59,9 @@ namespace Geekbot.net.Commands.Utils.Poll { try { + await ReplyAsync("Poll creation currently disabled"); + return; + var currentPoll = GetCurrentPoll(); if (currentPoll.Question != null && !currentPoll.IsFinshed) { @@ -75,34 +77,46 @@ namespace Geekbot.net.Commands.Utils.Poll return; } - var eb = new EmbedBuilder(); - eb.Title = $"Poll by {Context.User.Username}"; var question = pollList[0]; - eb.Description = question; pollList.RemoveAt(0); + + var eb = new EmbedBuilder + { + Title = $"Poll by {Context.User.Username}", + Description = question + }; + + var options = new List(); var i = 1; pollList.ForEach(option => { + options.Add(new PollQuestionModel() + { + OptionId = i, + OptionText = option + }); eb.AddInlineField($"Option {_emojiConverter.NumberToEmoji(i)}", option); i++; }); var pollMessage = await ReplyAsync("", false, eb.Build()); + + var poll = new PollModel() + { + Creator = Context.User.Id.AsLong(), + MessageId = pollMessage.Id.AsLong(), + IsFinshed = false, + Question = question, + Options = options + }; + _database.Polls.Add(poll); + i = 1; pollList.ForEach(option => { pollMessage.AddReactionAsync(new Emoji(_emojiConverter.NumberToEmoji(i))); + Task.Delay(500); i++; }); - var poll = new PollDataDto - { - Creator = Context.User.Id, - MessageId = pollMessage.Id, - IsFinshed = false, - Question = question, - Options = pollList - }; - var pollJson = JsonConvert.SerializeObject(poll); - _redis.HashSet($"{Context.Guild.Id}:Polls", new[] {new HashEntry(Context.Channel.Id, pollJson)}); } catch (Exception e) { @@ -123,15 +137,14 @@ namespace Geekbot.net.Commands.Utils.Poll return; } - var results = await GetPollResults(currentPoll); + currentPoll = await GetPollResults(currentPoll); var sb = new StringBuilder(); sb.AppendLine("**Poll Results**"); sb.AppendLine(currentPoll.Question); - foreach (var result in results) sb.AppendLine($"{result.VoteCount} - {result.Option}"); + foreach (var result in currentPoll.Options) sb.AppendLine($"{result.Votes} - {result.OptionText}"); await ReplyAsync(sb.ToString()); currentPoll.IsFinshed = true; - var pollJson = JsonConvert.SerializeObject(currentPoll); - _redis.HashSet($"{Context.Guild.Id}:Polls", new[] {new HashEntry(Context.Channel.Id, pollJson)}); + _database.Polls.Update(currentPoll); } catch (Exception e) { @@ -139,41 +152,49 @@ namespace Geekbot.net.Commands.Utils.Poll } } - private PollDataDto GetCurrentPoll() + private PollModel GetCurrentPoll() { try { - var currentPoll = _redis.HashGet($"{Context.Guild.Id}:Polls", Context.Channel.Id); - return JsonConvert.DeserializeObject(currentPoll.ToString()); + var currentPoll = _database.Polls.FirstOrDefault(poll => + poll.ChannelId.Equals(Context.Channel.Id.AsLong()) && + poll.GuildId.Equals(Context.Guild.Id.AsLong()) + ); + return currentPoll ?? new PollModel(); + } catch { - return new PollDataDto(); + return new PollModel(); } } - private async Task> GetPollResults(PollDataDto poll) + private async Task GetPollResults(PollModel poll) { - var message = (IUserMessage) await Context.Channel.GetMessageAsync(poll.MessageId); - var results = new List(); + var message = (IUserMessage) await Context.Channel.GetMessageAsync(poll.MessageId.AsUlong()); + + var results = new Dictionary(); foreach (var r in message.Reactions) + { try { - var option = int.Parse(r.Key.Name.ToCharArray()[0].ToString()); - var result = new PollResultDto - { - Option = poll.Options[option - 1], - VoteCount = r.Value.ReactionCount - }; - results.Add(result); + results.Add(r.Key.Name.ToCharArray()[0], r.Value.ReactionCount); } catch { // ignored } + } + + foreach (var q in poll.Options) + { + q.Votes = results.FirstOrDefault(e => e.Key.Equals(q.OptionId)).Value; + } - results.Sort((x, y) => y.VoteCount.CompareTo(x.VoteCount)); - return results; + return poll; + +// var sortedValues = results.OrderBy(e => e.Value); +// return sortedValues; } } } \ No newline at end of file diff --git a/Geekbot.net/Commands/Utils/Poll/PollDataDto.cs b/Geekbot.net/Commands/Utils/Poll/PollDataDto.cs deleted file mode 100644 index 3d21479..0000000 --- a/Geekbot.net/Commands/Utils/Poll/PollDataDto.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System.Collections.Generic; - -namespace Geekbot.net.Commands.Utils.Poll -{ - internal class PollDataDto - { - public ulong Creator { get; set; } - public ulong MessageId { get; set; } - public bool IsFinshed { get; set; } - public string Question { get; set; } - public List Options { get; set; } - } -} \ No newline at end of file diff --git a/Geekbot.net/Commands/Utils/Poll/PollResultDto.cs b/Geekbot.net/Commands/Utils/Poll/PollResultDto.cs deleted file mode 100644 index b4f14a2..0000000 --- a/Geekbot.net/Commands/Utils/Poll/PollResultDto.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace Geekbot.net.Commands.Utils.Poll -{ - internal class PollResultDto - { - public string Option { get; set; } - public int VoteCount { get; set; } - } -} \ No newline at end of file diff --git a/Geekbot.net/Database/DatabaseContext.cs b/Geekbot.net/Database/DatabaseContext.cs index e9de32c..ab786b1 100644 --- a/Geekbot.net/Database/DatabaseContext.cs +++ b/Geekbot.net/Database/DatabaseContext.cs @@ -16,7 +16,6 @@ namespace Geekbot.net.Database public DbSet Slaps { get; set; } public DbSet Globals { get; set; } public DbSet RoleSelfService { get; set; } - - // public DbSet UserSettings { get; set; } + public DbSet Polls { get; set; } } } \ No newline at end of file diff --git a/Geekbot.net/Database/DatabaseInitializer.cs b/Geekbot.net/Database/DatabaseInitializer.cs index 83660bb..7ae6cc7 100644 --- a/Geekbot.net/Database/DatabaseInitializer.cs +++ b/Geekbot.net/Database/DatabaseInitializer.cs @@ -40,7 +40,7 @@ namespace Geekbot.net.Database }); } database.Database.EnsureCreated(); - database.Database.Migrate(); + if(!_runParameters.InMemory) database.Database.Migrate(); } catch (Exception e) { diff --git a/Geekbot.net/Database/Models/PollModel.cs b/Geekbot.net/Database/Models/PollModel.cs new file mode 100644 index 0000000..3b12410 --- /dev/null +++ b/Geekbot.net/Database/Models/PollModel.cs @@ -0,0 +1,27 @@ +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; + +namespace Geekbot.net.Database.Models +{ + public class PollModel + { + [Key] + public int Id { get; set; } + + [Required] + public long GuildId { get; set; } + + [Required] + public long ChannelId { get; set; } + + public string Question { get; set; } + + public long Creator { get; set; } + + public long MessageId { get; set; } + + public List Options { get; set; } + + public bool IsFinshed { get; set; } + } +} \ No newline at end of file diff --git a/Geekbot.net/Database/Models/PollQuestionModel.cs b/Geekbot.net/Database/Models/PollQuestionModel.cs new file mode 100644 index 0000000..e251fe2 --- /dev/null +++ b/Geekbot.net/Database/Models/PollQuestionModel.cs @@ -0,0 +1,16 @@ +using System.ComponentModel.DataAnnotations; + +namespace Geekbot.net.Database.Models +{ + public class PollQuestionModel + { + [Key] + public int Id { get; set; } + + public int OptionId { get; set; } + + public string OptionText { get; set; } + + public int Votes { get; set; } + } +} \ No newline at end of file diff --git a/Geekbot.net/Database/Models/UserModel.cs b/Geekbot.net/Database/Models/UserModel.cs index f14ed61..b9c60ca 100644 --- a/Geekbot.net/Database/Models/UserModel.cs +++ b/Geekbot.net/Database/Models/UserModel.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace Geekbot.net.Database.Models @@ -24,6 +25,6 @@ namespace Geekbot.net.Database.Models public DateTimeOffset Joined { get; set; } - public string[] UsedNames { get; set; } + public List UsedNames { get; set; } } } \ No newline at end of file diff --git a/Geekbot.net/Database/Models/UserSettingsModel.cs b/Geekbot.net/Database/Models/UserSettingsModel.cs deleted file mode 100644 index 659ef1d..0000000 --- a/Geekbot.net/Database/Models/UserSettingsModel.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System.ComponentModel.DataAnnotations; - -namespace Geekbot.net.Database.Models -{ - public class UserSettingsModel - { - [Key] - public int Id { get; set; } - - [Required] - public long UserId { get; set; } - - // stuff to be added in the future - } -} \ No newline at end of file diff --git a/Geekbot.net/Database/Models/UserUsedNamesModel.cs b/Geekbot.net/Database/Models/UserUsedNamesModel.cs new file mode 100644 index 0000000..48ba873 --- /dev/null +++ b/Geekbot.net/Database/Models/UserUsedNamesModel.cs @@ -0,0 +1,15 @@ +using System; +using System.ComponentModel.DataAnnotations; + +namespace Geekbot.net.Database.Models +{ + public class UserUsedNamesModel + { + [Key] + public int Id { get; set; } + + public string Name { get; set; } + + public DateTimeOffset FirstSeen { get; set; } + } +} \ No newline at end of file diff --git a/Geekbot.net/Database/RedisMigration.cs b/Geekbot.net/Database/RedisMigration.cs index 005aa69..df2e90b 100644 --- a/Geekbot.net/Database/RedisMigration.cs +++ b/Geekbot.net/Database/RedisMigration.cs @@ -250,7 +250,7 @@ namespace Geekbot.net.Database case "ShowLeave": settings.ShowLeave = setting.Value.ToString() == "1"; break; - case "WikiDel": + case "ShowDelete": settings.ShowDelete = setting.Value.ToString() == "1"; break; case "WikiLang": @@ -272,9 +272,9 @@ namespace Geekbot.net.Database throw new NotImplementedException(); } } - catch + catch (Exception e) { - _logger.Warning(LogSource.Geekbot, $"Setting failed: {setting.Name} - {guild.Id}"); + _logger.Warning(LogSource.Geekbot, $"Setting failed: {setting.Name} - {guild.Id}", e); } } } @@ -297,7 +297,9 @@ namespace Geekbot.net.Database try { var namesSerialized = _redis.HashGet($"User:{user.Id}", "UsedNames").ToString(); - var names = Utf8Json.JsonSerializer.Deserialize(namesSerialized); + var names = namesSerialized != null + ? Utf8Json.JsonSerializer.Deserialize(namesSerialized) + : new string[] {user.Username}; _database.Users.AddIfNotExists(new UserModel() { UserId = user.Id.AsLong(), @@ -306,13 +308,13 @@ namespace Geekbot.net.Database AvatarUrl = user.GetAvatarUrl(ImageFormat.Auto, 1024), IsBot = user.IsBot, Joined = user.CreatedAt, - UsedNames = names + UsedNames = names.Select(name => new UserUsedNamesModel() {Name = name, FirstSeen = DateTimeOffset.Now}).ToList() }, model => model.UserId.Equals(user.Id.AsLong())); await _database.SaveChangesAsync(); } - catch + catch (Exception e) { - _logger.Warning(LogSource.Geekbot, $"User failed: {user.Username}"); + _logger.Warning(LogSource.Geekbot, $"User failed: {user.Username}", e); } } } diff --git a/Geekbot.net/Lib/UserRepository/UserRepository.cs b/Geekbot.net/Lib/UserRepository/UserRepository.cs index 263a2f3..b27a0a2 100644 --- a/Geekbot.net/Lib/UserRepository/UserRepository.cs +++ b/Geekbot.net/Lib/UserRepository/UserRepository.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Discord.WebSocket; @@ -36,10 +37,10 @@ namespace Geekbot.net.Lib.UserRepository savedUser.AvatarUrl = user.GetAvatarUrl() ?? ""; savedUser.IsBot = user.IsBot; savedUser.Joined = user.CreatedAt; - if (savedUser.UsedNames == null) savedUser.UsedNames = Enumerable.Empty().ToArray(); - if (!savedUser.UsedNames.Contains(user.Username)) + if (savedUser.UsedNames == null) savedUser.UsedNames = new List(); + if (!savedUser.UsedNames.Any(e => e.Name.Equals(user.Username))) { - savedUser.UsedNames = savedUser.UsedNames.Concat(new[] {user.Username}).ToArray(); + savedUser.UsedNames.Add(new UserUsedNamesModel { Name = user.Username, FirstSeen = DateTimeOffset.Now }); } if (isNew)