public async Task <IActionResult> PutSpecificItem([FromRoute] ulong guildId, [FromRoute] int caseId, [FromBody] ModCaseForPutDto newValue, [FromQuery] bool sendNotification = true, [FromQuery] bool handlePunishment = true)
        {
            await RequirePermission(guildId, caseId, APIActionPermission.Edit);

            Identity currentIdentity = await GetIdentity();

            if (!await currentIdentity.HasPermissionToExecutePunishment(guildId, newValue.PunishmentType))
            {
                throw new UnauthorizedException();
            }

            var repo = ModCaseRepository.CreateDefault(_serviceProvider, currentIdentity);

            ModCase modCase = await repo.GetModCase(guildId, caseId);

            modCase.Title       = newValue.Title;
            modCase.Description = newValue.Description;
            modCase.UserId      = newValue.UserId;
            if (newValue.OccuredAt.HasValue)
            {
                modCase.OccuredAt = newValue.OccuredAt.Value;
            }
            modCase.Labels            = newValue.Labels.Distinct().ToArray();
            modCase.Others            = newValue.Others;
            modCase.PunishmentType    = newValue.PunishmentType;
            modCase.PunishedUntil     = newValue.PunishedUntil;
            modCase.LastEditedByModId = currentIdentity.GetCurrentUser().Id;

            modCase = await repo.UpdateModCase(modCase, handlePunishment, sendNotification);

            return(Ok(modCase));
        }
        public async Task <IActionResult> CreateItem([FromRoute] ulong guildId, [FromRoute] int caseId, [FromBody] ModCaseCommentForCreateDto comment)
        {
            await RequirePermission(guildId, caseId, APIActionPermission.View);

            Identity currentIdentity = await GetIdentity();

            IUser currentUser = currentIdentity.GetCurrentUser();

            ModCase modCase = await ModCaseRepository.CreateDefault(_serviceProvider, currentIdentity).GetModCase(guildId, caseId);

            // suspects can only comment if last comment was not by him.
            if (!await currentIdentity.HasPermissionOnGuild(DiscordPermission.Moderator, guildId))
            {
                if (modCase.Comments.Any())
                {
                    if (modCase.Comments.Last().UserId == currentUser.Id)
                    {
                        throw new BaseAPIException("Already commented", APIError.LastCommentAlreadyFromSuspect);
                    }
                }
            }

            ModCaseComment createdComment = await ModCaseCommentRepository.CreateDefault(_serviceProvider, currentIdentity).CreateComment(guildId, caseId, comment.Message);

            return(StatusCode(201, new CommentsView(createdComment)));
        }
        public async Task <IActionResult> CreateItem([FromRoute] ulong guildId, [FromBody] ModCaseForCreateDto modCaseDto, [FromQuery] bool sendPublicNotification = true, [FromQuery] bool handlePunishment = true, [FromQuery] bool sendDmNotification = true)
        {
            Identity currentIdentity = await GetIdentity();

            if (!await currentIdentity.HasPermissionToExecutePunishment(guildId, modCaseDto.PunishmentType))
            {
                throw new UnauthorizedException();
            }

            ModCase newModCase = new()
            {
                Title       = modCaseDto.Title,
                Description = modCaseDto.Description,
                GuildId     = guildId,
                ModId       = currentIdentity.GetCurrentUser().Id,
                UserId      = modCaseDto.UserId,
                Labels      = modCaseDto.Labels.Distinct().ToArray(),
                Others      = modCaseDto.Others
            };

            if (modCaseDto.OccuredAt.HasValue)
            {
                newModCase.OccuredAt = modCaseDto.OccuredAt.Value;
            }
            newModCase.CreationType   = CaseCreationType.Default;
            newModCase.PunishmentType = modCaseDto.PunishmentType;
            newModCase.PunishedUntil  = modCaseDto.PunishedUntil;

            newModCase = await ModCaseRepository.CreateDefault(_serviceProvider, currentIdentity).CreateModCase(newModCase, handlePunishment, sendPublicNotification, sendDmNotification);

            return(StatusCode(201, newModCase));
        }
        public async Task <IActionResult> GetAllItems([FromRoute] ulong guildId, [FromQuery][Range(0, int.MaxValue)] int startPage = 0)
        {
            Identity currentIdentity = await GetIdentity();

            ulong userOnly = 0;

            if (!await currentIdentity.HasPermissionOnGuild(DiscordPermission.Moderator, guildId))
            {
                userOnly = currentIdentity.GetCurrentUser().Id;
            }
            // ========================================================
            List <CaseView> modCases = new();

            if (userOnly == 0)
            {
                modCases = (await ModCaseRepository.CreateDefault(_serviceProvider, currentIdentity).GetCasePagination(guildId, startPage)).Select(x => new CaseView(x)).ToList();
            }
            else
            {
                modCases = (await ModCaseRepository.CreateDefault(_serviceProvider, currentIdentity).GetCasePaginationFilteredForUser(guildId, userOnly, startPage)).Select(x => new CaseView(x)).ToList();
            }

            if (!(await GetRegisteredGuild(guildId)).PublishModeratorInfo)
            {
                if (!await currentIdentity.HasPermissionOnGuild(DiscordPermission.Moderator, guildId))
                {
                    foreach (var modCase in modCases)
                    {
                        modCase.RemoveModeratorInfo();
                    }
                }
            }

            return(Ok(modCases));
        }
        public async Task <IActionResult> Status()
        {
            Identity currentIdentity = await GetIdentity();

            if (!currentIdentity.IsSiteAdmin())
            {
                return(Unauthorized());
            }

            List <string> currentLogins = new();

            foreach (var login in _identityManager.GetCurrentIdentities())
            {
                if (login is DiscordOAuthIdentity)
                {
                    try
                    {
                        var user = login.GetCurrentUser();
                        if (user == null)
                        {
                            currentLogins.Add($"Invalid user.");
                        }
                        else
                        {
                            currentLogins.Add($"{user.Username}#{user.Discriminator}");
                        }
                    }
                    catch (Exception e)
                    {
                        _logger.LogError(e, "Error getting logged in user.");
                        currentLogins.Add($"Invalid user.");
                    }
                }
            }

            StatusRepository repo = StatusRepository.CreateDefault(_serviceProvider);

            StatusDetail botDetails = repo.GetBotStatus();
            StatusDetail dbDetails  = await repo.GetDbStatus();

            StatusDetail cacheDetails = repo.GetCacheStatus();

            return(Ok(new
            {
                botStatus = botDetails,
                dbStatus = dbDetails,
                cacheStatus = cacheDetails,
                loginsInLast15Minutes = currentLogins,
                defaultLanguage = _config.GetDefaultLanguage(),
                trackedInvites = await InviteRepository.CreateDefault(_serviceProvider).CountInvites(),
                modCases = await ModCaseRepository.CreateDefault(_serviceProvider, currentIdentity).CountAllCases(),
                guilds = await GuildConfigRepository.CreateDefault(_serviceProvider).CountGuildConfigs(),
                automodEvents = await AutoModerationEventRepository.CreateDefault(_serviceProvider).CountEvents(),
                userNotes = await UserNoteRepository.CreateWithBotIdentity(_serviceProvider).CountUserNotes(),
                userMappings = await UserMapRepository.CreateWithBotIdentity(_serviceProvider).CountAllUserMaps(),
                apiTokens = await TokenRepository.CreateDefault(_serviceProvider).CountTokens(),
                nextCache = _scheduler.GetNextCacheSchedule(),
                cachedDataFromDiscord = _discordAPI.GetCache().Keys
            }));
        }
Example #6
0
        public async Task DeleteConfirmation(string isPublic, string userID)
        {
            ModCaseRepository repo     = ModCaseRepository.CreateDefault(ServiceProvider, CurrentIdentity);
            List <ModCase>    modCases = await repo.GetCasesForGuildAndUser(Context.Guild.Id, Convert.ToUInt64(userID));

            modCases = modCases.Where(x => x.PunishmentActive && x.PunishmentType == PunishmentType.Mute).ToList();

            foreach (ModCase modCase in modCases)
            {
                await repo.DeleteModCase(modCase.GuildId, modCase.CaseId, false, true, isPublic == "1");
            }

            var castInteraction = Context.Interaction as SocketMessageComponent;

            var embed = castInteraction.Message.Embeds.FirstOrDefault().ToEmbedBuilder()
                        .WithColor(new Color(Convert.ToUInt32(int.Parse("7289da", NumberStyles.HexNumber)))); // discord blurple

            embed.Fields = new()
            {
                new EmbedFieldBuilder().WithName(Translator.T().CmdUndoResultTitle()).WithValue(Translator.T().CmdUndoUnmuteResultDeleted())
            };

            await castInteraction.UpdateAsync(message =>
            {
                message.Embed      = embed.Build();
                message.Components = new ComponentBuilder().Build();
            });
        }
Example #7
0
        public async Task <IActionResult> RestoreModCase([FromRoute] ulong guildId, [FromRoute] int caseId)
        {
            await RequirePermission(guildId, DiscordPermission.Moderator);

            ModCase modCase = await ModCaseRepository.CreateDefault(_serviceProvider, await GetIdentity()).RestoreCase(guildId, caseId);

            return(Ok(modCase));
        }
Example #8
0
        public async Task <IActionResult> DeleteModCase([FromRoute] ulong guildId, [FromRoute] int caseId)
        {
            Identity currentIdentity = await GetIdentity();

            await RequireSiteAdmin();

            await ModCaseRepository.CreateDefault(_serviceProvider, currentIdentity).DeleteModCase(guildId, caseId, true, true, false);

            return(Ok());
        }
        public async Task <IActionResult> DeleteSpecificItem([FromRoute] ulong guildId, [FromRoute] int caseId, [FromQuery] bool sendNotification = true, [FromQuery] bool handlePunishment = true, [FromQuery] bool forceDelete = false)
        {
            await RequirePermission(guildId, caseId, forceDelete?APIActionPermission.ForceDelete : APIActionPermission.Delete);

            Identity currentIdentity = await GetIdentity();

            ModCase modCase = await ModCaseRepository.CreateDefault(_serviceProvider, currentIdentity).DeleteModCase(guildId, caseId, forceDelete, handlePunishment, sendNotification);

            return(Ok(modCase));
        }
        public async Task <IActionResult> DeactivateCase([FromRoute] ulong guildId, [FromRoute] int caseId)
        {
            await RequirePermission(guildId, caseId, APIActionPermission.Edit);

            Identity currentIdentity = await GetIdentity();

            ModCase modCase = await ModCaseRepository.CreateDefault(_serviceProvider, currentIdentity).DeactivateModCase(guildId, caseId);

            return(Ok(modCase));
        }
Example #11
0
        public async Task Unmute([Summary("user", "User to unmute")] IUser user)
        {
            ModCaseRepository repo     = ModCaseRepository.CreateDefault(ServiceProvider, CurrentIdentity);
            List <ModCase>    modCases = (await repo.GetCasesForGuildAndUser(Context.Guild.Id, user.Id))
                                         .Where(x => x.PunishmentActive && x.PunishmentType == PunishmentType.Mute).ToList();

            if (modCases.Count == 0)
            {
                await Context.Interaction.RespondAsync(Translator.T().CmdUndoNoCases());

                return;
            }

            StringBuilder interactionString = new();

            interactionString.AppendLine(Translator.T().CmdUndoUnmuteFoundXCases(modCases.Count));
            foreach (ModCase modCase in modCases.Take(5))
            {
                int truncate = 50;
                if (modCase.PunishedUntil != null)
                {
                    truncate = 30;
                }
                interactionString.Append($"- [#{modCase.CaseId} - {modCase.Title.Truncate(truncate)}]");
                interactionString.Append($"({Config.GetBaseUrl()}/guilds/{modCase.GuildId}/cases/{modCase.CaseId})");
                if (modCase.PunishedUntil != null)
                {
                    interactionString.Append($" {Translator.T().Until()} {modCase.PunishedUntil.Value.ToDiscordTS()}");
                }
                interactionString.AppendLine();
            }
            if (modCases.Count > 5)
            {
                interactionString.AppendLine(Translator.T().AndXMore(modCases.Count - 5));
            }

            EmbedBuilder embed = new EmbedBuilder()
                                 .WithTitle(user.Username)
                                 .WithDescription(interactionString.ToString())
                                 .WithColor(Color.Orange);

            embed.AddField(Translator.T().CmdUndoResultTitle(), Translator.T().CmdUndoResultWaiting());

            var button = new ComponentBuilder()
                         .WithButton(Translator.T().CmdUndoUnmuteButtonsDelete(), $"unmute-delete:{user.Id}", ButtonStyle.Primary)
                         .WithButton(Translator.T().CmdUndoUnmuteButtonsDeactivate(), $"unmute-deactivate:{user.Id}", ButtonStyle.Secondary)
                         .WithButton(Translator.T().CmdUndoButtonsCancel(), "unmute-cancel", ButtonStyle.Danger);

            await Context.Interaction.RespondAsync(embed : embed.Build(), components : button.Build());

            IMessage responseMessage = await Context.Interaction.GetOriginalResponseAsync();
        }
Example #12
0
        public async Task Ban(
            [Summary("title", "The title of the modcase")] string title,
            [Summary("user", "User to punish")] IUser user,
            [Choice("None", 0)]
            [Choice("1 Hour", 1)]
            [Choice("1 Day", 24)]
            [Choice("1 Week", 168)]
            [Choice("1 Month", 672)]
            [Summary("hours", "How long the punishment should be")] long punishedForHours             = 0,
            [Summary("description", "The description of the modcase")] string description             = "",
            [Summary("dm-notification", "Whether to send a dm notification")] bool sendDmNotification = true,
            [Summary("public-notification", "Whether to send a public webhook notification")] bool sendPublicNotification    = true,
            [Summary("execute-punishment", "Whether to execute the punishment or just register it.")] bool executePunishment = true)
        {
            await Context.Interaction.DeferAsync(ephemeral : !sendPublicNotification);

            ModCase modCase = new()
            {
                Title   = title,
                GuildId = Context.Guild.Id,
                UserId  = user.Id,
                ModId   = CurrentIdentity.GetCurrentUser().Id
            };

            if (string.IsNullOrEmpty(description))
            {
                modCase.Description = title;
            }
            else
            {
                modCase.Description = description;
            }
            modCase.PunishmentType   = PunishmentType.Ban;
            modCase.PunishmentActive = executePunishment;
            modCase.PunishedUntil    = DateTime.UtcNow.AddHours(punishedForHours);
            if (punishedForHours == 0)
            {
                modCase.PunishedUntil = null; // Permanent ban.
            }
            modCase.CreationType = CaseCreationType.ByCommand;

            ModCase created = await ModCaseRepository.CreateDefault(ServiceProvider, CurrentIdentity).CreateModCase(modCase, executePunishment, sendPublicNotification, sendDmNotification);

            string url = $"{Config.GetBaseUrl()}/guilds/{created.GuildId}/cases/{created.CaseId}";
            await Context.Interaction.ModifyOriginalResponseAsync((MessageProperties msg) =>
            {
                msg.Content = Translator.T().CmdPunish(created.CaseId, url);
            });;
        }
    }
        public async Task <IActionResult> GetSpecificItem([FromRoute] ulong guildId, [FromRoute] int caseId)
        {
            await RequirePermission(guildId, caseId, APIActionPermission.View);

            Identity currentIdentity = await GetIdentity();

            CaseView modCase = new(await ModCaseRepository.CreateDefault(_serviceProvider, currentIdentity).GetModCase(guildId, caseId));

            if (!(await GetRegisteredGuild(guildId)).PublishModeratorInfo)
            {
                if (!await currentIdentity.HasPermissionOnGuild(DiscordPermission.Moderator, guildId))
                {
                    modCase.RemoveModeratorInfo();
                }
            }

            return(Ok(modCase));
        }
Example #14
0
        protected async Task RequirePermission(ulong guildId, int caseId, APIActionPermission permission)
        {
            Identity currentIdentity = await GetIdentity();

            ModCase modCase = await ModCaseRepository.CreateDefault(_serviceProvider, currentIdentity).GetModCase(guildId, caseId);

            if (modCase == null)
            {
                throw new ResourceNotFoundException();
            }
            if (!await currentIdentity.IsAllowedTo(permission, modCase))
            {
                throw new UnauthorizedException();
            }
            if (modCase.MarkedToDeleteAt != null && permission == APIActionPermission.Edit)
            {
                throw new CaseMarkedToBeDeletedException();
            }
        }
Example #15
0
        public async Task Kick(
            [Summary("title", "The title of the modcase")] string title,
            [Summary("user", "User to punish")] IUser user,
            [Summary("description", "The description of the modcase")] string description             = "",
            [Summary("dm-notification", "Whether to send a dm notification")] bool sendDmNotification = true,
            [Summary("public-notification", "Whether to send a public webhook notification")] bool sendPublicNotification    = true,
            [Summary("execute-punishment", "Whether to execute the punishment or just register it.")] bool executePunishment = true)
        {
            await Context.Interaction.DeferAsync(ephemeral : !sendPublicNotification);

            ModCase modCase = new()
            {
                Title   = title,
                GuildId = Context.Guild.Id,
                UserId  = user.Id,
                ModId   = CurrentIdentity.GetCurrentUser().Id
            };

            if (string.IsNullOrEmpty(description))
            {
                modCase.Description = title;
            }
            else
            {
                modCase.Description = description;
            }
            modCase.PunishmentType   = PunishmentType.Kick;
            modCase.PunishmentActive = executePunishment;
            modCase.PunishedUntil    = null;
            modCase.CreationType     = CaseCreationType.ByCommand;

            ModCase created = await ModCaseRepository.CreateDefault(ServiceProvider, CurrentIdentity).CreateModCase(modCase, executePunishment, sendPublicNotification, sendDmNotification);

            string url = $"{Config.GetBaseUrl()}/guilds/{created.GuildId}/cases/{created.CaseId}";
            await Context.Interaction.ModifyOriginalResponseAsync((MessageProperties msg) =>
            {
                msg.Content = Translator.T().CmdPunish(created.CaseId, url);
            });;
        }
    }
Example #16
0
        public async Task Deactivate(string userID)
        {
            ModCaseRepository repo     = ModCaseRepository.CreateDefault(ServiceProvider, CurrentIdentity);
            List <ModCase>    modCases = (await repo.GetCasesForGuildAndUser(Context.Guild.Id, Convert.ToUInt64(userID)))
                                         .Where(x => x.PunishmentActive && x.PunishmentType == PunishmentType.Ban).ToList();

            await repo.DeactivateModCase(modCases.ToArray());

            var castInteraction = Context.Interaction as SocketMessageComponent;

            var embed = castInteraction.Message.Embeds.FirstOrDefault().ToEmbedBuilder().WithColor(Color.Green);

            embed.Fields = new()
            {
                new EmbedFieldBuilder().WithName(Translator.T().CmdUndoResultTitle()).WithValue(Translator.T().CmdUndoUnbanResultDeactivated())
            };

            await castInteraction.UpdateAsync(message =>
            {
                message.Embed      = embed.Build();
                message.Components = new ComponentBuilder().Build();
            });
        }
Example #17
0
        private async Task HandleGuildRegister(GuildConfig guildConfig, bool importExistingBans)
        {
            using var scope = _serviceProvider.CreateScope();

            var discordAPI = scope.ServiceProvider.GetRequiredService <DiscordAPIInterface>();
            var scheduler  = scope.ServiceProvider.GetRequiredService <Scheduler>();
            var translator = scope.ServiceProvider.GetRequiredService <Translator>();

            await scheduler.CacheAllKnownGuilds();

            await scheduler.CacheAllGuildMembers(new List <ulong>());

            await scheduler.CacheAllGuildBans(new List <ulong>());

            if (importExistingBans)
            {
                translator.SetContext(guildConfig);
                ModCaseRepository modCaseRepository = ModCaseRepository.CreateWithBotIdentity(scope.ServiceProvider);
                foreach (IBan ban in await discordAPI.GetGuildBans(guildConfig.GuildId, CacheBehavior.OnlyCache))
                {
                    ModCase modCase = new()
                    {
                        Title          = string.IsNullOrEmpty(ban.Reason) ? translator.T().ImportedFromExistingBans() : ban.Reason,
                        Description    = string.IsNullOrEmpty(ban.Reason) ? translator.T().ImportedFromExistingBans() : ban.Reason,
                        GuildId        = guildConfig.GuildId,
                        UserId         = ban.User.Id,
                        Username       = ban.User.Username,
                        Labels         = new[] { translator.T().Imported() },
                        Discriminator  = ban.User.Discriminator,
                        CreationType   = CaseCreationType.Imported,
                        PunishmentType = PunishmentType.Ban,
                        PunishedUntil  = null
                    };
                    await modCaseRepository.ImportModCase(modCase);
                }
            }
        }
        public async Task <IActionResult> Get([FromRoute] ulong guildId)
        {
            await RequirePermission(guildId, DiscordPermission.Moderator);

            return(Ok(await ModCaseRepository.CreateDefault(_serviceProvider, await GetIdentity()).GetLabelUsages(guildId)));
        }
Example #19
0
        private async Task <CaseTable> GenerateTable(ulong guildId, ModcaseTableType tableType, int startPage = 0, ModCaseTableFilterDto search = null, ModcaseTableSortType sortBy = ModcaseTableSortType.Default)
        {
            Identity identity = await GetIdentity();

            GuildConfig guildConfig = await GetRegisteredGuild(guildId);

            ulong userOnly = 0;

            if (!await identity.HasPermissionOnGuild(DiscordPermission.Moderator, guildId))
            {
                userOnly = identity.GetCurrentUser().Id;
            }
            // ========================================================

            // SELECT
            List <ModCase> modCases = await ModCaseRepository.CreateDefault(_serviceProvider, identity).GetCasesForGuild(guildId);

            // ORDER BY
            switch (sortBy)
            {
            case ModcaseTableSortType.SortByExpiring:
                modCases = modCases.Where(x => x.PunishedUntil != null).OrderBy(x => x.PunishedUntil).ToList();
                break;

            case ModcaseTableSortType.SortByDeleting:
                modCases = modCases.OrderBy(x => x.MarkedToDeleteAt).ToList();
                break;
            }

            // WHERE
            if (userOnly != 0)
            {
                modCases = modCases.Where(x => x.UserId == userOnly).ToList();
            }

            switch (tableType)
            {
            case ModcaseTableType.OnlyPunishments:
                modCases = modCases.Where(x => x.PunishmentActive).ToList();
                break;

            case ModcaseTableType.OnlyBin:
                modCases = modCases.Where(x => x.MarkedToDeleteAt != null).ToList();
                break;
            }

            bool publishMod = guildConfig.PublishModeratorInfo || await identity.HasPermissionOnGuild(DiscordPermission.Moderator, guildId);

            List <ModCaseTableEntry> tmp = new();

            foreach (var c in modCases)
            {
                var entry = new ModCaseTableEntry(
                    c,
                    await _discordAPI.FetchUserInfo(c.ModId, CacheBehavior.OnlyCache),
                    await _discordAPI.FetchUserInfo(c.UserId, CacheBehavior.OnlyCache)
                    );
                if (!publishMod)
                {
                    entry.RemoveModeratorInfo();
                }
                tmp.Add(entry);
            }

            IEnumerable <ModCaseTableEntry> table = tmp.AsEnumerable();

            if (!string.IsNullOrWhiteSpace(search?.CustomTextFilter))
            {
                table = table.Where(t =>
                                    Contains(t.ModCase.Title, search.CustomTextFilter) ||
                                    Contains(t.ModCase.Description, search.CustomTextFilter) ||
                                    Contains(t.ModCase.GetPunishment(_translator), search.CustomTextFilter) ||
                                    Contains(t.ModCase.Username, search.CustomTextFilter) ||
                                    Contains(t.ModCase.Discriminator, search.CustomTextFilter) ||
                                    Contains(t.ModCase.Nickname, search.CustomTextFilter) ||
                                    Contains(t.ModCase.UserId, search.CustomTextFilter) ||
                                    Contains(t.ModCase.ModId, search.CustomTextFilter) ||
                                    Contains(t.ModCase.LastEditedByModId, search.CustomTextFilter) ||
                                    Contains(t.ModCase.CreatedAt, search.CustomTextFilter) ||
                                    Contains(t.ModCase.OccuredAt, search.CustomTextFilter) ||
                                    Contains(t.ModCase.LastEditedAt, search.CustomTextFilter) ||
                                    Contains(t.ModCase.Labels, search.CustomTextFilter) ||
                                    Contains(t.ModCase.CaseId.ToString(), search.CustomTextFilter) ||
                                    Contains("#" + t.ModCase.CaseId.ToString(), search.CustomTextFilter) ||

                                    Contains(t.Moderator, search.CustomTextFilter) ||
                                    Contains(t.Suspect, search.CustomTextFilter)
                                    );
            }

            if (search?.UserIds != null && search.UserIds.Count > 0)
            {
                table = table.Where(x => search.UserIds.Contains(x.ModCase.UserId));
            }
            if (search?.ModeratorIds != null && search.ModeratorIds.Count > 0)
            {
                table = table.Where(x =>
                                    search.ModeratorIds.Contains(x.ModCase.ModId) ||
                                    search.ModeratorIds.Contains(x.ModCase.LastEditedByModId)
                                    );
            }
            if (search?.Since != null && search.Since != DateTime.MinValue)
            {
                table = table.Where(x => x.ModCase.CreatedAt >= search.Since);
            }
            if (search?.Before != null && search.Before != DateTime.MinValue)
            {
                table = table.Where(x => x.ModCase.CreatedAt <= search.Before);
            }
            if (search?.PunishedUntilMin != null && search.PunishedUntilMin != DateTime.MinValue)
            {
                table = table.Where(x => x.ModCase.PunishedUntil >= search.PunishedUntilMin);
            }
            if (search?.PunishedUntilMax != null && search.PunishedUntilMax != DateTime.MinValue)
            {
                table = table.Where(x => x.ModCase.PunishedUntil <= search.PunishedUntilMax);
            }
            if (search?.Edited != null)
            {
                table = table.Where(x => x.ModCase.LastEditedAt == x.ModCase.CreatedAt != search.Edited.Value);
            }
            if (search?.CreationTypes != null && search.CreationTypes.Count > 0)
            {
                table = table.Where(x => search.CreationTypes.Contains(x.ModCase.CreationType));
            }
            if (search?.PunishmentTypes != null && search.PunishmentTypes.Count > 0)
            {
                table = table.Where(x => search.PunishmentTypes.Contains(x.ModCase.PunishmentType));
            }
            if (search?.PunishmentActive != null)
            {
                table = table.Where(x => x.ModCase.PunishmentActive == search.PunishmentActive.Value);
            }
            if (search?.LockedComments != null)
            {
                table = table.Where(x => x.ModCase.AllowComments != search.LockedComments.Value);
            }
            if (search?.MarkedToDelete != null)
            {
                table = table.Where(x => x.ModCase.MarkedToDeleteAt.HasValue == search.MarkedToDelete.Value);
            }

            return(new CaseTable(table.Skip(startPage * 20).Take(20).ToList(), table.Count()));
        }
Example #20
0
        public async Task <IActionResult> GetUserNetwork([FromQuery][Required] ulong userId)
        {
            Identity currentIdentity = await GetIdentity();

            List <string>           modGuilds  = new();
            List <DiscordGuildView> guildViews = new();

            List <GuildConfig> guildConfigs = await GuildConfigRepository.CreateDefault(_serviceProvider).GetAllGuildConfigs();

            if (guildConfigs.Count == 0)
            {
                throw new BaseAPIException("No guilds registered");
            }
            foreach (GuildConfig guildConfig in guildConfigs)
            {
                if (await currentIdentity.HasPermissionOnGuild(DiscordPermission.Moderator, guildConfig.GuildId))
                {
                    modGuilds.Add(guildConfig.GuildId.ToString());
                    guildViews.Add(new DiscordGuildView(_discordAPI.FetchGuildInfo(guildConfig.GuildId, CacheBehavior.Default)));
                }
            }
            if (modGuilds.Count == 0)
            {
                return(Unauthorized());
            }

            DiscordUserView searchedUser = DiscordUserView.CreateOrDefault(await _discordAPI.FetchUserInfo(userId, CacheBehavior.IgnoreButCacheOnError));

            // invites
            // ===============================================================================================
            InviteRepository inviteRepository = InviteRepository.CreateDefault(_serviceProvider);

            List <UserInviteExpandedView> invited = new();

            foreach (UserInvite invite in await inviteRepository.GetInvitedForUser(userId))
            {
                if (!modGuilds.Contains(invite.GuildId.ToString()))
                {
                    continue;
                }
                invited.Add(new UserInviteExpandedView(
                                invite,
                                await _discordAPI.FetchUserInfo(invite.JoinedUserId, CacheBehavior.OnlyCache),
                                await _discordAPI.FetchUserInfo(invite.InviteIssuerId, CacheBehavior.OnlyCache)
                                ));
            }

            List <UserInviteExpandedView> invitedBy = new();

            foreach (UserInvite invite in await inviteRepository.GetusedInvitesForUser(userId))
            {
                if (!modGuilds.Contains(invite.GuildId.ToString()))
                {
                    continue;
                }
                invitedBy.Add(new UserInviteExpandedView(
                                  invite,
                                  await _discordAPI.FetchUserInfo(invite.JoinedUserId, CacheBehavior.OnlyCache),
                                  await _discordAPI.FetchUserInfo(invite.InviteIssuerId, CacheBehavior.OnlyCache)
                                  ));
            }

            // mappings
            // ===============================================================================================
            UserMapRepository userMapRepository         = UserMapRepository.CreateDefault(_serviceProvider, currentIdentity);
            List <UserMappingExpandedView> userMappings = new();

            foreach (UserMapping userMapping in await userMapRepository.GetUserMapsByUser(userId))
            {
                if (!modGuilds.Contains(userMapping.GuildId.ToString()))
                {
                    continue;
                }
                userMappings.Add(new UserMappingExpandedView(
                                     userMapping,
                                     await _discordAPI.FetchUserInfo(userMapping.UserA, CacheBehavior.OnlyCache),
                                     await _discordAPI.FetchUserInfo(userMapping.UserB, CacheBehavior.OnlyCache),
                                     await _discordAPI.FetchUserInfo(userMapping.CreatorUserId, CacheBehavior.OnlyCache)
                                     ));
            }

            ModCaseRepository             modCaseRepository             = ModCaseRepository.CreateDefault(_serviceProvider, currentIdentity);
            AutoModerationEventRepository autoModerationEventRepository = AutoModerationEventRepository.CreateDefault(_serviceProvider);
            UserNoteRepository            userNoteRepository            = UserNoteRepository.CreateDefault(_serviceProvider, currentIdentity);

            List <CaseView> modCases = (await modCaseRepository.GetCasesForUser(userId)).Where(x => modGuilds.Contains(x.GuildId.ToString())).Select(x => new CaseView(x)).ToList();
            List <AutoModerationEventView> modEvents = (await autoModerationEventRepository.GetAllEventsForUser(userId)).Where(x => modGuilds.Contains(x.GuildId.ToString())).Select(x => new AutoModerationEventView(x)).ToList();
            List <UserNoteView>            userNotes = (await userNoteRepository.GetUserNotesByUser(userId)).Where(x => modGuilds.Contains(x.GuildId.ToString())).Select(x => new UserNoteView(x)).ToList();

            return(Ok(new
            {
                guilds = guildViews,
                user = searchedUser,
                invited,
                invitedBy,
                modCases,
                modEvents,
                userMappings,
                userNotes
            }));
        }
Example #21
0
        public async Task <IActionResult> GetModCaseView([FromRoute] ulong guildId, [FromRoute] int caseId)
        {
            await RequirePermission(guildId, caseId, APIActionPermission.View);

            GuildConfig guildConfig = await GetRegisteredGuild(guildId);

            Identity identity = await GetIdentity();

            ModCase modCase = await ModCaseRepository.CreateDefault(_serviceProvider, identity).GetModCase(guildId, caseId);

            IUser suspect = await _discordAPI.FetchUserInfo(modCase.UserId, CacheBehavior.OnlyCache);

            List <CommentExpandedView> comments = new();

            foreach (ModCaseComment comment in modCase.Comments)
            {
                comments.Add(new CommentExpandedView(
                                 comment,
                                 await _discordAPI.FetchUserInfo(comment.UserId, CacheBehavior.OnlyCache)
                                 ));
            }

            UserNoteExpandedView userNote = null;

            if (await identity.HasPermissionOnGuild(DiscordPermission.Moderator, guildId))
            {
                try
                {
                    var note = await UserNoteRepository.CreateDefault(_serviceProvider, identity).GetUserNote(guildId, modCase.UserId);

                    userNote = new UserNoteExpandedView(
                        note,
                        suspect,
                        await _discordAPI.FetchUserInfo(note.CreatorId, CacheBehavior.OnlyCache)
                        );
                }
                catch (ResourceNotFoundException) { }
            }

            CaseExpandedView caseView = new(
                modCase,
                await _discordAPI.FetchUserInfo(modCase.ModId, CacheBehavior.OnlyCache),
                await _discordAPI.FetchUserInfo(modCase.LastEditedByModId, CacheBehavior.OnlyCache),
                suspect,
                comments,
                userNote
                );

            if (modCase.LockedByUserId != 0)
            {
                caseView.LockedBy = DiscordUserView.CreateOrDefault(await _discordAPI.FetchUserInfo(modCase.LockedByUserId, CacheBehavior.OnlyCache));
            }
            if (modCase.DeletedByUserId != 0)
            {
                caseView.DeletedBy = DiscordUserView.CreateOrDefault(await _discordAPI.FetchUserInfo(modCase.DeletedByUserId, CacheBehavior.OnlyCache));
            }

            if (!(await identity.HasPermissionOnGuild(DiscordPermission.Moderator, guildId) || guildConfig.PublishModeratorInfo))
            {
                caseView.RemoveModeratorInfo();
            }

            return(Ok(caseView));
        }
Example #22
0
        public async Task View([Summary("id", "the id of the case")] long caseId, [Summary("guildid", "the id of the guild")] string guildId = "")
        {
            ulong parsedGuildId = 0;

            if (Context.Guild == null)
            {
                if (!ulong.TryParse(guildId, out parsedGuildId))
                {
                    await Context.Interaction.RespondAsync(Translator.T().CmdViewInvalidGuildId());

                    return;
                }
            }
            else if (string.IsNullOrEmpty(guildId))
            {
                parsedGuildId = Context.Guild.Id;
            }
            else
            {
                try
                {
                    parsedGuildId = ulong.Parse(guildId);
                }
                catch (Exception)
                {
                    await Context.Interaction.RespondAsync(Translator.T().CmdViewInvalidGuildId());

                    return;
                }
            }
            await Context.Interaction.RespondAsync("Getting modcases...");

            ModCase modCase;

            try
            {
                modCase = await ModCaseRepository.CreateDefault(ServiceProvider, CurrentIdentity).GetModCase(parsedGuildId, (int)caseId);
            }
            catch (ResourceNotFoundException)
            {
                await Context.Interaction.ModifyOriginalResponseAsync(message => message.Content = Translator.T().NotFound());

                return;
            }

            if (!await CurrentIdentity.IsAllowedTo(APIActionPermission.View, modCase))
            {
                await Context.Interaction.ModifyOriginalResponseAsync(message => message.Content = Translator.T().CmdViewNotAllowedToView());

                return;
            }

            EmbedBuilder embed = new();

            embed.WithUrl($"{Config.GetBaseUrl()}/guilds/{modCase.GuildId}/cases/{modCase.CaseId}");
            embed.WithTimestamp(modCase.CreatedAt);
            embed.WithColor(Color.Blue);

            IUser suspect = await DiscordAPI.FetchUserInfo(modCase.UserId, CacheBehavior.Default);

            if (suspect != null)
            {
                embed.WithThumbnailUrl(suspect.GetAvatarOrDefaultUrl());
            }

            embed.WithTitle($"#{modCase.CaseId} {modCase.Title.Truncate(200)}");

            embed.WithDescription(modCase.Description.Truncate(2000));

            embed.AddField($"{SCALES_EMOTE} - {Translator.T().Punishment()}", Translator.T().Enum(modCase.PunishmentType), true);

            if (modCase.PunishedUntil != null)
            {
                embed.AddField($"{ALARM_CLOCK} - {Translator.T().PunishmentUntil()}", modCase.PunishedUntil.Value.ToDiscordTS(), true);
            }

            if (modCase.Labels.Length > 0)
            {
                StringBuilder labels = new();
                foreach (string label in modCase.Labels)
                {
                    if (labels.ToString().Length + label.Length + 2 > 2000)
                    {
                        break;
                    }
                    labels.Append($"`{label}` ");
                }
                embed.AddField($"{SCROLL_EMOTE} - {Translator.T().Labels()}", labels.ToString(), false);
            }

            await Context.Interaction.ModifyOriginalResponseAsync(message => { message.Content = ""; message.Embed = embed.Build(); });
        }
Example #23
0
        public async Task Whois([Summary("user", "user to scan")] IUser user)
        {
            await Context.Interaction.RespondAsync("Getting WHOIS information...");

            IGuildUser member = null;

            try
            {
                member = Context.Guild.GetUser(user.Id);
            }
            catch (Exception) { }

            EmbedBuilder embed = new EmbedBuilder()
                                 .WithFooter($"UserId: {user.Id}")
                                 .WithTimestamp(DateTime.UtcNow)
                                 .WithColor(Color.Blue)
                                 .WithDescription(user.Mention);

            List <UserInvite> invites = await InviteRepository.CreateDefault(ServiceProvider).GetusedInvitesForUserAndGuild(user.Id, Context.Guild.Id);

            List <UserInvite> filteredInvites = invites.OrderByDescending(x => x.JoinedAt).ToList();

            if (member != null && member.JoinedAt != null)
            {
                filteredInvites = filteredInvites.FindAll(x => x.JoinedAt >= member.JoinedAt.Value.UtcDateTime);
            }
            StringBuilder joinedInfo = new();

            if (member != null)
            {
                joinedInfo.AppendLine(member.JoinedAt.Value.DateTime.ToDiscordTS());
            }
            if (filteredInvites.Count > 0)
            {
                UserInvite usedInvite = filteredInvites.First();
                joinedInfo.AppendLine(Translator.T().CmdWhoisUsedInvite(usedInvite.UsedInvite));
                if (usedInvite.InviteIssuerId != 0)
                {
                    joinedInfo.AppendLine(Translator.T().CmdWhoisInviteBy(usedInvite.InviteIssuerId));
                }
            }
            if (!string.IsNullOrEmpty(joinedInfo.ToString()))
            {
                embed.AddField(Translator.T().Joined(), joinedInfo.ToString(), true);
            }
            embed.AddField(Translator.T().Registered(), user.CreatedAt.DateTime.ToDiscordTS(), true);

            embed.WithAuthor(user);
            embed.WithThumbnailUrl(user.GetAvatarOrDefaultUrl(size: 1024));

            try
            {
                UserNote userNote = await UserNoteRepository.CreateDefault(ServiceProvider, CurrentIdentity).GetUserNote(Context.Guild.Id, user.Id);

                embed.AddField(Translator.T().UserNote(), userNote.Description.Truncate(1000), false);
            }
            catch (ResourceNotFoundException) { }

            List <UserMapping> userMappings = await UserMapRepository.CreateDefault(ServiceProvider, CurrentIdentity).GetUserMapsByGuildAndUser(Context.Guild.Id, user.Id);

            if (userMappings.Count > 0)
            {
                StringBuilder userMappingsInfo = new();
                foreach (UserMapping userMapping in userMappings.Take(5))
                {
                    ulong otherUser = userMapping.UserA == user.Id ? userMapping.UserB : userMapping.UserA;
                    userMappingsInfo.AppendLine($"<@{otherUser}> - {userMapping.Reason.Truncate(80)}");
                }
                if (userMappings.Count > 5)
                {
                    userMappingsInfo.Append("[...]");
                }
                embed.AddField($"{Translator.T().UserMaps()} [{userMappings.Count}]", userMappingsInfo.ToString(), false);
            }

            List <ModCase> cases = await ModCaseRepository.CreateWithBotIdentity(ServiceProvider).GetCasesForGuildAndUser(Context.Guild.Id, user.Id);

            List <ModCase> activeCases = cases.FindAll(c => c.PunishmentActive);

            if (cases.Count > 0)
            {
                StringBuilder caseInfo = new();
                foreach (ModCase modCase in cases.Take(5))
                {
                    caseInfo.Append($"[{modCase.CaseId} - {modCase.Title.Truncate(50)}]");
                    caseInfo.Append($"({Config.GetBaseUrl()}/guilds/{modCase.GuildId}/cases/{modCase.CaseId})\n");
                }
                if (cases.Count > 5)
                {
                    caseInfo.Append("[...]");
                }
                embed.AddField($"{Translator.T().Cases()} [{cases.Count}]", caseInfo.ToString(), false);

                if (activeCases.Count > 0)
                {
                    StringBuilder activeInfo = new();
                    foreach (ModCase modCase in activeCases.Take(5))
                    {
                        activeInfo.Append($"{modCase.GetPunishment(Translator)} ");
                        if (modCase.PunishedUntil != null)
                        {
                            activeInfo.Append($"({Translator.T().Until()} {modCase.PunishedUntil.Value.ToDiscordTS()}) ");
                        }
                        activeInfo.Append($"[{modCase.CaseId} - {modCase.Title.Truncate(50)}]");
                        activeInfo.Append($"({Config.GetBaseUrl()}/guilds/{modCase.GuildId}/cases/{modCase.CaseId})\n");
                    }
                    if (activeCases.Count > 5)
                    {
                        activeInfo.Append("[...]");
                    }
                    embed.AddField($"{Translator.T().ActivePunishments()} [{activeCases.Count}]", activeInfo.ToString(), false);
                }
            }
            else
            {
                embed.AddField($"{Translator.T().Cases()} [0]", Translator.T().CmdWhoisNoCases(), false);
            }

            await Context.Interaction.ModifyOriginalResponseAsync(message => { message.Content = ""; message.Embed = embed.Build(); });
        }