Ejemplo n.º 1
0
        /// <summary>
        /// Returns the result of getting the view.
        /// </summary>
        /// <returns>The view.</returns>
        public async Task OnGet()
        {
            var sessionErrors  = HttpContext.Session.GetString("SettingsErrors");
            var sessionOptions = HttpContext.Session.GetString("SettingsErrorsOptions");

            HttpContext.Session.Remove("SettingsErrors");
            HttpContext.Session.Remove("SettingsErrorsOptions");
            if (!string.IsNullOrEmpty(sessionErrors))
            {
                var errors  = JsonConvert.DeserializeObject <List <ModelStateError> >(sessionErrors);
                var options = JsonConvert.DeserializeObject <SelectedOptions>(sessionOptions);
                foreach (var error in errors)
                {
                    ModelState.AddModelError($"AppOptions.{error.Key}", error.ErrorMessage);
                }
                AppOptions          = options;
                TempData["Invalid"] = true;
                return;
            }

            var space = await _client.GetSpace();

            SpaceName = space.Name;
            AppOptions.EnableEditorialFeatures = HttpContext.Session.GetString("EditorialFeatures") == "Enabled";
            IsUsingCustomCredentials           = _manager.IsUsingCustomCredentials;
        }
Ejemplo n.º 2
0
        public async Task <IActionResult> Index()
        {
            if (appsettingsEmpty)
            {
                return(View("NoAppSettings"));
            }

            var space = await _client.GetSpace();

            var entries = await _client.GetEntries <dynamic>();

            var assets = await _client.GetAssets();

            var contentfulExampleModel = new ContentfulExampleModel()
            {
                Space   = space,
                Entries = entries.ToList(),
                Assets  = assets.ToList()
            };

            return(View(contentfulExampleModel));
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Invokes the view component and returns the result.
        /// </summary>
        /// <returns>The view.</returns>
        public async Task <IViewComponentResult> InvokeAsync()
        {
            Space space = null;

            try
            {
                // Try to get the space, if this fails we're probably in a state of bad credentials.
                space = await _client.GetSpace();
            }
            catch
            {
                // Getting the space failed, set some default values.
                space = new Space()
                {
                    Locales = new List <Locale>()
                    {
                        new Locale
                        {
                            Code    = "en-US",
                            Default = true,
                            Name    = "U.S. English"
                        }
                    }
                };
            }
            var selectedLocale = HttpContext.Session.GetString(Startup.LOCALE_KEY) ?? CultureInfo.CurrentCulture.ToString();
            var localeInfo     = new LocalesInfo
            {
                Locales        = space.Locales,
                SelectedLocale = space?.Locales.FirstOrDefault(c => c.Code == selectedLocale) ?? space?.Locales.Single(c => c.Default),
            };

            HttpContext.Session.SetString(Startup.LOCALE_KEY, localeInfo.SelectedLocale?.Code);

            localeInfo.UsePreviewApi = _client.IsPreviewClient;

            return(View(localeInfo));
        }
Ejemplo n.º 4
0
        /// <inheritdoc />
        public IEnumerable <IDocument> Execute(IReadOnlyList <IDocument> inputs, IExecutionContext context)
        {
            Space space = null;

            try
            {
                space = _client.GetSpace().Result;
            }
            catch (AggregateException ae)
            {
                ae.Handle((ex) => {
                    if (ex is ContentfulException)
                    {
                        Trace.TraceError($"Error when fetching space from Contentful: {ex.Message}");
                        Trace.TraceError($"Details: {(ex as ContentfulException).ErrorDetails.Errors}");
                        Trace.TraceError($"ContentfulRequestId:{(ex as ContentfulException).RequestId}");
                    }

                    return(false);
                });
            }

            var queryBuilder = CreateQueryBuilder();
            ContentfulCollection <JObject> entries = null;

            try
            {
                entries = _client.GetEntries(queryBuilder).Result;
            }
            catch (AggregateException ae)
            {
                ae.Handle((ex) => {
                    if (ex is ContentfulException)
                    {
                        Trace.TraceError($"Error when fetching entries from Contentful: {ex.Message}");
                        Trace.TraceError($"Details: {(ex as ContentfulException).ErrorDetails.Errors}");
                        Trace.TraceError($"ContentfulRequestId:{(ex as ContentfulException).RequestId}");
                    }

                    return(false);
                });
            }

            if (_recursive && entries.Total > entries.Items.Count())
            {
                entries = FetchEntriesRecursively(entries);
            }

            var includedAssets  = entries.IncludedAssets;
            var includedEntries = entries.IncludedEntries;

            var locales = space.Locales.Where(l => l.Default);

            if (_locale == "*")
            {
                locales = space.Locales;
            }
            else if (!string.IsNullOrEmpty(_locale))
            {
                locales = space.Locales.Where(l => l.Code == _locale);
            }

            if (!locales.Any())
            {
                //Warn or throw here?
                throw new ArgumentException($"Locale {_locale} not found for space. Note that locale codes are case-sensitive.");
            }

            foreach (var entry in entries)
            {
                foreach (var locale in locales)
                {
                    var localeCode = locale.Code;

                    var items = (entry as IEnumerable <KeyValuePair <string, JToken> >).ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

                    var content = "No content";

                    content = items.ContainsKey(_contentField) ? GetNextValidJTokenValue(items[_contentField], locale).Value <string>() : "No content";

                    if (string.IsNullOrEmpty(_contentField))
                    {
                        content = "";
                    }

                    var metaData = items
                                   .Where(c => !c.Key.StartsWith("$") && c.Key != "sys")
                                   .Select(c => new KeyValuePair <string, object>(c.Key, GetNextValidJTokenValue(c.Value, locale))).ToList();
                    metaData.Add(new KeyValuePair <string, object>(ContentfulKeys.EntryId, $"{entry["sys"]["id"]}"));
                    metaData.Add(new KeyValuePair <string, object>(ContentfulKeys.EntryLocale, localeCode));
                    metaData.Add(new KeyValuePair <string, object>(ContentfulKeys.IncludedAssets, includedAssets));
                    metaData.Add(new KeyValuePair <string, object>(ContentfulKeys.IncludedEntries, includedEntries));
                    var doc = context.GetDocument(context.GetContentStream(content), metaData);

                    yield return(doc);
                }
            }

            JToken GetNextValidJTokenValue(JToken token, Locale locale)
            {
                var localizedField = token.Children <JProperty>().FirstOrDefault(c => c.Name == locale.Code);

                if (localizedField == null && locale.FallbackCode != null)
                {
                    return(GetNextValidJTokenValue(token, locales.FirstOrDefault(c => c.Code == locale.FallbackCode)));
                }

                return(localizedField?.Value);
            }
        }
Ejemplo n.º 5
0
        private IEnumerable <ValidationResult> MakeTestCalls(HttpClient httpClient, IContentfulClient contentfulClient, IViewLocalizer localizer)
        {
            ValidationResult validationResult = null;

            try
            {
                var space = contentfulClient.GetSpace().Result;
            }
            catch (AggregateException ae)
            {
                ae.Handle((ce) => {
                    if (ce is ContentfulException)
                    {
                        if ((ce as ContentfulException).StatusCode == 401)
                        {
                            validationResult = new ValidationResult(localizer["deliveryKeyInvalidLabel"].Value, new[] { nameof(AccessToken) });
                        }
                        else if ((ce as ContentfulException).StatusCode == 404)
                        {
                            validationResult = new ValidationResult(localizer["spaceOrTokenInvalid"].Value, new[] { nameof(SpaceId) });
                        }
                        else
                        {
                            validationResult = new ValidationResult($"{localizer["somethingWentWrongLabel"].Value}: {ce.Message}", new[] { nameof(AccessToken) });
                        }
                        return(true);
                    }
                    return(false);
                });
            }

            if (validationResult != null)
            {
                yield return(validationResult);
            }

            contentfulClient = new ContentfulClient(httpClient, AccessToken, PreviewToken, SpaceId, true);

            try
            {
                var space = contentfulClient.GetSpace().Result;
            }
            catch (AggregateException ae)
            {
                ae.Handle((ce) => {
                    if (ce is ContentfulException)
                    {
                        if ((ce as ContentfulException).StatusCode == 401)
                        {
                            validationResult = new ValidationResult(localizer["previewKeyInvalidLabel"].Value, new[] { nameof(PreviewToken) });
                        }
                        else if ((ce as ContentfulException).StatusCode == 404)
                        {
                            validationResult = new ValidationResult(localizer["spaceOrTokenInvalid"].Value, new[] { nameof(SpaceId) });
                        }
                        else
                        {
                            validationResult = new ValidationResult($"{localizer["somethingWentWrongLabel"].Value}: {ce.Message}", new[] { nameof(PreviewToken) });
                        }
                        return(true);
                    }
                    return(false);
                });
            }

            if (validationResult != null)
            {
                yield return(validationResult);
            }
        }