using System.Security.Claims; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.SignalR; using PlotDirector.Companion.Protocol; using PlotLine.Hubs; using PlotLine.Services.NativeCompanion; namespace PlotLine.Controllers; [ApiController,Authorize(AuthenticationSchemes=DesktopPairing.Scheme),Route("api/native-companion/manuscript-capture")] public sealed class NativeManuscriptCaptureController(NativeManuscriptCapture capture,IHubContext live):ControllerBase { [HttpDelete("{id:guid}")] public async Task Cancel(Guid id){var user=int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);var state=await capture.Fail(user,User.FindFirstValue("NativeCompanion.Grant")??"",id);if(state!=null)await live.Clients.Group(WordCompanionFollowHub.PresenceGroup(user)).SendAsync("OnboardingScanFailed",state);return Ok(new NativePresence());} [HttpPost,RequestSizeLimit(100*1024*1024)] public async Task Accept(ManuscriptCapture input) { var user=int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!); try{var grant=User.FindFirstValue("NativeCompanion.Grant")??""; if(await capture.AcceptParagraphSnapshot(user,grant,input)){ var state=await capture.AcceptedParagraphState(user,input.RequestId); await live.Clients.Group(WordCompanionFollowHub.PresenceGroup(user)).SendAsync("ParagraphSnapshotAccepted",new{bookId=state.BookId,revision=state.Revision}); return Ok(new NativePresence{CaptureRequestId=input.RequestId,Revision=input.Revision,ParagraphRevision=state.Revision,ParagraphSnapshotHash=state.SnapshotHash,CanonicalParagraphIds=state.Paragraphs.Select(p=>p.Occurrence.Id).ToArray()}); } var stateImport=await capture.Accept(user,User.FindFirstValue("NativeCompanion.Grant")??"",input);await live.Clients.Group(WordCompanionFollowHub.PresenceGroup(user)).SendAsync("OnboardingScanCompleted",stateImport);return Ok(new NativePresence{CaptureRequestId=input.RequestId,Revision=input.Revision,CanonicalParagraphIds=capture.AcceptedParagraphIds(user,input.RequestId)});} catch(System.IO.IOException){return StatusCode(503,new{code="capture_storage_unavailable",message="The manuscript could not be durably saved yet. Retry the same capture; no success has been claimed.",retryable=true});} catch(Microsoft.Data.SqlClient.SqlException){return StatusCode(503,new{code="capture_storage_unavailable",message="The manuscript could not be durably saved yet. Retry the same capture; no success has been claimed.",retryable=true});} catch(CaptureSubmissionRejected e){return StatusCode(e.Status,new{code=e.Code,message=e.Message,retryable=false});} catch(UnauthorizedAccessException){return Forbid();}catch(ArgumentException e){return BadRequest(new{message=e.Message});}catch(InvalidOperationException){return Conflict(new{message="The import wizard changed. Refresh it before retrying the transfer."});} } }