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) : 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("/writing-problems")] 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. 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); SetSeo("The Writing Problem Solver", "Tell us what’s making your novel complicated and find a practical way to untangle it.", "/writing-problems", state is null); 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("/writing-problems/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 }); 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)); } } [HttpGet("/writing-problems/{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(); SetSeo(page.PageTitle,page.Description,$"/{(feature ? "features" : "writing-problems")}/{page.Slug}",page.Index,page.SocialImage); return View("Page",new SolverPageView(graph,page,feature)); } 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)] }); } }