using System.Security.Claims; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Data.SqlClient; using PlotLine.Data; using PlotLine.Models; using PlotLine.Services.NativeCompanion; using PlotDirector.Companion.Protocol; namespace PlotLine.Controllers; [Authorize,Route("Writer/Work")] public sealed class WriterWorkController(WriterWorkRepository work,NativePresenceStore presence):Controller { private int Actor=>int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!); [HttpGet("State")] public async Task State(int bookId) { Response.Headers.CacheControl="no-store"; try {var state=await work.State(Actor,bookId);var current=state.Current;if(current?.StartedUtcDateTime.UtcNow.AddSeconds(-45)?current.Capabilities:null,live=current.MediaReceivedUtc>DateTime.UtcNow.AddSeconds(-45)&&presence.Read(Actor,bookId).Any(l=>l.Instance==current.NativeInstance&&l.Session==current.NativeDocument&&l.Grant==current.NativeGrant),coveragePartial=current.CoveragePartial,sequence=current.BrowserSequence}});} catch(SqlException e)when(e.Number==51000){return NotFound();} } [HttpPost("Start"),ValidateAntiForgeryToken] public async Task Start(int bookId,int? chapterId,string kind,Guid requestId,bool pauseOnEdit=true) { if(requestId==Guid.Empty||kind is not("Writing" or "Editing" or "Planning" or "Reading" or "AudioReview")||kind=="AudioReview"&&!chapterId.HasValue)return BadRequest("Choose a chapter and activity."); var leases=presence.Read(Actor,bookId).ToArray();var lease=leases.Length==1?leases[0]:leases.Count(x=>x.Position.Active)==1?leases.Single(x=>x.Position.Active):null; try {await work.Execute(new{Action="start",UserID=Actor,BookID=bookId,ChapterID=chapterId,Kind=kind,SessionID=requestId,PauseOnEdit=pauseOnEdit,NativeInstance=kind=="AudioReview"?lease?.Instance:null,NativeDocument=kind=="AudioReview"?lease?.Session:null,NativeGrant=kind=="AudioReview"?lease?.Grant:null});return Ok(new{sessionID=requestId});} catch(SqlException e)when(e.Number==51000){return Conflict(new{message="Session could not start. Check book access, chapter availability and Reports recording settings."});} } [HttpPost("Heartbeat"),ValidateAntiForgeryToken] public Task Heartbeat(int bookId,Guid sessionId,long sequence,bool engaged)=>sequence<=0?Task.FromResult(BadRequest()):Change(new{Action="heartbeat",UserID=Actor,BookID=bookId,SessionID=sessionId,Sequence=sequence,Engaged=engaged}); [HttpPost("End"),ValidateAntiForgeryToken] public Task End(int bookId,Guid sessionId,string? note) {if(note?.Length>2000)return Task.FromResult(BadRequest());return Change(new{Action="end",UserID=Actor,BookID=bookId,SessionID=sessionId,Note=note});} [HttpPost("Preference"),ValidateAntiForgeryToken] public Task Preference(int bookId,Guid sessionId,bool pauseOnEdit)=>Change(new{Action="preference",UserID=Actor,BookID=bookId,SessionID=sessionId,PauseOnEdit=pauseOnEdit}); [HttpPost("Command"),ValidateAntiForgeryToken] public async Task Command(int bookId,Guid sessionId,string command) { try { var current=(await work.State(Actor,bookId)).Current;if(current?.SessionID!=sessionId)current=null; if(current==null||!presence.Read(Actor,bookId).Any(l=>l.Instance==current.NativeInstance&&l.Session==current.NativeDocument&&l.Grant==current.NativeGrant)||command is not("play" or "pause" or "back15" or "forward15")||!(current.Capabilities??"").Split(',').Contains(command))return Conflict(new{message="This media operation is unavailable."}); return await Change(new{Action="command",UserID=Actor,BookID=bookId,SessionID=sessionId,CommandID=Guid.NewGuid(),Command=command}); } catch(SqlException e)when(e.Number==51000){return NotFound();} } [HttpGet("Export")] public async Task Export(int bookId,DateTime? day=null) {try{return Json((await work.History(Actor,bookId,day)).Select(x=>new{x.SessionID,x.BookID,x.ChapterID,x.Kind,startedUtc=DateTime.SpecifyKind(x.StartedUtc,DateTimeKind.Utc),endedUtc=x.EndedUtc.HasValue?DateTime.SpecifyKind(x.EndedUtc.Value,DateTimeKind.Utc):(DateTime?)null,x.EngagedSeconds,x.PlaybackSeconds,x.UniqueSeconds,x.CoveragePartial,x.Pauses,x.Seeks,x.Note,x.StartRevision,x.EndRevision,x.StartParagraphCount,x.EndParagraphCount,x.ChangesDuringSession,x.AdditionsDuringSession,x.RemovalsDuringSession,x.ChangedParagraphs}));}catch(SqlException e)when(e.Number==51000){return NotFound();}} [HttpPost("Erase"),ValidateAntiForgeryToken] public Task Erase(int bookId,bool confirm)=>confirm?Change(new{Action="erase",UserID=Actor,BookID=bookId}):Task.FromResult(BadRequest("Confirm erasure.")); private async Task Change(object values) {try{await work.Execute(values);return Ok();}catch(SqlException e)when(e.Number==51000){return Conflict(new{message="Session ended, expired, or recording is paused. Check Reports or start a new session."});}} } [ApiController,Authorize(AuthenticationSchemes=DesktopPairing.Scheme),Route("api/native-companion/instances/{instance:guid}/documents/{document:guid}/audio-review")] public sealed class NativeAudioReviewController(WriterWorkRepository work,NativePresenceStore presence):ControllerBase { [HttpPost,RequestSizeLimit(4096)] public async Task Observe(Guid instance,Guid document,AudioReviewObservation value) { var user=int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);var grant=User.FindFirstValue("NativeCompanion.Grant"); var lease=presence.Read(user,value.BookID).SingleOrDefault(x=>x.Instance==instance&&x.Session==document&&x.Grant==grant); if(lease==null||value.BookID<=0)return Forbid(); try { PlotLine.Services.Writer.AudioReviewMetrics.Validate(value); var current=(await work.State(user,value.BookID)).Current;if(current?.Kind!="AudioReview"||current.NativeInstance!=instance||current.NativeDocument!=document||current.NativeGrant!=grant)current=null; if(current==null||current.StartedUtc