PlotDirector/PlotLine/Controllers/ParagraphManuscriptController.cs

45 lines
3.8 KiB
C#

using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using PlotLine.Services.Manuscript;
using PlotLine.Services.NativeCompanion;
namespace PlotLine.Controllers;
[Authorize,Route("manuscript/paragraphs")]
public sealed class ParagraphManuscriptController(ParagraphManuscriptService manuscripts,NativeManuscriptCapture capture,NativePresenceStore presence):Controller
{
private int Author=>int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);
[HttpGet]
public async Task<IActionResult> Index(int bookId,int page=1,int evidencePage=1)
{
if(!manuscripts.Enabled)return NotFound();
try{var model=await manuscripts.Workspace(Author,bookId,page);model.EvidencePage=Math.Max(1,evidencePage);model.Message=TempData["ParagraphMessage"] as string;return View(model);}catch(UnauthorizedAccessException){return Forbid();}
}
[HttpPost("enable"),ValidateAntiForgeryToken]
public Task<IActionResult> Enable(int bookId,string mode)=>Run(bookId,async()=>{await manuscripts.Enable(Author,bookId,mode);return "Paragraph tracking preference saved. Word prose is never rewritten by PlotDirector.";});
[HttpPost("snapshot"),ValidateAntiForgeryToken]
public Task<IActionResult> Snapshot(int bookId,Guid? instanceId=null,Guid? sessionId=null)
{
Guid requested=Guid.Empty;
return Run(bookId,async()=>{if(!ModelState.IsValid)throw new ArgumentException("Invalid Word document selection.");requested=await capture.RequestParagraphSnapshot(Author,bookId,instanceId:instanceId,sessionId:sessionId);return requested==Guid.Empty?"A transfer is already pending. Refresh after it finishes.":"Word snapshot requested. Keep Word open until the transfer is acknowledged.";},()=>requested);
}
[HttpPost("cancel"),ValidateAntiForgeryToken]
public Task<IActionResult> Cancel(int bookId)=>Run(bookId,async()=>{await capture.CancelParagraphSnapshot(Author,bookId);return "Pending snapshot cancelled. Already acknowledged snapshots remain saved.";});
[HttpPost("change"),ValidateAntiForgeryToken]
public Task<IActionResult> Change(int bookId,long revision,string action,Guid target,Guid other,string? text,string? eventKey,bool primary,int from,int to,int? startOffset,int? endOffset)=>Run(bookId,async()=>{
string? kind=null;int eventId=0;if(action=="anchor"){var pieces=eventKey?.Split(':');if(pieces?.Length!=2||pieces[0] is not ("Knowledge" or "Relationship")||!int.TryParse(pieces[1],out eventId))throw new ArgumentException("Choose a saved knowledge or relationship event.");kind=pieces[0];}
await manuscripts.Change(Author,bookId,revision,action,target,other,text,kind,eventId,primary,from-1,to-1,startOffset,endOffset);presence.BooksChanged(Author);return "Manuscript structure and evidence updated. Word prose is unchanged.";});
private async Task<IActionResult> Run(int book,Func<Task<string>> work,Func<Guid>? requestId=null)
{
if(!manuscripts.Enabled)return NotFound();
var ajax=Request.Headers["X-Requested-With"]=="XMLHttpRequest";
string message;var status=200;
try{message=await work();}catch(UnauthorizedAccessException){return ajax?StatusCode(403,new{message="Only the authorised book owner can synchronise this manuscript."}):Forbid();}
catch(Exception e)when(e is ArgumentException or InvalidOperationException){message=e.Message;status=409;}
catch(SqlException e)when(e.Number==51000){message=e.Message;status=409;}
catch(SqlException){message="The change was refused. Check your owner permissions, finish any active import, then refresh before retrying.";status=409;}
if(ajax)return StatusCode(status,new{message,requestId=requestId?.Invoke()});
TempData["ParagraphMessage"]=message;return RedirectToAction(nameof(Index),new{bookId=book});
}
}