PlotDirector/PlotLine/Controllers/StoryElementReferencesController.cs

152 lines
7.4 KiB
C#

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using PlotLine.Data;
using PlotLine.Services;
namespace PlotLine.Controllers;
[Authorize]
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
public sealed class StoryElementReferencesController(
ICurrentUserService currentUser,
StoryElementReferenceRepository references,
IUploadStorageService storage,
IProjectCollaborationRepository collaboration,
ISubscriptionService subscriptions,
ContextSavedData savedData,
ILogger<StoryElementReferencesController> logger) : Controller
{
private const string StorageFolder = StoryElementReferenceStorage.Folder;
[HttpGet]
public async Task<IActionResult> List(StoryElementType entityType, int entityId)
{
if (!ModelState.IsValid || currentUser.UserId is not int userId) return NotFound();
var model = await references.ListAsync(userId, new(entityType, entityId));
return model is null ? NotFound() : PartialView("Components/StoryElementReferences/Default", model);
}
[HttpGet]
public async Task<IActionResult> Download(StoryElementType entityType, int entityId, int referenceId)
{
if (!ModelState.IsValid || currentUser.UserId is not int userId) return NotFound();
var entry = await references.FileAsync(userId, new(entityType, entityId), referenceId);
var path = storage.TryResolvePublicPath(entry?.StoragePath, "uploads/" + StorageFolder);
if (entry is null || path is null) return NotFound();
FileStream stream;
try { stream = System.IO.File.OpenRead(path); }
catch (IOException) { return NotFound(); }
Response.Headers.XContentTypeOptions = "nosniff";
return entry.Kind == "Image"
? File(stream, "image/webp")
: File(stream, "application/octet-stream", entry.OriginalFileName);
}
[HttpPost]
[ValidateAntiForgeryToken]
[RequestSizeLimit(11L * 1024 * 1024)]
public async Task<IActionResult> Add(StoryElementType entityType, int entityId, string kind,
string? note, IFormFile? upload)
{
if (!ModelState.IsValid || currentUser.UserId is not int userId) return NotFound();
var scope = new StoryElementReferenceScope(entityType, entityId);
var list = await references.ListAsync(userId, scope);
if (list?.Access.CanEdit != true) return NotFound();
note = (note ?? "").Trim();
if (note.Length > 500) return Return(scope, "Use 500 characters or fewer.");
if (kind == "Characteristic" && upload is null && note.Length > 0)
{
return await Finish(scope, await references.ChangeAsync(userId, scope, "add", null, null, kind, note));
}
if (kind is not ("Image" or "Attachment") || (kind == "Image" && entityType == StoryElementType.Character) ||
upload is null || upload.Length is <= 0 or > MapReferenceImageService.MaxUploadBytes)
return Return(scope, "Enter a characteristic or select a file up to 10 MB.");
var filename = Path.GetFileName(upload.FileName.Replace('\\', '/'));
if (string.IsNullOrWhiteSpace(filename) || filename.Length > 300 || filename.Any(char.IsControl))
return Return(scope, "Choose a file with a valid name up to 300 characters.");
var owner = await collaboration.GetOwnerUserIdAsync(list.Access.ProjectID);
if (owner is null) return NotFound();
var filenameOnDisk = Guid.NewGuid().ToString("N") + ".blob";
var storagePath = storage.GetPublicPath(StorageFolder, filenameOnDisk);
var physicalPath = storage.GetFilePath(StorageFolder, filenameOnDisk);
long size;
try
{
using var content = new MemoryStream();
await upload.CopyToAsync(content);
var bytes = kind == "Image"
? MapReferenceImageService.Normalize(content.ToArray(), filename).ImageData!
: content.ToArray();
size = bytes.LongLength;
var quota = await subscriptions.CanUploadFileAsync(owner.Value, size);
if (!quota.Allowed) return Return(scope, quota.Message ?? "The project storage limit would be exceeded.");
storage.GetDirectory(StorageFolder);
await using var file = new FileStream(physicalPath, FileMode.CreateNew, FileAccess.Write);
await file.WriteAsync(bytes);
}
catch (InvalidDataException exception) { return Return(scope, exception.Message); }
catch (IOException exception)
{
logger.LogWarning(exception, "Could not write a story element reference upload.");
RemoveFile(storagePath);
return Return(scope, "The file could not be saved. Try again.");
}
// Retain the file on an uncertain database outcome so a committed reference stays usable.
var change = await references.ChangeAsync(userId, scope, "add", null, null, kind, note, storagePath, filename, size);
if (change?.Changed != true) RemoveFile(storagePath);
return await Finish(scope, change);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Change(StoryElementType entityType, int entityId, int referenceId,
string operation, string? version, string? note)
{
if (!ModelState.IsValid || currentUser.UserId is not int userId ||
operation is not ("edit" or "delete" or "caption")) return NotFound();
var scope = new StoryElementReferenceScope(entityType, entityId);
note = (note ?? "").Trim();
if (note.Length > 500) return Return(scope, "Use 500 characters or fewer.");
byte[]? expectedVersion = null;
if (operation != "caption")
{
expectedVersion = new byte[8];
if (version is null || !Convert.TryFromBase64String(version, expectedVersion, out int written) || written != 8)
return BadRequest();
}
var change = await references.ChangeAsync(userId, scope, operation, referenceId, expectedVersion, null, note);
if (change?.StoragePath is string path) RemoveFile(path);
return await Finish(scope, change);
}
private async Task<IActionResult> Finish(StoryElementReferenceScope scope, StoryElementReferenceChange? change)
{
if (change is null) return NotFound();
if (!change.Changed)
return Return(scope, "The reference changed or the note is empty. Review the saved references and try again.");
await savedData.Activity(change.ProjectID, scope.EntityType.ToString(), scope.EntityID);
TempData["ReferenceSaved"] = "References updated.";
return Return(scope);
}
private IActionResult Return(StoryElementReferenceScope scope, string? error = null)
{
if (error is not null) TempData["ReferenceError"] = error;
return RedirectToAction("Details", scope.DetailsController, new { id = scope.EntityID, tab = "reference" },
scope.EntityType == StoryElementType.Character && Request.Form["operation"] == "caption"
? "character-gallery" : "story-element-references");
}
private void RemoveFile(string path)
{
try { storage.TryDeleteFile(path, "uploads/" + StorageFolder); }
catch (IOException exception) { logger.LogWarning(exception, "Reference file cleanup failed."); }
catch (UnauthorizedAccessException exception) { logger.LogWarning(exception, "Reference file cleanup failed."); }
}
}