104 lines
6.1 KiB
C#
104 lines
6.1 KiB
C#
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) : Controller
|
||
{
|
||
private readonly ITimeLimitedDataProtector protector = protection.CreateProtector("WritingSolver.history.v1").ToTimeLimitedDataProtector();
|
||
private sealed record History(string Version, List<SolverAnswer> Answers);
|
||
private string Encode(SolverGraph graph, IEnumerable<SolverAnswer> answers) => protector.Protect(JsonSerializer.Serialize(new History(graph.Version, answers.ToList())), TimeSpan.FromHours(2));
|
||
private List<SolverAnswer> Decode(SolverGraph graph, string? state)
|
||
{
|
||
if (string.IsNullOrEmpty(state)) return [];
|
||
if (state.Length > 16000) throw new InvalidDataException("History too large.");
|
||
var history = JsonSerializer.Deserialize<History>(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<IActionResult> Index(string? state = null, bool choose = false)
|
||
{
|
||
Response.Headers.CacheControl = "no-store";
|
||
Response.Headers["Referrer-Policy"] = "no-referrer";
|
||
var graph = await repository.GetAsync();
|
||
List<SolverAnswer> 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) Response.Headers["X-Robots-Tag"] = "noindex, follow";
|
||
if (Complete(graph, outcome) is {} completed) return completed;
|
||
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<IActionResult> 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("/writing-problems/{slug}")]
|
||
public async Task<IActionResult> Solution(string slug) => await Page(slug,false);
|
||
[HttpGet("/features/{slug}")]
|
||
public async Task<IActionResult> Feature(string slug) => await Page(slug,true);
|
||
private async Task<IActionResult> 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);
|
||
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)]
|
||
});
|
||
}
|
||
}
|