Esempio n. 1
0
        public async Task <IPagedResults <TModel> > SelectAsync(IDbDataParameter[] dbParams)
        {
            IPagedResults <TModel> output = null;

            using (var context = _dbContext)
            {
                output = await context.ExecuteReaderAsync <IPagedResults <TModel> >(
                    CommandType.StoredProcedure,
                    "SelectTagsPaged",
                    async reader =>
                {
                    if ((reader != null) && (reader.HasRows))
                    {
                        output = new PagedResults <TModel>();
                        while (await reader.ReadAsync())
                        {
                            var tag = ActivateInstanceOf <TModel> .Instance();
                            tag.PopulateModel(reader);
                            output.Data.Add(tag);
                        }

                        if (await reader.NextResultAsync())
                        {
                            await reader.ReadAsync();
                            output.PopulateTotal(reader);
                        }
                    }

                    return(output);
                },
                    dbParams);
            }

            return(output);
        }
Esempio n. 2
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. 3
0
        async Task <Moderator> GetModerator(
            User user,
            Topic topic,
            IPagedResults <Moderator> moderators)
        {
            // Get all moderators
            if (moderators == null)
            {
                moderators = await _moderatorStore.QueryAsync()
                             .Take(int.MaxValue, false)
                             .ToList();
            }

            if (moderators == null)
            {
                return(null);
            }

            // Get all moderator entries for given identity and resource
            var userEntries = moderators.Data
                              .Where(m => m.UserId == user.Id & m.CategoryId == topic.CategoryId)
                              .ToList();

            // No moderator entries for the user and resource
            if (!userEntries.Any())
            {
                return(null);
            }

            return(userEntries[0]);
        }
Esempio n. 4
0
        public async Task <IPagedResults <Models.Media> > SelectAsync(IDbDataParameter[] dbParams)
        {
            IPagedResults <Models.Media> output = null;

            using (var context = _dbContext)
            {
                output = await context.ExecuteReaderAsync <IPagedResults <Models.Media> >(
                    CommandType.StoredProcedure,
                    "SelectMediaPaged",
                    async reader =>
                {
                    if ((reader != null) && (reader.HasRows))
                    {
                        output = new PagedResults <Models.Media>();
                        while (await reader.ReadAsync())
                        {
                            var entity = new Models.Media();
                            entity.PopulateModel(reader);
                            output.Data.Add(entity);
                        }

                        if (await reader.NextResultAsync())
                        {
                            await reader.ReadAsync();
                            output.PopulateTotal(reader);
                        }
                    }

                    return(output);
                },
                    dbParams);
            }

            return(output);
        }
Esempio n. 5
0
        async Task <IDictionary <int, IList <EntityTag> > > BuildLookUpTable()
        {
            // Get index view model from context
            var viewModel = _actionContextAccessor.ActionContext.HttpContext.Items[typeof(EntityIndexViewModel <Doc>)] as EntityIndexViewModel <Doc>;

            if (viewModel == null)
            {
                return(null);
            }

            // We need results
            if (viewModel.Results == null)
            {
                return(null);
            }

            // Get all entities for our current view
            var entities = viewModel.Results;

            // Get all entity tag relationships for displayed entities
            IPagedResults <EntityTag> entityTags = null;

            if (entities?.Data != null)
            {
                entityTags = await _entityTagStore.QueryAsync()
                             .Take(int.MaxValue, false)
                             .Select <EntityTagQueryParams>(q =>
                {
                    q.EntityId.IsIn(entities.Data.Select(e => e.Id).ToArray());
                    q.EntityReplyId.Equals(0);
                })
                             .ToList();
            }

            // Build a dictionary of entity and tag relationships
            var output = new ConcurrentDictionary <int, IList <EntityTag> >();

            if (entityTags?.Data != null)
            {
                foreach (var entityTag in entityTags.Data)
                {
                    var tag = entityTags.Data.FirstOrDefault(t => t.TagId == entityTag.TagId);
                    if (tag != null)
                    {
                        tag.Id = tag.TagId;
                        output.AddOrUpdate(entityTag.EntityId, new List <EntityTag>()
                        {
                            tag
                        }, (k, v) =>
                        {
                            v.Add(tag);
                            return(v);
                        });
                    }
                }
            }

            return(output);
        }
Esempio n. 6
0
        async Task <IDictionary <int, IList <Label> > > BuildLookUpTable(IEnumerable <Label> labels)
        {
            // Get topic index view model from context
            var viewModel = _actionContextAccessor.ActionContext.HttpContext.Items[typeof(EntityIndexViewModel <Article>)] as EntityIndexViewModel <Article>;

            if (viewModel == null)
            {
                return(null);
            }

            // We need results
            if (viewModel.Results == null)
            {
                return(null);
            }

            // Get all entities for our current view
            var entities = viewModel.Results;

            // Get all entity label relationships for displayed entities
            IPagedResults <EntityLabel> entityLabels = null;

            if (entities?.Data != null)
            {
                entityLabels = await _entityLabelStore.QueryAsync()
                               .Take(int.MaxValue, false)
                               .Select <EntityLabelQueryParams>(q =>
                {
                    q.EntityId.IsIn(entities.Data.Select(e => e.Id).ToArray());
                })
                               .ToList();
            }

            // Build a dictionary of entity and label relationships
            var output = new ConcurrentDictionary <int, IList <Label> >();

            if (entityLabels?.Data != null)
            {
                var labelList = labels.ToList();
                foreach (var entityLabel in entityLabels.Data)
                {
                    var label = labelList.FirstOrDefault(l => l.Id == entityLabel.LabelId);
                    if (label != null)
                    {
                        output.AddOrUpdate(entityLabel.EntityId, new List <Label>()
                        {
                            label
                        }, (k, v) =>
                        {
                            v.Add(label);
                            return(v);
                        });
                    }
                }
            }

            return(output);
        }
Esempio n. 7
0
 public RolesIndexViewModel(
     IPagedResults <Role> results,
     RoleIndexOptions options,
     PagerOptions pager)
 {
     this.Results = results;
     this.Options = options;
     this.Pager   = pager;
     this.Pager.SetTotal(results?.Total ?? 0);
 }
Esempio n. 8
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. 9
0
        async Task <IEnumerable <AggregatedModel <int, Entity> > > SelectEntitiesGroupedByViewsAsync(ReportOptions options)
        {
            // Get views by grouped by entity id for specified range
            var viewsById = options.FeatureId > 0
                ? await _aggregatedEntityMetricsRepository.SelectGroupedByIntAsync(
                "EntityId",
                options.Start,
                options.End,
                options.FeatureId)
                : await _aggregatedEntityMetricsRepository.SelectGroupedByIntAsync(
                "EntityId",
                options.Start,
                options.End);

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

            if (viewsById != null)
            {
                entities = await _entityStore.QueryAsync()
                           .Take(1, 10)
                           .Select <EntityQueryParams>(q =>
                {
                    q.Id.IsIn(viewsById.Data.Select(d => d.Aggregate).ToArray());
                })
                           .OrderBy("CreatedDate", OrderBy.Desc)
                           .ToList();
            }

            // Build aggregated list
            List <AggregatedModel <int, Entity> > metrics = null;

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

            return(metrics?.OrderByDescending(o => o.Aggregate.Count) ?? null);
        }
Esempio n. 10
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. 11
0
        async Task HydrateModeratorContext(
            Topic topic,
            IViewProviderContext context,
            IPagedResults <Moderator> moderators = null)
        {
            // Add moderator to context
            if (context.Controller.HttpContext.Items[typeof(Moderator)] == null)
            {
                var user = await _contextFacade.GetAuthenticatedUserAsync();

                if (user != null)
                {
                    context.Controller.HttpContext.Items[typeof(Moderator)] = await GetModerator(user, topic, moderators);
                }
            }
        }
Esempio n. 12
0
        public override async Task <IViewProviderResult> BuildEditAsync(File file, IViewProviderContext context)
        {
            // No need to update the Create / Add view
            if (file.Id == 0)
            {
                return(default(IViewProviderResult));
            }

            // Get entity relationships for file
            var relationships = await _entityFileStore.QueryAsync()
                                .Take(int.MaxValue, false)
                                .Select <EntityFileQueryParams>(q =>
            {
                q.FileId.Equals(file.Id);
            })
                                .ToList();

            // Get entities for file
            IPagedResults <Entity> entities = null;

            if (relationships?.Data != null)
            {
                entities = await _entityStore.QueryAsync()
                           .Take(int.MaxValue, false)
                           .Select <EntityQueryParams>(q =>
                {
                    q.Id.IsIn(relationships.Data.Select(f => f.EntityId).ToArray());
                })
                           .ToList();
            }

            // Build view model
            var viewModel = new FileEntitiesViewModel()
            {
                Results = entities
            };

            // Return view
            return(Views(
                       View <FileEntitiesViewModel>("Admin.Edit.FileEntities", model => viewModel)
                       .Zone("content-right").Order(5)
                       ));
        }
Esempio n. 13
0
        public async Task <IPagedResults <User> > SelectAsync(IDbDataParameter[] dbParams)
        {
            IPagedResults <User> results = null;

            using (var context = _dbContext)
            {
                results = await context.ExecuteReaderAsync <IPagedResults <User> >(
                    CommandType.StoredProcedure,
                    "SelectUsersPaged",
                    async reader =>
                {
                    if ((reader != null) && (reader.HasRows))
                    {
                        var output = new PagedResults <User>();

                        while (await reader.ReadAsync())
                        {
                            var user = new User();
                            user.PopulateModel(reader);
                            output.Data.Add(user);
                        }

                        if (await reader.NextResultAsync())
                        {
                            if (reader.HasRows)
                            {
                                await reader.ReadAsync();
                                output.PopulateTotal(reader);
                            }
                        }

                        return(output);
                    }

                    return(null);
                },
                    dbParams);
            }

            return(results);
        }
Esempio n. 14
0
        public async Task<IPagedResults<EntityMetric>> SelectAsync(IDbDataParameter[] dbParams)
        {
            IPagedResults<EntityMetric> output = null;
            using (var context = _dbContext)
            {
                output = await context.ExecuteReaderAsync<IPagedResults<EntityMetric>>(
                    CommandType.StoredProcedure,
                    "SelectEntityMetricsPaged",
                    async reader =>
                    {
                        if ((reader != null) && (reader.HasRows))
                        {
                            output = new PagedResults<EntityMetric>();
                            while (await reader.ReadAsync())
                            {
                                var metric = new EntityMetric();
                                metric.PopulateModel(reader);
                                output.Data.Add(metric);
                            }

                            if (await reader.NextResultAsync())
                            {
                                if (reader.HasRows)
                                {
                                    await reader.ReadAsync();
                                    output.PopulateTotal(reader);
                                }
                            }

                        }

                        return output;
                    },
                    dbParams);
            
            }

            return output;

        }
Esempio n. 15
0
        public async Task <IPagedResults <Role> > SelectAsync(IDbDataParameter[] dbParams)
        {
            IPagedResults <Role> output = null;

            using (var context = _dbContext)
            {
                output = await context.ExecuteReaderAsync(
                    CommandType.StoredProcedure,
                    "SelectRolesPaged",
                    async reader =>
                {
                    if ((reader != null) && (reader.HasRows))
                    {
                        output = new PagedResults <Role>();
                        while (await reader.ReadAsync())
                        {
                            var role = new Role();
                            role.PopulateModel(reader);
                            output.Data.Add(role);
                        }

                        if (await reader.NextResultAsync())
                        {
                            if (reader.HasRows)
                            {
                                await reader.ReadAsync();
                                output.PopulateTotal(reader);
                            }
                        }
                    }

                    return(output);
                },
                    dbParams);
            }

            return(output);
        }
Esempio n. 16
0
        public async Task <IPagedResults <FeatureEntityCount> > SelectAsync(IDbDataParameter[] dbParams)
        {
            IPagedResults <FeatureEntityCount> results = null;

            using (var context = _dbContext)
            {
                results = await context.ExecuteReaderAsync(
                    CommandType.StoredProcedure,
                    "SelectEntitiesPaged",
                    async reader =>
                {
                    if ((reader != null) && (reader.HasRows))
                    {
                        var output = new PagedResults <FeatureEntityCount>();
                        while (await reader.ReadAsync())
                        {
                            var entity = new FeatureEntityCount();
                            entity.PopulateModel(reader);
                            output.Data.Add(entity);
                        }

                        if (await reader.NextResultAsync())
                        {
                            await reader.ReadAsync();
                            output.PopulateTotal(reader);
                        }

                        return(output);
                    }

                    return(null);
                },
                    dbParams);
            }

            return(results);
        }
Esempio n. 17
0
 public FileSettingsViewModel(
     IPagedResults <Role> results,
     RoleIndexOptions options,
     PagerOptions pager) : base(results, options, pager)
 {
 }
Esempio n. 18
0
        public async Task <IActionResult> Get(
            int page        = 1,
            int size        = 10,
            string keywords = "",
            SortBy sort     = SortBy.LastReply,
            OrderBy order   = OrderBy.Desc)
        {
            // Get search settings
            var searchSettings = await _searchSettingsStore.GetAsync();

            // Set default sort column if auto is specified
            if (sort == SortBy.LastReply)
            {
                // Get search settings
                if (searchSettings != null)
                {
                    sort = searchSettings.SearchType == SearchTypes.Tsql
                        ? SortBy.LastReply
                        : SortBy.Rank;
                }
                else
                {
                    sort = SortBy.LastReply;
                }
            }

            // Get results
            var entities = await _searchService
                           .ConfigureDb(o =>
            {
                if (searchSettings != null)
                {
                    o.SearchType = searchSettings.SearchType;
                }
            })
                           .ConfigureQuery(async q =>
            {
                // Hide hidden?
                if (!await _authorizationService.AuthorizeAsync(HttpContext.User,
                                                                Permissions.SearchHidden))
                {
                    q.HidePrivate.True();
                }

                // Hide spam?
                if (!await _authorizationService.AuthorizeAsync(HttpContext.User,
                                                                Permissions.SearchSpam))
                {
                    q.HideSpam.True();
                }

                // Hide deleted?
                if (!await _authorizationService.AuthorizeAsync(HttpContext.User,
                                                                Permissions.SearchDeleted))
                {
                    q.HideDeleted.True();
                }

                // Hide private?
                if (!await _authorizationService.AuthorizeAsync(HttpContext.User,
                                                                Permissions.SearchPrivate))
                {
                    q.HidePrivate.True();
                }
            })
                           .GetResultsAsync(new EntityIndexOptions()
            {
                Search = keywords,
                Sort   = sort,
                Order  = order
            }, new PagerOptions()
            {
                Page = page,
                Size = size
            });

            IPagedResults <SearchApiResult> results = null;

            if (entities != null)
            {
                results = new PagedResults <SearchApiResult>
                {
                    Total = entities.Total
                };

                var baseUrl = await _contextFacade.GetBaseUrlAsync();

                foreach (var entity in entities.Data)
                {
                    var url = baseUrl + _contextFacade.GetRouteUrl(new RouteValueDictionary()
                    {
                        ["area"]       = entity.ModuleId,
                        ["controller"] = "Home",
                        ["action"]     = "Display",
                        ["opts.id"]    = entity.Id,
                        ["opts.alias"] = entity.Alias
                    });

                    results.Data.Add(new SearchApiResult()
                    {
                        Id        = entity.Id,
                        CreatedBy = new UserApiResult()
                        {
                            Id          = entity.CreatedBy.Id,
                            DisplayName = entity.CreatedBy.DisplayName,
                            UserName    = entity.CreatedBy.UserName,
                            Avatar      = entity.CreatedBy.Avatar,
                            Url         = baseUrl + _contextFacade.GetRouteUrl(new RouteValueDictionary()
                            {
                                ["area"]       = "Plato.Users",
                                ["controller"] = "Home",
                                ["action"]     = "Display",
                                ["opts.id"]    = entity.CreatedBy.Id,
                                ["opts.alias"] = entity.CreatedBy.Alias
                            })
                        },
                        ModifiedBy = new UserApiResult()
                        {
                            Id          = entity.ModifiedBy.Id,
                            DisplayName = entity.ModifiedBy.DisplayName,
                            UserName    = entity.ModifiedBy.UserName,
                            Avatar      = entity.ModifiedBy.Avatar,
                            Url         = baseUrl + _contextFacade.GetRouteUrl(new RouteValueDictionary()
                            {
                                ["area"]       = "Plato.Users",
                                ["controller"] = "Home",
                                ["action"]     = "Display",
                                ["opts.id"]    = entity.ModifiedBy.Id,
                                ["opts.alias"] = entity.ModifiedBy.Alias
                            })
                        },
                        LastReplyBy = new UserApiResult()
                        {
                            Id          = entity.LastReplyBy.Id,
                            DisplayName = entity.LastReplyBy.DisplayName,
                            UserName    = entity.LastReplyBy.UserName,
                            Avatar      = entity.LastReplyBy.Avatar,
                            Url         = baseUrl + _contextFacade.GetRouteUrl(new RouteValueDictionary()
                            {
                                ["area"]       = "Plato.Users",
                                ["controller"] = "Home",
                                ["action"]     = "Display",
                                ["opts.id"]    = entity.LastReplyBy.Id,
                                ["opts.alias"] = entity.LastReplyBy.Alias
                            })
                        },
                        Title       = entity.Title,
                        Excerpt     = entity.Abstract,
                        Url         = url,
                        CreatedDate = new FriendlyDate()
                        {
                            Text  = entity.CreatedDate.ToPrettyDate(),
                            Value = entity.CreatedDate
                        },
                        ModifiedDate = new FriendlyDate()
                        {
                            Text  = entity.ModifiedDate.ToPrettyDate(),
                            Value = entity.ModifiedDate
                        },
                        LastReplyDate = new FriendlyDate()
                        {
                            Text  = entity.LastReplyDate.ToPrettyDate(),
                            Value = entity.LastReplyDate
                        },
                        Relevance = entity.Relevance
                    });
                }
            }

            IPagedApiResults <SearchApiResult> output = null;

            if (results != null)
            {
                output = new PagedApiResults <SearchApiResult>()
                {
                    Page       = page,
                    Size       = size,
                    Total      = results.Total,
                    TotalPages = results.Total.ToSafeCeilingDivision(size),
                    Data       = results.Data
                };
            }

            return(output != null
                ? base.Result(output)
                : base.NoResults());
        }
Esempio n. 19
0
        public async Task <IActionResult> Get(
            int page        = 1,
            int size        = 10,
            string keywords = "",
            string sort     = "LastReplyDate",
            OrderBy order   = OrderBy.Desc)
        {
            var entities = await GetEntities(
                page,
                size,
                keywords,
                sort,
                order);

            IPagedResults <EntityApiResult> results = null;

            if (entities != null)
            {
                results = new PagedResults <EntityApiResult>
                {
                    Total = entities.Total
                };

                var baseUrl = await _contextFacade.GetBaseUrlAsync();

                foreach (var entity in entities.Data)
                {
                    var createdByUrl = baseUrl + _contextFacade.GetRouteUrl(new RouteValueDictionary()
                    {
                        ["area"]       = "Plato.Users",
                        ["controller"] = "Home",
                        ["action"]     = "Display",
                        ["opts.id"]    = entity.CreatedBy.Id,
                        ["opts.alias"] = entity.CreatedBy.Alias
                    });

                    var modifiedByUrl = baseUrl + _contextFacade.GetRouteUrl(new RouteValueDictionary()
                    {
                        ["area"]       = "Plato.Users",
                        ["controller"] = "Home",
                        ["action"]     = "Display",
                        ["opts.id"]    = entity.ModifiedBy.Id,
                        ["opts.alias"] = entity.ModifiedBy.Alias
                    });

                    var url = _contextFacade.GetRouteUrl(new RouteValueDictionary()
                    {
                        ["area"]       = entity.ModuleId,
                        ["controller"] = "Home",
                        ["action"]     = "Display",
                        ["opts.id"]    = entity.Id,
                        ["opts.alias"] = entity.Alias
                    });

                    results.Data.Add(new EntityApiResult()
                    {
                        Id        = entity.Id,
                        CreatedBy = new UserApiResult()
                        {
                            Id          = entity.CreatedBy.Id,
                            DisplayName = entity.CreatedBy.DisplayName,
                            UserName    = entity.CreatedBy.UserName,
                            Url         = createdByUrl
                        },
                        ModifiedBy = new UserApiResult()
                        {
                            Id          = entity.ModifiedBy.Id,
                            DisplayName = entity.ModifiedBy.DisplayName,
                            UserName    = entity.ModifiedBy.UserName,
                            Url         = modifiedByUrl
                        },
                        LastReplyBy = new UserApiResult()
                        {
                            Id          = entity.ModifiedBy.Id,
                            DisplayName = entity.ModifiedBy.DisplayName,
                            UserName    = entity.ModifiedBy.UserName,
                            Url         = modifiedByUrl
                        },
                        Title       = entity.Title,
                        Message     = entity.Message,
                        Url         = url,
                        CreatedDate = new FriendlyDate()
                        {
                            Text  = entity.CreatedDate.ToPrettyDate(),
                            Value = entity.CreatedDate
                        }
                    });
                }
            }

            IPagedApiResults <EntityApiResult> output = null;

            if (results != null)
            {
                output = new PagedApiResults <EntityApiResult>()
                {
                    Page       = page,
                    Size       = size,
                    Total      = results.Total,
                    TotalPages = results.Total.ToSafeCeilingDivision(size),
                    Data       = results.Data
                };
            }

            return(output != null
                ? base.Result(output)
                : base.NoResults());
        }
Esempio n. 20
0
        public async Task <IActionResult> Index([FromBody] TagApiParams parameters)
        {
            // Get tags
            var tags = await GetTags(parameters);

            // Build results
            IPagedResults <TagApiResult> results = null;

            if (tags != null)
            {
                // Get feature for tags
                IShellFeature feature = null;
                if (parameters.FeatureId > 0)
                {
                    feature = await _shellFeatureStore.GetByIdAsync(parameters.FeatureId);
                }

                results = new PagedResults <TagApiResult>
                {
                    Total = tags.Total
                };

                var baseUrl = await _contextFacade.GetBaseUrlAsync();

                foreach (var tag in tags.Data)
                {
                    var url = _contextFacade.GetRouteUrl(new RouteValueDictionary()
                    {
                        ["area"]       = feature?.ModuleId ?? "Plato.Tags",
                        ["controller"] = "Home",
                        ["action"]     = "Tag",
                        ["opts.id"]    = tag.Id,
                        ["opts.alias"] = tag.Alias
                    });

                    results.Data.Add(new TagApiResult()
                    {
                        Id       = tag.Id,
                        Name     = tag.Name,
                        Entities = tag.TotalEntities.ToPrettyInt(),
                        Follows  = tag.TotalFollows.ToPrettyInt(),
                        Url      = url
                    });
                }
            }

            IPagedApiResults <TagApiResult> output = null;

            if (results != null)
            {
                output = new PagedApiResults <TagApiResult>()
                {
                    Page       = parameters.Page,
                    Size       = parameters.Size,
                    Total      = results.Total,
                    TotalPages = results.Total.ToSafeCeilingDivision(parameters.Size),
                    Data       = results.Data
                };
            }

            return(output != null
                ? base.Result(output)
                : base.NoResults());
        }
Esempio n. 21
0
        async Task <IDictionary <int, IList <Label> > > BuildLookUpTable(IEnumerable <Label> labels)
        {
            // Get topic index view model from context
            var viewModel = _actionContextAccessor.ActionContext.HttpContext.Items[typeof(EntityIndexViewModel <Topic>)] as EntityIndexViewModel <Topic>;

            if (viewModel == null)
            {
                return(null);
            }

            // Get all entities for our current view
            var entities = await _entityService
                           .ConfigureQuery(async q =>
            {
                // Hide private?
                if (!await _authorizationService.AuthorizeAsync(_httpContextAccessor.HttpContext.User,
                                                                Permissions.ViewPrivateTopics))
                {
                    q.HidePrivate.True();
                }

                // Hide hidden?
                if (!await _authorizationService.AuthorizeAsync(_httpContextAccessor.HttpContext.User,
                                                                Permissions.ViewHiddenTopics))
                {
                    q.HideHidden.True();
                }

                // Hide spam?
                if (!await _authorizationService.AuthorizeAsync(_httpContextAccessor.HttpContext.User,
                                                                Permissions.ViewSpamTopics))
                {
                    q.HideSpam.True();
                }

                // Hide deleted?
                if (!await _authorizationService.AuthorizeAsync(_httpContextAccessor.HttpContext.User,
                                                                Permissions.ViewDeletedTopics))
                {
                    q.HideDeleted.True();
                }
            })
                           .GetResultsAsync(viewModel?.Options, viewModel?.Pager);

            // Get all entity label relationships for displayed entities
            IPagedResults <EntityLabel> entityLabels = null;

            if (entities?.Data != null)
            {
                entityLabels = await _entityLabelStore.QueryAsync()
                               .Select <EntityLabelQueryParams>(q =>
                {
                    q.EntityId.IsIn(entities.Data.Select(e => e.Id).ToArray());
                })
                               .ToList();
            }

            // Build a dictionary of entity and label relationships
            var output = new ConcurrentDictionary <int, IList <Label> >();

            if (entityLabels?.Data != null)
            {
                var labelList = labels.ToList();
                foreach (var entityLabel in entityLabels.Data)
                {
                    var label = labelList.FirstOrDefault(l => l.Id == entityLabel.LabelId);
                    if (label != null)
                    {
                        output.AddOrUpdate(entityLabel.EntityId, new List <Label>()
                        {
                            label
                        }, (k, v) =>
                        {
                            v.Add(label);
                            return(v);
                        });
                    }
                }
            }

            return(output);
        }
Esempio n. 22
0
        public async Task <IActionResult> Get(
            int page        = 1,
            int size        = 10,
            string keywords = "",
            string sort     = "LastLoginDate",
            OrderBy order   = OrderBy.Desc)
        {
            var users = await GetUsers(
                page,
                size,
                keywords,
                sort,
                order);

            IPagedResults <UserApiResult> results = null;

            if (users != null)
            {
                results = new PagedResults <UserApiResult>
                {
                    Total = users.Total
                };

                var baseUrl = await _contextFacade.GetBaseUrlAsync();

                foreach (var user in users.Data)
                {
                    var profileUrl = baseUrl + _contextFacade.GetRouteUrl(new RouteValueDictionary()
                    {
                        ["area"]       = "Plato.Users",
                        ["controller"] = "Home",
                        ["action"]     = "Display",
                        ["opts.id"]    = user.Id,
                        ["opts.alias"] = user.Alias
                    });

                    results.Data.Add(new UserApiResult()
                    {
                        Id          = user.Id,
                        DisplayName = user.DisplayName,
                        UserName    = user.UserName,
                        Url         = profileUrl,
                        Avatar      = user.Avatar
                    });
                }
            }

            IPagedApiResults <UserApiResult> output = null;

            if (results != null)
            {
                output = new PagedApiResults <UserApiResult>()
                {
                    Page       = page,
                    Size       = size,
                    Total      = results.Total,
                    TotalPages = results.Total.ToSafeCeilingDivision(size),
                    Data       = results.Data
                };
            }

            return(output != null
                ? base.Result(output)
                : base.NoResults());
        }
Esempio n. 23
0
        public async Task <IActionResult> Get(
            int page      = 1,
            int size      = 10,
            string sort   = "CreatedDate",
            OrderBy order = OrderBy.Desc)
        {
            // Ensure we are authenticated
            var user = await base.GetAuthenticatedUserAsync();

            if (user == null)
            {
                return(base.UnauthorizedException());
            }

            // Get notifications
            var userNotifications = await GetUserNotifications(
                page,
                size,
                user.Id,
                sort,
                order);

            IPagedResults <UserNotificationApiResult> results = null;

            if (userNotifications != null)
            {
                results = new PagedResults <UserNotificationApiResult>
                {
                    Total = userNotifications.Total
                };

                var baseUrl = await _contextFacade.GetBaseUrlAsync();

                foreach (var userNotification in userNotifications.Data)
                {
                    var toUrl = baseUrl + _contextFacade.GetRouteUrl(new RouteValueDictionary()
                    {
                        ["area"]       = "Plato.Users",
                        ["controller"] = "Home",
                        ["action"]     = "Display",
                        ["opts.id"]    = userNotification.To.Id,
                        ["opts.alias"] = userNotification.To.Alias
                    });

                    var fromUrl = baseUrl + _contextFacade.GetRouteUrl(new RouteValueDictionary()
                    {
                        ["area"]       = "Plato.Users",
                        ["controller"] = "Home",
                        ["action"]     = "Display",
                        ["opts.id"]    = userNotification.From.Id,
                        ["opts.alias"] = userNotification.From.Alias
                    });

                    var url = userNotification.Url;
                    if (url != null)
                    {
                        var noHttp      = url.IndexOf("http://", StringComparison.OrdinalIgnoreCase) == -1;
                        var noHttps     = url.IndexOf("https://", StringComparison.OrdinalIgnoreCase) == -1;
                        var relativeUrl = (noHttp && noHttps);
                        if (relativeUrl)
                        {
                            url = baseUrl + url;
                        }
                    }

                    results.Data.Add(new UserNotificationApiResult()
                    {
                        Id = userNotification.Id,
                        To = new UserApiResult()
                        {
                            Id          = userNotification.To.Id,
                            DisplayName = userNotification.To.DisplayName,
                            UserName    = userNotification.To.UserName,
                            Avatar      = userNotification.To.Avatar,
                            Url         = toUrl
                        },
                        From = new UserApiResult()
                        {
                            Id          = userNotification.From.Id,
                            DisplayName = userNotification.From.DisplayName,
                            UserName    = userNotification.From.UserName,
                            Avatar      = userNotification.From.Avatar,
                            Url         = fromUrl
                        },
                        Title   = userNotification.Title,
                        Message = userNotification.Message,
                        Url     = url,
                        Date    = new FriendlyDate()
                        {
                            Text  = userNotification.CreatedDate.ToPrettyDate(),
                            Value = userNotification.CreatedDate
                        }
                    });
                }
            }

            IPagedApiResults <UserNotificationApiResult> output = null;

            if (results != null)
            {
                output = new PagedApiResults <UserNotificationApiResult>()
                {
                    Page       = page,
                    Size       = size,
                    Total      = results.Total,
                    TotalPages = results.Total.ToSafeCeilingDivision(size),
                    Data       = results.Data
                };
            }

            return(output != null
                ? base.Result(output)
                : base.NoResults());
        }
Esempio n. 24
0
        public async Task <IActionResult> Get(
            int page          = 1,
            int size          = 10,
            int entityId      = 0,
            int entityReplyId = 0,
            string sort       = "CreatedDate",
            OrderBy order     = OrderBy.Desc)
        {
            // Get histories
            var histories = await GetEntityHistory(
                page,
                size,
                entityId,
                entityReplyId,
                sort,
                order);

            IPagedResults <EntityHistoryApiResult> results = null;

            if (histories != null)
            {
                results = new PagedResults <EntityHistoryApiResult>
                {
                    Total = histories.Total
                };

                var baseUrl = await _contextFacade.GetBaseUrlAsync();

                foreach (var history in histories.Data)
                {
                    var createdByUrl = baseUrl + _contextFacade.GetRouteUrl(new RouteValueDictionary()
                    {
                        ["area"]       = "Plato.Users",
                        ["controller"] = "Home",
                        ["action"]     = "Display",
                        ["opts.id"]    = history.CreatedBy.Id,
                        ["opts.alias"] = history.CreatedBy.Alias
                    });

                    var sb = new StringBuilder();
                    sb.Append(history.CreatedBy.DisplayName)
                    .Append(" ")
                    .Append(history.MajorVersion == 1 && history.MinorVersion == 0
                            ? T["created"].Value
                            : T["edited"].Value)
                    .Append(" ")
                    .Append(history.CreatedDate.ToPrettyDate());

                    results.Data.Add(new EntityHistoryApiResult()
                    {
                        Id        = history.Id,
                        Text      = sb.ToString(),
                        Version   = history.Version,
                        CreatedBy = new UserApiResult()
                        {
                            Id          = history.CreatedBy.Id,
                            DisplayName = history.CreatedBy.DisplayName,
                            UserName    = history.CreatedBy.UserName,
                            Avatar      = history.CreatedBy.Avatar,
                            Url         = createdByUrl
                        },
                        Date = new FriendlyDate()
                        {
                            Text  = history.CreatedDate.ToPrettyDate(),
                            Value = history.CreatedDate
                        }
                    });
                }
            }

            IPagedApiResults <EntityHistoryApiResult> output = null;

            if (results != null)
            {
                output = new PagedApiResults <EntityHistoryApiResult>()
                {
                    Page       = page,
                    Size       = size,
                    Total      = results.Total,
                    TotalPages = results.Total.ToSafeCeilingDivision(size),
                    Data       = results.Data
                };
            }

            return(output != null
                ? base.Result(output)
                : base.NoResults());
        }
Esempio n. 25
0
        public async Task <IActionResult> Get(
            int page        = 1,
            int size        = 10,
            string keywords = "",
            string sort     = "TotalEntities",
            OrderBy order   = OrderBy.Desc)
        {
            var tags = await GetTags(
                page,
                size,
                keywords,
                sort,
                order);

            IPagedResults <TagApiResult> results = null;

            if (tags != null)
            {
                results = new PagedResults <TagApiResult>
                {
                    Total = tags.Total
                };

                var baseUrl = await _contextFacade.GetBaseUrlAsync();

                foreach (var tag in tags.Data)
                {
                    var url = _contextFacade.GetRouteUrl(new RouteValueDictionary()
                    {
                        ["area"]       = "Plato.Tags",
                        ["controller"] = "Home",
                        ["action"]     = "Tag",
                        ["opts.id"]    = tag.Id,
                        ["opts.alias"] = tag.Alias
                    });

                    results.Data.Add(new TagApiResult()
                    {
                        Id   = tag.Id,
                        Name = tag.Name,
                        Url  = url
                    });
                }
            }

            IPagedApiResults <TagApiResult> output = null;

            if (results != null)
            {
                output = new PagedApiResults <TagApiResult>()
                {
                    Page       = page,
                    Size       = size,
                    Total      = results.Total,
                    TotalPages = results.Total.ToSafeCeilingDivision(size),
                    Data       = results.Data
                };
            }

            return(output != null
                ? base.Result(output)
                : base.NoResults());
        }