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 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 Validate(int book,ChapterObservation observation)=>await Run(async()=>await chapters.Accept(Author,User.FindFirstValue("NativeCompanion.Grant")??"",book,observation)); private async Task Run(Func> 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."});}} }