PlotDirector/PlotLine/Controllers/NativeChapterSyncController.cs

27 lines
2.7 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,ILogger<NativeChapterSyncController>? logger=null):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)
{
logger?.LogInformation("Native chapter observation received Trace={Trace} Book={Book} Chapter={Chapter} Request={Request} Session={Session}",HttpContext.TraceIdentifier,book,observation.ChapterId,observation.RequestId,observation.SessionId);
return 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 e){logger?.LogWarning("Native chapter request storage failure Trace={Trace} SqlNumber={SqlNumber}",HttpContext.TraceIdentifier,e.Number);return Conflict(new ChapterSyncReply{State="Failed",Message=e.Number==-2?"Chapter checkpoint storage timed out. Previously accepted work is retained; retry synchronisation. Reference: "+HttpContext.TraceIdentifier:e.Number==51000?e.Message+" Reference: "+HttpContext.TraceIdentifier:"Chapter checkpoint storage failed. Previously accepted work is retained. Reference: "+HttpContext.TraceIdentifier});}}
}