oliverbooth.dev/OliverBooth/Controllers/BlogApiController.cs

86 lines
2.7 KiB
C#
Raw Normal View History

2023-08-11 14:51:20 +00:00
using Humanizer;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using OliverBooth.Data.Blog;
using OliverBooth.Services;
namespace OliverBooth.Controllers;
2023-08-11 14:41:02 +00:00
/// <summary>
/// Represents a controller for the blog API.
/// </summary>
[ApiController]
[Route("api/blog")]
[Produces("application/json")]
[EnableCors("BlogApi")]
public sealed class BlogApiController : ControllerBase
{
private readonly BlogService _blogService;
2023-08-11 14:41:02 +00:00
/// <summary>
/// Initializes a new instance of the <see cref="BlogApiController" /> class.
/// </summary>
/// <param name="blogService">The <see cref="BlogService" />.</param>
public BlogApiController(BlogService blogService)
{
_blogService = blogService;
}
[Route("count")]
public IActionResult Count()
{
2023-08-10 21:56:49 +00:00
if (!ValidateReferer()) return NotFound();
return Ok(new { count = _blogService.AllPosts.Count });
}
2023-08-10 21:57:13 +00:00
[HttpGet("all/{skip:int?}/{take:int?}")]
public IActionResult GetAllBlogPosts(int skip = 0, int take = -1)
{
2023-08-10 21:56:49 +00:00
if (!ValidateReferer()) return NotFound();
if (take == -1) take = _blogService.AllPosts.Count;
return Ok(_blogService.AllPosts.Skip(skip).Take(take).Select(post => new
{
id = post.Id,
commentsEnabled = post.EnableComments,
identifier = post.GetDisqusIdentifier(),
author = post.AuthorId,
title = post.Title,
published = post.Published.ToUnixTimeSeconds(),
formattedDate = post.Published.ToString("dddd, d MMMM yyyy HH:mm"),
updated = post.Updated?.ToUnixTimeSeconds(),
humanizedTimestamp = post.Updated?.Humanize() ?? post.Published.Humanize(),
excerpt = _blogService.GetExcerpt(post, out bool trimmed),
trimmed,
2023-08-11 14:42:48 +00:00
url = Url.Page("/Article",
new
{
2023-08-11 14:42:48 +00:00
area = "blog",
2023-08-10 21:53:15 +00:00
year = post.Published.ToString("yyyy"),
month = post.Published.ToString("MM"),
day = post.Published.ToString("dd"),
slug = post.Slug
})
}));
}
[HttpGet("author/{id:guid}")]
public IActionResult GetAuthor(Guid id)
{
2023-08-10 21:56:49 +00:00
if (!ValidateReferer()) return NotFound();
if (!_blogService.TryGetAuthor(id, out Author? author)) return NotFound();
return Ok(new
{
id = author.Id,
name = author.Name,
avatarHash = author.AvatarHash,
});
}
2023-08-10 21:57:13 +00:00
2023-08-10 21:56:49 +00:00
private bool ValidateReferer()
{
var referer = Request.Headers["Referer"].ToString();
return referer.StartsWith(Url.PageLink("/index",values: new{area="blog"})!);
2023-08-10 21:56:49 +00:00
}
}