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
            }));
        }
예제 #2
0
        public async Task <IActionResult> DeleteUserNote([FromRoute] ulong guildId, [FromRoute] ulong userId)
        {
            await RequirePermission(guildId, DiscordPermission.Moderator);

            await UserNoteRepository.CreateDefault(_serviceProvider, await GetIdentity()).DeleteUserNote(guildId, userId);

            return(Ok());
        }
예제 #3
0
        public async Task <IActionResult> CreateUserNote([FromRoute] ulong guildId, [FromBody] UserNoteForUpdateDto userNote)
        {
            await RequirePermission(guildId, DiscordPermission.Moderator);

            UserNote createdUserNote = await UserNoteRepository.CreateDefault(_serviceProvider, await GetIdentity()).CreateOrUpdateUserNote(guildId, userNote.UserId, userNote.Description);

            return(StatusCode(201, new UserNoteView(createdUserNote)));
        }
예제 #4
0
        public async Task <IActionResult> GetUserNote([FromRoute] ulong guildId)
        {
            await RequirePermission(guildId, DiscordPermission.Moderator);

            List <UserNote> userNotes = await UserNoteRepository.CreateDefault(_serviceProvider, await GetIdentity()).GetUserNotesByGuild(guildId);

            return(Ok(userNotes.Select(x => new UserNoteView(x))));
        }
예제 #5
0
        public async Task <IActionResult> GetGuildUserNoteView([FromRoute] ulong guildId)
        {
            await RequirePermission(guildId, DiscordPermission.Moderator);

            List <UserNote> userNotes = await UserNoteRepository.CreateDefault(_serviceProvider, await GetIdentity()).GetUserNotesByGuild(guildId);

            List <UserNoteExpandedView> userNoteViews = new();

            foreach (UserNote userNote in userNotes)
            {
                userNoteViews.Add(new UserNoteExpandedView(
                                      userNote,
                                      await _discordAPI.FetchUserInfo(userNote.UserId, CacheBehavior.OnlyCache),
                                      await _discordAPI.FetchUserInfo(userNote.CreatorId, CacheBehavior.OnlyCache)));
            }

            return(Ok(userNoteViews));
        }
예제 #6
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(); });
        }
예제 #7
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));
        }
예제 #8
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
            }));
        }