50 lines
5.1 KiB
C#
50 lines
5.1 KiB
C#
using System.Security.Claims;
|
|
using Microsoft.AspNetCore.Authorization;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using PlotLine.Data;
|
|
using PlotLine.Services.Investigations;
|
|
namespace PlotLine.Controllers;
|
|
[Authorize,ResponseCache(NoStore=true,Location=ResponseCacheLocation.None)]
|
|
public sealed class InvestigationCompanionController(InvestigationAccess gate,IInvestigationGuidanceRepository repository,InvestigationGuidanceService service,IInvestigationRepository investigations):Controller
|
|
{
|
|
IActionResult Error(int status,string message){
|
|
if(ControllerContext.ActionDescriptor.ActionName==nameof(Open)){
|
|
Response.StatusCode=status;ViewData["Failure"]=message;
|
|
if(int.TryParse(Request.Form["bookId"],out var book))ViewData["BookID"]=book;
|
|
if(Guid.TryParse(Request.Form["id"],out var id))ViewData["InvestigationID"]=id;
|
|
return View("~/Views/InvestigationCompanion/Failure.cshtml");
|
|
}
|
|
return StatusCode(status,new{message});
|
|
}
|
|
int Author=>int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);
|
|
async Task<IActionResult> Guard(Func<Task<IActionResult>> run){if(!gate.Enabled)return NotFound();Response.Headers["X-Robots-Tag"]="noindex, nofollow, noarchive";try{return await run();}catch(Exception e)when(e is UnauthorizedAccessException or KeyNotFoundException){return NotFound();}catch(ArgumentException e){return Error(400,e.Message);}catch(Microsoft.Data.SqlClient.SqlException e)when(e.Number==51000){return NotFound();}catch(Microsoft.Data.SqlClient.SqlException e)when(e.Number==51002){return Error(409,"Guidance changed in another window. Refresh before trying again.");}catch(Exception e)when(e is Microsoft.Data.SqlClient.SqlException or TimeoutException){return Error(503,"Guidance is temporarily unavailable. Your saved investigation is retained.");}}
|
|
async Task<(GuidanceRecord,PlotLine.Models.Investigations.Catalogue)> Verify(GuidanceRecord r){var(i,_,_)=InvestigationGuidanceService.Decode(r);if(i.UserID!=Author||i.BookID!=r.BookID||i.ProjectID!=r.ProjectID)throw new UnauthorizedAccessException();var c=await service.Catalogue(i.CatalogueVersion);if(c.Synthetic&&!(await HttpContext.RequestServices.GetRequiredService<IAuthorizationService>().AuthorizeAsync(User,null,"AdminOnly")).Succeeded)throw new UnauthorizedAccessException();return(r,c);}
|
|
async Task<(GuidanceRecord,PlotLine.Models.Investigations.Catalogue)> Load(int? project,int? book,Guid? id)=>await Verify(await repository.Read(Author,project,book,id)??throw new KeyNotFoundException());
|
|
[HttpGet("/InvestigationCompanion/Summary")]
|
|
public Task<IActionResult> Summary(int? projectId,int? bookId)=>Guard(async()=>{
|
|
if(projectId is not >0&&bookId is not >0)return Json(new{active=false});
|
|
var r=await repository.Read(Author,projectId,bookId);if(r==null)return Json(new{active=false});
|
|
var(verified,c)=await Verify(r); // same ownership guard as explicit IDs
|
|
return Json(new{active=true,summary=service.Summary(verified,c),resultsUrl=Url.Action("Index","WriterInvestigations",new{bookId=r.BookID,id=r.ID})});
|
|
});
|
|
[HttpGet("/InvestigationCompanion/Evidence")]
|
|
public Task<IActionResult> Evidence(int bookId,Guid id,string finding)=>Guard(async()=>{
|
|
var(r,c)=await Load(null,bookId,id);var(i,_,s)=InvestigationGuidanceService.Decode(r);service.Select(r,c,s,finding,null);
|
|
var full=await investigations.Read(Author,bookId,id)??throw new KeyNotFoundException();
|
|
return Json(full.Answers.Where(a=>c.Questions.Any(q=>q.Id==a.Question&&q.Options.Any(o=>o.Id==a.Option&&o.Contributions.Any(v=>v.Hypothesis==finding&&v.Weight>0)))).Take(5).Select(a=>{var q=c.Questions.Single(q=>q.Id==a.Question);return new{question=q.Text,answer=q.Options.Single(o=>o.Id==a.Option).Text,explanation=a.Explanation};}));
|
|
});
|
|
[HttpPost("/InvestigationCompanion/Update"),ValidateAntiForgeryToken]
|
|
public Task<IActionResult> Update(int bookId,Guid id,int version,string operation,string? finding,string? capability,string? progress)=>Guard(async()=>{
|
|
var(r,c)=await Load(null,bookId,id);if(r.GuidanceVersion!=version)return Error(409,"Guidance changed in another window. Refresh before trying again.");var(_,_,s)=InvestigationGuidanceService.Decode(r);
|
|
if(operation is "select" or "progress"){
|
|
if(!r.IsActive)throw new ArgumentException("Activate this investigation first.");service.Select(r,c,s,finding??"",capability);
|
|
if(operation=="progress"){if(capability==null||!InvestigationGuidanceService.ProgressStates.Contains(progress))throw new ArgumentException("Choose a progress state.");s.Progress[InvestigationGuidanceService.Key(finding!,capability)]=progress!;}
|
|
}else if(operation is not("activate" or "dismiss" or "finish"))throw new ArgumentException("Unknown guidance action.");
|
|
await service.Save(Author,r,s,operation is "select" or "progress"?"save":operation);
|
|
if(operation=="activate")return RedirectToAction("Index","WriterInvestigations",new{bookId,id});
|
|
return Json(new{ok=true});
|
|
});
|
|
[HttpPost("/InvestigationCompanion/Open"),ValidateAntiForgeryToken]
|
|
public Task<IActionResult> Open(int bookId,Guid id,string finding,string capability)=>Guard(async()=>{var(r,c)=await Load(null,bookId,id);var target=await service.Open(Author,r,c,finding,capability);return RedirectToAction(target.Action,target.Controller,target.Values);});
|
|
}
|