PlotDirector/PlotLine/Controllers/NativeChapterSyncController.cs

23 lines
2.1 KiB
C#

using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using PlotDirector.Companion.Protocol.Manuscript;
using PlotLine.Services.Manuscript;
using PlotLine.Services.NativeCompanion;
namespace PlotLine.Controllers;
[ApiController,Authorize(AuthenticationSchemes=DesktopPairing.Scheme),Route("api/native-companion/books/{book:int}/chapter-sync")]
public sealed class NativeChapterSyncController(ChapterSyncService chapters):ControllerBase
{
private int Author=>int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);
[HttpGet]
public async Task<IActionResult> Manifest(int book,Guid session,long wordRevision)=>await Run(async()=>await chapters.Manifest(Author,book,session,wordRevision));
[HttpPost("validate"),RequestSizeLimit(4*1024*1024)]
public async Task<IActionResult> Validate(int book,ChapterObservation observation)=>await Run(async()=>await chapters.Accept(Author,User.FindFirstValue("NativeCompanion.Grant")??"",book,observation));
[HttpPost("repair")]
public async Task<IActionResult> Repair(int book,ChapterFinish selected)=>await Run(async()=>new ChapterRepairRequested{OperationId=await chapters.Repair(Author,book,selected.InstanceId,selected.SessionId,selected.WordRevision),Message="Chapter repair requested; accepted import and author decisions are retained."});
[HttpPost("finish")]
public async Task<IActionResult> Finish(int book,ChapterFinish completion)=>await Run(async()=>await chapters.Finish(Author,User.FindFirstValue("NativeCompanion.Grant")??"",book,completion));
private async Task<IActionResult> Run(Func<Task<object>> read)
{try{return Ok(await read());}catch(UnauthorizedAccessException){return Forbid();}catch(Exception e)when(e is ArgumentException or InvalidOperationException){return Conflict(new ChapterSyncReply{State="Needs review",Message=e.Message});}catch(Microsoft.Data.SqlClient.SqlException){return Conflict(new ChapterSyncReply{State="Failed",Message="The accepted manuscript changed or chapter validation was refused. Existing work is preserved; refresh and retry."});}}
}