65 lines
3.1 KiB
C#
65 lines
3.1 KiB
C#
using Microsoft.AspNetCore.Mvc;
|
|
using Microsoft.AspNetCore.Authorization;
|
|
using PlotLine.Models;
|
|
using PlotLine.Services;
|
|
using System.Diagnostics;
|
|
using PlotLine.Data;
|
|
|
|
namespace PlotLine.Controllers
|
|
{
|
|
public class HomeController : Controller
|
|
{
|
|
[AllowAnonymous]
|
|
[HttpGet("/", Name = PublicRouteNames.Home)]
|
|
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
|
|
public async Task<IActionResult> Index([FromServices] ApplicationStartup startup,
|
|
[FromServices] ICurrentUserService user, [FromServices] IProjectRepository projects,
|
|
[FromServices] IBookRepository books)
|
|
{
|
|
if (user.UserId is not int userId)
|
|
return RedirectToAction("Index", "Projects");
|
|
|
|
var choice = startup.ReadChoice(HttpContext, userId);
|
|
if (choice == ApplicationStartup.Projects)
|
|
return RedirectToAction("Index", "Projects");
|
|
|
|
var recent = startup.ReadRecent(HttpContext, userId);
|
|
var project = recent != null ? await projects.GetForUserAsync(recent.ProjectID, userId) : null;
|
|
project ??= (await projects.ListForUserAsync(userId)).FirstOrDefault();
|
|
if (project is null) return RedirectToAction("Index", "Projects");
|
|
|
|
var page = choice == ApplicationStartup.Resume ? recent?.Page ?? "writer" : choice;
|
|
var destination = ApplicationStartup.Resolve(page);
|
|
if (destination is null) return RedirectToAction("Index", "Projects");
|
|
|
|
var projectBooks = (await books.ListByProjectAsync(project.ProjectID)).Where(book => !book.IsArchived).ToArray();
|
|
var book = projectBooks.FirstOrDefault(book => book.BookID == recent?.BookID) ?? projectBooks.FirstOrDefault();
|
|
return destination.ProjectAsId
|
|
? RedirectToAction(destination.Action, destination.Controller, new { id = project.ProjectID })
|
|
: RedirectToAction(destination.Action, destination.Controller,
|
|
new { projectId = project.ProjectID, bookId = book?.BookID });
|
|
}
|
|
|
|
[Authorize, HttpGet("Startup")]
|
|
public IActionResult Startup([FromServices] ApplicationStartup startup, [FromServices] ICurrentUserService user)
|
|
=> user.UserId is int id ? View(startup.ReadChoice(HttpContext, id)) : Challenge();
|
|
|
|
[Authorize, HttpPost("Startup"), ValidateAntiForgeryToken]
|
|
public IActionResult Startup(string page, [FromServices] ApplicationStartup startup,
|
|
[FromServices] ICurrentUserService user)
|
|
{
|
|
if (user.UserId is not int id) return Challenge();
|
|
if (!ApplicationStartup.Destinations.ContainsKey(page ?? "")) return BadRequest();
|
|
startup.SaveChoice(HttpContext, id, page!);
|
|
return RedirectToAction(nameof(Index));
|
|
}
|
|
|
|
[AllowAnonymous]
|
|
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
|
|
public IActionResult Error()
|
|
{
|
|
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
|
|
}
|
|
}
|
|
}
|