PlotDirector/PlotLine/Controllers/StoryElementReferencesController.cs

204 lines
10 KiB
C#

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using PlotLine.Data;
using PlotLine.Services;
using PlotLine.ViewModels;
namespace PlotLine.Controllers;
[Authorize]
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
public sealed class StoryElementReferencesController(
ICurrentUserService currentUser,
StoryElementReferenceRepository references,
IUploadStorageService storage,
IProjectCollaborationRepository collaboration,
ISubscriptionService subscriptions,
ICharacterService characters,
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",
new StoryElementReferenceWorkspace(model,
await StoryElementReferenceWorkspace.ReadStorageAsync(model, userId, collaboration, subscriptions)));
}
[HttpGet]
public async Task<IActionResult> Download(StoryElementType entityType, int entityId, int referenceId, bool save = false)
{
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";
if (save) return File(stream, "application/octet-stream", entry.OriginalFileName);
if (entry.Kind == "Image") return File(stream, "image/webp");
var header = new byte[320];
var length = await stream.ReadAtLeastAsync(header, header.Length, false);
stream.Position = 0;
var audioType = StoryElementAttachmentPolicy.AudioType(entry.OriginalFileName);
if (audioType is not null && StoryElementAttachmentPolicy.IsAudio(entry.OriginalFileName, header.AsSpan(0, length)))
return File(stream, audioType, enableRangeProcessing: true);
if (StoryElementAttachmentPolicy.IsPdf(entry.OriginalFileName, header.AsSpan(0, length)))
{
Response.Headers.ContentSecurityPolicy = "sandbox; default-src 'none'";
return File(stream, "application/pdf", enableRangeProcessing: true);
}
return 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 (upload is null || upload.Length is <= 0 or > MapReferenceImageService.MaxUploadBytes)
return Return(scope, "Enter a characteristic or select a non-empty 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.");
kind = StoryElementAttachmentPolicy.IsImage(filename) ? "Image" : "Attachment";
if (kind == "Image" && entityType == StoryElementType.Character)
{
try
{
var result = await characters.UploadCharacterImageAsync(new CharacterImageUploadViewModel
{
CharacterID = entityId, ImageUpload = upload, Caption = note
});
if (!result.Succeeded) return Return(scope, result.ErrorMessage ?? "The image could not be saved.");
await savedData.Activity(list.Access.ProjectID, scope.EntityType.ToString(), scope.EntityID);
return Success(scope);
}
catch (SubscriptionLimitException exception) { return Return(scope, exception.Message); }
}
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;
long? storageLimit;
try
{
using var content = new MemoryStream();
await upload.CopyToAsync(content);
var bytes = kind == "Image"
? MapReferenceImageService.Normalize(content.ToArray(), filename).ImageData!
: content.ToArray();
if (kind == "Attachment" && !StoryElementAttachmentPolicy.IsAudio(filename, bytes) &&
!StoryElementAttachmentPolicy.IsAllowedDocument(filename, bytes))
return Return(scope, "Unsupported file or file contents. Choose an image, audio file, PDF, text file, DOCX or XLSX.");
size = bytes.LongLength;
var quota = await subscriptions.CanUploadFileAsync(owner.Value, size);
if (!quota.Allowed)
return Return(scope, owner.Value == userId ? quota.Message : "The project storage allowance would be exceeded.");
storageLimit = quota.MaximumAllowedBytes >= 999999L * 1024 * 1024 ? null : quota.MaximumAllowedBytes;
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 (SubscriptionLimitException 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, storageLimitBytes: storageLimit);
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, string? title = null)
{
if (!ModelState.IsValid || currentUser.UserId is not int userId ||
operation is not ("edit" or "delete" or "caption" or "primary" or "clear")) return NotFound();
var scope = new StoryElementReferenceScope(entityType, entityId);
note = (note ?? "").Trim();
if (note.Length > 500) return Return(scope, "Use 500 characters or fewer.");
title = title?.Trim();
if (title?.Length > 160) return Return(scope, "Use 160 characters or fewer for the title.");
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, title: string.IsNullOrWhiteSpace(title) ? null : title);
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.QuotaExceeded) return Return(scope, "This upload would exceed the account storage allowance.");
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);
return Success(scope);
}
private IActionResult Success(StoryElementReferenceScope scope)
{
if (WantsJson) return Ok(new { message = "References updated." });
TempData["ReferenceSaved"] = "References updated.";
return Return(scope);
}
private bool WantsJson => Request.Headers["X-Requested-With"] == "XMLHttpRequest";
private IActionResult Return(StoryElementReferenceScope scope, string? error = null)
{
if (error is not null)
{
if (WantsJson) return BadRequest(new { message = error });
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."); }
}
}