Example #1
0
        public async Task LogBankCreateAsync(GuildBank bank, ulong modId)
        {
            // Do not log if there is nowhere to log.
            if (bank.LogChannelId == null)
            {
                return;
            }

            var guild = await _client.GetGuildAsync(bank.GuildId);

            var channel = (ISocketMessageChannel)await guild.GetChannelAsync((ulong)bank.LogChannelId);

            var admin = await guild.GetUserAsync(modId);

            var logMessage = new EmbedBuilder()
                             .WithAuthor(admin)
                             .WithFooter($"Req. by {admin.Username}#{admin.Discriminator}");

            logMessage.WithDescription("The following bank was created:");
            logMessage
            .AddField("Name", $"{bank.Name}", true)
            .AddField("Log Channel", $"<#{bank.LogChannelId}>", true);

            await channel.SendMessageAsync(embed : logMessage.Build());
        }
Example #2
0
        public async Task LogBankItemQuantityUpdateAsync(GuildBank bank, GuildBankItem item, double amount, ulong modId, ulong?transactorId = null)
        {
            // Do not log if there is nowhere to log.
            if (bank.LogChannelId == null)
            {
                return;
            }

            var guild = await _client.GetGuildAsync(bank.GuildId);

            var channel = (ISocketMessageChannel)await guild.GetChannelAsync((ulong)bank.LogChannelId);

            var admin = await guild.GetUserAsync(modId);

            var transactor = await guild.GetUserAsync(transactorId ?? modId);

            var logMessage = new EmbedBuilder()
                             .WithAuthor(transactor)
                             .WithFooter($"Req. by {admin.Username}#{admin.Discriminator}");

            try { logMessage.WithThumbnailUrl(item.ImageUrl); }
            catch (ArgumentException) { /* URL is not well formed. Ignore error, will not display image as it wont work in the first place. */ }

            var action = amount > 0 ? "Picked up" : "Deposited";

            logMessage.WithDescription($"{action} **{amount}** **{item.Name}** from **{bank.Name}**. New Total: **{item.Quantity}**.");

            await channel.SendMessageAsync(embed : logMessage.Build()).ConfigureAwait(false);
        }
Example #3
0
        public async Task LogBankItemDeleteAsync(GuildBank bank, GuildBankItem item, ulong modId)
        {
            // Do not log if there is nowhere to log.
            if (bank.LogChannelId == null)
            {
                return;
            }

            var guild = await _client.GetGuildAsync(bank.GuildId);

            var channel = (ISocketMessageChannel)await guild.GetChannelAsync((ulong)bank.LogChannelId);

            var admin = await guild.GetUserAsync(modId);

            var logMessage = new EmbedBuilder()
                             .WithAuthor(admin)
                             .WithFooter($"Req. by {admin.Username}#{admin.Discriminator}");

            logMessage.WithDescription($"The following item was deleted from bank **{bank.Name}**:");
            logMessage
            .AddField("Name", item.Name, true)
            .AddField("Description", item.Description ?? "N/A", true)
            .AddField("Quantity", item.Quantity, true)
            .AddField("Value", item.Value, true);

            try { logMessage.WithThumbnailUrl(item.ImageUrl); }
            catch (ArgumentException) { /* URL is not well formed. Ignore error, will not display image as it wont work in the first place. */ }

            await channel.SendMessageAsync(embed : logMessage.Build());
        }
Example #4
0
        public async Task UpdateBankItemAsync(GuildBank bank, int itemId, ulong adminId, Action <GuildBankItem> changes, ulong?transactorId = null)
        {
            // Get the item.
            var item = await GetBankItemAsync(bank, itemId);

            // Check if item exists and is part of the bank.
            if (item == null || item.GuildBankId != bank.Id)
            {
                throw new BankItemNotFoundException();
            }

            // Create a copy for logging purposes.
            var oldItem = item.MemberwiseClone();

            // Apply changes.
            changes(item);

            // Ensure core values weren't changed.
            item.Id          = oldItem.Id;
            item.GuildBankId = oldItem.GuildBankId;

            // Log changes.
            await _transactions.LogBankItemUpdateAsync(bank, oldItem, item, adminId);

            // Save Changes
            await _context.SaveChangesAsync();
        }
Example #5
0
        public async Task <IActionResult> EditBank(ulong guildId, int bankId,
                                                   [Bind(nameof(GuildBank.Name), nameof(GuildBank.LogChannelId), nameof(GuildBank.ModeratorRoleId))]
                                                   GuildBank bank)
        {
            var userId = User.GetId();

            // Ensure user has admin rights
            if (!await _client.ValidateGuildAdminAsync(userId, guildId))
            {
                throw new UserNotGuildAdminException();
            }

            // If not renaming this would always return itself. Check for id difference instead.
            var dbBank = await _bank.GetGuildBankAsync(guildId, bank.Name);

            if (dbBank != null && dbBank.Id != bankId)
            {
                throw new BankNameAlreadyExistsException();
            }

            await _bank.UpdateGuildBankAsync(guildId, bankId, userId, b =>
            {
                b.Name            = bank.Name;
                b.LogChannelId    = bank.LogChannelId;
                b.ModeratorRoleId = bank.ModeratorRoleId;
            });

            return(Ok());
        }
Example #6
0
        public async Task LogBankItemUpdateAsync(GuildBank bank, GuildBankItem oldItem, GuildBankItem newItem, ulong modId)
        {
            // Do not log if there is nowhere to log.
            if (bank.LogChannelId == null)
            {
                return;
            }

            var guild = await _client.GetGuildAsync(bank.GuildId);

            var channel = (ISocketMessageChannel)await guild.GetChannelAsync((ulong)bank.LogChannelId);

            var admin = await guild.GetUserAsync(modId);

            var logMessage = new EmbedBuilder()
                             .WithAuthor(admin)
                             .WithFooter($"Req. by {admin.Username}#{admin.Discriminator}");

            logMessage.WithDescription($"The item **{oldItem.Name}** from bank **{bank.Name}** was modified:");

            try { logMessage.WithThumbnailUrl(oldItem.ImageUrl); }
            catch (ArgumentException) { /* URL is not well formed. Ignore error, will not display image as it wont work in the first place. */ }

            var imgChanged = false;

            if (oldItem.ImageUrl != newItem.ImageUrl)
            {
                try
                {
                    imgChanged = true;
                    logMessage.WithImageUrl(newItem.ImageUrl);
                    logMessage.AddField("Image", newItem.ImageUrl, true);
                }
                catch (ArgumentException) { /* URL is not well formed. Ignore error, will not display image as it wont work in the first place. */ }
            }

            if (oldItem.Name != newItem.Name)
            {
                logMessage.AddField("Name", $"{oldItem.Name} -> {newItem.Name}", true);
            }
            if (oldItem.Description != newItem.Description)
            {
                logMessage.AddField("Description", $"{oldItem.Description ?? "N/A"} -> {newItem.Description ?? "N/A"}", true);
            }
            if (Math.Abs(oldItem.Quantity - newItem.Quantity) > 0.000001)
            {
                logMessage.AddField("Quantity", $"{oldItem.Quantity} -> {newItem.Quantity}", true);
            }
            if (Math.Abs(oldItem.Value - newItem.Value) > 0.000001)
            {
                logMessage.AddField("Value", $"{oldItem.Value} -> {newItem.Value}", true);
            }

            if (logMessage.Fields.Count > 0 || imgChanged)
            {
                await channel.SendMessageAsync(embed : logMessage.Build()).ConfigureAwait(false);
            }
        }
Example #7
0
        public Task <List <GuildBankItem> > GetBankItemsAsync(GuildBank bank, Func <IQueryable <GuildBankItem>, IQueryable <GuildBankItem> >?options = null)
        {
            var items = _context.GuildBankItems as IQueryable <GuildBankItem>;

            if (options != null)
            {
                items = options.Invoke(items);
            }
            return(items.Where(u => u.GuildBankId == bank.Id).ToListAsync());
        }
Example #8
0
        public async Task <GuildBankItem?> GetBankItemAsync(GuildBank bank, string itemName, Func <IQueryable <GuildBankItem>, IQueryable <GuildBankItem> >?options = null)
        {
            var items = _context.GuildBankItems as IQueryable <GuildBankItem>;

            if (options != null)
            {
                items = options.Invoke(items);
            }
            return(await items.SingleOrDefaultAsync(i => i.GuildBankId == bank.Id && i.Name == itemName));
        }
Example #9
0
        public async Task LogBankUpdateAsync(GuildBank oldBank, GuildBank newBank, ulong modId)
        {
            // Do not log if there is nowhere to log.
            if (newBank.LogChannelId == null && oldBank.LogChannelId == null)
            {
                return;
            }

            var guild = await _client.GetGuildAsync(oldBank.GuildId);

            var admin = await guild.GetUserAsync(modId);

            // Special case: Log channel change in old channel and log other changes in the updated channel.
            // Ensure that old bank has a log channel.
            // Ensure that the log channel ids differ.
            if (oldBank.LogChannelId != null && oldBank.LogChannelId != newBank.LogChannelId)
            {
                var c = (ISocketMessageChannel)await guild.GetChannelAsync((ulong)oldBank.LogChannelId);

                var comment = newBank.LogChannelId == null
                    ? $"Log channel for bank **{oldBank.Name}** was removed."
                    : $"Log channel for bank **{oldBank.Name}** was changed to <#{newBank.LogChannelId}>.";
                try
                {
                    await c.SendMessageAsync(embed : new EmbedBuilder()
                                             .WithAuthor(admin)
                                             .WithFooter($"Req. by {admin.Username}#{admin.Discriminator}")
                                             .WithDescription(comment).Build());
                }
                catch (HttpException) { /* Ignore error. Bot most likely does not have access to previous channel anymore. No point disallowing log channel change. */ }
            }

            // Ensure that the updated bank has a log channel.
            if (newBank.LogChannelId == null)
            {
                return;
            }

            var channel = (ISocketMessageChannel)await guild.GetChannelAsync((ulong)newBank.LogChannelId);

            // There is only one value to edit.
            if (oldBank.Name != newBank.Name)
            {
                var logMessage = new EmbedBuilder()
                                 .WithAuthor(admin)
                                 .WithFooter($"Req. by {admin.Username}#{admin.Discriminator}");

                logMessage.WithDescription($"The bank **{oldBank.Name}** was modified:");
                logMessage.AddField("Name", $"{oldBank.Name} -> {newBank.Name}", true);
                await channel.SendMessageAsync(embed : logMessage.Build());
            }
        }
Example #10
0
        public async Task RemoveBankItemAsync(GuildBank bank, int itemId, ulong moderatorId)
        {
            // Get the item.
            var item = await GetBankItemAsync(bank, itemId);

            // Check if item exists and is part of the bank.
            if (item == null || item.GuildBankId != bank.Id)
            {
                throw new BankItemNotFoundException();
            }

            // Remove from database.
            _context.Remove(item);

            // Log removal.
            await _transactions.LogBankItemDeleteAsync(bank, item, moderatorId);

            await _context.SaveChangesAsync();
        }
Example #11
0
        /// <summary>
        /// Validates if the user has access write access to the guild bank.
        /// </summary>
        /// <param name="bank">Bank to check access of.</param>
        /// <param name="userId">Id of user.</param>
        /// <returns>Corresponding HTTP error result. null if user has write access.</returns>
        private async Task <bool> ValidateWriteAccess(GuildBank bank, ulong userId)
        {
            // Get the guild and check if it is present.
            var guild = await _client.GetGuildAsync(bank.GuildId);

            if (guild == null)
            {
                throw new GuildNotFoundException();
            }

            // Check if user even exists in the guild.
            var user = await guild.GetUserAsync(userId);

            if (user == null)
            {
                throw new UserNotFoundException();
            }

            // Check if user has write access to the bank.
            return(user.RoleIds.Any(r => r == bank.ModeratorRoleId) || user.GuildPermissions.Administrator);
        }
Example #12
0
        public async Task UpdateBankItemQuantityAsync(GuildBank bank, int itemId, ulong adminId, double deltaQuantity,
                                                      ulong?transactorId = null)
        {
            // Get the item.
            var item = await GetBankItemAsync(bank, itemId);

            // Check if item exists and is part of the bank.
            if (item == null || item.GuildBankId != bank.Id)
            {
                throw new BankItemNotFoundException();
            }

            // Apply quantity change.
            item.Quantity += deltaQuantity;

            // Log changes.
            await _transactions.LogBankItemQuantityUpdateAsync(bank, item, deltaQuantity, adminId);

            // Save Changes
            await _context.SaveChangesAsync();
        }
Example #13
0
        public async Task <GuildBankItem> CreateBankItemAsync(GuildBank bank, GuildBankItem item, ulong adminId)
        {
            if (item.Name == null)
            {
                throw new NameNotProvidedException();
            }

            // Ensure item is in the correct bank.
            item.GuildBankId = bank.Id;

            // Add the bank to database.
            _context.GuildBankItems.Add(item);

            // Log changes.
            await _transactions.LogBankItemCreateAsync(bank, item, adminId);

            // Save Changes
            await _context.SaveChangesAsync();

            // Lastly return the item.
            return(item);
        }
Example #14
0
        public async Task <IActionResult> CreateGuild(Guild guild)
        {
            if (ModelState.IsValid)
            {
                var ssPlayerModel = HttpContext.Session.GetObject <PlayerModel>("ssPlayerModel");

                //Create new guild
                Guild NewGuild = new Guild();
                NewGuild            = guild;
                NewGuild.Leader     = ssPlayerModel.Nickname;
                NewGuild.PlayerList = ssPlayerModel.Nickname;

                var guildnammecheck = await _db.Guild.FirstOrDefaultAsync(u => u.Name == NewGuild.Name);

                if (guildnammecheck == null)
                {
                    _db.Guild.Add(NewGuild);

                    //Create Bank for new guild
                    GuildBank NewGuildBank = new GuildBank();
                    NewGuildBank.GuildId = NewGuild.Id;
                    _db.GuildBank.Add(NewGuildBank);

                    //Change player GuildName
                    ssPlayerModel.GuildName = NewGuild.Name;
                    ssPlayerModel.GuildRank = "Leader";
                    _db.PlayerModel.Update(ssPlayerModel);
                }
                else
                {
                    return(RedirectToAction("Index"));
                }

                await _db.SaveChangesAsync();
            }

            return(RedirectToAction("Index"));
        }
Example #15
0
        public async Task LogBankDeleteAsync(GuildBank bank, ulong modId)
        {
            // Do not log if there is nowhere to log.
            if (bank.LogChannelId == null)
            {
                return;
            }

            var guild = await _client.GetGuildAsync(bank.GuildId);

            var channel = (ISocketMessageChannel)await guild.GetChannelAsync((ulong)bank.LogChannelId);

            var admin = await guild.GetUserAsync(modId);

            var logMessage = new EmbedBuilder()
                             .WithAuthor(admin)
                             .WithFooter($"Req. by {admin.Username}#{admin.Discriminator}");

            logMessage.WithDescription("The following bank was deleted:");

            logMessage
            .AddField("Name", $"{bank.Name}", true)
            .AddField("Log Channel", $"<#{bank.LogChannelId}>", true);

            await channel.SendMessageAsync(embed : logMessage.Build());

            // Offload logging of item deletions to another thread.
            _ = Task.Factory.StartNew(async() =>
            {
                if (bank.Contents != null)
                {
                    foreach (var item in bank.Contents)
                    {
                        await LogBankItemDeleteAsync(bank, item, modId);
                    }
                }
            });
        }
Example #16
0
        public async Task <GuildBank> CreateGuildBankAsync(ulong guildId, ulong adminId, GuildBank bank)
        {
            if (string.IsNullOrWhiteSpace(bank.Name))
            {
                throw new NameNotProvidedException();
            }

            // Ensure foreign key constraint is not violated.
            var guild = await _context.Guilds.FindAsync(guildId);

            if (guild == null)
            {
                guild = new Guild(guildId);
                _context.Guilds.Add(guild);
            }

            // Ensure the added bank's guild id is correct.
            bank.GuildId = guildId;

            // Add the bank
            _context.GuildBanks.Add(bank);

            // Log the creation of the bank
            await _transactions.LogBankCreateAsync(bank, adminId);

            // Save changes
            await _context.SaveChangesAsync();

            // Return the added bank
            return(bank);
        }