From 5a1950c79c45b69418e41f178713d123fe01daba Mon Sep 17 00:00:00 2001 From: Codex Date: Sun, 6 Dec 2026 15:24:24 +0000 Subject: [PATCH] Refine shared story element references and attachments --- PlotLine.Tests/StoryElementReferenceTests.cs | 39 ++- .../StoryElementReferencesController.cs | 82 +++++- .../Data/StoryElementReferenceRepository.cs | 10 +- PlotLine/Models/ProjectBackupModels.cs | 4 + .../Services/ProjectBackupGraphValidation.cs | 5 + ...ProjectBackupStoredFieldContract.Schema.cs | 2 +- .../Services/StoryElementAttachmentPolicy.cs | 72 +++++ .../StoryElementReferenceWorkspace.cs | 19 ++ PlotLine/Sql/354_ReferenceWorkspace.sql | 189 +++++++++++++ .../StoryElementReferencesViewComponent.cs | 11 +- PlotLine/Views/Characters/Details.cshtml | 2 + .../Views/Characters/_WorkspaceGallery.cshtml | 19 +- .../Views/Characters/_WorkspaceTab.cshtml | 5 +- PlotLine/Views/Locations/Details.cshtml | 2 + PlotLine/Views/Locations/Edit.cshtml | 1 + .../StoryElementReferences/Default.cshtml | 238 ++++++++++------ .../_ReferenceActions.cshtml | 39 +++ PlotLine/Views/StoryAssets/Details.cshtml | 2 +- .../Views/StoryAssets/_AssetIdentity.cshtml | 4 + .../StoryAssets/_AssetPrimaryImage.cshtml | 30 -- .../wwwroot/css/story-element-references.css | 89 ++++++ .../wwwroot/js/story-element-references.js | 265 ++++++++++++++++-- 22 files changed, 942 insertions(+), 187 deletions(-) create mode 100644 PlotLine/Services/StoryElementAttachmentPolicy.cs create mode 100644 PlotLine/Services/StoryElementReferenceWorkspace.cs create mode 100644 PlotLine/Sql/354_ReferenceWorkspace.sql create mode 100644 PlotLine/Views/Shared/Components/StoryElementReferences/_ReferenceActions.cshtml delete mode 100644 PlotLine/Views/StoryAssets/_AssetPrimaryImage.cshtml create mode 100644 PlotLine/wwwroot/css/story-element-references.css diff --git a/PlotLine.Tests/StoryElementReferenceTests.cs b/PlotLine.Tests/StoryElementReferenceTests.cs index e8247acb..edab24b7 100644 --- a/PlotLine.Tests/StoryElementReferenceTests.cs +++ b/PlotLine.Tests/StoryElementReferenceTests.cs @@ -1,3 +1,4 @@ +using System.IO.Compression; using System.Text.Json; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; @@ -11,7 +12,7 @@ internal static class StoryElementReferenceTests { public static async Task Run() { - var guest = new StoryElementReferencesController(new Guest(), null!, null!, null!, null!, null!, null!); + var guest = new StoryElementReferencesController(new Guest(), null!, null!, null!, null!, null!, null!, null!); foreach (var entity in Enum.GetValues()) { Check(await guest.List(entity, 1) is NotFoundResult, "Reference lists require authentication."); @@ -22,6 +23,19 @@ internal static class StoryElementReferenceTests "Removing references requires authentication."); } + Check(StoryElementAttachmentPolicy.IsImage("reference.PNG"), "Image routing is case insensitive."); + Check(StoryElementAttachmentPolicy.IsAudio("interview.wav", "RIFF0000WAVE"u8), "WAV has an audio type."); + Check(!StoryElementAttachmentPolicy.IsAudio("video.wav", "RIFF0000AVI "u8), "A renamed video is rejected."); + Check(StoryElementAttachmentPolicy.IsAllowedDocument("notes.csv", "name,description"u8.ToArray()), "CSV text is accepted."); + Check(StoryElementAttachmentPolicy.IsAllowedDocument("plan.pdf", "%PDF-1.7"u8.ToArray()), "PDF is accepted."); + Check(!StoryElementAttachmentPolicy.IsAllowedDocument("setup.txt", [77, 90, 0, 0]), "A binary renamed to text is rejected."); + Check(!StoryElementAttachmentPolicy.IsAllowedDocument("setup.js", "alert(1)"u8.ToArray()), "Scripts are rejected."); + Check(StoryElementAttachmentPolicy.IsAllowedDocument("notes.docx", OfficeFile("word/document.xml")), "Word documents are accepted."); + Check(StoryElementAttachmentPolicy.IsAllowedDocument("plan.xlsx", OfficeFile("xl/workbook.xml")), "Excel workbooks are accepted."); + Check(!StoryElementAttachmentPolicy.IsAllowedDocument("notes.docx", OfficeFile("word/document.xml", "word/vbaProject.bin")), + "An Office archive with a macro project is rejected."); + Check(!StoryElementAttachmentPolicy.IsAllowedDocument("archive.zip", OfficeFile("word/document.xml")), "ZIP uploads are rejected."); + var legacy = new ProjectBackupExport { Project = new() { ProjectID = 4 } }; var legacyJson = JsonSerializer.Serialize(legacy); Check(!legacyJson.Contains("\"StoryElementReferences\"", StringComparison.Ordinal), @@ -29,6 +43,10 @@ internal static class StoryElementReferenceTests Check(JsonSerializer.Serialize(JsonSerializer.Deserialize(legacyJson)) == legacyJson, "Reading and reserializing a legacy package must preserve its fingerprint."); + const string oldReference = """{"ReferenceID":1,"CharacterID":7,"LocationID":null,"StoryAssetID":null,"Kind":"Characteristic","Note":"Left-handed","StoragePath":null,"OriginalFileName":null}"""; + Check(JsonSerializer.Serialize(JsonSerializer.Deserialize(oldReference)) == oldReference, + "Older backups with references retain their serialized fingerprint."); + string root = Directory.CreateTempSubdirectory("plotdirector-reference-test-").FullName; try { @@ -53,10 +71,10 @@ internal static class StoryElementReferenceTests StoryElementReferences = [ new() { ReferenceID = 1, CharacterID = 7, Kind = "Characteristic", Note = "Left-handed" }, - new() { ReferenceID = 2, LocationID = 7, Kind = "Image", Note = "Doorway", + new() { ReferenceID = 2, LocationID = 7, Kind = "Image", Note = "Doorway", IsPrimary = true, OriginalFileName = "Sketch.png", StoragePath = uploads.GetPublicPath(folder, "image.blob") }, new() { ReferenceID = 3, StoryAssetID = 7, Kind = "Attachment", - OriginalFileName = "Document.txt", StoragePath = uploads.GetPublicPath(folder, "document.blob") } + OriginalFileName = "Document.txt", Title = "Research notes", StoragePath = uploads.GetPublicPath(folder, "document.blob") } ] } }; @@ -64,6 +82,8 @@ internal static class StoryElementReferenceTests var restored = JsonSerializer.Deserialize(JsonSerializer.Serialize(backup))!; Check(ProjectBackupFiles.Validate(restored) is null, "All uploaded reference bytes survive serialization."); var items = restored.Data.StoryElementReferences!; + Check(items[1].IsPrimary == true && items[2].Title == "Research notes", + "Primary-image selection and attachment titles survive backup serialization."); Check(items[0].Note == "Left-handed" && items[0].StoragePath is null, "Notes are independent of files."); Check(!StoryElementReferenceStorage.ValidBackupImage(attachment), "Arbitrary attachments cannot serve as images."); using (await files.StageAsync(restored, importingCopy: true)) @@ -85,7 +105,18 @@ internal static class StoryElementReferenceTests Directory.Delete(root, recursive: true); } - Console.WriteLine("PASS story element reference authentication, image normalization and portable file round-trip"); + Console.WriteLine("PASS reference authentication, attachment validation and backup round-trip"); + } + + private static byte[] OfficeFile(params string[] parts) + { + using var bytes = new MemoryStream(); + using (var zip = new ZipArchive(bytes, ZipArchiveMode.Create, leaveOpen: true)) + { + zip.CreateEntry("[Content_Types].xml"); + foreach (var part in parts) zip.CreateEntry(part); + } + return bytes.ToArray(); } private static void Check(bool condition, string message) diff --git a/PlotLine/Controllers/StoryElementReferencesController.cs b/PlotLine/Controllers/StoryElementReferencesController.cs index 9600d9fe..44a80856 100644 --- a/PlotLine/Controllers/StoryElementReferencesController.cs +++ b/PlotLine/Controllers/StoryElementReferencesController.cs @@ -2,6 +2,7 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using PlotLine.Data; using PlotLine.Services; +using PlotLine.ViewModels; namespace PlotLine.Controllers; @@ -13,6 +14,7 @@ public sealed class StoryElementReferencesController( IUploadStorageService storage, IProjectCollaborationRepository collaboration, ISubscriptionService subscriptions, + ICharacterService characters, ContextSavedData savedData, ILogger logger) : Controller { @@ -23,11 +25,13 @@ public sealed class StoryElementReferencesController( { 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); + return model is null ? NotFound() : PartialView("Components/StoryElementReferences/Default", + new StoryElementReferenceWorkspace(model, + await StoryElementReferenceWorkspace.ReadStorageAsync(model, userId, collaboration, subscriptions))); } [HttpGet] - public async Task Download(StoryElementType entityType, int entityId, int referenceId) + public async Task 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); @@ -37,15 +41,26 @@ public sealed class StoryElementReferencesController( 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); + 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 Add(StoryElementType entityType, int entityId, string kind, + public async Task Add(StoryElementType entityType, int entityId, string? kind, string? note, IFormFile? upload) { if (!ModelState.IsValid || currentUser.UserId is not int userId) return NotFound(); @@ -60,13 +75,28 @@ public sealed class StoryElementReferencesController( 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."); + 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(); @@ -74,6 +104,7 @@ public sealed class StoryElementReferencesController( var storagePath = storage.GetPublicPath(StorageFolder, filenameOnDisk); var physicalPath = storage.GetFilePath(StorageFolder, filenameOnDisk); long size; + long? storageLimit; try { using var content = new MemoryStream(); @@ -81,14 +112,20 @@ public sealed class StoryElementReferencesController( 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, quota.Message ?? "The project storage limit would be exceeded."); + 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."); @@ -97,7 +134,7 @@ public sealed class StoryElementReferencesController( } // 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); + 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); } @@ -105,13 +142,15 @@ public sealed class StoryElementReferencesController( [HttpPost] [ValidateAntiForgeryToken] public async Task Change(StoryElementType entityType, int entityId, int referenceId, - string operation, string? version, string? note) + 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")) return NotFound(); + 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") { @@ -119,7 +158,7 @@ public sealed class StoryElementReferencesController( 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); + 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); } @@ -127,16 +166,29 @@ public sealed class StoryElementReferencesController( private async Task 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) TempData["ReferenceError"] = error; + 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"); diff --git a/PlotLine/Data/StoryElementReferenceRepository.cs b/PlotLine/Data/StoryElementReferenceRepository.cs index 009db2ec..f7e43926 100644 --- a/PlotLine/Data/StoryElementReferenceRepository.cs +++ b/PlotLine/Data/StoryElementReferenceRepository.cs @@ -16,8 +16,8 @@ public sealed record StoryElementReferenceScope(StoryElementType EntityType, int }; } -public sealed record StoryElementReference(int ReferenceID, string Kind, string Note, string? OriginalFileName, byte[] Version); -public sealed record StoryElementReferenceAccess(int ProjectID, string EntityName, bool CanEdit); +public sealed record StoryElementReference(int ReferenceID, string Kind, string Note, string? OriginalFileName, byte[] Version, string? Title, bool IsPrimary); +public sealed record StoryElementReferenceAccess(int ProjectID, string EntityName, bool CanEdit, string? LegacyImagePath); public sealed record StoryElementReferenceList(StoryElementReferenceScope Scope, StoryElementReferenceAccess Access, IReadOnlyList Items); public sealed record StoryElementReferenceFile(string Kind, string StoragePath, string OriginalFileName); @@ -26,6 +26,7 @@ public sealed class StoryElementReferenceChange public int ProjectID { get; init; } public bool Changed { get; init; } public string? StoragePath { get; init; } + public bool QuotaExceeded { get; init; } } public sealed class StoryElementReferenceRepository(ISqlConnectionFactory connections) @@ -52,14 +53,15 @@ public sealed class StoryElementReferenceRepository(ISqlConnectionFactory connec public async Task ChangeAsync(int userId, StoryElementReferenceScope scope, string action, int? referenceId, byte[]? version, string? kind, string? note, - string? storagePath = null, string? originalFileName = null, long? fileSizeBytes = null) + string? storagePath = null, string? originalFileName = null, long? fileSizeBytes = null, + string? title = null, long? storageLimitBytes = null) { using var connection = connections.CreateConnection(); return await connection.QuerySingleOrDefaultAsync(Procedure, new { UserID = userId, EntityType = scope.EntityType.ToString(), scope.EntityID, Action = action, ReferenceID = referenceId, Version = version, Kind = kind, Note = note, - StoragePath = storagePath, OriginalFileName = originalFileName, FileSizeBytes = fileSizeBytes + StoragePath = storagePath, OriginalFileName = originalFileName, FileSizeBytes = fileSizeBytes, Title = title, StorageLimitBytes = storageLimitBytes }, commandType: CommandType.StoredProcedure); } } diff --git a/PlotLine/Models/ProjectBackupModels.cs b/PlotLine/Models/ProjectBackupModels.cs index a9c49a63..ac9dd174 100644 --- a/PlotLine/Models/ProjectBackupModels.cs +++ b/PlotLine/Models/ProjectBackupModels.cs @@ -301,6 +301,10 @@ public sealed class ProjectBackupStoryElementReference public int? CharacterID { get; set; } public int? LocationID { get; set; } public int? StoryAssetID { get; set; } + [System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull)] + public string? Title { get; set; } + [System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull)] + public bool? IsPrimary { get; set; } public string Kind { get; set; } = ""; public string Note { get; set; } = ""; public string? StoragePath { get; set; } diff --git a/PlotLine/Services/ProjectBackupGraphValidation.cs b/PlotLine/Services/ProjectBackupGraphValidation.cs index 8dfe16ca..7955d63a 100644 --- a/PlotLine/Services/ProjectBackupGraphValidation.cs +++ b/PlotLine/Services/ProjectBackupGraphValidation.cs @@ -142,8 +142,13 @@ internal static class ProjectBackupGraphValidation return $"Project backup {entity.Collection}.{link.Column} references a missing or foreign {link.TargetCollection} record."; } } + var primaryReferenceOwners = new HashSet<(int? LocationID, int? StoryAssetID)>(); foreach (var reference in backup.Data.StoryElementReferences ?? []) { + if (reference.Title?.Length > 160 || + (reference.IsPrimary.HasValue && (reference.IsPrimary != true || reference.Kind != "Image" || + reference.CharacterID.HasValue || !primaryReferenceOwners.Add((reference.LocationID, reference.StoryAssetID))))) + return "Project backup contains invalid attachment metadata."; if (new[] { reference.CharacterID, reference.LocationID, reference.StoryAssetID }.Count(id => id.HasValue) != 1 || reference.Note is null || reference.Note.Length > 500) return "Project backup contains an invalid story element reference."; diff --git a/PlotLine/Services/ProjectBackupStoredFieldContract.Schema.cs b/PlotLine/Services/ProjectBackupStoredFieldContract.Schema.cs index df018ab5..089d8c9c 100644 --- a/PlotLine/Services/ProjectBackupStoredFieldContract.Schema.cs +++ b/PlotLine/Services/ProjectBackupStoredFieldContract.Schema.cs @@ -22,7 +22,7 @@ internal static partial class ProjectBackupStoredFieldContract ["CharacterAttributeTypes"]=("CharacterAttributeTypeID,ProjectID,AttributeName,DataType,IsNormallyStable,SortOrder,IsActive","ProjectID"), ["CharacterEnrichmentEvidence"]=("CharacterEnrichmentEvidenceID,CharacterEnrichmentRunID,CharacterID,SceneID,FieldName,Value,Evidence,Confidence,Source,CreatedUtc","SceneID,Value,Evidence"), ["CharacterEnrichmentRuns"]=("CharacterEnrichmentRunID,ProjectID,BookID,UserID,StoryIntelligenceBookPipelineID,CharacterResolutionVersion,Status,TotalCharacters,ProcessedCharacters,CurrentStage,CurrentMessage,QueuedUtc,StartedUtc,CompletedUtc,FailedUtc,AttemptCount,Model,InputTokens,OutputTokens,TotalTokens,DurationMs,ErrorMessage,ErrorDetail,IsCurrent,UpdatedUtc,CharacterID","StoryIntelligenceBookPipelineID,CurrentStage,CurrentMessage,StartedUtc,CompletedUtc,FailedUtc,Model,InputTokens,OutputTokens,TotalTokens,DurationMs,ErrorMessage,ErrorDetail,CharacterID"), - ["StoryElementReferences"]=("ReferenceID,CharacterID,LocationID,StoryAssetID,Kind,Note,StoragePath,OriginalFileName","CharacterID,LocationID,StoryAssetID,StoragePath,OriginalFileName"), + ["StoryElementReferences"]=("ReferenceID,CharacterID,LocationID,StoryAssetID,Kind,Note,StoragePath,OriginalFileName,Title,IsPrimary","CharacterID,LocationID,StoryAssetID,StoragePath,OriginalFileName,Title,IsPrimary"), ["CharacterImages"]=("CharacterImageID,CharacterID,ProjectID,ImagePath,ThumbnailPath,Caption,SortOrder,UploadedDateUTC,IsDeleted,DeletedDateUTC","Caption,DeletedDateUTC"), ["CharacterIntelligenceEvidenceEvents"]=("CharacterIntelligenceEvidenceEventID,CharacterIntelligenceProfileID,SceneResultID,FieldName,PreviousValue,NewValue,Evidence,Confidence,IsContradiction,Source,CreatedUtc","PreviousValue,NewValue,Evidence"), ["CharacterIntelligenceProfiles"]=("CharacterIntelligenceProfileID,ImportSessionID,ProjectID,BookID,CanonicalIdentityKey,CanonicalName,ProfileJson,Confidence,NarrativeImportance,IsRecurring,EvidenceVersion,LastUpdatedSceneResultID,CreatedUtc,UpdatedUtc","NarrativeImportance,LastUpdatedSceneResultID"), diff --git a/PlotLine/Services/StoryElementAttachmentPolicy.cs b/PlotLine/Services/StoryElementAttachmentPolicy.cs new file mode 100644 index 00000000..71f6628b --- /dev/null +++ b/PlotLine/Services/StoryElementAttachmentPolicy.cs @@ -0,0 +1,72 @@ +using System.IO.Compression; +using System.Text; + +namespace PlotLine.Services; + +public static class StoryElementAttachmentPolicy +{ + public const string AcceptedExtensions = ".png,.jpg,.jpeg,.webp,.mp3,.wav,.flac,.ogg,.pdf,.txt,.csv,.tsv,.docx,.xlsx"; + + public static bool IsImage(string filename) => Extension(filename) is ".png" or ".jpg" or ".jpeg" or ".webp"; + + public static string? AudioType(string filename) => Extension(filename) switch + { + ".mp3" => "audio/mpeg", + ".wav" => "audio/wav", + ".flac" => "audio/flac", + ".ogg" => "audio/ogg", + _ => null + }; + + public static bool IsAudio(string filename, ReadOnlySpan bytes) => Extension(filename) switch + { + ".mp3" => bytes.Length >= 4 && (bytes.StartsWith("ID3"u8) || + (bytes[0] == 0xff && (bytes[1] & 0xe6) == 0xe2)), + ".wav" => bytes.Length >= 12 && bytes.StartsWith("RIFF"u8) && bytes[8..].StartsWith("WAVE"u8), + ".flac" => bytes.StartsWith("fLaC"u8), + ".ogg" => bytes.Length > 27 && bytes.StartsWith("OggS"u8) && + bytes.Length > 27 + bytes[26] && + (bytes[(27 + bytes[26])..].StartsWith("OpusHead"u8) || + bytes[(27 + bytes[26])..].StartsWith("\x01vorbis"u8)), + _ => false + }; + + public static bool IsPdf(string filename, ReadOnlySpan bytes) => + Extension(filename) == ".pdf" && bytes.StartsWith("%PDF-"u8); + + public static bool IsAllowedDocument(string filename, byte[] bytes) => Extension(filename) switch + { + ".pdf" => IsPdf(filename, bytes), + ".txt" or ".csv" or ".tsv" => IsText(bytes), + ".docx" => IsOfficeDocument(bytes, "word/document.xml"), + ".xlsx" => IsOfficeDocument(bytes, "xl/workbook.xml"), + _ => false + }; + + private static string Extension(string filename) => Path.GetExtension(filename).ToLowerInvariant(); + + private static bool IsText(byte[] bytes) + { + try + { + return new UTF8Encoding(false, true).GetString(bytes) + .All(character => !char.IsControl(character) || character is '\r' or '\n' or '\t'); + } + catch (DecoderFallbackException) { return false; } + } + + private static bool IsOfficeDocument(byte[] bytes, string mainPart) + { + try + { + using var archive = new ZipArchive(new MemoryStream(bytes), ZipArchiveMode.Read); + return archive.GetEntry("[Content_Types].xml") is not null && + archive.GetEntry(mainPart) is not null && + !archive.Entries.Any(entry => + entry.Name.Equals("vbaProject.bin", StringComparison.OrdinalIgnoreCase) || + entry.FullName.Contains("/embeddings/", StringComparison.OrdinalIgnoreCase) || + entry.FullName.Contains("/activeX/", StringComparison.OrdinalIgnoreCase)); + } + catch (InvalidDataException) { return false; } + } +} diff --git a/PlotLine/Services/StoryElementReferenceWorkspace.cs b/PlotLine/Services/StoryElementReferenceWorkspace.cs new file mode 100644 index 00000000..c6e88685 --- /dev/null +++ b/PlotLine/Services/StoryElementReferenceWorkspace.cs @@ -0,0 +1,19 @@ +using PlotLine.Data; +using PlotLine.Models; +using PlotLine.ViewModels; + +namespace PlotLine.Services; + +public sealed record StoryElementReferenceWorkspace(StoryElementReferenceList References, StorageUsage? Storage, + CharacterDetailViewModel? CharacterGallery = null, int GalleryPages = 1) +{ + public static async Task ReadStorageAsync(StoryElementReferenceList references, + int userId, IProjectCollaborationRepository collaboration, ISubscriptionService subscriptions) + { + // Account-level totals belong to the account owner, even on a shared project. + var owner = await collaboration.GetOwnerUserIdAsync(references.Access.ProjectID); + if (owner != userId) return null; + try { return await subscriptions.GetStorageUsageAsync(owner.Value); } + catch (SubscriptionLimitException) { return null; } + } +} diff --git a/PlotLine/Sql/354_ReferenceWorkspace.sql b/PlotLine/Sql/354_ReferenceWorkspace.sql new file mode 100644 index 00000000..8e7c9905 --- /dev/null +++ b/PlotLine/Sql/354_ReferenceWorkspace.sql @@ -0,0 +1,189 @@ +SET ANSI_NULLS ON; +GO +SET QUOTED_IDENTIFIER ON; +SET ANSI_PADDING ON; +SET ANSI_WARNINGS ON; +SET ARITHABORT ON; +SET CONCAT_NULL_YIELDS_NULL ON; +SET NUMERIC_ROUNDABORT OFF; +GO +IF COL_LENGTH(N'dbo.StoryElementReferences', N'Title') IS NULL + ALTER TABLE dbo.StoryElementReferences ADD Title nvarchar(160) NULL; +IF COL_LENGTH(N'dbo.StoryElementReferences', N'IsPrimary') IS NULL + ALTER TABLE dbo.StoryElementReferences ADD IsPrimary bit NULL; +GO +IF OBJECT_ID(N'dbo.CK_StoryElementReferences_Primary', N'C') IS NULL + ALTER TABLE dbo.StoryElementReferences ADD CONSTRAINT CK_StoryElementReferences_Primary + CHECK (IsPrimary IS NULL OR (IsPrimary = 1 AND Kind = 'Image' AND CharacterID IS NULL)); +GO +IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'dbo.StoryElementReferences') + AND name = N'UX_StoryElementReferences_PrimaryLocation') + CREATE UNIQUE INDEX UX_StoryElementReferences_PrimaryLocation ON dbo.StoryElementReferences(LocationID) + WHERE LocationID IS NOT NULL AND IsPrimary = 1; +IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'dbo.StoryElementReferences') + AND name = N'UX_StoryElementReferences_PrimaryAsset') + CREATE UNIQUE INDEX UX_StoryElementReferences_PrimaryAsset ON dbo.StoryElementReferences(StoryAssetID) + WHERE StoryAssetID IS NOT NULL AND IsPrimary = 1; +GO + +CREATE OR ALTER PROCEDURE dbo.StoryElementReference_Access + @UserID int, @EntityType varchar(12), @EntityID int, @Action varchar(12), + @ReferenceID int = NULL, @Version binary(8) = NULL, @Kind varchar(14) = NULL, + @Note nvarchar(500) = NULL, @StoragePath nvarchar(1000) = NULL, + @OriginalFileName nvarchar(300) = NULL, @FileSizeBytes bigint = NULL, + @Title nvarchar(160) = NULL, @StorageLimitBytes bigint = NULL +AS +BEGIN + SET NOCOUNT ON; + SET XACT_ABORT ON; + + DECLARE @ProjectID int, @EntityName nvarchar(300), @CanEdit bit, @OwnerID int, + @CharacterID int, @LocationID int, @AssetID int, @LegacyImagePath nvarchar(1000); + BEGIN TRY + BEGIN TRANSACTION; + IF @EntityType = 'Character' + BEGIN + SET @CharacterID = @EntityID; + SELECT @ProjectID = ProjectID, @EntityName = CharacterName + FROM dbo.Characters WITH (HOLDLOCK) WHERE CharacterID = @EntityID AND IsArchived = 0; + END + ELSE IF @EntityType = 'Location' + BEGIN + SET @LocationID = @EntityID; + SELECT @ProjectID = ProjectID, @EntityName = LocationName + FROM dbo.Locations WITH (HOLDLOCK) WHERE LocationID = @EntityID AND IsArchived = 0; + END + ELSE IF @EntityType = 'Asset' + BEGIN + SET @AssetID = @EntityID; + SELECT @ProjectID = ProjectID, @EntityName = AssetName, @LegacyImagePath = ImagePath + FROM dbo.StoryAssets WITH (HOLDLOCK) WHERE StoryAssetID = @EntityID AND IsArchived = 0; + END + + SELECT @CanEdit = CONVERT(bit, MAX(CASE WHEN a.AccessRole IN (N'Owner', N'Collaborator') THEN 1 ELSE 0 END)) + FROM dbo.ProjectUserAccess a WITH (HOLDLOCK) + INNER JOIN dbo.Projects p WITH (HOLDLOCK) ON p.ProjectID = a.ProjectID AND p.IsArchived = 0 + WHERE a.ProjectID = @ProjectID AND a.UserID = @UserID AND a.IsActive = 1; + + IF @CanEdit IS NULL OR (@Action NOT IN ('list', 'file') AND @CanEdit = 0) + BEGIN + IF @Action = 'list' + SELECT @ProjectID AS ProjectID, @EntityName AS EntityName, @CanEdit AS CanEdit, + @LegacyImagePath AS LegacyImagePath WHERE 1 = 0; + COMMIT; + RETURN; + END + + IF @Action = 'list' + BEGIN + SELECT @ProjectID AS ProjectID, @EntityName AS EntityName, @CanEdit AS CanEdit, @LegacyImagePath AS LegacyImagePath; + SELECT ReferenceID, Kind, Note, OriginalFileName, Version, Title, CONVERT(bit, COALESCE(IsPrimary, 0)) AS IsPrimary + FROM dbo.StoryElementReferences + WHERE CharacterID = @CharacterID OR LocationID = @LocationID OR StoryAssetID = @AssetID + ORDER BY ReferenceID; + END + ELSE IF @Action = 'file' + BEGIN + SELECT Kind, StoragePath, OriginalFileName + FROM dbo.StoryElementReferences + WHERE ReferenceID = @ReferenceID AND StoragePath IS NOT NULL + AND (CharacterID = @CharacterID OR LocationID = @LocationID OR StoryAssetID = @AssetID); + END + ELSE IF @Action = 'add' + BEGIN + IF @StoragePath IS NOT NULL + BEGIN + SELECT TOP (1) @OwnerID = UserID FROM dbo.ProjectUserAccess WITH (HOLDLOCK) + WHERE ProjectID = @ProjectID AND AccessRole = N'Owner' AND IsActive = 1 + ORDER BY ProjectUserAccessID; + IF @OwnerID IS NULL THROW 51010, 'Project owner unavailable.', 1; + IF @StorageLimitBytes IS NOT NULL AND @FileSizeBytes > + @StorageLimitBytes - (SELECT COALESCE(SUM(FileSizeBytes), 0) + FROM dbo.UserFile WITH (UPDLOCK, HOLDLOCK) WHERE UserID = @OwnerID AND IsDeleted = 0) + BEGIN + SELECT @ProjectID AS ProjectID, CONVERT(bit, 0) AS Changed, CONVERT(bit, 1) AS QuotaExceeded; + COMMIT; + RETURN; + END + END + + INSERT dbo.StoryElementReferences (CharacterID, LocationID, StoryAssetID, Kind, Note, StoragePath, OriginalFileName) + VALUES (@CharacterID, @LocationID, @AssetID, @Kind, @Note, @StoragePath, @OriginalFileName); + IF @StoragePath IS NOT NULL + INSERT dbo.UserFile (UserID, ProjectID, EntityType, EntityID, FileName, OriginalFileName, ContentType, FileSizeBytes, StoragePath) + VALUES (@OwnerID, @ProjectID, N'StoryElementReference', CONVERT(int, SCOPE_IDENTITY()), + RIGHT(@StoragePath, CHARINDEX('/', REVERSE(@StoragePath)) - 1), @OriginalFileName, + CASE @Kind WHEN 'Image' THEN N'image/webp' ELSE N'application/octet-stream' END, @FileSizeBytes, @StoragePath); + SELECT @ProjectID AS ProjectID, CONVERT(bit, 1) AS Changed; + END + ELSE IF @Action = 'caption' + BEGIN + UPDATE dbo.CharacterImages SET Caption = NULLIF(@Note, N'') + WHERE CharacterImageID = @ReferenceID AND CharacterID = @CharacterID AND ProjectID = @ProjectID AND IsDeleted = 0; + SELECT @ProjectID AS ProjectID, CONVERT(bit, @@ROWCOUNT) AS Changed; + END + ELSE IF @Action IN ('primary', 'clear') + BEGIN + DECLARE @LockResult int, @Resource nvarchar(255) = CONCAT(N'StoryReferencePrimary:', @EntityType, N':', @EntityID); + EXEC @LockResult = sys.sp_getapplock @Resource = @Resource, @LockMode = 'Exclusive', + @LockOwner = 'Transaction', @LockTimeout = 5000; + IF @LockResult < 0 THROW 51010, 'Primary image selection is busy.', 1; + + DECLARE @ImageID int; + SELECT @ImageID = ReferenceID FROM dbo.StoryElementReferences WITH (UPDLOCK) + WHERE ReferenceID = @ReferenceID AND Version = @Version AND Kind = 'Image' + AND (@Action = 'primary' OR IsPrimary = 1) + AND (LocationID = @LocationID OR StoryAssetID = @AssetID); + + IF @ImageID IS NOT NULL + BEGIN + UPDATE dbo.StoryElementReferences + SET IsPrimary = NULL + WHERE IsPrimary = 1 AND (LocationID = @LocationID OR StoryAssetID = @AssetID); + IF @Action = 'primary' + UPDATE dbo.StoryElementReferences SET IsPrimary = 1 WHERE ReferenceID = @ImageID; + END + SELECT @ProjectID AS ProjectID, CONVERT(bit, CASE WHEN @ImageID IS NULL THEN 0 ELSE 1 END) AS Changed; + END + ELSE IF @Action = 'edit' + BEGIN + UPDATE dbo.StoryElementReferences SET Note = @Note, Title = @Title + WHERE ReferenceID = @ReferenceID AND Version = @Version + AND (Kind <> 'Characteristic' OR LEN(@Note) > 0) + AND (CharacterID = @CharacterID OR LocationID = @LocationID OR StoryAssetID = @AssetID); + SELECT @ProjectID AS ProjectID, CONVERT(bit, @@ROWCOUNT) AS Changed; + END + ELSE IF @Action = 'delete' + BEGIN + DECLARE @Removed TABLE (StoragePath nvarchar(1000)); + DELETE dbo.StoryElementReferences + OUTPUT deleted.StoragePath INTO @Removed + WHERE ReferenceID = @ReferenceID AND Version = @Version + AND (CharacterID = @CharacterID OR LocationID = @LocationID OR StoryAssetID = @AssetID); + SELECT @ProjectID AS ProjectID, CONVERT(bit, COUNT(*)) AS Changed, MAX(StoragePath) AS StoragePath + FROM @Removed; + END + + COMMIT; + END TRY + BEGIN CATCH + IF XACT_STATE() <> 0 ROLLBACK; + THROW; + END CATCH +END; +GO + +CREATE OR ALTER PROCEDURE dbo.StoryElementReference_Backup @ProjectID int +AS +BEGIN + SET NOCOUNT ON; + SELECT r.ReferenceID, r.CharacterID, r.LocationID, r.StoryAssetID, + r.Kind, r.Note, r.StoragePath, r.OriginalFileName, r.Title, r.IsPrimary + FROM dbo.StoryElementReferences r + LEFT JOIN dbo.Characters c ON c.CharacterID = r.CharacterID + LEFT JOIN dbo.Locations l ON l.LocationID = r.LocationID + LEFT JOIN dbo.StoryAssets a ON a.StoryAssetID = r.StoryAssetID + WHERE COALESCE(c.ProjectID, l.ProjectID, a.ProjectID) = @ProjectID + ORDER BY r.ReferenceID; +END; +GO diff --git a/PlotLine/ViewComponents/StoryElementReferencesViewComponent.cs b/PlotLine/ViewComponents/StoryElementReferencesViewComponent.cs index 02864d53..82a522f0 100644 --- a/PlotLine/ViewComponents/StoryElementReferencesViewComponent.cs +++ b/PlotLine/ViewComponents/StoryElementReferencesViewComponent.cs @@ -1,16 +1,21 @@ using Microsoft.AspNetCore.Mvc; using PlotLine.Data; using PlotLine.Services; +using PlotLine.ViewModels; namespace PlotLine.ViewComponents; public sealed class StoryElementReferencesViewComponent( - ICurrentUserService currentUser, StoryElementReferenceRepository references) : ViewComponent + ICurrentUserService currentUser, StoryElementReferenceRepository references, + IProjectCollaborationRepository collaboration, ISubscriptionService subscriptions) : ViewComponent { - public async Task InvokeAsync(StoryElementType entityType, int entityId) + public async Task InvokeAsync(StoryElementType entityType, int entityId, + CharacterDetailViewModel? characterGallery = null, int galleryPages = 1) { if (currentUser.UserId is not int userId) return Content(""); var model = await references.ListAsync(userId, new(entityType, entityId)); - return model is null ? Content("") : View(model); + return model is null ? Content("") : View(new StoryElementReferenceWorkspace(model, + await StoryElementReferenceWorkspace.ReadStorageAsync(model, userId, collaboration, subscriptions), + characterGallery, galleryPages)); } } diff --git a/PlotLine/Views/Characters/Details.cshtml b/PlotLine/Views/Characters/Details.cshtml index 84d13a01..f4b51124 100644 --- a/PlotLine/Views/Characters/Details.cshtml +++ b/PlotLine/Views/Characters/Details.cshtml @@ -17,6 +17,8 @@ @foreach(var key in new[]{"ImageMessage","RelationshipMessage","CharacterMessage"}){if(TempData[key] is string message){}} @if(TempData["ImageError"] is string error){
@error
} @section Scripts{ + + diff --git a/PlotLine/Views/Characters/_WorkspaceGallery.cshtml b/PlotLine/Views/Characters/_WorkspaceGallery.cshtml index 0f84f76a..dd1f5404 100644 --- a/PlotLine/Views/Characters/_WorkspaceGallery.cshtml +++ b/PlotLine/Views/Characters/_WorkspaceGallery.cshtml @@ -1,10 +1,6 @@ @model CharacterDetailViewModel
-
-

Character Images

-

Keep portraits, full-body references, clothing notes, expressions, and inspiration images together.

-
@if (Model.WorkspaceCanEdit && !string.IsNullOrWhiteSpace(Model.Character.AvatarImagePath)) {
@@ -14,19 +10,6 @@ }
- - -
- - -
-
- - -
- - - @if (!Model.Images.Any()) {

No gallery images yet.

@@ -38,7 +21,7 @@ { var isAvatarSource = Model.Character.AvatarSourceCharacterImageID == image.CharacterImageID;