using System.Security.Claims; using System.Text.Json; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using PlotDirector.Companion.Protocol; using PlotLine.Data; using PlotLine.Services.NativeCompanion; namespace PlotLine.Controllers; [Authorize,Route("native-companion")] public sealed class NativeWorkspaceController(IWordCompanionRepository access,IBookRepository books,INativeReviewRepository reviews,NativePresenceStore presence):Controller { private int Author=>int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!); [HttpGet("workspace")] public async Task Workspace(int bookId,Guid? instanceId,Guid? sessionId,string view="book") { if(await access.GetBookStructureAsync(bookId,Author)==null)return Forbid();var book=await books.GetAsync(bookId);if(book==null)return NotFound(); return View(new NativeWorkspaceModel(bookId,book.ProjectID,book.BookDisplayTitle,instanceId,sessionId,view is "context" or "intent"?view:"book",await reviews.List(Author,bookId))); } [HttpGet("presence")] public async Task Presence(int bookId) { if(await access.GetBookStructureAsync(bookId,Author)==null)return Forbid();Response.Headers.CacheControl="no-store"; return Json(presence.Read(Author,bookId).Select(l=>new{instanceId=l.Instance,sessionId=l.Session,manuscriptId=l.Position.ManuscriptId,l.Position.BookId,l.Position.ChapterId,l.Position.SceneId,l.Position.DocumentTitle,l.Position.Active,l.Position.WordAvailable,updated=l.Updated,expires=l.Updated.AddSeconds(45)})); } [HttpPost("import/preview"),ValidateAntiForgeryToken] public async Task ImportPreview(int bookId,Guid[] reviews,[FromServices] NativeImportService importer) {try{return View(await importer.Preview(Author,bookId,reviews));}catch(UnauthorizedAccessException){return Forbid();}catch(Exception e)when(e is ArgumentException or System.Security.Cryptography.CryptographicException){return BadRequest(e is ArgumentException?e.Message:"Source capture unavailable. Re-analyse with the updated Companion.");}} [HttpPost("import/commit"),ValidateAntiForgeryToken] public async Task ImportCommit(string confirmation,bool confirm,[FromServices] NativeImportService importer) {if(!confirm)return BadRequest("Explicit import confirmation is required.");try{return View(await importer.Commit(Author,confirmation));}catch(UnauthorizedAccessException){return Forbid();}catch(ArgumentException e){return Conflict(e.Message);}catch(Microsoft.Data.SqlClient.SqlException){return Conflict("Import could not commit. Review decisions are preserved. Preview again; existing story data has not been replaced.");}} [HttpGet("status")] public async Task Status() { Response.Headers.CacheControl="no-store";var leases=presence.Read(Author,0);var allowed=new HashSet(); foreach(var book in leases.Select(l=>l.Position.BookId).Distinct())if(await access.GetBookStructureAsync(book,Author)!=null)allowed.Add(book); return Json(leases.Where(l=>allowed.Contains(l.Position.BookId)).Select(l=>new{instanceId=l.Instance,sessionId=l.Session,l.Position.BookId,l.Position.DocumentTitle,l.Position.ChapterId,l.Position.SceneId,l.Position.Active,l.Position.WordAvailable,updated=l.Updated,expires=l.Updated.AddSeconds(45)})); } [HttpGet("reviews/{id:guid}")] public async Task Review(Guid id) { var row=await reviews.Get(Author,id);if(row==null)return NotFound();if(await access.GetBookStructureAsync(row.BookID,Author)==null)return Forbid(); var book=await books.GetAsync(row.BookID);if(book==null)return NotFound(); return View(new NativeReviewModel(row,JsonSerializer.Deserialize(row.ResultJson)!,string.IsNullOrEmpty(row.DecisionsJson)?[]:JsonSerializer.Deserialize(row.DecisionsJson)!,presence.Read(Author,row.BookID).Where(l=>l.Position.WordAvailable&&l.Position.ManuscriptId==row.ManuscriptID&&l.Position.Revision==JsonSerializer.Deserialize(row.ResultJson)!.DocumentRevision).ToArray(),book.ProjectID)); } [HttpPost("reviews/{id:guid}/navigate"),ValidateAntiForgeryToken] public async Task Navigate(Guid id,int index,Guid instanceId,Guid sessionId) { var row=await reviews.Get(Author,id);if(row==null)return NotFound();if(await access.GetBookStructureAsync(row.BookID,Author)==null)return Forbid();var result=JsonSerializer.Deserialize(row.ResultJson)!; if(index<0||index>=result.Scenes.Length)return BadRequest();if(!presence.Navigate(Author,row.BookID,instanceId,sessionId,row.ManuscriptID,result.DocumentRevision,result.Scenes[index].Start))return Conflict("Word session is unavailable or this snapshot changed. Detect and review again."); TempData["NativeReviewSaved"]="Navigation requested for the selected Word session. No text changes.";return RedirectToAction(nameof(Review),new{id}); } [HttpPost("reviews/{id:guid}"),ValidateAntiForgeryToken,RequestSizeLimit(2*1024*1024),RequestFormLimits(ValueCountLimit=2200)] public async Task Decide(Guid id,int version,List scenes) { var row=await reviews.Get(Author,id);if(row==null)return NotFound();if(await access.GetBookStructureAsync(row.BookID,Author)==null)return Forbid(); var result=JsonSerializer.Deserialize(row.ResultJson)!; if(scenes==null)return BadRequest("No review decisions supplied.");foreach(var scene in scenes)scene.Summary??=""; if(scenes.Count!=result.Scenes.Length||scenes.Select(s=>s.Index).Distinct().Count()!=scenes.Count||scenes.Any(s=>s.Index<0||s.Index>=result.Scenes.Length||s.State is not ("pending" or "approved" or "rejected")||string.IsNullOrWhiteSpace(s.Title)||s.Title.Length>200||s.Summary==null||s.Summary.Length>600))return BadRequest("Invalid review. Refresh and retry; nothing was imported."); if(!await reviews.Decide(Author,id,version,JsonSerializer.Serialize(scenes)))return Conflict("This review changed in another window. Reload before saving; nothing was overwritten."); TempData["NativeReviewSaved"]="Review decisions saved. No manuscript or canonical story records were changed.";return RedirectToAction(nameof(Review),new{id}); } } public sealed record NativeWorkspaceModel(int Book,int Project,string Title,Guid? Instance,Guid? Session,string Mode,IReadOnlyList Reviews){public int BookID=>Book;public int ProjectID=>Project;} public sealed record NativeReviewModel(NativeReview Row,AiChapterResult Result,NativeSceneDecision[] Decisions,NativeLease[] Sessions,int ProjectID=0){public int BookID=>Row.BookID;} public sealed class NativeSceneDecision {public int Index {get;set;}public string State {get;set;}="pending";public string Title {get;set;}="";public string Summary {get;set;}="";}