PlotDirector/PlotLine/Controllers/LocationWorkspaceController.cs

163 lines
11 KiB
C#

using System.Data;
using System.Security.Cryptography;
using System.Text.Json;
using Dapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using PlotLine.Data;
using PlotLine.Models;
using PlotLine.Services;
using PlotLine.Services.Context;
namespace PlotLine.Controllers;
[Authorize]
public sealed class LocationWorkspaceController(ISqlConnectionFactory connections, ICurrentUserService user,
IProjectRepository projects, ContextWorkspaceNotifications notifications, IDataProtectionProvider protection) : Controller
{
public sealed record Alias(int LocationID, string Value);
public sealed record Link(int LocationID, int ID, string Name, string Kind);
public sealed record Usage(int LocationID, int SceneCount);
public sealed record Option(int ID, string Name);
public sealed record Change(int Id, string Value, string Version);
public sealed record Assignment(int ProjectId, string Attribute, Change[] Changes);
public sealed record Receipt(int User, int ProjectId, string Attribute, Change[] Changes, DateTime Expires);
public sealed record UndoRequest(string Token);
public sealed record CreateRequest(int ProjectId, string Name, int? ParentId);
private IDataProtector Protector => protection.CreateProtector("LocationWorkspace.Undo.v1");
[HttpGet]
public async Task<IActionResult> Directory(int projectId)
{
if (user.UserId is not int author) return Unauthorized();
var project = await projects.GetForUserAsync(projectId, author);
if (project is null) return NotFound();
using var db = connections.CreateConnection();
using var result = await db.QueryMultipleAsync("dbo.Location_WorkspaceRead", new { ProjectID = projectId, UserID = author }, commandType: CommandType.StoredProcedure);
var records = (await result.ReadAsync<LocationWorkspaceRecord>()).ToArray();
var aliases = (await result.ReadAsync<LocationAlias>()).ToLookup(a => a.LocationID, a => a.Alias);
var maps = (await result.ReadAsync<Link>()).ToLookup(a => a.LocationID);
var floors = (await result.ReadAsync<Link>()).ToLookup(a => a.LocationID);
var usage = (await result.ReadAsync<Usage>()).ToDictionary(a => a.LocationID, a => a.SceneCount);
await result.ReadAsync<Option>(); // Keep the established six-result directory contract for other readers.
result.Dispose();
var taxonomy = (await db.QueryAsync<LocationTypeTaxonomyEntry>("dbo.LocationTypeTaxonomy_Read", commandType: CommandType.StoredProcedure)).ToArray();
return Json(new { canEdit = ContextEditPolicy.CanEdit(project), types = taxonomy.Where(t => t.IsAssignable).Select(LocationWorkspaceIcons.Presentation), taxonomy = taxonomy.Select(LocationWorkspaceIcons.Presentation),
locations = records.Select(r => new { id = r.LocationID, name = r.LocationName, parent = r.ParentLocationID,
type = r.LocationTypeID?.ToString() ?? "", typeName = r.LocationTypeName, classification = r.Classification ?? "",
relationships = r.RelationshipCount, characters = r.CharacterCount, assets = r.AssetCount,
description = r.Description ?? "", quickAdd = r.ShowInQuickAddBar ? "1" : "0", detection = r.ExcludeFromCompanionDetection ? "1" : "0",
version = r.UpdatedDate.ToString("O"), aliases = aliases[r.LocationID], maps = maps[r.LocationID], floors = floors[r.LocationID], scenes = usage.GetValueOrDefault(r.LocationID) }) });
}
[HttpGet]
public async Task<IActionResult> Taxonomy()
{
using var db = connections.CreateConnection();
var taxonomy = await db.QueryAsync<LocationTypeTaxonomyEntry>("dbo.LocationTypeTaxonomy_Read", commandType: CommandType.StoredProcedure);
return Json(taxonomy.Select(LocationWorkspaceIcons.Presentation));
}
[HttpGet]
public async Task<IActionResult> Picker(int projectId)
{
if (user.UserId is not int author) return Unauthorized();
if (await projects.GetForUserAsync(projectId, author) is null) return NotFound();
using var db = connections.CreateConnection();
using var result = await db.QueryMultipleAsync("dbo.Location_PickerRead", new { ProjectID = projectId, UserID = author }, commandType: CommandType.StoredProcedure);
var locations = (await result.ReadAsync<LocationWorkspaceRecord>()).ToArray();
var aliases = (await result.ReadAsync<LocationAlias>()).ToLookup(a => a.LocationID, a => a.Alias);
result.Dispose();
var taxonomy = await db.QueryAsync<LocationTypeTaxonomyEntry>("dbo.LocationTypeTaxonomy_Read", commandType: CommandType.StoredProcedure);
return Json(new { types = taxonomy.Where(t => t.IsAssignable).Select(LocationWorkspaceIcons.Presentation),
locations = locations.Select(r => new { id = r.LocationID, name = r.LocationName, parent = r.ParentLocationID,
type = r.LocationTypeID?.ToString() ?? "", aliases = aliases[r.LocationID] }) });
}
[HttpPost, ValidateAntiForgeryToken]
public async Task<IActionResult> Assign([FromBody] Assignment input)
{
if (user.UserId is null) return Unauthorized();
if (!ModelState.IsValid || input is null || input.Changes is null || input.Changes.Length is < 1 or > 2000
|| input.Changes.Any(c => c is null || c.Value is null || c.Value.Length > 1000000 || !DateTime.TryParse(c.Version, out _))
|| input.Changes.Select(c => c.Id).Distinct().Count() != input.Changes.Length) return BadRequest(new { message = "Choose a valid selection." });
if (input.Attribute is not ("type" or "classification" or "parent" or "name" or "description" or "quickAdd" or "detection"))
return BadRequest(new { message = "Unknown location attribute." });
if (input.Attribute == "classification" && input.Changes.Any(c => c.Value is not ("" or "Real" or "Fictional" or "Fictionalised")))
return BadRequest(new { message = "Choose a supported classification." });
return await Execute(input, false);
}
[HttpPost, ValidateAntiForgeryToken]
public async Task<IActionResult> Undo([FromBody] UndoRequest request)
{
if (user.UserId is not int author) return Unauthorized();
if (!ModelState.IsValid || string.IsNullOrWhiteSpace(request?.Token)) return BadRequest(new { message = "Undo is unavailable." });
try
{
var receipt = JsonSerializer.Deserialize<Receipt>(Protector.Unprotect(request.Token));
if (receipt is null || receipt.User != author || receipt.Expires < DateTime.UtcNow) return BadRequest(new { message = "Undo has expired." });
return await Execute(new(receipt.ProjectId, receipt.Attribute, receipt.Changes), true);
}
catch (Exception e) when (e is CryptographicException or JsonException or ArgumentException)
{ return BadRequest(new { message = "Undo is unavailable." }); }
}
private async Task<IActionResult> Execute(Assignment input, bool restore)
{
try
{
using var db = connections.CreateConnection();
var previous = (await db.QueryAsync<Change>("dbo.Location_WorkspaceAssign", new { ProjectID = input.ProjectId,
UserID = user.UserId, input.Attribute, Changes = JsonSerializer.Serialize(input.Changes), Restore = restore }, commandType: CommandType.StoredProcedure)).ToArray();
string? undoToken = previous.Length == 0 ? null : Protector.Protect(JsonSerializer.Serialize(new Receipt(user.UserId!.Value,
input.ProjectId, input.Attribute, previous, DateTime.UtcNow.AddMinutes(10))));
if (previous.Length > 0) await notifications.Invalidate(user.UserId!.Value, projectId: input.ProjectId, kind: "locations");
return Json(new { saved = true, undoToken, changes = previous.Select(c => new { c.Id, c.Version, value = input.Attribute == "type" && int.TryParse(input.Changes.Single(i => i.Id == c.Id).Value, out var typeId) ? typeId.ToString() : input.Changes.Single(i => i.Id == c.Id).Value }), attribute = input.Attribute });
}
catch (SqlException e) when (e.Number is 51010 or 51011 or 51012)
{ return StatusCode(e.Number == 51010 ? 403 : 409, new { message = e.Message }); }
}
public sealed record MergeRequest(int ProjectId, int SourceId, int TargetId, string SourceVersion, string TargetVersion, bool Confirm);
[HttpPost, ValidateAntiForgeryToken]
public async Task<IActionResult> Merge([FromBody] MergeRequest input)
{
if (user.UserId is not int author) return Unauthorized();
if (!ModelState.IsValid || input is null || !input.Confirm || !DateTime.TryParse(input.SourceVersion, out var sourceVersion)
|| !DateTime.TryParse(input.TargetVersion, out var targetVersion)) return BadRequest(new { message = "Review and confirm the merge." });
try
{
using var db = connections.CreateConnection();
var parameters = new DynamicParameters(new { ProjectID = input.ProjectId, UserID = author, SourceID = input.SourceId, TargetID = input.TargetId });
// Dapper's default DateTime binding rounds to SQL datetime precision; review versions are datetime2.
parameters.Add("SourceVersion", sourceVersion, DbType.DateTime2);
parameters.Add("TargetVersion", targetVersion, DbType.DateTime2);
await db.QuerySingleAsync<EntityMergeResult>("dbo.Location_WorkspaceMerge", parameters, commandType: CommandType.StoredProcedure);
await notifications.Invalidate(author, projectId: input.ProjectId, kind: "locations");
return Json(new { id = input.TargetId });
}
catch (SqlException e) when (e.Number is 51000 or 51010 or 51011 or 51012)
{ return StatusCode(e.Number == 51010 ? 403 : 409, new { message = e.Message }); }
}
[HttpPost, ValidateAntiForgeryToken]
public async Task<IActionResult> Create([FromBody] CreateRequest input)
{
if (user.UserId is not int author) return Unauthorized();
if (!ModelState.IsValid || input is null || string.IsNullOrWhiteSpace(input.Name) || input.Name.Length > 200) return BadRequest(new { message = "Enter a name of up to 200 characters." });
try
{
using var db = connections.CreateConnection();
var id = await db.QuerySingleAsync<int>("dbo.Location_WorkspaceCreate", new { ProjectID = input.ProjectId, UserID = author, input.Name, ParentID = input.ParentId }, commandType: CommandType.StoredProcedure);
await notifications.Invalidate(author, projectId: input.ProjectId, kind: "locations");
return Json(new { id });
}
catch (SqlException e) when (e.Number is 51010 or 51012)
{ return StatusCode(e.Number == 51010 ? 403 : 409, new { message = e.Message }); }
}
}