97 lines
2.5 KiB
C#
97 lines
2.5 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 BlogRepository _repo;
|
|
|
|
public BlogController(BlogRepository repo)
|
|
{
|
|
_repo = repo;
|
|
}
|
|
|
|
public async Task<IActionResult> Page(int page)
|
|
{
|
|
var offset = (page - 1) * MaxPostsPerPage;
|
|
var posts = (await _repo.GetLatestPostsAsync(MaxPostsPerPage, offset)).Select(p => new BlogPostPreviewViewModel(p));
|
|
var maxPages = (await _repo.GetCountAsync()) / MaxPostsPerPage;
|
|
var model = new BlogViewModel(posts, page, maxPages);
|
|
return View(model);
|
|
}
|
|
|
|
public async Task<IActionResult> Entry(string url)
|
|
{
|
|
try {
|
|
var post = await _repo.GetPostByUrlAsync(url);
|
|
var model = new BlogPostViewModel(post);
|
|
return View(model);
|
|
} catch (InvalidOperationException) {
|
|
return NotFound();
|
|
}
|
|
}
|
|
|
|
[Authorize]
|
|
public async Task<IActionResult> Edit(int? id) {
|
|
if (!id.HasValue)
|
|
return View();
|
|
|
|
try {
|
|
var post = await _repo.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 post = submission.Id.HasValue ? await _repo.GetPostByIdAsync(submission.Id.Value) : new BlogPost();
|
|
|
|
post.UpdateTitle(submission.Title);
|
|
post.UpdateDraft(submission.Content);
|
|
|
|
var savedPost = await _repo.SavePost(post);
|
|
|
|
return RedirectToAction(nameof(Edit), new{savedPost.Id});
|
|
}
|
|
|
|
[Authorize]
|
|
public async Task<IActionResult> Manage() {
|
|
var posts = await _repo.GetAllPostsAsync();
|
|
var models = posts.OrderByDescending(post => post.Timestamp).Select(post => new BlogPostViewModel(post));
|
|
return View(models);
|
|
}
|
|
|
|
[Authorize]
|
|
public async Task<IActionResult> Publish(int id) {
|
|
var post = await _repo.GetPostByIdAsync(id);
|
|
post.Publish();
|
|
await _repo.SavePost(post);
|
|
|
|
return RedirectToAction(nameof(Manage));
|
|
}
|
|
|
|
[Authorize]
|
|
public async Task<IActionResult> Delete(int id) {
|
|
await _repo.DeletePostAsync(id);
|
|
|
|
return RedirectToAction(nameof(Manage));
|
|
}
|
|
}
|
|
}
|