Skip to content

Commit

Permalink
Cleanup IContentManager (#16077)
Browse files Browse the repository at this point in the history
---------

Co-authored-by: Hisham Bin Ateya <hishamco_2007@yahoo.com>
Co-authored-by: Zoltán Lehóczky <zoltan.lehoczky@lombiq.com>
  • Loading branch information
3 people authored May 22, 2024
1 parent 58149c4 commit 77c69c6
Show file tree
Hide file tree
Showing 15 changed files with 291 additions and 309 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ public async Task<IActionResult> Update([FromForm] DashboardPartViewModel[] part
return Unauthorized();
}

var contentItemIds = parts.Select(i => i.ContentItemId).ToList();
var contentItemIds = parts.Select(i => i.ContentItemId).ToArray();

// Load the latest version first if any.
var latestItems = await _contentManager.GetAsync(contentItemIds, VersionOptions.Latest);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,15 +91,15 @@ public async Task<IActionResult> SearchContentItems(string part, string field, s
.GetAsync(results.Select(r => r.ContentItemId));

var selectedItems = new List<VueMultiselectItemViewModel>();
var user = _httpContextAccessor.HttpContext?.User;
foreach (var contentItem in contentItems)
{
selectedItems.Add(new VueMultiselectItemViewModel()
{
Id = contentItem.ContentItemId,
DisplayText = contentItem.ToString(),
HasPublished = contentItem.IsPublished(),
IsViewable = await _authorizationService.AuthorizeAsync(_httpContextAccessor.HttpContext?.User,
CommonPermissions.EditContent, contentItem)
IsViewable = await _authorizationService.AuthorizeAsync(user, CommonPermissions.EditContent, contentItem)
});
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
@model OrchardCore.ContentFields.ViewModels.DisplayContentPickerFieldViewModel
@using OrchardCore.ContentManagement
@using OrchardCore.Mvc.Utilities
@using OrchardCore.ContentManagement.Metadata.Models

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,17 +20,15 @@ public async ValueTask<FluidValue> ProcessAsync(FluidValue input, FilterArgument
{
if (input.Type == FluidValues.Array)
{
// List of content item ids
var contentItemIds = input.Enumerate(ctx).Select(x => x.ToStringValue()).ToArray();
// List of content item ids to return.
var contentItemIds = input.Enumerate(ctx).Select(x => x.ToStringValue());

return FluidValue.Create(await _contentManager.GetAsync(contentItemIds), ctx.Options);
}
else
{
var contentItemId = input.ToStringValue();

return FluidValue.Create(await _contentManager.GetAsync(contentItemId), ctx.Options);
}
var contentItemId = input.ToStringValue();

return FluidValue.Create(await _contentManager.GetAsync(contentItemId), ctx.Options);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,13 @@
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using OrchardCore;
using OrchardCore.ContentManagement;
using OrchardCore.ContentManagement.Records;
using YesSql;

#pragma warning disable CA1050 // Declare types in namespaces
namespace OrchardCore;

public static class ContentRazorHelperExtensions
#pragma warning restore CA1050 // Declare types in namespaces
{
/// <summary>
/// Returns a content item id by its handle.
Expand All @@ -30,54 +29,53 @@ public static Task<string> GetContentItemIdByHandleAsync(this IOrchardHelper orc
/// </summary>
/// <param name="orchardHelper">The <see cref="IOrchardHelper"/>.</param>
/// <param name="handle">The handle to load.</param>
/// <param name="latest">Whether a draft should be loaded if available. <c>false</c> by default.</param>
/// <example>GetContentItemByHandleAsync("alias:carousel").</example>
/// <example>GetContentItemByHandleAsync("slug:myblog/my-blog-post", true).</example>
/// <param name="option">A specific version to load or the default version.</param>
/// <returns>A content item with the specific name, or <c>null</c> if it doesn't exist.</returns>
public static async Task<ContentItem> GetContentItemByHandleAsync(this IOrchardHelper orchardHelper, string handle, bool latest = false)
public static async Task<ContentItem> GetContentItemByHandleAsync(this IOrchardHelper orchardHelper, string handle, VersionOptions option = null)
{
var contentItemId = await GetContentItemIdByHandleAsync(orchardHelper, handle);
var contentManager = orchardHelper.HttpContext.RequestServices.GetService<IContentManager>();
return await contentManager.GetAsync(contentItemId, latest ? VersionOptions.Latest : VersionOptions.Published);
return await contentManager.GetAsync(contentItemId, option);
}

/// <summary>
/// Loads a content item by its id.
/// </summary>
/// <param name="orchardHelper">The <see cref="IOrchardHelper"/>.</param>
/// <param name="contentItemId">The content item id to load.</param>
/// <param name="latest">Whether a draft should be loaded if available. <c>false</c> by default.</param>
/// <example>GetContentItemByIdAsync("4xxxxxxxxxxxxxxxx").</example>
/// <param name="option">A specific version to load or the default version.</param>
/// <returns>A content item with the specific id, or <c>null</c> if it doesn't exist.</returns>
public static Task<ContentItem> GetContentItemByIdAsync(this IOrchardHelper orchardHelper, string contentItemId, bool latest = false)
public static Task<ContentItem> GetContentItemByIdAsync(this IOrchardHelper orchardHelper, string contentItemId, VersionOptions option = null)
{
var contentManager = orchardHelper.HttpContext.RequestServices.GetService<IContentManager>();
return contentManager.GetAsync(contentItemId, latest ? VersionOptions.Latest : VersionOptions.Published);

return contentManager.GetAsync(contentItemId, option);
}

/// <summary>
/// Loads a list of content items by their ids.
/// </summary>
/// <param name="orchardHelper">The <see cref="IOrchardHelper"/>.</param>
/// <param name="contentItemIds">The content item ids to load.</param>
/// <param name="latest">Whether a draft should be loaded if available. <c>false</c> by default.</param>
/// <param name="option">A specific version to load or the default version.</param>
/// <returns>A list of content items with the specific ids.</returns>
public static Task<IEnumerable<ContentItem>> GetContentItemsByIdAsync(this IOrchardHelper orchardHelper, IEnumerable<string> contentItemIds, bool latest = false)
public static Task<IEnumerable<ContentItem>> GetContentItemsByIdAsync(this IOrchardHelper orchardHelper, IEnumerable<string> contentItemIds, VersionOptions option = null)
{
var contentManager = orchardHelper.HttpContext.RequestServices.GetService<IContentManager>();
return contentManager.GetAsync(contentItemIds, latest);

return contentManager.GetAsync(contentItemIds, option);
}

/// <summary>
/// Loads a content item by its version id.
/// </summary>
/// <param name="orchardHelper">The <see cref="IOrchardHelper"/>.</param>
/// <param name="contentItemVersionId">The content item version id to load.</param>
/// <example>GetContentItemByVersionIdAsync("4xxxxxxxxxxxxxxxx").</example>
/// <returns>A content item with the specific version id, or <c>null</c> if it doesn't exist.</returns>
public static Task<ContentItem> GetContentItemByVersionIdAsync(this IOrchardHelper orchardHelper, string contentItemVersionId)
{
var contentManager = orchardHelper.HttpContext.RequestServices.GetService<IContentManager>();

return contentManager.GetVersionAsync(contentItemVersionId);
}

Expand All @@ -102,6 +100,8 @@ public static async Task<IEnumerable<ContentItem>> QueryContentItemsAsync(this I
/// <param name="maxContentItems">The maximum content items to return.</param>
public static Task<IEnumerable<ContentItem>> GetRecentContentItemsByContentTypeAsync(this IOrchardHelper orchardHelper, string contentType, int maxContentItems = 10)
{
return orchardHelper.QueryContentItemsAsync(query => query.Where(x => x.ContentType == contentType && x.Published == true).OrderByDescending(x => x.CreatedUtc).Take(maxContentItems));
return orchardHelper.QueryContentItemsAsync(query => query.Where(x => x.ContentType == contentType && x.Published == true)
.OrderByDescending(x => x.CreatedUtc)
.Take(maxContentItems));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,32 +2,31 @@
using System.Threading.Tasks;
using Microsoft.AspNetCore.Html;
using Microsoft.Extensions.DependencyInjection;
using OrchardCore;
using OrchardCore.Infrastructure.Html;
using OrchardCore.Liquid;
using OrchardCore.Markdown.Services;
using OrchardCore.Shortcodes.Services;

#pragma warning disable CA1050 // Declare types in namespaces
namespace OrchardCore;

public static class ContentRazorHelperExtensions
#pragma warning restore CA1050 // Declare types in namespaces
{
/// <summary>
/// Converts Markdown string to HTML.
/// </summary>
/// <param name="orchardHelper">The <see cref="IOrchardHelper"/>.</param>
/// <param name="markdown">The markdown to convert.</param>
/// <param name="sanitize">Whether to sanitze the markdown. Defaults to <see langword="true"/>.</param>
/// <param name="sanitize">Whether to sanitize the markdown. Defaults to <see langword="true"/>.</param>
public static async Task<IHtmlContent> MarkdownToHtmlAsync(this IOrchardHelper orchardHelper, string markdown, bool sanitize = true)
{
var shortcodeService = orchardHelper.HttpContext.RequestServices.GetRequiredService<IShortcodeService>();
var markdownService = orchardHelper.HttpContext.RequestServices.GetRequiredService<IMarkdownService>();

// The default Markdown option is to entity escape html
// so filters must be run after the markdown has been processed.
markdown = markdownService.ToHtml(markdown ?? "");
markdown = markdownService.ToHtml(markdown ?? string.Empty);

// The liquid rendering is for backwards compatability and can be removed in a future version.
// The liquid rendering is for backwards compatibility and can be removed in a future version.
if (!sanitize)
{
var liquidTemplateManager = orchardHelper.HttpContext.RequestServices.GetRequiredService<ILiquidTemplateManager>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ await shellScope.UsingAsync(async scope =>

var allPublishedContentItems = await contentManager.GetAsync(updatedContentItemIds);
allPublished = allPublishedContentItems.DistinctBy(x => x.ContentItemId).ToDictionary(k => k.ContentItemId, v => v);
var allLatestContentItems = await contentManager.GetAsync(updatedContentItemIds, latest: true);
var allLatestContentItems = await contentManager.GetAsync(updatedContentItemIds, VersionOptions.Latest);
allLatest = allLatestContentItems.DistinctBy(x => x.ContentItemId).ToDictionary(k => k.ContentItemId, v => v);

// Group all DocumentIndex by index to batch update them.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json.Nodes;
using System.Threading.Tasks;
using OrchardCore.ContentManagement.Handlers;

namespace OrchardCore.ContentManagement;

public static class ContentManagerExtensions
{
public static Task<TAspect> PopulateAspectAsync<TAspect>(this IContentManager contentManager, IContent content) where TAspect : new()
{
return contentManager.PopulateAspectAsync(content, new TAspect());
}

public static async Task<bool> HasPublishedVersionAsync(this IContentManager contentManager, IContent content)
{
if (content?.ContentItem == null)
{
return false;
}

return content.ContentItem.IsPublished() ||
(await contentManager.GetAsync(content.ContentItem.ContentItemId, VersionOptions.Published) != null);
}

public static Task<ContentItemMetadata> GetContentItemMetadataAsync(this IContentManager contentManager, IContent content)
{
return contentManager.PopulateAspectAsync<ContentItemMetadata>(content);
}

public static async Task<IEnumerable<ContentItem>> LoadAsync(this IContentManager contentManager, IEnumerable<ContentItem> contentItems)
{
ArgumentNullException.ThrowIfNull(contentItems);

var results = new List<ContentItem>(contentItems.Count());

foreach (var contentItem in contentItems)
{
results.Add(await contentManager.LoadAsync(contentItem));
}

return results;
}

public static async IAsyncEnumerable<ContentItem> LoadAsync(this IContentManager contentManager, IAsyncEnumerable<ContentItem> contentItems)
{
ArgumentNullException.ThrowIfNull(contentItems);

await foreach (var contentItem in contentItems)
{
yield return await contentManager.LoadAsync(contentItem);
}
}

public static async Task<ContentValidateResult> UpdateValidateAndCreateAsync(this IContentManager contentManager, ContentItem contentItem, VersionOptions options)
{
await contentManager.UpdateAsync(contentItem);
var result = await contentManager.ValidateAsync(contentItem);

if (result.Succeeded)
{
await contentManager.CreateAsync(contentItem, options);
}

return result;
}

/// <summary>
/// Gets either the container content item with the specified id and version, or if the json path supplied gets the contained content item.
/// </summary>
/// <param name="contentManager">The <see cref="IContentManager"/> instance.</param>
/// <param name="contentItemId">The id content item id to load.</param>
/// <param name="options">The version option.</param>
/// <param name="jsonPath">The json path of the contained content item.</param>
public static async Task<ContentItem> GetAsync(this IContentManager contentManager, string contentItemId, string jsonPath, VersionOptions options = null)
{
var contentItem = await contentManager.GetAsync(contentItemId, options);

// It represents a contained content item.
if (!string.IsNullOrEmpty(jsonPath))
{
var root = (JsonObject)contentItem.Content;
contentItem = root.SelectNode(jsonPath)?.ToObject<ContentItem>();

return contentItem;
}

return contentItem;
}
}
Loading

0 comments on commit 77c69c6

Please sign in to comment.