using System.Security.Claims; using System.Text.Json; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using PlotLine.Data; using PlotLine.Models.Investigations; using PlotLine.Services.Investigations; namespace PlotLine.Controllers; [Authorize] [ResponseCache(NoStore=true,Location=ResponseCacheLocation.None)] public sealed class WriterInvestigationsController(InvestigationAccess gate,IInvestigationRepository repository,InvestigationService service,IInvestigationGuidanceRepository guidance,InvestigationGuidanceService companion):Controller { async Task IsAdmin()=> (await HttpContext.RequestServices.GetRequiredService().AuthorizeAsync(User,null,"AdminOnly")).Succeeded; async Task EnsureCatalogue(Catalogue c){if(c.Synthetic&&!await IsAdmin())throw new UnauthorizedAccessException();} int Author=>int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!); async Task Guard(Func> 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(Microsoft.Data.SqlClient.SqlException e)when(e.Number==51000){return NotFound();}catch(Microsoft.Data.SqlClient.SqlException e)when(e.Number==51002){Response.StatusCode=409;ViewData["Failure"]=e.Message;return View("Failure");}catch(ArgumentException e){Response.StatusCode=400;ViewData["Failure"]=e.Message;return View("Failure");}catch(Exception e)when(e is Microsoft.Data.SqlClient.SqlException or TimeoutException){Response.StatusCode=503;ViewData["Failure"]="Investigations are temporarily unavailable. No unconfirmed save should be assumed successful. Return to Explore to resume.";return View("Failure");}} [HttpGet("/Writer/Explore/Investigate")] public Task Index(int bookId,Guid? id,string? question=null,string? catalogueVersion=null)=>Guard(async()=>{ if(id.HasValue)ViewData["GuidanceVersion"]=(await guidance.Read(Author,null,bookId,id.Value))?.GuidanceVersion??0; var project=await service.Project(bookId);Catalogue c;Investigation? row=null;Evaluation? state=null; if(id.HasValue){(row,c)=await service.Read(Author,bookId,id.Value);await EnsureCatalogue(c);state=service.Current(c,row);if(question!=null&&!row.Presented.Contains(question))return BadRequest();ViewData["Question"]=question??state.NextQuestion;} else {if(catalogueVersion!=null&&!await IsAdmin())return NotFound();c=await (catalogueVersion==null?service.AuthorCatalogue():repository.Catalogue(catalogueVersion))??throw new ArgumentException("The investigation catalogue is not available yet.");await EnsureCatalogue(c);} var savedRows=await repository.List(Author,bookId);var saved=new List();var labels=new Dictionary();var catalogues=new Dictionary{{c.Version,c}};var admin=await IsAdmin(); foreach(var item in savedRows){ if(!catalogues.TryGetValue(item.CatalogueVersion,out var old)){old=await repository.Catalogue(item.CatalogueVersion);if(old==null)continue;catalogues[old.Version]=old;} if(!old.Synthetic||admin){saved.Add(item);labels[item.ID]=old.Concerns.Single(r=>r.Id==item.Concern).Text;} } ViewData["SavedConcernLabels"]=labels; return View(new InvestigationPage(row,c,state,saved,project,bookId)); }); [HttpPost("/Writer/Explore/Investigate/Start"),ValidateAntiForgeryToken] public Task Start(int bookId,string concern,string? catalogueVersion=null)=>Guard(async()=>{if(catalogueVersion!=null&&!await IsAdmin())return NotFound();var c=await (catalogueVersion==null?service.AuthorCatalogue():repository.Catalogue(catalogueVersion))??throw new ArgumentException("The investigation catalogue is unavailable.");await EnsureCatalogue(c);var row=await service.Start(Author,bookId,concern,c.Version);return RedirectToAction(nameof(Index),new{bookId,id=row.ID});}); [HttpPost("/Writer/Explore/Investigate/Answer"),ValidateAntiForgeryToken] public Task Answer(int bookId,Guid id,int version,string? question,string? option,string? explanation,string operation="answer")=>Guard(async()=>{ ViewData["Explanation"]=explanation;ViewData["Option"]=option;var(i,c)=await service.Read(Author,bookId,id);await EnsureCatalogue(c);if(version!=i.Version){Response.StatusCode=409;ViewData["Failure"]="Another window changed this investigation. Your answer is retained below. Resume the latest version before submitting again.";ViewData["Explanation"]=explanation;ViewData["Option"]=option;return View("Failure");} if((operation is "answer" or "save")&&option!=null){InvestigationService.Answer(i,c,question??"",option??"",explanation);} else if(operation is "further" or "disagree"){i.Accepted=false;i.ContinueUntil=Math.Min(c.MaxAnswers,i.Answers.Count+2);} else if(operation=="accept")i.Accepted=true; else if(operation=="save"){if((explanation?.Length??0)>2000)throw new ArgumentException("Please keep your explanation within2,000 characters.");i.DraftQuestion=question;i.DraftExplanation=explanation;} else throw new ArgumentException("Choose an answer before continuing."); await service.Persist(i,c,version,operation); return RedirectToAction(nameof(Index),new{bookId,id,question=operation=="disagree"&&i.CurrentQuestion==null?i.Answers.LastOrDefault()?.Question:null,saved=operation=="save"?true:(bool?)null}); }); [HttpPost("/Writer/Explore/Investigate/Open"),ValidateAntiForgeryToken] public Task Open(int bookId,Guid id,int version,string capability)=>Guard(async()=>{ var(i,c)=await service.Read(Author,bookId,id);await EnsureCatalogue(c);if(version!=i.Version)throw new ArgumentException("Resume the latest version before opening a tool."); var r=await guidance.Read(Author,i.ProjectID,bookId,id)??throw new KeyNotFoundException(); var saved=InvestigationGuidanceService.Decode(r);var finding=InvestigationGuidanceService.Recommended(saved.Investigation,saved.Evaluation).FirstOrDefault(h=>c.Hypotheses.Single(x=>x.Id==h).Capabilities.Contains(capability))??throw new ArgumentException("This destination is not currently recommended."); var target=await companion.Open(Author,r,c,Request.Form["finding"].FirstOrDefault()??finding,capability); return RedirectToAction(target.Action,target.Controller,target.Values); }); [Authorize(Policy="AdminOnly"),HttpGet("/admin/writer-investigations")] public Task Admin()=>Guard(async()=>View("Admin",await repository.Catalogue())); [Authorize(Policy="AdminOnly"),HttpPost("/admin/writer-investigations"),ValidateAntiForgeryToken,RequestSizeLimit(1_200_000)] public Task Import(string json,string operation)=>Guard(async()=>{var c=CatalogueValidator.Parse(json);if(operation=="publish")await repository.Publish(JsonSerializer.Serialize(c,CatalogueValidator.Json),User.Identity?.Name??"administrator");ViewData["Message"]=operation=="publish"?"New immutable catalogue version published.":"Validation passed; nothing written.";return View("Admin",c);}); [Authorize(Policy="AdminOnly"),HttpGet("/admin/writer-investigations/export")] public Task Export(string? version)=>Guard(async()=>Content(JsonSerializer.Serialize(await repository.Catalogue(version),CatalogueValidator.Json),"application/json")); [Authorize(Policy="AdminOnly"),HttpGet("/admin/writer-investigations/simulator")] public Task Simulator(int bookId,Guid id)=>Guard(async()=>{var(i,c)=await service.Read(Author,bookId,id);ViewData["Events"]=await repository.Replay(Author,bookId,id);return View("Simulator",new InvestigationPage(i,c,service.Current(c,i),[],i.ProjectID,i.BookID));}); [Authorize(Policy="AdminOnly"),HttpGet("/admin/writer-investigations/diagnostics")] public Task Diagnostics(int bookId,Guid id)=>Guard(async()=>{var(i,c)=await service.Read(Author,bookId,id);return Json(new{investigation=i,evaluation=service.Current(c,i),trace=InvestigationDiagnostics.Trace(c,i.Concern,i.Answers,service.Current(c,i).AvailableCapabilities.ToHashSet(),i.ContinueUntil),destinations=c.Capabilities,events=await repository.Replay(Author,bookId,id)});}); }