Esempio n. 1
0
        async Task SendLastUpdatedContentsAsync()
        {
            try
            {
                var filterBy = Filters <Content> .And(
                    Filters <Content> .Equals("Status", $"{ApprovalStatus.Published}"),
                    Filters <Content> .GreaterOrEquals("StartingTime", "@nowHourQuater()"),
                    Filters <Content> .Or(
                        Filters <Content> .Equals("EndingTime", "-"),
                        Filters <Content> .LessThan("EndingTime", "@nowHourQuater()")
                        ),
                    Filters <Content> .IsNull("ParentID")
                    );

                Func <string> func_GetNowHourQuater = () => this.GetNowHourQuater().ToDTString();
                filterBy.Prepare(null, null, new Dictionary <string, object>
                {
                    { "nowHourQuater", func_GetNowHourQuater }
                });
                var sortBy = Sorts <Content> .Descending("StartingTime").ThenByDescending("LastUpdated");

                var objects = await Content.FindAsync(filterBy, sortBy, 20, 1, $"{this.GetCacheKey(filterBy, sortBy)}:1", this.CancellationTokenSource.Token).ConfigureAwait(false);

                var messages = objects.Select(content => new BaseMessage
                {
                    Type = $"{this.ServiceName}#Content#Update",
                    Data = content.ToJson()
                }).ToList();
                await this.SendUpdateMessagesAsync(messages, "*", null, this.CancellationTokenSource.Token).ConfigureAwait(false);
            }
            catch { }
        }
Esempio n. 2
0
        public async Task <long> GetVersion(string type, string id)
        {
            FilterDefinition <EventCommit> query = CommitFilters.ByAggregate(type, id);

            EventCommit result = await Collection.Find(query).Sort(Sorts.Descending(x => x.VersionEvents))
                                 .FirstOrDefaultAsync();

            return(result.VersionEvents);
        }
Esempio n. 3
0
        private async IAsyncEnumerable <EventCommit> Enumerate(FilterDefinition <EventCommit> query,
                                                               EnumerateDirection direction, int?limit,
                                                               [EnumeratorCancellation] CancellationToken token)
        {
            FindOptions options;

            if (DeactivateTimeoutOnRead)
            {
                options = new FindOptions()
                {
                    NoCursorTimeout = true,
                    MaxTime         = TimeSpan.MaxValue,
                    MaxAwaitTime    = TimeSpan.MaxValue,
                };
            }
            else
            {
                options = new FindOptions();
            }

            SortDefinition <EventCommit> sort;

            if (direction == EnumerateDirection.Ascending)
            {
                sort = Sorts.Ascending(x => x.Ordinal);
            }
            else
            {
                sort = Sorts.Descending(x => x.Ordinal);
            }

            var find = Collection
                       .Find(query, options)
                       .Sort(sort);


            if (limit.HasValue && limit > 0)
            {
                find = find.Limit(limit);
            }

            IAsyncCursor <EventCommit> cursor = await find
                                                .ToCursorAsync(token);

            while (await cursor.MoveNextAsync(token) && !token.IsCancellationRequested)
            {
                foreach (EventCommit item in cursor.Current)
                {
                    token.ThrowIfCancellationRequested();
                    yield return(item);
                }
            }
        }
        public async Task <JToken> FetchLogsAsync(int pageNumber = 1, int pageSize = 100, string correlationID = null, string developerID = null, string appID = null, string serviceName = null, string objectName = null, CancellationToken cancellationToken = default)
        {
            var  logs         = new JArray();
            long totalRecords = 0;

            using (var context = new RepositoryContext(false, await this.LoggingDataSource.StartSessionAsync <LoggingItem>(cancellationToken).ConfigureAwait(false)))
            {
                var filter = Filters <LoggingItem> .And();

                if (!string.IsNullOrWhiteSpace(correlationID))
                {
                    filter.Add(Filters <LoggingItem> .Equals("CorrelationID", correlationID));
                }
                if (!string.IsNullOrWhiteSpace(developerID))
                {
                    filter.Add(Filters <LoggingItem> .Equals("DeveloperID", developerID));
                }
                if (!string.IsNullOrWhiteSpace(appID))
                {
                    filter.Add(Filters <LoggingItem> .Equals("AppID", appID));
                }
                if (!string.IsNullOrWhiteSpace(serviceName))
                {
                    filter.Add(Filters <LoggingItem> .Equals("ServiceName", serviceName));
                }
                if (!string.IsNullOrWhiteSpace(objectName))
                {
                    filter.Add(Filters <LoggingItem> .Equals("ObjectName", objectName));
                }

                totalRecords = await RepositoryMediator.CountAsync(context, this.LoggingDataSource, filter, null, false, null, 0, cancellationToken).ConfigureAwait(false);

                var loggingItems = await RepositoryMediator.FindAsync(context, this.LoggingDataSource, filter, Sorts <LoggingItem> .Descending("Time"), pageSize, pageNumber, null, false, null, 0, cancellationToken).ConfigureAwait(false);

                loggingItems?.ForEach(loggingItem => logs.Add(loggingItem.ToJson()));
            }

            var totalPages = new Tuple <long, int>(totalRecords, pageSize).GetTotalPages();

            return(new JObject
            {
                { "Pagination", new Tuple <long, int, int, int>(totalRecords, totalPages, pageSize, totalPages > 0 && pageNumber > totalPages ? totalPages : pageNumber).GetPagination() },
                { "Objects", logs }
            });
        }
Esempio n. 5
0
        async Task <JObject> SearchContentsAsync(RequestInfo requestInfo, CancellationToken cancellationToken)
        {
            // check permissions
            if (!await this.IsAuthorizedAsync(requestInfo, "content", Components.Security.Action.View, cancellationToken).ConfigureAwait(false))
            {
                throw new AccessDeniedException();
            }

            // prepare
            var request = requestInfo.GetRequestExpando();

            var query = request.Get <string>("FilterBy.Query");

            if (request.Get <ExpandoObject>("FilterBy", null)?.ToFilterBy <Content>() is FilterBys <Content> filter)
            {
                if (filter.Children.FirstOrDefault(f => f is FilterBy <Content> && (f as FilterBy <Content>).Attribute.IsEquals("Status")) == null && !await this.IsServiceAdministratorAsync(requestInfo).ConfigureAwait(false))
                {
                    filter.Add(Filters <Content> .Equals("Status", $"{ApprovalStatus.Published}"));
                }
            }
            else
            {
                filter = Filters <Content> .And(
                    Filters <Content> .Equals("Status", $"{ApprovalStatus.Published}"),
                    Filters <Content> .GreaterOrEquals("StartingTime", "@nowHourQuater()"),
                    Filters <Content> .Or(
                        Filters <Content> .Equals("EndingTime", "-"),
                        Filters <Content> .LessThan("EndingTime", "@nowHourQuater()")
                        ),
                    Filters <Content> .IsNull("ParentID")
                    );
            }

            var filterBy = filter.Clone();

            if (filterBy.Children.FirstOrDefault(f => f is FilterBy <Content> && (f as FilterBy <Content>).Attribute.IsEquals("StartingTime")) is FilterBy <Content> startingTime && "@nowHourQuater()".IsStartsWith(startingTime.Value as string))
            {
                startingTime.Value = this.GetNowHourQuater();
            }
            if (filterBy.Children.FirstOrDefault(f => f is FilterBy <Content> && (f as FilterBy <Content>).Attribute.IsEquals("EndingTime")) is FilterBy <Content> endingTime && "@nowHourQuater()".IsStartsWith(endingTime.Value as string))
            {
                endingTime.Value = this.GetNowHourQuater().ToDTString();
            }
            if (filterBy.Children.FirstOrDefault(f => f is FilterBys <Content> && (f as FilterBys <Content>).Operator.Equals(GroupOperator.Or) && (f as FilterBys <Content>).Children.FirstOrDefault(cf => cf is FilterBy <Content> && (cf as FilterBy <Content>).Attribute.IsEquals("EndingTime")) != null) is FilterBys <Content> orEndingTime)
            {
                orEndingTime.Children.Where(f => f is FilterBy <Content> && (f as FilterBy <Content>).Attribute.IsEquals("EndingTime") && "@nowHourQuater()".IsStartsWith((f as FilterBy <Content>).Value as string)).ForEach(f => (f as FilterBy <Content>).Value = this.GetNowHourQuater().ToDTString());
            }

            Func <string> func_GetNowHourQuater = () => this.GetNowHourQuater().ToDTString();

            filterBy.Prepare(null, requestInfo, new Dictionary <string, object>
            {
                { "nowHourQuater", func_GetNowHourQuater }
            });

            var sortBy = request.Get <ExpandoObject>("SortBy", null)?.ToSortBy <Content>();

            if (sortBy == null && string.IsNullOrWhiteSpace(query))
            {
                var filterByParentID = filterBy.Children.FirstOrDefault(f => f is FilterBy <Content> && (f as FilterBy <Content>).Attribute.IsEquals("ParentID"));
                sortBy = filterByParentID != null && filterByParentID is FilterBy <Content> && (filterByParentID as FilterBy <Content>).Value != null && (filterByParentID as FilterBy <Content>).Value.ToString().IsValidUUID()
                                        ? Sorts <Content> .Descending("OrderIndex")
                                        : Sorts <Content> .Descending("StartingTime").ThenByDescending("LastUpdated");
            }

            var pagination = request.Has("Pagination")
                                ? request.Get <ExpandoObject>("Pagination").GetPagination()
                                : new Tuple <long, int, int, int>(-1, 0, 20, 1);

            var pageNumber = pagination.Item4;

            // check cache
            var cacheKey = string.IsNullOrWhiteSpace(query)
                                ? this.GetCacheKey(filterBy, sortBy)
                                : "";

            var json = !cacheKey.Equals("")
                                ? await Utility.Cache.GetAsync <string>($"{cacheKey }{pageNumber}:json").ConfigureAwait(false)
                                : "";

            if (!string.IsNullOrWhiteSpace(json))
            {
                return(JObject.Parse(json));
            }

            // prepare pagination
            var totalRecords = pagination.Item1 > -1
                                ? pagination.Item1
                                : string.IsNullOrWhiteSpace(query)
                                        ? await Content.CountAsync(filterBy, $"{cacheKey}total", cancellationToken).ConfigureAwait(false)
                                        : await Content.CountAsync(query, filterBy, cancellationToken).ConfigureAwait(false);

            var pageSize = pagination.Item3;

            var totalPages = (new Tuple <long, int>(totalRecords, pageSize)).GetTotalPages();

            if (totalPages > 0 && pageNumber > totalPages)
            {
                pageNumber = totalPages;
            }

            // search
            var objects = totalRecords > 0
                                ? string.IsNullOrWhiteSpace(query)
                                        ? await Content.FindAsync(filterBy, sortBy, pageSize, pageNumber, $"{cacheKey}{pageNumber}", cancellationToken).ConfigureAwait(false)
                                        : await Content.SearchAsync(query, filterBy, pageSize, pageNumber, cancellationToken).ConfigureAwait(false)
                                : new List <Content>();

            // build the result
            pagination = new Tuple <long, int, int, int>(totalRecords, totalPages, pageSize, pageNumber);
            var files = totalRecords > 0
                                ? await this.GetFilesAsync(requestInfo, objects.Select(obj => obj.ID).ToString(",") + ",", objects.ToJObject("ID", obj => new JValue(obj.Title)).ToString(Formatting.None), cancellationToken).ConfigureAwait(false)
                                : new JObject();

            var result = new JObject
            {
                { "FilterBy", filter.ToClientJson(query) },
                { "SortBy", sortBy?.ToClientJson() },
                { "Pagination", pagination.GetPagination() },
                { "Objects", objects.ToJsonArray(ojson =>
                    {
                        ojson["MediaURI"] = ojson.Get <string>("MediaURI").Replace("~~", this.FilesHttpURI);
                        ojson.UpdateFiles(files[ojson.Get <string>("ID")]);
                    }) }
            };

            // update cache
            if (!cacheKey.Equals(""))
            {
                await Utility.Cache.SetAsync($"{cacheKey }{pageNumber}:json", result.ToString(this.IsDebugLogEnabled ? Formatting.Indented : Formatting.None), Utility.Cache.ExpirationTime / 2, cancellationToken).ConfigureAwait(false);
            }

            // return the result
            return(result);
        }