86 lines
5.6 KiB
C#
86 lines
5.6 KiB
C#
using System.Security.Cryptography;
|
|
using System.Text.Json;
|
|
using Microsoft.AspNetCore.Authorization;
|
|
using Microsoft.AspNetCore.DataProtection;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using Microsoft.AspNetCore.Mvc.Filters;
|
|
using PlotLine.Data;
|
|
using PlotLine.Models.WritingSolver;
|
|
using PlotLine.Services;
|
|
namespace PlotLine.Controllers;
|
|
|
|
// Run before authorization: even the review endpoints are unavailable outside Development.
|
|
public sealed class SolverReviewDevelopmentOnlyAttribute : Attribute,IAsyncAuthorizationFilter,IOrderedFilter
|
|
{
|
|
public int Order=>int.MinValue;
|
|
public Task OnAuthorizationAsync(AuthorizationFilterContext context)
|
|
{
|
|
if(!context.HttpContext.RequestServices.GetRequiredService<IWebHostEnvironment>().IsDevelopment())context.Result=new NotFoundResult();
|
|
context.HttpContext.Response.Headers.CacheControl="private, no-store";
|
|
context.HttpContext.Response.Headers["X-Robots-Tag"]="noindex, nofollow";
|
|
return Task.CompletedTask;
|
|
}
|
|
}
|
|
[SolverReviewDevelopmentOnly]
|
|
[Authorize(Policy="AdminOnly")]
|
|
[Route("admin/writing-solver-review")]
|
|
public sealed class WritingSolverReviewController(WritingSolverReview review,WritingSolverReviewStore store,IWritingSolverRepository repository,IDataProtectionProvider protection):Controller
|
|
{
|
|
private sealed record History(string Version,List<SolverAnswer> Answers);
|
|
[HttpGet("")]
|
|
public async Task<IActionResult> Index(string? category=null,string? status="unresolved")
|
|
{
|
|
var items=await store.List();
|
|
return View(new SolverReviewList(items.Where(x=>(category is null||x.Category==category)&&(status!="resolved"||x.Resolved)&&(status!="unresolved"||!x.Resolved)).ToArray(),await review.Enabled(HttpContext),category,status));
|
|
}
|
|
[HttpPost("mode")][ValidateAntiForgeryToken]
|
|
public IActionResult Mode(bool enabled)
|
|
{
|
|
if(enabled)Response.Cookies.Append(WritingSolverReview.Cookie,"on",new CookieOptions{HttpOnly=true,Secure=Request.IsHttps,SameSite=SameSiteMode.Strict,IsEssential=true,Path="/",MaxAge=TimeSpan.FromDays(1)});
|
|
else Response.Cookies.Delete(WritingSolverReview.Cookie,new CookieOptions{Path="/"});
|
|
return Redirect(enabled?"/problem-solver":"/admin/writing-solver-review");
|
|
}
|
|
[HttpPost("feedback")][ValidateAntiForgeryToken]
|
|
public async Task<IActionResult> Feedback(string state,string category,string? note)
|
|
{
|
|
if(!await review.Enabled(HttpContext))return Forbid();
|
|
if(!WritingSolverReview.Categories.Contains(category)||note?.Length>2000||state is null||state.Length>16000)return BadRequest("Choose a feedback category and use at most 2,000 characters.");
|
|
try
|
|
{
|
|
var protector=protection.CreateProtector("WritingSolver.history.v1").ToTimeLimitedDataProtector();
|
|
var history=JsonSerializer.Deserialize<History>(protector.Unprotect(state,out _));
|
|
var graph=await repository.GetAsync();
|
|
if(history is null||history.Version!=graph.Version)return Conflict("The graph changed. Reopen the solver before capturing feedback.");
|
|
var captured=review.Capture(graph,history.Answers);
|
|
if(captured.AnswerCount!=history.Answers.Count)return BadRequest("This journey is no longer valid. Reopen the solver before capturing feedback.");
|
|
var outcome=WritingSolverEngine.Evaluate(graph,history.Answers);
|
|
var path=outcome.Solutions.FirstOrDefault() is {} solution?"/problem-solver/"+solution.Slug:"/problem-solver";
|
|
var item=new SolverReviewFeedback(Guid.NewGuid(),category,string.IsNullOrWhiteSpace(note)?null:note.Trim(),path,false,captured);
|
|
await store.Save(item);
|
|
return RedirectToAction(nameof(Detail),new{id=item.Id});
|
|
}
|
|
catch(Exception ex)when(ex is CryptographicException or JsonException){return BadRequest("The review journey expired. Reopen the solver before capturing feedback.");}
|
|
}
|
|
[HttpGet("{id:guid}")]
|
|
public async Task<IActionResult> Detail(Guid id)
|
|
{var item=await store.Find(id);return item is null?NotFound():View(new SolverReviewDetail(item,null));}
|
|
[HttpPost("{id:guid}/status")][ValidateAntiForgeryToken]
|
|
public async Task<IActionResult> Status(Guid id,bool resolved)
|
|
{if(!await store.Resolve(id,resolved))return NotFound();return RedirectToAction(nameof(Detail),new{id});}
|
|
[HttpPost("{id:guid}/replay")][ValidateAntiForgeryToken]
|
|
public async Task<IActionResult> Replay(Guid id)
|
|
{var item=await store.Find(id);return item is null?NotFound():View("Detail",new SolverReviewDetail(item,review.Capture(await repository.GetAsync(),item.Captured.Answers)));}
|
|
[HttpPost("{id:guid}/resume")][ValidateAntiForgeryToken]
|
|
public async Task<IActionResult> Resume(Guid id)
|
|
{
|
|
var item=await store.Find(id);if(item is null)return NotFound();var graph=await repository.GetAsync();
|
|
if(WritingSolverReview.Hash(graph)!=item.Captured.GraphHash)return Conflict("The graph has changed. Replay this capture to compare it with the current conversation.");
|
|
var protector=protection.CreateProtector("WritingSolver.history.v1").ToTimeLimitedDataProtector();
|
|
var state=protector.Protect(JsonSerializer.Serialize(new History(graph.Version,item.Captured.Answers)),TimeSpan.FromHours(2));
|
|
return RedirectToAction("Index","WritingProblems",new{state});
|
|
}
|
|
[HttpGet("{id:guid}/export")]
|
|
public async Task<IActionResult> Export(Guid id)
|
|
{var item=await store.Find(id);return item is null?NotFound():File(System.Text.Encoding.UTF8.GetBytes(JsonSerializer.Serialize(item,new JsonSerializerOptions{WriteIndented=true})),"application/json","solver-review-"+id+".json");}
|
|
}
|