66 lines
7.3 KiB
C#
66 lines
7.3 KiB
C#
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<IActionResult> Workspace(int bookId,Guid? instanceId,Guid? sessionId,string view="book")
|
|
{
|
|
var structure=await access.GetBookStructureAsync(bookId,Author);if(structure==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),structure.Chapters));
|
|
}
|
|
[HttpGet("presence")]
|
|
public async Task<IActionResult> Presence(int bookId)
|
|
{
|
|
var structure=await access.GetBookStructureAsync(bookId,Author);if(structure==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,chapterTitle=structure.Chapters.FirstOrDefault(c=>c.ChapterId==l.Position.ChapterId)?.Title,sceneTitle=structure.Chapters.SelectMany(c=>c.Scenes).FirstOrDefault(s=>s.SceneId==l.Position.SceneId)?.Title,l.Position.CanParagraphSync,l.Position.BookId,l.Position.ChapterId,l.Position.SceneId,l.Position.DocumentTitle,l.Position.Active,l.Position.WordAvailable,l.Position.WordRunning,l.Position.WordSaved,l.Position.CanCapture,updated=l.Updated,expires=l.Updated.AddSeconds(45)}));
|
|
}
|
|
[HttpPost("import/preview"),ValidateAntiForgeryToken]
|
|
public async Task<IActionResult> 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<IActionResult> 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<IActionResult> Status()
|
|
{
|
|
Response.Headers.CacheControl="no-store";var leases=presence.Read(Author,0);var allowed=new HashSet<int>{0};
|
|
foreach(var book in leases.Select(l=>l.Position.BookId).Where(b=>b>0).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,l.Position.WordRunning,l.Position.WordSaved,l.Position.CanCapture,updated=l.Updated,expires=l.Updated.AddSeconds(45)}));
|
|
}
|
|
[HttpGet("reviews/{id:guid}")]
|
|
public async Task<IActionResult> 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<AiChapterResult>(row.ResultJson)!,string.IsNullOrEmpty(row.DecisionsJson)?[]:JsonSerializer.Deserialize<NativeSceneDecision[]>(row.DecisionsJson)!,presence.Read(Author,row.BookID).Where(l=>l.Position.WordAvailable&&l.Position.ManuscriptId==row.ManuscriptID&&l.Position.Revision==JsonSerializer.Deserialize<AiChapterResult>(row.ResultJson)!.DocumentRevision).ToArray(),book.ProjectID));
|
|
}
|
|
[HttpPost("reviews/{id:guid}/navigate"),ValidateAntiForgeryToken]
|
|
public async Task<IActionResult> 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<AiChapterResult>(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<IActionResult> Decide(Guid id,int version,List<NativeSceneDecision> 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<AiChapterResult>(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<NativeReview> Reviews,IReadOnlyList<PlotLine.Models.WordCompanionChapterStructureDto>? Chapters=null){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;}="";}
|