86 lines
2.3 KiB
C#
86 lines
2.3 KiB
C#
using System;
|
|
using System.Linq;
|
|
using System.Threading.Tasks;
|
|
using Microsoft.AspNetCore.Authorization;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using Website.Data;
|
|
using Website.Models;
|
|
using Website.ViewModels;
|
|
|
|
namespace Website.Controllers {
|
|
public class BlogController:Controller {
|
|
private const int MaxPostsPerPage = 10;
|
|
private readonly IBlogApi _api;
|
|
|
|
public BlogController(IBlogApi api) => _api = api;
|
|
|
|
public async Task<IActionResult> Page(int page) {
|
|
var offset = (page - 1) * MaxPostsPerPage;
|
|
var posts = (await _api.GetLatestPostsAsync(MaxPostsPerPage, offset)).Select(p => new BlogPostSnippetViewModel(p));
|
|
var maxPages = (await _api.GetCountAsync()) / MaxPostsPerPage;
|
|
var model = new BlogViewModel(posts, page, maxPages);
|
|
return View(model);
|
|
}
|
|
|
|
public async Task<IActionResult> Entry(string url, bool preview = false) {
|
|
try {
|
|
var post = await _api.GetPostByUrlAsync(url);
|
|
|
|
if (!preview && string.IsNullOrEmpty(post.Content))
|
|
return NotFound();
|
|
|
|
var model = new BlogPostViewModel(post, preview);
|
|
return View(model);
|
|
} catch (InvalidOperationException) {
|
|
return NotFound();
|
|
}
|
|
}
|
|
|
|
[Authorize]
|
|
public async Task<IActionResult> Edit(int? id) {
|
|
if (!id.HasValue)
|
|
return View();
|
|
|
|
try {
|
|
var post = await _api.GetPostByIdAsync(id.Value);
|
|
var model = new BlogPostSubmission {
|
|
Id = post.Id,
|
|
Title = post.Title,
|
|
Content = post.Draft
|
|
};
|
|
return View(model);
|
|
} catch (InvalidOperationException) {
|
|
return NotFound();
|
|
}
|
|
}
|
|
|
|
[Authorize]
|
|
[HttpPost]
|
|
public async Task<IActionResult> Save(BlogPostSubmission submission) {
|
|
var savedPost = await _api.SavePost(submission);
|
|
|
|
return RedirectToAction(nameof(Edit), new { savedPost.Id });
|
|
}
|
|
|
|
[Authorize]
|
|
public async Task<IActionResult> Manage() {
|
|
var posts = await _api.GetAllPostsAsync();
|
|
var models = posts.OrderByDescending(post => post.Timestamp).Select(post => new BlogPostViewModel(post, false));
|
|
return View(models);
|
|
}
|
|
|
|
[Authorize]
|
|
public async Task<IActionResult> Publish(int id) {
|
|
await _api.PublishPostAsync(id);
|
|
|
|
return RedirectToAction(nameof(Manage));
|
|
}
|
|
|
|
[Authorize]
|
|
public async Task<IActionResult> Delete(int id) {
|
|
await _api.DeletePostAsync(id);
|
|
|
|
return RedirectToAction(nameof(Manage));
|
|
}
|
|
}
|
|
}
|