2023-08-06 15:57:23 +01:00
|
|
|
|
using Humanizer;
|
2023-08-08 01:30:32 +01:00
|
|
|
|
using Microsoft.AspNetCore.Mvc;
|
2023-08-06 15:57:23 +01:00
|
|
|
|
using Microsoft.AspNetCore.Mvc.RazorPages;
|
|
|
|
|
using Microsoft.EntityFrameworkCore;
|
|
|
|
|
using OliverBooth.Data;
|
|
|
|
|
using OliverBooth.Data.Blog;
|
|
|
|
|
|
|
|
|
|
namespace OliverBooth.Pages.Blog;
|
|
|
|
|
|
|
|
|
|
public class Index : PageModel
|
|
|
|
|
{
|
|
|
|
|
private readonly IDbContextFactory<BlogContext> _dbContextFactory;
|
|
|
|
|
|
|
|
|
|
public Index(IDbContextFactory<BlogContext> dbContextFactory)
|
|
|
|
|
{
|
|
|
|
|
_dbContextFactory = dbContextFactory;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public IReadOnlyCollection<BlogPost> BlogPosts { get; private set; } = ArraySegment<BlogPost>.Empty;
|
|
|
|
|
|
|
|
|
|
public string SanitizeContent(string content)
|
|
|
|
|
{
|
2023-08-08 01:30:32 +01:00
|
|
|
|
content = content.Replace("<!--more-->", string.Empty);
|
2023-08-06 15:57:23 +01:00
|
|
|
|
|
|
|
|
|
while (content.Contains("\n\n"))
|
|
|
|
|
{
|
|
|
|
|
content = content.Replace("\n\n", "\n");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return Markdig.Markdown.ToHtml(content.Trim());
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public string TrimContent(string content, out bool trimmed)
|
|
|
|
|
{
|
|
|
|
|
ReadOnlySpan<char> span = content.AsSpan();
|
2023-08-08 01:30:32 +01:00
|
|
|
|
int moreIndex = span.IndexOf("<!--more-->", StringComparison.Ordinal);
|
2023-08-06 15:57:23 +01:00
|
|
|
|
trimmed = moreIndex != -1 || span.Length > 256;
|
|
|
|
|
return moreIndex != -1 ? span[..moreIndex].Trim().ToString() : content.Truncate(256);
|
|
|
|
|
}
|
2023-08-08 01:30:32 +01:00
|
|
|
|
|
2023-08-06 15:57:23 +01:00
|
|
|
|
public Author? GetAuthor(BlogPost post)
|
|
|
|
|
{
|
|
|
|
|
using BlogContext context = _dbContextFactory.CreateDbContext();
|
|
|
|
|
return context.Authors.FirstOrDefault(a => a.Id == post.AuthorId);
|
|
|
|
|
}
|
|
|
|
|
|
2023-08-08 01:30:32 +01:00
|
|
|
|
public IActionResult OnGet([FromQuery(Name = "p")] int? postId = null)
|
2023-08-06 15:57:23 +01:00
|
|
|
|
{
|
|
|
|
|
using BlogContext context = _dbContextFactory.CreateDbContext();
|
2023-08-08 01:30:32 +01:00
|
|
|
|
if (postId is null)
|
|
|
|
|
{
|
|
|
|
|
BlogPosts = context.BlogPosts.ToArray();
|
|
|
|
|
return Page();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
BlogPost? post = context.BlogPosts.FirstOrDefault(p => p.WordPressId == postId);
|
|
|
|
|
|
|
|
|
|
if (post is not null)
|
|
|
|
|
{
|
2023-08-08 01:56:13 +01:00
|
|
|
|
return Redirect($"/blog/{post.Published:yyyy/MM/dd}/{post.Slug}");
|
2023-08-08 01:30:32 +01:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return NotFound();
|
2023-08-06 15:57:23 +01:00
|
|
|
|
}
|
|
|
|
|
}
|