PlotDirector/PlotLine/Controllers/NarrativeFocusController.cs

24 lines
1.6 KiB
C#

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using PlotLine.Services;
namespace PlotLine.Controllers;
[Authorize,ResponseCache(NoStore=true,Location=ResponseCacheLocation.None)]
public sealed class NarrativeFocusController(INarrativeFocus focus,ICurrentUserService currentUser,SharedManuscriptFocus? shared=null) : Controller
{
[HttpGet]
public Task<IActionResult> Read(int projectId,int bookId) => Execute(() => focus.Read(currentUser.UserId!.Value,projectId,bookId));
[HttpPost,ValidateAntiForgeryToken]
public Task<IActionResult> Set(int projectId,int bookId,int? chapterId,int? sceneId,long version,int direction=0) =>
Execute(async () => {var state=await focus.Set(currentUser.UserId!.Value,projectId,bookId,chapterId,sceneId,version,direction);if(shared!=null)await shared.Announce(currentUser.UserId.Value,projectId,bookId);return state;});
private async Task<IActionResult> Execute(Func<Task<NarrativeFocusState>> operation)
{
if(currentUser.UserId is null)return Challenge();
if(!ModelState.IsValid)return BadRequest(new{message="Choose a valid chapter or scene."});
try{return Json(await operation());}
catch(UnauthorizedAccessException){return NotFound();}
catch(SqlException e)when(e.Number==51000){return NotFound(new{message="This narrative position is no longer available in this book."});}
catch(NarrativeFocusConflictException){return Conflict(new{message="Current focus changed in another window. Review it and try again."});}
}
}