PlotDirector/PlotLine/Controllers/WritingProblemsController.cs

81 lines
4.7 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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<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. 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<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 });
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<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);
return View("Page",new SolverPageView(graph,page,feature));
}
private void SetSeo(string title,string description,string path,bool index,string? image=null)
{
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)]
});
}
}