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

            List <UserMapping> userMappings = await UserMapRepository.CreateDefault(_serviceProvider, await GetIdentity()).GetUserMapsByGuildAndUser(guildId, userId);

            return(Ok(userMappings.Select(x => new UserMappingView(x))));
        }
        public async Task <IActionResult> DeleteUserMap([FromRoute] ulong guildId, [FromRoute] int id)
        {
            await RequirePermission(guildId, DiscordPermission.Moderator);

            var repo = UserMapRepository.CreateDefault(_serviceProvider, await GetIdentity());

            UserMapping userMap = await repo.GetUserMap(id);

            if (userMap.GuildId != guildId)
            {
                throw new ResourceNotFoundException();
            }

            await UserMapRepository.CreateDefault(_serviceProvider, await GetIdentity()).DeleteUserMap(id);

            return(Ok());
        }
        public async Task <IActionResult> UpdateUserMap([FromRoute] ulong guildId, [FromRoute] int id, [FromBody] UserMappingForUpdateDto userMapDto)
        {
            await RequirePermission(guildId, DiscordPermission.Moderator);

            var repo = UserMapRepository.CreateDefault(_serviceProvider, await GetIdentity());

            UserMapping userMap = await repo.GetUserMap(id);

            if (userMap.GuildId != guildId)
            {
                throw new ResourceNotFoundException();
            }

            UserMapping result = await repo.CreateOrUpdateUserMap(guildId, userMap.UserA, userMap.UserB, userMapDto.Reason);

            return(Ok(new UserMappingView(result)));
        }
        public async Task <IActionResult> CreateUserMap([FromRoute] ulong guildId, [FromBody] UserMappingForCreateDto userMapDto)
        {
            await RequirePermission(guildId, DiscordPermission.Moderator);

            var repo = UserMapRepository.CreateDefault(_serviceProvider, await GetIdentity());

            try
            {
                await repo.GetUserMap(guildId, userMapDto.UserA, userMapDto.UserB);

                throw new ResourceAlreadyExists();
            }
            catch (ResourceNotFoundException) { }

            UserMapping userMap = await repo.CreateOrUpdateUserMap(guildId, userMapDto.UserA, userMapDto.UserB, userMapDto.Reason);

            return(StatusCode(201, new UserMappingView(userMap)));
        }
示例#6
0
        public async Task <IActionResult> GetGuildUserNoteView([FromRoute] ulong guildId)
        {
            await RequirePermission(guildId, DiscordPermission.Moderator);

            UserMapRepository  repository   = UserMapRepository.CreateDefault(_serviceProvider, await GetIdentity());
            List <UserMapping> userMappings = await repository.GetUserMapsByGuild(guildId);

            List <UserMappingExpandedView> userMappingViews = new();

            foreach (UserMapping userMapping in userMappings)
            {
                userMappingViews.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)
                                         ));
            }

            return(Ok(userMappingViews));
        }
示例#7
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(); });
        }
示例#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
            }));
        }