using System.Security.Cryptography; using System.Text.Json; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.Mvc; using PlotLine.Data; using PlotLine.Models.WritingSolver; using PlotLine.Services; namespace PlotLine.Controllers; [AllowAnonymous] public sealed class WritingProblemsController(IWritingSolverRepository repository, IDataProtectionProvider protection, IConfiguration configuration, WritingSolverResultContext resultContext, WritingProblemEditorial? editorial = null) : Controller { private readonly ITimeLimitedDataProtector protector = protection.CreateProtector("WritingSolver.history.v1").ToTimeLimitedDataProtector(); private sealed record History(string Version, List Answers); private string Encode(SolverGraph graph, IEnumerable answers) => protector.Protect(JsonSerializer.Serialize(new History(graph.Version, answers.ToList())), TimeSpan.FromHours(2)); private List Decode(SolverGraph graph, string? state) { if (string.IsNullOrEmpty(state)) return []; if (state.Length > 16000) throw new InvalidDataException("History too large."); var history = JsonSerializer.Deserialize(protector.Unprotect(state, out _)); if (history is null || history.Version != graph.Version) throw new InvalidDataException("The question collection has changed. Please begin again."); return history.Answers; } [HttpGet("/problem-solver")] public async Task Index(string? state = null, bool choose = false) { Response.Headers.CacheControl = "no-store"; Response.Headers["Referrer-Policy"] = "no-referrer"; var graph = await repository.GetAsync(); List history = []; string? error = choose ? "Choose an answer to continue, keeping to the number shown in the question. Use Something else on its own if the other answers don’t fit." : null; try { history = Decode(graph,state); } catch (Exception ex) when (ex is CryptographicException or JsonException or InvalidDataException) { error = "Your previous conversation has expired or changed. Let’s start afresh."; } var outcome = WritingSolverEngine.Evaluate(graph,history); if (state is not null || choose) Response.Headers["X-Robots-Tag"] = "noindex, follow"; if (Complete(graph, outcome) is {} completed) return completed; SetSeo("The Problem Solver", "Tell us what’s making your novel complicated and find a practical way to untangle it.", "/problem-solver", state is null && !choose); ViewData["BackState"] = outcome.Answers.Count > 0 ? Encode(graph,outcome.Answers.Take(outcome.Answers.Count-1)) : null; return View(new SolverJourney(graph,outcome,Encode(graph,outcome.Answers),error)); } [HttpPost("/problem-solver/answer")] [ValidateAntiForgeryToken] public async Task Answer(string state, string node, string[] choices) { var graph = await repository.GetAsync(); try { var history = Decode(graph,state); var before = WritingSolverEngine.Evaluate(graph,history); if (before.Next?.Id != node) return BadRequest("That question is no longer current. Go back and try again."); history.Add(new(node, choices)); var after = WritingSolverEngine.Evaluate(graph,history); if (after.Answers.Count != history.Count) return RedirectToAction(nameof(Index), new { state, choose = true }); if (Complete(graph, after) is {} completed) return completed; return RedirectToAction(nameof(Index), new { state = Encode(graph, after.Answers) }); } catch (Exception ex) when (ex is CryptographicException or JsonException or InvalidDataException) { return RedirectToAction(nameof(Index)); } } private IActionResult? Complete(SolverGraph graph, SolverOutcome outcome) { if (outcome.Next is not null || outcome.Reassurance is not null || outcome.Solutions.FirstOrDefault() is not {} solution) return null; resultContext.Save(HttpContext, graph, outcome, solution.Slug); return RedirectToAction(nameof(Solution), new { slug = solution.Slug }); } [HttpGet("/problem-solver/browse")] [HttpGet("/problem-solver/browse/{problemArea}")] public async Task Browse(string? problemArea=null) { if(editorial is null)return NotFound(); var group=problemArea is null?null:editorial.Catalog.Areas.FirstOrDefault(a=>a.Id==problemArea); if(problemArea is not null && group is null)return NotFound(); var path="/problem-solver/browse"+(group is null?"":"/"+group.Id); SetSeo(group is null?"Browse writing problems":group.Title+" writing problems",group?.Description??"Explore writing problems by area, with practical ways to recognise and inspect them.",path,true); return View("Browse",new WritingProblemBrowse(await repository.GetAsync(),editorial.Catalog,group)); } [HttpGet("/problem-solver/{slug}")] public async Task Solution(string slug) => await Page(slug,false); [HttpGet("/features/{slug}")] public async Task Feature(string slug) => await Page(slug,true); private async Task Page(string slug,bool feature) { var graph = await repository.GetAsync(); SolverPage? page = feature ? graph.Features.FirstOrDefault(p => p.Active && p.Slug == slug) : graph.Solutions.FirstOrDefault(p => p.Active && p.Slug == slug); if (page is null) return NotFound(); var article=feature?null:editorial?.Find(page.Id); SetSeo(article?.Title??page.PageTitle,article?.Description??page.Description,$"/{(feature ? "features" : "problem-solver")}/{page.Slug}",page.Index,page.SocialImage); SolverJourney? journey = null; if (!feature) { Response.Headers.CacheControl = "private, no-store"; Response.Headers.Vary = "Cookie"; Response.Headers["Referrer-Policy"] = "no-referrer"; if (resultContext.Read(HttpContext, graph, slug) is {} outcome) { journey = new(graph, outcome, Encode(graph, outcome.Answers)); ViewData["BackState"] = Encode(graph, outcome.Answers.Take(outcome.Answers.Count - 1)); } } return View("Page",new SolverPageView(graph,page,feature,journey)); } private void SetSeo(string title,string description,string path,bool index,string? image=null) { index = index && configuration.GetValue("WritingSolver:EnableIndexing", true); if (!index) Response.Headers["X-Robots-Tag"] = "noindex, follow"; ViewData["Robots"] = index ? "index, follow" : "noindex, follow"; PublicSeo.Apply(ViewData,configuration,new SeoMetadata { Title=title, Description=description, CanonicalPath=path, OgImage=image, JsonLd=[PublicSeo.WebPageJsonLd(configuration,"WebPage",title,path,description)] }); } }