PlotDirector/PlotLine/Services/ApplicationStartup.cs

73 lines
3.7 KiB
C#

using System.Security.Cryptography;
using System.Text.Json;
using Microsoft.AspNetCore.DataProtection;
namespace PlotLine.Services;
public sealed class ApplicationStartup(IDataProtectionProvider protection)
{
public sealed record Destination(string Label, string Controller, string Action, bool ProjectAsId = false);
public sealed record Recent(string Page, int ProjectID, int? BookID);
public const string Projects = "projects";
public const string Resume = "resume";
public static readonly IReadOnlyDictionary<string, Destination> Destinations = new Dictionary<string, Destination>
{
[Projects] = new("Projects", "Projects", "Index"),
["overview"] = new("Project Overview", "Projects", "Details", ProjectAsId: true),
["timeline"] = new("Timeline", "Timeline", "Index"),
["plotlines"] = new("Plotlines", "PlotLineWorkspace", "Index"),
["writer"] = new("Writer Home", "Writer", "Index"),
[Resume] = new("Where I left off", "Home", "Index")
};
private static readonly IReadOnlyDictionary<string, Destination> WriterDestinations = new Dictionary<string, Destination>
{
["write"] = new("Write", "Writer", "Write"),
["plan"] = new("Plan", "Writer", "Plan"),
["explore"] = new("Explore", "Writer", "Explore"),
["review"] = new("Review", "Writer", "Review"),
["reflect"] = new("Reflect", "Writer", "Reflect")
};
public static Destination? Resolve(string page) => Destinations.GetValueOrDefault(page) ?? WriterDestinations.GetValueOrDefault(page);
public string ReadChoice(HttpContext context, int userId)
=> Read<string>(context, userId, "choice") is { } page && Destinations.ContainsKey(page) ? page : Projects;
public void SaveChoice(HttpContext context, int userId, string choice)
=> Write(context, userId, "choice", choice);
public Recent? ReadRecent(HttpContext context, int userId) => Read<Recent>(context, userId, "recent");
public void Remember(HttpContext context, int userId, int projectId, int? bookId)
{
if (!HttpMethods.IsGet(context.Request.Method) || context.Response.HasStarted) return;
var controller = context.Request.RouteValues["controller"]?.ToString();
var action = context.Request.RouteValues["action"]?.ToString();
var page = Destinations.Concat(WriterDestinations).FirstOrDefault(pair =>
pair.Value.Controller == controller && pair.Value.Action == action).Key;
if (page is null or Projects or Resume) return;
var recent = new Recent(page, projectId, bookId);
if (recent != ReadRecent(context, userId)) Write(context, userId, "recent", recent);
}
private T? Read<T>(HttpContext context, int userId, string key)
{
if (!context.Request.Cookies.TryGetValue(CookieName(userId, key), out var value)) return default;
try { return JsonSerializer.Deserialize<T>(Protector(userId, key).Unprotect(value)); }
catch (Exception ex) when (ex is CryptographicException or JsonException) { return default; }
}
private void Write<T>(HttpContext context, int userId, string key, T value) =>
context.Response.Cookies.Append(CookieName(userId, key), Protector(userId, key).Protect(JsonSerializer.Serialize(value)),
new CookieOptions { HttpOnly = true, Secure = context.Request.IsHttps, SameSite = SameSiteMode.Lax,
MaxAge = TimeSpan.FromDays(365), Path = "/" });
private IDataProtector Protector(int userId, string key) =>
protection.CreateProtector("PlotDirector.ApplicationStartup.v1", userId.ToString(), key);
private static string CookieName(int userId, string key) => $"pd-start-{userId}-{key}";
}