Esempio n. 1
0
        public override async Task <IViewProviderResult> BuildIndexAsync(Topic topic, IViewProviderContext context)
        {
            // Get all moderators
            var moderators = await _moderatorStore.QueryAsync()
                             .Take(int.MaxValue, false)
                             .ToList();

            // Add moderator to context
            await HydrateModeratorContext(topic, context, moderators);

            // ----------------

            // Add moderators panel to sidebar

            IPagedResults <User> users = null;

            if (moderators != null)
            {
                users = await _platoUserStore.QueryAsync()
                        .Take(20, false)
                        .Select <UserQueryParams>(q =>
                {
                    q.Id.IsIn(moderators.Data.Select(m => m.UserId).ToArray());
                })
                        .OrderBy("LastLoginDate", OrderBy.Desc)
                        .ToList();
            }

            return(Views(View <ModeratorsViewModel>("Topic.Moderators.Index.Sidebar", model =>
            {
                model.Moderators = users?.Data ?? null;
                return model;
            }).Zone("content-right").Order(100)
                         ));
        }
Esempio n. 2
0
        async Task <IEnumerable <User> > GetUsersAsync(ISpamOperation operation)
        {
            var roleNames = new List <string>(2);

            if (operation.NotifyAdmin)
            {
                roleNames.Add(DefaultRoles.Administrator);
            }
            if (operation.NotifyStaff)
            {
                roleNames.Add(DefaultRoles.Staff);
            }
            if (roleNames.Count == 0)
            {
                return(null);
            }
            var users = await _platoUserStore.QueryAsync()
                        .Select <UserQueryParams>(q =>
            {
                q.RoleName.IsIn(roleNames.ToArray());
            })
                        .ToList();

            return(users?.Data);
        }
Esempio n. 3
0
        // ------------------

        async Task <ICommandResultBase> InstallEntitiesAsync(SampleDataDescriptor descriptor)
        {
            var output = new CommandResultBase();

            // Get sample users
            var users = await _platoUserStore.QueryAsync()
                        .OrderBy("LastLoginDate", OrderBy.Desc)
                        .ToList();

            // We need sample users to create sample entities
            if (users == null || users.Data == null)
            {
                return(output.Failed("You must create sample users first!"));
            }

            for (var i = 0; i < descriptor.EntitiesToCreate; i++)
            {
                var result = await InstallEntitiesInternalAsync(descriptor, users?.Data);

                if (!result.Succeeded)
                {
                    return(output.Failed(result.Errors.ToArray()));
                }
            }

            return(output.Success());
        }
Esempio n. 4
0
        public Task ReportAsync(ReportSubmission <Reply> submission)
        {
            // Defer notifications for execution after request completes
            _deferredTaskManager.AddTask(async ctx =>
            {
                // Get users to notify
                var users = await _platoUserStore.QueryAsync()
                            .Select <UserQueryParams>(q =>
                {
                    q.RoleName.IsIn(new[]
                    {
                        DefaultRoles.Administrator,
                        DefaultRoles.Staff
                    });
                })
                            .ToList();

                // No users to notify
                if (users?.Data == null)
                {
                    return;
                }

                // If anonymous use bot as sender
                var from = submission.Who ??
                           await _platoUserStore.GetPlatoBotAsync();

                // Send notifications
                foreach (var user in users.Data)
                {
                    // Web notification
                    if (user.NotificationEnabled(_userNotificationTypeDefaults, WebNotifications.ReplyReport))
                    {
                        await _notificationManager.SendAsync(new Notification(WebNotifications.ReplyReport)
                        {
                            To   = user,
                            From = from
                        }, submission);
                    }

                    // Email notification
                    if (user.NotificationEnabled(_userNotificationTypeDefaults, EmailNotifications.ReplyReport))
                    {
                        await _notificationManager.SendAsync(new Notification(EmailNotifications.ReplyReport)
                        {
                            To = user
                        }, submission);
                    }
                }
            });

            return(Task.CompletedTask);
        }
Esempio n. 5
0
        async Task <IEnumerable <AggregatedModel <int, User> > > SelectUsersByReputationAsync(ReportOptions options)
        {
            // Get views by id for specified range
            var viewsById = options.FeatureId > 0
                ? await _aggregatedUserReputationRepository.SelectSummedByIntAsync(
                "CreatedUserId",
                options.Start,
                options.End,
                options.FeatureId)
                : await _aggregatedUserReputationRepository.SelectSummedByIntAsync(
                "CreatedUserId",
                options.Start,
                options.End);

            // Get all entities matching ids
            IPagedResults <User> mostViewedEntities = null;

            if (viewsById != null)
            {
                mostViewedEntities = await _platoUserStore.QueryAsync()
                                     .Take(1, 100)
                                     .Select <UserQueryParams>(q =>
                {
                    q.Id.IsIn(viewsById.Data.Select(d => d.Aggregate).ToArray());
                })
                                     .OrderBy("CreatedDate", OrderBy.Desc)
                                     .ToList();
            }

            // Build combined result
            List <AggregatedModel <int, User> > entityMetrics = null;

            if (mostViewedEntities?.Data != null)
            {
                foreach (var entity in mostViewedEntities.Data)
                {
                    // Get or add aggregate
                    var aggregate = viewsById?.Data.FirstOrDefault(m => m.Aggregate == entity.Id);
                    if (aggregate != null)
                    {
                        if (entityMetrics == null)
                        {
                            entityMetrics = new List <AggregatedModel <int, User> >();
                        }
                        entityMetrics.Add(new AggregatedModel <int, User>(aggregate, entity));
                    }
                }
            }

            return(entityMetrics?.OrderByDescending(o => o.Aggregate.Count) ?? null);
        }
Esempio n. 6
0
        async Task <IEnumerable <AggregatedModel <int, User> > > SelectUsersByReputationAsync(ReportOptions options)
        {
            // Get reputation for specified range
            var viewsById = options.FeatureId > 0
                ? await _aggregatedUserReputationRepository.SelectSummedByIntAsync(
                "CreatedUserId",
                options.Start,
                options.End,
                options.FeatureId)
                : await _aggregatedUserReputationRepository.SelectSummedByIntAsync(
                "CreatedUserId",
                options.Start,
                options.End);

            // Get all users matching awarded rep
            IPagedResults <User> users = null;

            if (viewsById != null)
            {
                users = await _platoUserStore.QueryAsync()
                        .Take(100, false)
                        .Select <UserQueryParams>(q =>
                {
                    q.Id.IsIn(viewsById.Data.Select(d => d.Aggregate).ToArray());
                })
                        .OrderBy("CreatedDate", OrderBy.Desc)
                        .ToList();
            }

            // Build total rep awarded and user
            List <AggregatedModel <int, User> > topUsers = null;

            if (users?.Data != null)
            {
                foreach (var entity in users.Data)
                {
                    // Get or add aggregate
                    var aggregate = viewsById?.Data.FirstOrDefault(m => m.Aggregate == entity.Id);
                    if (aggregate != null)
                    {
                        if (topUsers == null)
                        {
                            topUsers = new List <AggregatedModel <int, User> >();
                        }
                        topUsers.Add(new AggregatedModel <int, User>(aggregate, entity));
                    }
                }
            }

            return(topUsers?.OrderByDescending(o => o.Aggregate.Count) ?? null);
        }
Esempio n. 7
0
        public async Task <IPagedResults <TModel> > GetResultsAsync(
            UserIndexOptions options,
            PagerOptions pager)
        {
            return(await _platoUserStore.QueryAsync()
                   .Configure(_configureDb)
                   .Take(pager.Page, pager.Size)
                   .Select <UserQueryParams>(q =>
            {
                switch (options.Filter)
                {
                case FilterBy.Confirmed:
                    q.ShowConfirmed.True();
                    break;

                case FilterBy.Unconfirmed:
                    q.HideConfirmed.True();
                    break;

                case FilterBy.Verified:
                    q.ShowVerified.True();
                    break;

                case FilterBy.Staff:
                    q.ShowStaff.True();
                    break;

                case FilterBy.Spam:
                    q.ShowSpam.True();
                    break;

                case FilterBy.Banned:
                    q.ShowBanned.True();
                    break;
                }

                if (!string.IsNullOrEmpty(options.Search))
                {
                    q.Keywords.Like(options.Search);
                }

                // ----------------
                // Additional parameter configuration
                // ----------------

                _configureParams?.Invoke(q);
            })
                   .OrderBy(options.Sort.ToString(), options.Order)
                   .ToList());
        }
Esempio n. 8
0
        public async Task <IList <User> > GetUsersInRoleAsync(string roleName, CancellationToken cancellationToken)
        {
            if (string.IsNullOrEmpty(roleName))
            {
                throw new ArgumentNullException(nameof(roleName));
            }

            cancellationToken.ThrowIfCancellationRequested();

            var results = await _platoUserStore.QueryAsync()
                          .Select <UserQueryParams>(q => q.RoleName.Equals(roleName))
                          .OrderBy("Id", OrderBy.Desc)
                          .ToList();

            return(results.Data);
        }
Esempio n. 9
0
        // ------------------

        async Task <ICommandResultBase> InstallEntitiesAsync(SampleDataDescriptor descriptor)
        {
            var output = new CommandResultBase();

            // Get sample users
            var users = await _platoUserStore.QueryAsync()
                        .OrderBy("LastLoginDate", OrderBy.Desc)
                        .ToList();

            // We need sample users to create sample entities
            if (users == null || users.Data == null)
            {
                return(output.Failed("You must create sample users first!"));
            }

            // Ensure the feature is enabled
            var feature = await _featureFacade.GetFeatureByIdAsync(descriptor.ModuleId);

            if (feature == null)
            {
                // Skip faeture if not enabled
                return(output.Success());
            }

            // If we add sample entities multiple times ensure the sort order
            // for new entities is always incremented starting from the highest
            // existing sort order for any existing entities
            var sortOrder = await GetStartingEntitySortOrderAsync(feature.Id);

            for (var i = 0; i < descriptor.EntitiesToCreate; i++)
            {
                var result = await InstallEntityInternalAsync(descriptor, users?.Data, sortOrder + i);

                if (!result.Succeeded)
                {
                    return(output.Failed(result.Errors.ToArray()));
                }
            }

            return(output.Success());
        }
Esempio n. 10
0
        async Task <IPagedResults <User> > GetUsers(
            int page,
            int pageSize,
            string username,
            string sortBy,
            OrderBy sortOrder)
        {
            return(await _platoUserStore.QueryAsync()
                   .Take(page, pageSize)
                   .Select <UserQueryParams>(q =>
            {
                q.HideSpam.True();
                q.HideUnconfirmed.True();
                q.HideBanned.True();

                if (!String.IsNullOrEmpty(username))
                {
                    q.Keywords.StartsWith(username);
                }
            })
                   .OrderBy(sortBy, sortOrder)
                   .ToList());
        }
Esempio n. 11
0
        public async Task ExecuteAsync(object sender, SafeTimerEventArgs args)
        {
            var feature = await _featureFacade.GetFeatureByIdAsync("Plato.Questions");

            if (feature == null)
            {
                return;
            }

            var bot = await _userStore.GetPlatoBotAsync();

            foreach (var badge in this.Badges)
            {
                // Replacements for SQL script
                var replacements = new Dictionary <string, string>()
                {
                    ["{name}"]      = badge.Name,
                    ["{threshold}"] = badge.Threshold.ToString(),
                    ["{featureId}"] = feature.Id.ToString()
                };

                var userIds = await _dbHelper.ExecuteReaderAsync <IList <int> >(Sql, replacements, async reader =>
                {
                    var users = new List <int>();
                    while (await reader.ReadAsync())
                    {
                        if (reader.ColumnIsNotNull("UserId"))
                        {
                            users.Add(Convert.ToInt32(reader["UserId"]));
                        }
                    }

                    return(users);
                });

                if (userIds?.Count > 0)
                {
                    // Get all users awarded the badge
                    var users = await _userStore.QueryAsync()
                                .Take(1, userIds.Count)
                                .Select <UserQueryParams>(q => { q.Id.IsIn(userIds.ToArray()); })
                                .OrderBy("LastLoginDate", OrderBy.Desc)
                                .ToList();

                    // Send notifications
                    if (users != null)
                    {
                        foreach (var user in users.Data)
                        {
                            // ---------------
                            // Award reputation for new badges
                            // ---------------

                            var badgeReputation = badge.GetReputation();
                            if (badgeReputation.Points != 0)
                            {
                                await _userReputationAwarder.AwardAsync(badgeReputation, user.Id, $"{badge.Name} badge awarded");
                            }

                            // ---------------
                            // Trigger notifications
                            // ---------------

                            // Email notification
                            if (user.NotificationEnabled(_userNotificationTypeDefaults, EmailNotifications.NewBadge))
                            {
                                await _notificationManager.SendAsync(new Notification(EmailNotifications.NewBadge)
                                {
                                    To   = user,
                                    From = bot
                                }, badge);
                            }

                            // Web notification
                            if (user.NotificationEnabled(_userNotificationTypeDefaults, WebNotifications.NewBadge))
                            {
                                await _notificationManager.SendAsync(new Notification(WebNotifications.NewBadge)
                                {
                                    To   = user,
                                    From = bot
                                }, badge);
                            }
                        }
                    }

                    _cacheManager.CancelTokens(typeof(UserBadgeStore));
                }
            }
        }
Esempio n. 12
0
        async Task <IEnumerable <IUser> > ReduceUsersAsync(IEnumerable <Follows.Models.Follow> follows, TEntityReply reply)
        {
            // We always need follows to process
            if (follows == null)
            {
                return(null);
            }

            // Get the entity for the reply
            var entity = await _entityStore.GetByIdAsync(reply.EntityId);

            // We always need an entity
            if (entity == null)
            {
                return(null);
            }

            // Get all users from the supplied follows
            var users = await _platoUserStore.QueryAsync()
                        .Select <UserQueryParams>(q =>
            {
                q.Id.IsIn(follows
                          .Select(f => f.CreatedUserId)
                          .ToArray());
            })
                        .ToList();

            // No users to further process
            if (users?.Data == null)
            {
                return(null);
            }

            // Build users reducing for permissions
            var result = new Dictionary <int, IUser>();

            foreach (var user in users.Data)
            {
                // Ensure the user is only added once
                if (!result.ContainsKey(user.Id))
                {
                    result.Add(user.Id, user);
                }

                // If the reply is hidden but the user does
                // not have permission to view hidden replies
                if (reply.IsHidden)
                {
                    var principal = await _claimsPrincipalFactory.CreateAsync(user);

                    if (!await _authorizationService.AuthorizeAsync(principal,
                                                                    entity.CategoryId, Discuss.Permissions.ViewHiddenReplies))
                    {
                        result.Remove(user.Id);
                    }
                }

                // The reply has been flagged as SPAM but the user does
                // not have permission to view replies flagged as SPAM
                if (reply.IsSpam)
                {
                    var principal = await _claimsPrincipalFactory.CreateAsync(user);

                    if (!await _authorizationService.AuthorizeAsync(principal,
                                                                    entity.CategoryId, Discuss.Permissions.ViewSpamReplies))
                    {
                        result.Remove(user.Id);
                    }
                }

                // The reply is soft deleted but the user does
                // not have permission to view soft deleted replies
                if (reply.IsDeleted)
                {
                    var principal = await _claimsPrincipalFactory.CreateAsync(user);

                    if (!await _authorizationService.AuthorizeAsync(principal,
                                                                    entity.CategoryId, Discuss.Permissions.ViewDeletedReplies))
                    {
                        result.Remove(user.Id);
                    }
                }
            }

            return(result.Count > 0 ? result.Values : null);
        }
Esempio n. 13
0
        async Task <IEnumerable <IUser> > ReduceUsersAsync(IEnumerable <Follows.Models.Follow> follows, IEntity entity)
        {
            // We always need follows to process
            if (follows == null)
            {
                return(null);
            }

            // Get all users following the entity
            var users = await _platoUserStore.QueryAsync()
                        .Select <UserQueryParams>(q =>
            {
                q.Id.IsIn(follows
                          .Select(f => f.CreatedUserId)
                          .ToArray());
            })
                        .ToList();

            // No users to further process
            if (users?.Data == null)
            {
                return(null);
            }

            // Build users reducing for permissions
            var result = new Dictionary <int, IUser>();

            foreach (var user in users.Data)
            {
                if (!result.ContainsKey(user.Id))
                {
                    result.Add(user.Id, user);
                }

                // If the entity is hidden but the user does
                // not have permission to view hidden entities
                if (entity.IsHidden)
                {
                    var principal = await _claimsPrincipalFactory.CreateAsync(user);

                    if (!await _authorizationService.AuthorizeAsync(principal,
                                                                    entity.CategoryId, Docs.Permissions.ViewHiddenDocs))
                    {
                        result.Remove(user.Id);
                    }
                }

                // If we are not the entity author and the entity is private
                // ensure we have permission to view private entities
                if (user.Id != entity.CreatedUserId && entity.IsPrivate)
                {
                    var principal = await _claimsPrincipalFactory.CreateAsync(user);

                    if (!await _authorizationService.AuthorizeAsync(principal,
                                                                    entity.CategoryId, Docs.Permissions.ViewPrivateDocs))
                    {
                        result.Remove(user.Id);
                    }
                }

                // The entity has been flagged as SPAM but the user does
                // not have permission to view entities flagged as SPAM
                if (entity.IsSpam)
                {
                    var principal = await _claimsPrincipalFactory.CreateAsync(user);

                    if (!await _authorizationService.AuthorizeAsync(principal,
                                                                    entity.CategoryId, Docs.Permissions.ViewSpamDocs))
                    {
                        result.Remove(user.Id);
                    }
                }

                // The entity is soft deleted but the user does
                // not have permission to view soft deleted entities
                if (entity.IsDeleted)
                {
                    var principal = await _claimsPrincipalFactory.CreateAsync(user);

                    if (!await _authorizationService.AuthorizeAsync(principal,
                                                                    entity.CategoryId, Docs.Permissions.ViewDeletedDocs))
                    {
                        result.Remove(user.Id);
                    }
                }
            }

            return(result.Count > 0 ? result.Values : null);
        }