-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathSiteTextServiceBase.cs
More file actions
62 lines (50 loc) · 2.19 KB
/
SiteTextServiceBase.cs
File metadata and controls
62 lines (50 loc) · 2.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
using AngleSharp;
using Microsoft.AspNetCore.Html;
using OrchardCore.ContentManagement;
using OrchardCore.Markdown.Models;
using OrchardCore.Markdown.Services;
using System;
using System.Threading.Tasks;
namespace Lombiq.HelpfulExtensions.Extensions.SiteTexts.Services;
public abstract class SiteTextServiceBase : ISiteTextService
{
protected readonly IContentManager _contentManager;
protected readonly IMarkdownService _markdownService;
protected SiteTextServiceBase(IContentManager contentManager, IMarkdownService markdownService)
{
_contentManager = contentManager;
_markdownService = markdownService;
}
public abstract Task<HtmlString> RenderHtmlByIdAsync(string contentItemId);
protected Task<MarkdownBodyPart> GetSiteTextMarkdownBodyPartByIdAsync(string contentItemId)
{
ArgumentNullException.ThrowIfNull(contentItemId);
return GetSiteTextMarkdownBodyPartByIdInnerAsync(contentItemId);
}
protected async Task<HtmlString> RenderMarkdownAsync(string markdown)
{
var html = _markdownService.ToHtml(markdown.Trim());
using var context = BrowsingContext.New(Configuration.Default);
using var doc = await context.OpenAsync(response => response.Content($"<html><body>{html}</body></html>"));
// If it's a single-line expression, then it's presumably inline so don't wrap it in a <p> element.
if (doc.Body is { ChildElementCount: 1, FirstElementChild: { } first } &&
first.TagName.EqualsOrdinalIgnoreCase("P"))
{
html = first.InnerHtml.Trim();
}
return new(html);
}
private async Task<MarkdownBodyPart> GetSiteTextMarkdownBodyPartByIdInnerAsync(string contentItemId)
{
if (await _contentManager.GetAsync(contentItemId) is not { } contentItem)
{
throw new InvalidOperationException($"A content with the ID \"{contentItemId}\" does not exist.");
}
if (!contentItem.TryGet<MarkdownBodyPart>(out var part))
{
throw new InvalidOperationException(
$"A content with the ID \"{contentItemId}\" does not have a {nameof(MarkdownBodyPart)}.");
}
return part;
}
}