oliverbooth.dev/OliverBooth/Pages/Blog/Article.cshtml.cs

64 lines
2.1 KiB
C#
Raw Normal View History

2023-08-08 01:17:23 +01:00
using Markdig;
2023-08-08 00:28:33 +01:00
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using OliverBooth.Data;
using OliverBooth.Data.Blog;
namespace OliverBooth.Pages.Blog;
public class Article : PageModel
{
private readonly IDbContextFactory<BlogContext> _dbContextFactory;
2023-08-08 00:34:15 +01:00
private readonly MarkdownPipeline _markdownPipeline;
2023-08-08 00:34:15 +01:00
public Article(IDbContextFactory<BlogContext> dbContextFactory, MarkdownPipeline markdownPipeline)
{
_dbContextFactory = dbContextFactory;
2023-08-08 00:34:15 +01:00
_markdownPipeline = markdownPipeline;
}
2023-08-08 00:28:33 +01:00
public Author Author { get; private set; }
2023-08-08 01:17:23 +01:00
/// <summary>
/// Gets a value indicating whether the post is a legacy WordPress post.
/// </summary>
/// <value>
/// <see langword="true" /> if the post is a legacy WordPress post; otherwise, <see langword="false" />.
/// </value>
public bool IsWordPressLegacyPost => Post?.WordPressId.HasValue ?? false;
2023-08-08 00:28:33 +01:00
public BlogPost Post { get; private set; } = new();
public string SanitizeContent(string content)
{
2023-08-08 00:28:33 +01:00
content = content.Replace("<!--more-->", string.Empty);
while (content.Contains("\n\n"))
{
content = content.Replace("\n\n", "\n");
}
2023-08-08 00:34:15 +01:00
return Markdown.ToHtml(content.Trim(), _markdownPipeline);
}
2023-08-08 00:28:33 +01:00
public IActionResult OnGet(int year, int month, int day, string slug)
{
using BlogContext context = _dbContextFactory.CreateDbContext();
Post = context.BlogPosts.FirstOrDefault(p => p.Published.Year == year &&
p.Published.Month == month &&
2023-08-08 00:28:33 +01:00
p.Published.Day == day &&
p.Slug == slug)!;
2023-08-08 00:28:33 +01:00
// ReSharper disable once ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract
if (Post is null)
{
Response.StatusCode = 404;
2023-08-08 00:28:33 +01:00
return NotFound();
}
2023-08-08 00:28:33 +01:00
Author = context.Authors.FirstOrDefault(a => a.Id == Post.AuthorId)!;
return Page();
}
}