From d089f2d7b564ab2e570b8913df998b49da954664 Mon Sep 17 00:00:00 2001 From: Codex Date: Sat, 5 Dec 2026 17:22:38 +0000 Subject: [PATCH] Add shared story element references --- PlotLine.Tests/Program.cs | 1 + PlotLine.Tests/StoryElementReferenceTests.cs | 113 +++++++++++++ .../StoryElementReferencesController.cs | 151 +++++++++++++++++ PlotLine/Data/ProjectBackupRepository.cs | 5 + .../Data/StoryElementReferenceRepository.cs | 65 ++++++++ PlotLine/Models/ProjectBackupModels.cs | 14 ++ PlotLine/Program.cs | 11 ++ PlotLine/Services/BookBackupGraph.cs | 4 +- PlotLine/Services/CoreServices.cs | 9 +- PlotLine/Services/ImportServices.cs | 11 +- PlotLine/Services/ProjectBackupFiles.cs | 14 +- .../Services/ProjectBackupGraphValidation.cs | 21 ++- .../Services/ProjectBackupMapValidation.cs | 4 +- ...ProjectBackupStoredFieldContract.Schema.cs | 1 + .../Services/StoryElementReferenceStorage.cs | 20 +++ PlotLine/Sql/349_StoryElementReferences.sql | 157 ++++++++++++++++++ .../Sql/350_StoryElementReferenceBackup.sql | 89 ++++++++++ .../StoryElementReferencesViewComponent.cs | 16 ++ PlotLine/Views/Characters/Details.cshtml | 3 + .../Views/Characters/_WorkspaceGallery.cshtml | 16 +- PlotLine/Views/Locations/Details.cshtml | 6 + .../StoryElementReferences/Default.cshtml | 114 +++++++++++++ PlotLine/Views/StoryAssets/Details.cshtml | 5 + .../wwwroot/js/story-element-references.js | 55 ++++++ 24 files changed, 892 insertions(+), 13 deletions(-) create mode 100644 PlotLine.Tests/StoryElementReferenceTests.cs create mode 100644 PlotLine/Controllers/StoryElementReferencesController.cs create mode 100644 PlotLine/Data/StoryElementReferenceRepository.cs create mode 100644 PlotLine/Services/StoryElementReferenceStorage.cs create mode 100644 PlotLine/Sql/349_StoryElementReferences.sql create mode 100644 PlotLine/Sql/350_StoryElementReferenceBackup.sql create mode 100644 PlotLine/ViewComponents/StoryElementReferencesViewComponent.cs create mode 100644 PlotLine/Views/Shared/Components/StoryElementReferences/Default.cshtml create mode 100644 PlotLine/wwwroot/js/story-element-references.js diff --git a/PlotLine.Tests/Program.cs b/PlotLine.Tests/Program.cs index 4013724d..f83904e1 100644 --- a/PlotLine.Tests/Program.cs +++ b/PlotLine.Tests/Program.cs @@ -15,6 +15,7 @@ using PlotLine.Models; using PlotLine.Services; using PlotLine.ViewModels; +if (args.Contains("--story-element-references")) { await StoryElementReferenceTests.Run(); return; } if(args.Contains("--context-assets")){ContextAssetsTests.Run();Console.WriteLine("PASS Context Assets historical custody and location");return;} if(args.Contains("--context-warnings")){ContextWarningsTests.Run();return;} if(args.Contains("--context-metrics")){ContextMetricsTests.Run();return;} diff --git a/PlotLine.Tests/StoryElementReferenceTests.cs b/PlotLine.Tests/StoryElementReferenceTests.cs new file mode 100644 index 00000000..e8247acb --- /dev/null +++ b/PlotLine.Tests/StoryElementReferenceTests.cs @@ -0,0 +1,113 @@ +using System.Text.Json; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Options; +using PlotLine.Controllers; +using PlotLine.Data; +using PlotLine.Models; +using PlotLine.Services; + +internal static class StoryElementReferenceTests +{ + public static async Task Run() + { + var guest = new StoryElementReferencesController(new Guest(), null!, null!, null!, null!, null!, null!); + foreach (var entity in Enum.GetValues()) + { + Check(await guest.List(entity, 1) is NotFoundResult, "Reference lists require authentication."); + Check(await guest.Download(entity, 1, 2) is NotFoundResult, "Reference files require authentication."); + Check(await guest.Add(entity, 1, "Characteristic", "A characteristic", null) is NotFoundResult, + "Creating references requires authentication."); + Check(await guest.Change(entity, 1, 2, "delete", "AAAAAAAAAAA=", null) is NotFoundResult, + "Removing references requires authentication."); + } + + var legacy = new ProjectBackupExport { Project = new() { ProjectID = 4 } }; + var legacyJson = JsonSerializer.Serialize(legacy); + Check(!legacyJson.Contains("\"StoryElementReferences\"", StringComparison.Ordinal), + "Legacy package fingerprints must omit the absent reference collection."); + Check(JsonSerializer.Serialize(JsonSerializer.Deserialize(legacyJson)) == legacyJson, + "Reading and reserializing a legacy package must preserve its fingerprint."); + + string root = Directory.CreateTempSubdirectory("plotdirector-reference-test-").FullName; + try + { + var environment = new TestEnvironment { WebRootPath = root, ContentRootPath = root }; + var uploads = new UploadStorageService(Options.Create(new StorageSettings { UploadsRoot = root }), environment); + var files = new ProjectBackupFiles(uploads); + var image = MapReferenceImageService.Normalize(MapAppearanceTests.Image(), "Sketch.png").ImageData!; + var attachment = "An attachment's original bytes"u8.ToArray(); + var folder = StoryElementReferenceStorage.Folder; + uploads.GetDirectory(folder); + await File.WriteAllBytesAsync(uploads.GetFilePath(folder, "image.blob"), image); + await File.WriteAllBytesAsync(uploads.GetFilePath(folder, "document.blob"), attachment); + + var backup = new ProjectBackupExport + { + Project = new() { ProjectID = 4 }, + Data = new() + { + Characters = [new() { CharacterID = 7, ProjectID = 4 }], + Locations = [new() { LocationID = 7, ProjectID = 4 }], + StoryAssets = [new() { StoryAssetID = 7, ProjectID = 4 }], + StoryElementReferences = + [ + new() { ReferenceID = 1, CharacterID = 7, Kind = "Characteristic", Note = "Left-handed" }, + new() { ReferenceID = 2, LocationID = 7, Kind = "Image", Note = "Doorway", + 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") } + ] + } + }; + await files.CaptureAsync(backup); + 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[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)) + { + Check(items[1].StoragePath != backup.Data.StoryElementReferences![1].StoragePath, + "Staging a restored generation must preserve the current reference file."); + Check(File.ReadAllBytes(uploads.TryResolvePublicPath(items[1].StoragePath)!).SequenceEqual(image), + "Restored images retain their normalized bytes."); + Check(File.ReadAllBytes(uploads.TryResolvePublicPath(items[2].StoragePath)!).SequenceEqual(attachment), + "Restored attachments retain their original bytes."); + Check(items[2].OriginalFileName == "Document.txt", "Restored filenames remain available for downloads."); + } + Check(!File.Exists(uploads.TryResolvePublicPath(items[2].StoragePath)), + "An abandoned restore cleans up its staged reference files."); + Check(File.Exists(uploads.GetFilePath(folder, "document.blob")), "An abandoned restore keeps current files."); + } + finally + { + Directory.Delete(root, recursive: true); + } + + Console.WriteLine("PASS story element reference authentication, image normalization and portable file round-trip"); + } + + private static void Check(bool condition, string message) + { + if (!condition) throw new InvalidOperationException(message); + } + + private sealed class Guest : ICurrentUserService + { + public int? UserId => null; + public string? Email => null; + public string? DisplayName => null; + public bool IsAuthenticated => false; + } + + private sealed class TestEnvironment : IWebHostEnvironment + { + public string ApplicationName { get; set; } = ""; + public string EnvironmentName { get; set; } = ""; + public string ContentRootPath { get; set; } = ""; + public string WebRootPath { get; set; } = ""; + public Microsoft.Extensions.FileProviders.IFileProvider ContentRootFileProvider { get; set; } = null!; + public Microsoft.Extensions.FileProviders.IFileProvider WebRootFileProvider { get; set; } = null!; + } +} diff --git a/PlotLine/Controllers/StoryElementReferencesController.cs b/PlotLine/Controllers/StoryElementReferencesController.cs new file mode 100644 index 00000000..91686dfb --- /dev/null +++ b/PlotLine/Controllers/StoryElementReferencesController.cs @@ -0,0 +1,151 @@ +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 logger) : Controller +{ + private const string StorageFolder = StoryElementReferenceStorage.Folder; + + [HttpGet] + public async Task 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 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 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 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 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 }, + 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."); } + } +} diff --git a/PlotLine/Data/ProjectBackupRepository.cs b/PlotLine/Data/ProjectBackupRepository.cs index d35ee4dd..0577f28c 100644 --- a/PlotLine/Data/ProjectBackupRepository.cs +++ b/PlotLine/Data/ProjectBackupRepository.cs @@ -158,6 +158,10 @@ public sealed class ProjectBackupRepository(ISqlConnectionFactory connectionFact } + data.StoryElementReferences = (await connection.QueryAsync( + "dbo.StoryElementReference_Backup", new { ProjectID = projectId }, + commandType: CommandType.StoredProcedure, transaction: transaction)).ToList(); + data.SceneThreads = (await connection.QueryAsync( "dbo.SceneThread_Backup", new { ProjectID = projectId }, commandType: CommandType.StoredProcedure, transaction: transaction)).ToList(); @@ -237,6 +241,7 @@ public sealed class ProjectBackupRepository(ISqlConnectionFactory connectionFact nameof(data.OnboardingManuscriptBuildSceneMap), nameof(data.OnboardingManuscriptBuildCharacterMap), nameof(data.CharacterImages), + nameof(data.StoryElementReferences), nameof(data.WordCompanionSceneAssets), nameof(data.WordCompanionSceneLocations), nameof(data.ManuscriptDocuments), diff --git a/PlotLine/Data/StoryElementReferenceRepository.cs b/PlotLine/Data/StoryElementReferenceRepository.cs new file mode 100644 index 00000000..009db2ec --- /dev/null +++ b/PlotLine/Data/StoryElementReferenceRepository.cs @@ -0,0 +1,65 @@ +using System.Data; +using Dapper; + +namespace PlotLine.Data; + +public enum StoryElementType { Character, Location, Asset } + +public sealed record StoryElementReferenceScope(StoryElementType EntityType, int EntityID) +{ + public string DetailsController => EntityType switch + { + StoryElementType.Character => "Characters", + StoryElementType.Location => "Locations", + StoryElementType.Asset => "StoryAssets", + _ => throw new ArgumentOutOfRangeException(nameof(EntityType)) + }; +} + +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 StoryElementReferenceList(StoryElementReferenceScope Scope, + StoryElementReferenceAccess Access, IReadOnlyList Items); +public sealed record StoryElementReferenceFile(string Kind, string StoragePath, string OriginalFileName); +public sealed class StoryElementReferenceChange +{ + public int ProjectID { get; init; } + public bool Changed { get; init; } + public string? StoragePath { get; init; } +} + +public sealed class StoryElementReferenceRepository(ISqlConnectionFactory connections) +{ + private const string Procedure = "dbo.StoryElementReference_Access"; + + public async Task ListAsync(int userId, StoryElementReferenceScope scope) + { + using var connection = connections.CreateConnection(); + using var results = await connection.QueryMultipleAsync(Procedure, + new { UserID = userId, EntityType = scope.EntityType.ToString(), scope.EntityID, Action = "list" }, + commandType: CommandType.StoredProcedure); + var access = await results.ReadSingleOrDefaultAsync(); + return access is null ? null : new(scope, access, (await results.ReadAsync()).AsList()); + } + + public async Task FileAsync(int userId, StoryElementReferenceScope scope, int referenceId) + { + using var connection = connections.CreateConnection(); + return await connection.QuerySingleOrDefaultAsync(Procedure, + new { UserID = userId, EntityType = scope.EntityType.ToString(), scope.EntityID, Action = "file", ReferenceID = referenceId }, + commandType: CommandType.StoredProcedure); + } + + 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) + { + 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 + }, commandType: CommandType.StoredProcedure); + } +} diff --git a/PlotLine/Models/ProjectBackupModels.cs b/PlotLine/Models/ProjectBackupModels.cs index 819eb485..a9c49a63 100644 --- a/PlotLine/Models/ProjectBackupModels.cs +++ b/PlotLine/Models/ProjectBackupModels.cs @@ -62,6 +62,8 @@ public sealed class ProjectBackupData public IReadOnlyList OnboardingManuscriptBuildSceneMap { get; set; } = []; public IReadOnlyList OnboardingManuscriptBuildCharacterMap { get; set; } = []; + [System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull)] + public IReadOnlyList? StoryElementReferences { get; set; } public IReadOnlyList CharacterImages { get; set; } = []; public IReadOnlyList WordCompanionSceneAssets { get; set; } = []; public IReadOnlyList WordCompanionSceneLocations { get; set; } = []; @@ -293,6 +295,18 @@ public sealed class ProjectBackupCompanionSceneLocation public DateTime UpdatedDate { get; set; } } +public sealed class ProjectBackupStoryElementReference +{ + public int ReferenceID { get; set; } + public int? CharacterID { get; set; } + public int? LocationID { get; set; } + public int? StoryAssetID { get; set; } + public string Kind { get; set; } = ""; + public string Note { get; set; } = ""; + public string? StoragePath { get; set; } + public string? OriginalFileName { get; set; } +} + public sealed class ProjectBackupFile { public string Path { get; set; } = string.Empty; diff --git a/PlotLine/Program.cs b/PlotLine/Program.cs index b90dda6f..1cc85309 100644 --- a/PlotLine/Program.cs +++ b/PlotLine/Program.cs @@ -290,6 +290,7 @@ public class Program builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); + builder.Services.AddScoped(); builder.Services.AddSingleton(); builder.Services.AddScoped(); builder.Services.AddScoped(); @@ -435,6 +436,16 @@ public class Program } await next(); }); + app.Use(async (context, next) => + { + if (context.Request.Path.StartsWithSegments("/uploads/" + StoryElementReferenceStorage.Folder)) + { + context.Response.StatusCode = StatusCodes.Status404NotFound; + return; + } + + await next(); + }); app.UseStaticFiles(); var uploadStorage = app.Services.GetRequiredService(); app.UseStaticFiles(new StaticFileOptions diff --git a/PlotLine/Services/BookBackupGraph.cs b/PlotLine/Services/BookBackupGraph.cs index 6050740c..6c5811fb 100644 --- a/PlotLine/Services/BookBackupGraph.cs +++ b/PlotLine/Services/BookBackupGraph.cs @@ -9,10 +9,10 @@ namespace PlotLine.Services; public static class BookBackupGraph { public static readonly JsonSerializerOptions Json = new() { PropertyNameCaseInsensitive = true }; - internal static readonly HashSet Common = new(StringComparer.Ordinal) { "StoryIntelligenceIllustrationDemands", "Characters", "CharacterAliases", "CharacterImages", "CharacterAttributeTypes", "CharacterRelationships", "Locations", "LocationAliases", "LocationRelationships", "FloorPlans", "FloorPlanFloors", "FloorPlanBlocks", "FloorPlanTransitions", "StoryMaps", "MapFeatures", "MapRelationships", "MapReferenceImages", "PlotLines", "PlotThreads", "StoryAssets", "AssetAliases", "AssetStates", "AssetDependencies", "SceneMetricTypes", "TimelineSettings", "TimelineMetricSettings", "GenreMetricPresets", "GenreMetricPresetMetrics" }; + internal static readonly HashSet Common = new(StringComparer.Ordinal) { "StoryIntelligenceIllustrationDemands", "Characters", "CharacterAliases", "CharacterImages", "StoryElementReferences", "CharacterAttributeTypes", "CharacterRelationships", "Locations", "LocationAliases", "LocationRelationships", "FloorPlans", "FloorPlanFloors", "FloorPlanBlocks", "FloorPlanTransitions", "StoryMaps", "MapFeatures", "MapRelationships", "MapReferenceImages", "PlotLines", "PlotThreads", "StoryAssets", "AssetAliases", "AssetStates", "AssetDependencies", "SceneMetricTypes", "TimelineSettings", "TimelineMetricSettings", "GenreMetricPresets", "GenreMetricPresetMetrics" }; internal static readonly Dictionary Aliases = new() { ["TimelineSettings"] = "ProjectTimelineSettings", ["TimelineMetricSettings"] = "ProjectTimelineMetricSettings", ["AssetCustodyCharacters"] = "AssetCustodyEventCharacters" }; internal static string Table(string collection) => Aliases.GetValueOrDefault(collection, collection); - internal static object[] Rows(ProjectBackupExport b, string c) => ((IEnumerable)typeof(ProjectBackupData).GetProperty(c)!.GetValue(b.Data)!).Cast().ToArray(); + internal static object[] Rows(ProjectBackupExport b, string c) => ((IEnumerable?)typeof(ProjectBackupData).GetProperty(c)!.GetValue(b.Data))?.Cast().ToArray() ?? []; internal static object? Value(object row, string field) => row.GetType().GetProperty(field)?.GetValue(row); internal static string? Identity(string c) => ProjectBackupGraphValidation.Entities.FirstOrDefault(e => e.Collection == c)?.Identity; internal static void SetRows(ProjectBackupExport b, string c, IEnumerable rows) { var p = typeof(ProjectBackupData).GetProperty(c)!; var type = p.PropertyType.GetGenericArguments()[0]; var list = (IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(type))!; foreach (var r in rows) list.Add(r); p.SetValue(b.Data, list); } diff --git a/PlotLine/Services/CoreServices.cs b/PlotLine/Services/CoreServices.cs index 14018194..e47028ba 100644 --- a/PlotLine/Services/CoreServices.cs +++ b/PlotLine/Services/CoreServices.cs @@ -10054,9 +10054,12 @@ public sealed class CharacterService( return new(false, "Character not found."); } - return model.ImageUpload is null - ? new(false, "Choose an image to upload.") - : await visualIdentityImages.UploadCharacterGalleryImageAsync(character, model.ImageUpload, model.Caption); + if (model.ImageUpload is null) return new(false, "Choose an image to upload."); + + var result = await visualIdentityImages.UploadCharacterGalleryImageAsync(character, model.ImageUpload, model.Caption); + if (result.Succeeded) + await activity.RecordAsync(character.ProjectID, "Updated", "Character", character.CharacterID, character.CharacterName); + return result; } public async Task SaveCharacterAvatarAsync(CharacterAvatarCropViewModel model) diff --git a/PlotLine/Services/ImportServices.cs b/PlotLine/Services/ImportServices.cs index 1d45ca5e..f6336706 100644 --- a/PlotLine/Services/ImportServices.cs +++ b/PlotLine/Services/ImportServices.cs @@ -861,7 +861,7 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService internal static readonly string[] ProjectBackupIdentityTables = [ "ProjectTimelineSettings", "TimelineViewPresets", "SceneMetricTypes", "Books", "Chapters", "Scenes", "StoryMaps", - "StoryMemoryIllustrationAssignments", "StoryMemoryIllustrationDemands", "StoryIntelligenceIllustrationDemands", "WholeBookPlotSynthesisRuns", "StoryIntelligenceNarrativeCandidates", "StoryIntelligenceNarrativeCandidateEvidence", "StoryIntelligenceNarrativeCandidateEvents", "CharacterEnrichmentRuns", "CharacterEnrichmentEvidence", "StoryIntelligenceReviewCandidateGenerations", "StoryIntelligenceReviewCandidates", "StoryIntelligenceReviewCandidateEvidence", "StoryIntelligenceBookPipelines", "StoryMemoryCharacters", "StoryMemoryCharacterAliases", "StoryMemoryCharacterAttributes", "StoryMemoryLocations", "StoryMemoryAssets", "StoryMemoryRelationships", "StoryMemoryProcessedSceneResults", "StoryMemoryImportPreferences", "CharacterIntelligenceProfiles", "CharacterIntelligenceEvidenceEvents", "StoryIntelligenceRuns", "StoryIntelligenceChapterResults", "StoryIntelligenceSceneResults", "StoryIntelligenceImportCommits", "CoreImportBasicLocationReviews", "CoreImportBasicLocationCandidates", "CoreImportBasicLocationEvidence", "SceneAssetSuggestions", "SceneCharacterSuggestions", "SceneLocationSuggestions", "OnboardingManuscriptBuilds", "CharacterImages", "WordCompanionSceneAssets", "WordCompanionSceneLocations", "ManuscriptDocuments", "WritingPlans", "WritingScheduleItems", "CharacterAliases", "AssetAliases", "LocationAliases", "AuthorPlotSeeds", "ContinuityWarningAcknowledgements", + "StoryMemoryIllustrationAssignments", "StoryMemoryIllustrationDemands", "StoryIntelligenceIllustrationDemands", "WholeBookPlotSynthesisRuns", "StoryIntelligenceNarrativeCandidates", "StoryIntelligenceNarrativeCandidateEvidence", "StoryIntelligenceNarrativeCandidateEvents", "CharacterEnrichmentRuns", "CharacterEnrichmentEvidence", "StoryIntelligenceReviewCandidateGenerations", "StoryIntelligenceReviewCandidates", "StoryIntelligenceReviewCandidateEvidence", "StoryIntelligenceBookPipelines", "StoryMemoryCharacters", "StoryMemoryCharacterAliases", "StoryMemoryCharacterAttributes", "StoryMemoryLocations", "StoryMemoryAssets", "StoryMemoryRelationships", "StoryMemoryProcessedSceneResults", "StoryMemoryImportPreferences", "CharacterIntelligenceProfiles", "CharacterIntelligenceEvidenceEvents", "StoryIntelligenceRuns", "StoryIntelligenceChapterResults", "StoryIntelligenceSceneResults", "StoryIntelligenceImportCommits", "CoreImportBasicLocationReviews", "CoreImportBasicLocationCandidates", "CoreImportBasicLocationEvidence", "SceneAssetSuggestions", "SceneCharacterSuggestions", "SceneLocationSuggestions", "OnboardingManuscriptBuilds", "CharacterImages", "StoryElementReferences", "WordCompanionSceneAssets", "WordCompanionSceneLocations", "ManuscriptDocuments", "WritingPlans", "WritingScheduleItems", "CharacterAliases", "AssetAliases", "LocationAliases", "AuthorPlotSeeds", "ContinuityWarningAcknowledgements", "SceneOutcomes", "PlotLines", "PlotThreads", "ThreadEvents", "AssetStates", "StoryAssets", "AssetEvents", "AssetDependencies", "AssetCustodyEvents", "AssetCustodyEventCharacters", "Characters", "SceneCharacters", "CharacterAttributeTypes", "CharacterAttributeEvents", "CharacterKnowledge", "CharacterRelationships", @@ -1031,7 +1031,7 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService foreach(var run in backup.Data.StoryIntelligenceRuns) NewId("StoryIntelligenceRuns",run.StoryIntelligenceRunID); RebindAuditActors(backup.Project); foreach (var collection in typeof(ProjectBackupData).GetProperties()) - foreach (var row in (System.Collections.IEnumerable)collection.GetValue(backup.Data)!) + foreach (var row in BookBackupGraph.Rows(backup, collection.Name)) RebindAuditActors(row); foreach (var settings in backup.Data.TimelineSettings) @@ -1926,6 +1926,13 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService row.SceneID=ExistingOrNew("Scenes",row.SceneID); row.AcceptedThreadEventID=ExistingOrNewNullable("ThreadEvents",row.AcceptedThreadEventID); } + foreach (var reference in backup.Data.StoryElementReferences ?? []) + { + reference.ReferenceID = NewId("StoryElementReferences", reference.ReferenceID); + reference.CharacterID = ExistingOrNewNullable("Characters", reference.CharacterID); + reference.LocationID = ExistingOrNewNullable("Locations", reference.LocationID); + reference.StoryAssetID = ExistingOrNewNullable("StoryAssets", reference.StoryAssetID); + } foreach (var image in backup.Data.CharacterImages) { image.CharacterImageID=NewId("CharacterImages",image.CharacterImageID); diff --git a/PlotLine/Services/ProjectBackupFiles.cs b/PlotLine/Services/ProjectBackupFiles.cs index 6c6f7694..44a77519 100644 --- a/PlotLine/Services/ProjectBackupFiles.cs +++ b/PlotLine/Services/ProjectBackupFiles.cs @@ -40,6 +40,9 @@ public sealed class ProjectBackupFiles(IUploadStorageService storage) : IProject yield return new(character.AvatarImagePath,folder,"CharacterAvatar",character.CharacterID,x=>character.AvatarImagePath=x); yield return new(character.AvatarThumbnailPath,folder,"CharacterAvatar",character.CharacterID,x=>character.AvatarThumbnailPath=x); } + foreach (var reference in backup.Data.StoryElementReferences ?? []) + yield return new(reference.StoragePath, StoryElementReferenceStorage.Folder, "StoryElementReference", + reference.ReferenceID, path => reference.StoragePath = path); foreach(var image in backup.Data.CharacterImages) { if(image.IsDeleted) continue; @@ -87,6 +90,14 @@ public sealed class ProjectBackupFiles(IUploadStorageService storage) : IProject foreach(var file in backup.Files) if(file.Path is null || !referenced.Contains(file.Path) || file.Data is null || !string.Equals(file.Sha256,Convert.ToHexString(SHA256.HashData(file.Data)),StringComparison.OrdinalIgnoreCase)) return "Project backup contains an unreferenced file or file bytes do not match their checksum."; + foreach (var reference in backup.Data.StoryElementReferences ?? []) + { + if (reference.StoragePath is null) continue; + var bytes = backup.Files.FirstOrDefault(file => file.Path == reference.StoragePath)?.Data; + if (bytes is not { Length: > 0 and <= (int)MapReferenceImageService.MaxUploadBytes } || + (reference.Kind == "Image" && !StoryElementReferenceStorage.ValidBackupImage(bytes))) + return "Project backup contains an invalid story element reference file."; + } if(backup.FormatVersion is ("1.3" or "1.4" or "1.5") && references.Any(reference=>!backup.Files.Any(file=>file.Path==reference.Path))) return "Project backup is missing bytes for a referenced uploaded file."; return null; @@ -134,7 +145,8 @@ public sealed class ProjectBackupFiles(IUploadStorageService storage) : IProject var extension=Path.GetExtension(file.Path); if(extension.Length is <2 or >12 || extension[1..].Any(character=>!char.IsAsciiLetterOrDigit(character)))extension=".bin"; // Imported bytes must not become executable same-origin web content. Preserve bytes as a binary download. - if(IsActiveWebFile(file.Path))extension=".bin"; + if (owner.EntityType == "StoryElementReference") extension = ".blob"; + else if(IsActiveWebFile(file.Path))extension=".bin"; var filename=$"backup-{Guid.NewGuid():N}{extension.ToLowerInvariant()}"; var physical=storage.GetFilePath(owner.Folder,filename); storage.GetDirectory(owner.Folder); diff --git a/PlotLine/Services/ProjectBackupGraphValidation.cs b/PlotLine/Services/ProjectBackupGraphValidation.cs index 347cc8ba..8dfe16ca 100644 --- a/PlotLine/Services/ProjectBackupGraphValidation.cs +++ b/PlotLine/Services/ProjectBackupGraphValidation.cs @@ -1,4 +1,3 @@ -using System.Collections; using PlotLine.Models; namespace PlotLine.Services; @@ -46,6 +45,8 @@ internal static class ProjectBackupGraphValidation new("OnboardingManuscriptBuildChapterMap",null,new Link("OnboardingManuscriptBuildID","OnboardingManuscriptBuilds","OnboardingManuscriptBuildID"),new Link("ChapterID","Chapters","ChapterID")), new("OnboardingManuscriptBuildSceneMap",null,new Link("OnboardingManuscriptBuildID","OnboardingManuscriptBuilds","OnboardingManuscriptBuildID"),new Link("SceneID","Scenes","SceneID")), new("OnboardingManuscriptBuildCharacterMap",null,new Link("OnboardingManuscriptBuildID","OnboardingManuscriptBuilds","OnboardingManuscriptBuildID"),new Link("CharacterID","Characters","CharacterID")), + new("StoryElementReferences", "ReferenceID", new Link("CharacterID", "Characters", "CharacterID"), + new Link("LocationID", "Locations", "LocationID"), new Link("StoryAssetID", "StoryAssets", "StoryAssetID")), new("CharacterImages","CharacterImageID",new Link("CharacterID","Characters","CharacterID"),new Link("ProjectID","Project","ProjectID")), new("WordCompanionSceneAssets","WordCompanionSceneAssetID",new Link("SceneID","Scenes","SceneID"),new Link("StoryAssetID","StoryAssets","StoryAssetID")), new("WordCompanionSceneLocations","WordCompanionSceneLocationID",new Link("SceneID","Scenes","SceneID"),new Link("LocationID","Locations","LocationID")), @@ -120,7 +121,7 @@ internal static class ProjectBackupGraphValidation public static string? Validate(ProjectBackupExport backup,bool portable=false) { if(backup.Project is null || backup.Project.ProjectID<=0) return "Project backup contains an invalid source project identifier."; - var rows=Entities.ToDictionary(entity=>entity.Collection,entity=>((IEnumerable)typeof(ProjectBackupData).GetProperty(entity.Collection)!.GetValue(backup.Data)!).Cast().ToArray()); + var rows=Entities.ToDictionary(entity=>entity.Collection,entity=>BookBackupGraph.Rows(backup,entity.Collection)); object? Value(object row,string column)=>row.GetType().GetProperty(column)?.GetValue(row); foreach(var entity in Entities) { @@ -141,6 +142,22 @@ internal static class ProjectBackupGraphValidation return $"Project backup {entity.Collection}.{link.Column} references a missing or foreign {link.TargetCollection} record."; } } + foreach (var reference in backup.Data.StoryElementReferences ?? []) + { + 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."; + if (reference.Kind == "Characteristic") + { + if (string.IsNullOrWhiteSpace(reference.Note) || reference.StoragePath is not null || reference.OriginalFileName is not null) + return "Project backup contains an invalid key characteristic."; + } + else if (reference.Kind is not ("Image" or "Attachment") || + string.IsNullOrWhiteSpace(reference.OriginalFileName) || reference.OriginalFileName.Length > 300 || + reference.OriginalFileName.Any(c => char.IsControl(c) || c is '/' or '\\') || + string.IsNullOrWhiteSpace(reference.StoragePath)) + return "Project backup contains an invalid story element file reference."; + } if (backup.Data.SceneChecklistItems.Any(item => item.SceneID.HasValue == item.ChapterID.HasValue)) return "Project backup contains a checklist item without exactly one chapter or scene."; if (backup.Data.SceneChecklistItems.Any(item => !Context.IntentChecklistLinks.IsValidBackup(item.IntentLinksJson))) diff --git a/PlotLine/Services/ProjectBackupMapValidation.cs b/PlotLine/Services/ProjectBackupMapValidation.cs index 08a8807c..aa42a6bd 100644 --- a/PlotLine/Services/ProjectBackupMapValidation.cs +++ b/PlotLine/Services/ProjectBackupMapValidation.cs @@ -7,10 +7,10 @@ internal static class ProjectBackupMapValidation { public static string? Validate(ProjectBackupExport backup) { - if (backup.Data is null || typeof(ProjectBackupData).GetProperties().Any(property => property.GetValue(backup.Data) is null)) + if (backup.Data is null || typeof(ProjectBackupData).GetProperties().Any(property => property.Name != nameof(ProjectBackupData.StoryElementReferences) && property.GetValue(backup.Data) is null)) return "Project backup data contains a null entity collection."; var data=backup.Data; - if (typeof(ProjectBackupData).GetProperties().Any(property => ((System.Collections.IEnumerable)property.GetValue(data)!).Cast().Any(item=>item is null))) + if (typeof(ProjectBackupData).GetProperties().Any(property => ((System.Collections.IEnumerable?)property.GetValue(data))?.Cast().Any(item=>item is null) == true)) return "Project backup contains a null entity record."; if(data.MapFeatures.Any(x=>x.Type is null || x.Layer is null || x.GeometryJson is null)) return "Project backup contains invalid map feature fields."; if (data.StoryMaps.Any(x=>x is null) || data.MapFeatures.Any(x=>x is null) || data.MapRelationships.Any(x=>x is null) diff --git a/PlotLine/Services/ProjectBackupStoredFieldContract.Schema.cs b/PlotLine/Services/ProjectBackupStoredFieldContract.Schema.cs index afe5864f..df018ab5 100644 --- a/PlotLine/Services/ProjectBackupStoredFieldContract.Schema.cs +++ b/PlotLine/Services/ProjectBackupStoredFieldContract.Schema.cs @@ -22,6 +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"), ["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/StoryElementReferenceStorage.cs b/PlotLine/Services/StoryElementReferenceStorage.cs new file mode 100644 index 00000000..867991d6 --- /dev/null +++ b/PlotLine/Services/StoryElementReferenceStorage.cs @@ -0,0 +1,20 @@ +namespace PlotLine.Services; + +public static class StoryElementReferenceStorage +{ + public const string Folder = "story-element-references"; + + public static bool ValidBackupImage(byte[] bytes) + { + if (bytes.Length < 12 || bytes.Length > MapReferenceImageService.MaxStoredBytes || + !bytes.AsSpan(0, 4).SequenceEqual("RIFF"u8) || !bytes.AsSpan(8, 4).SequenceEqual("WEBP"u8)) + return false; + + try + { + RasterImageValidation.Inspect(bytes, MapReferenceImageService.MaxPixels); + return true; + } + catch (InvalidDataException) { return false; } + } +} diff --git a/PlotLine/Sql/349_StoryElementReferences.sql b/PlotLine/Sql/349_StoryElementReferences.sql new file mode 100644 index 00000000..e4e63865 --- /dev/null +++ b/PlotLine/Sql/349_StoryElementReferences.sql @@ -0,0 +1,157 @@ +SET ANSI_NULLS ON; +GO +SET QUOTED_IDENTIFIER ON; +GO + +IF OBJECT_ID(N'dbo.StoryElementReferences', N'U') IS NULL +BEGIN + CREATE TABLE dbo.StoryElementReferences + ( + ReferenceID int IDENTITY(1,1) NOT NULL PRIMARY KEY, + CharacterID int NULL REFERENCES dbo.Characters(CharacterID) ON DELETE CASCADE, + LocationID int NULL REFERENCES dbo.Locations(LocationID) ON DELETE CASCADE, + StoryAssetID int NULL REFERENCES dbo.StoryAssets(StoryAssetID) ON DELETE CASCADE, + Kind varchar(14) NOT NULL, + Note nvarchar(500) NOT NULL, + StoragePath nvarchar(1000) NULL, + OriginalFileName nvarchar(300) NULL, + Version rowversion NOT NULL, + CONSTRAINT CK_StoryElementReferences_Entity CHECK + ((CASE WHEN CharacterID IS NULL THEN 0 ELSE 1 END + + CASE WHEN LocationID IS NULL THEN 0 ELSE 1 END + + CASE WHEN StoryAssetID IS NULL THEN 0 ELSE 1 END) = 1), + CONSTRAINT CK_StoryElementReferences_Content CHECK + ((Kind = 'Characteristic' AND LEN(Note) > 0 AND StoragePath IS NULL AND OriginalFileName IS NULL) OR + (Kind IN ('Image', 'Attachment') AND StoragePath IS NOT NULL AND OriginalFileName IS NOT NULL)) + ); + CREATE INDEX IX_StoryElementReferences_Character ON dbo.StoryElementReferences(CharacterID, ReferenceID) WHERE CharacterID IS NOT NULL; + CREATE INDEX IX_StoryElementReferences_Location ON dbo.StoryElementReferences(LocationID, ReferenceID) WHERE LocationID IS NOT NULL; + CREATE INDEX IX_StoryElementReferences_Asset ON dbo.StoryElementReferences(StoryAssetID, ReferenceID) WHERE StoryAssetID IS NOT NULL; +END; +GO + +CREATE OR ALTER TRIGGER dbo.StoryElementReferences_MarkFilesDeleted +ON dbo.StoryElementReferences AFTER DELETE +AS +BEGIN + SET NOCOUNT ON; + UPDATE f SET IsDeleted = 1, DeletedDateUTC = SYSUTCDATETIME() + FROM dbo.UserFile f + INNER JOIN deleted d ON d.ReferenceID = f.EntityID AND d.StoragePath = f.StoragePath + WHERE f.EntityType = N'StoryElementReference' AND f.IsDeleted = 0; +END; +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 +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; + 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 + 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 WHERE 1 = 0; + COMMIT; + RETURN; + END + + IF @Action = 'list' + BEGIN + SELECT @ProjectID AS ProjectID, @EntityName AS EntityName, @CanEdit AS CanEdit; + SELECT ReferenceID, Kind, Note, OriginalFileName, Version + 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; + 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 = 'edit' + BEGIN + UPDATE dbo.StoryElementReferences SET Note = @Note + 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 diff --git a/PlotLine/Sql/350_StoryElementReferenceBackup.sql b/PlotLine/Sql/350_StoryElementReferenceBackup.sql new file mode 100644 index 00000000..d32e9ca1 --- /dev/null +++ b/PlotLine/Sql/350_StoryElementReferenceBackup.sql @@ -0,0 +1,89 @@ +SET ANSI_NULLS ON; +GO +SET QUOTED_IDENTIFIER ON; +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 + 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 + +CREATE OR ALTER PROCEDURE dbo.StoryElementReference_Restore @ProjectID int, @JsonData nvarchar(max) +AS +BEGIN + SET NOCOUNT ON; + IF EXISTS ( + SELECT 1 + FROM OPENJSON(@JsonData, '$.Data.StoryElementReferences') WITH + ( + ReferenceID int, CharacterID int, LocationID int, StoryAssetID int, StoragePath nvarchar(1000) + ) 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, -1) <> @ProjectID + OR (r.StoragePath IS NOT NULL AND NOT EXISTS ( + SELECT 1 FROM dbo.UserFile f + WHERE f.ProjectID = @ProjectID AND f.EntityType = N'StoryElementReference' + AND f.EntityID = r.ReferenceID AND f.StoragePath = r.StoragePath AND f.IsDeleted = 0 + AND f.FileSizeBytes BETWEEN 1 AND 10485760 + AND f.StoragePath LIKE N'/uploads/story-element-references/%.blob' + AND CHARINDEX(N'/', f.StoragePath, LEN(N'/uploads/story-element-references/') + 1) = 0 + )) + ) + THROW 51005, 'Story element reference has an invalid project link or missing staged file.', 1; + + EXEC dbo.ProjectRestore_InsertJsonTable N'StoryElementReferences', + N'$.Data.StoryElementReferences', @JsonData, @ProjectID, 0; + + UPDATE f SET OriginalFileName = r.OriginalFileName, + ContentType = CASE r.Kind WHEN 'Image' THEN N'image/webp' ELSE N'application/octet-stream' END + FROM dbo.UserFile f + INNER JOIN dbo.StoryElementReferences r ON r.ReferenceID = f.EntityID AND r.StoragePath = f.StoragePath + WHERE f.ProjectID = @ProjectID AND f.EntityType = N'StoryElementReference' AND f.IsDeleted = 0; +END; +GO + +-- Keep the audited graph and outer recovery wrapper intact apart from these hooks. +DECLARE @name sysname = N'dbo.ProjectRestore_ApplyGraph236'; +DECLARE @definition nvarchar(max) = OBJECT_DEFINITION(OBJECT_ID(@name)); +IF @definition IS NULL THROW 51000, 'Missing canonical project restore graph.', 1; +IF CHARINDEX(N'EXEC dbo.StoryElementReference_Restore', @definition) = 0 +BEGIN + DECLARE @beforeDelete nvarchar(100) = N'DECLARE @PreviousMapRevision'; + DECLARE @afterFiles nvarchar(100) = N'DECLARE EnableCursor CURSOR'; + IF CHARINDEX(@beforeDelete, @definition) = 0 OR CHARINDEX(@afterFiles, @definition) = 0 + THROW 51000, 'Review project restore hooks for story element references.', 1; + + SET @definition = REPLACE(@definition, @beforeDelete, N' + IF JSON_QUERY(@JsonData, ''$.Data.StoryElementReferences'') IS NULL AND EXISTS ( + SELECT 1 + 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 + ) + THROW 51006, ''This backup omits existing story element references. Restore was aborted.'', 1; + ' + @beforeDelete); + SET @definition = REPLACE(@definition, @afterFiles, N' + EXEC dbo.StoryElementReference_Restore @ProjectID, @JsonData; + + ' + @afterFiles); + SET @definition = STUFF(@definition, 1, CHARINDEX(N'PROCEDURE', @definition) - 1, N'CREATE OR ALTER '); + SET @definition = REPLACE(@definition, N'PROCEDURE dbo.ProjectRestore_ApplyFromJson', N'PROCEDURE ' + @name); + IF CHARINDEX(N'PROCEDURE ' + @name, @definition) = 0 + THROW 51000, 'Unexpected project restore graph header.', 1; + EXEC sys.sp_executesql @definition; +END; +GO diff --git a/PlotLine/ViewComponents/StoryElementReferencesViewComponent.cs b/PlotLine/ViewComponents/StoryElementReferencesViewComponent.cs new file mode 100644 index 00000000..02864d53 --- /dev/null +++ b/PlotLine/ViewComponents/StoryElementReferencesViewComponent.cs @@ -0,0 +1,16 @@ +using Microsoft.AspNetCore.Mvc; +using PlotLine.Data; +using PlotLine.Services; + +namespace PlotLine.ViewComponents; + +public sealed class StoryElementReferencesViewComponent( + ICurrentUserService currentUser, StoryElementReferenceRepository references) : ViewComponent +{ + public async Task InvokeAsync(StoryElementType entityType, int entityId) + { + 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); + } +} diff --git a/PlotLine/Views/Characters/Details.cshtml b/PlotLine/Views/Characters/Details.cshtml index 6765d673..2e7affe2 100644 --- a/PlotLine/Views/Characters/Details.cshtml +++ b/PlotLine/Views/Characters/Details.cshtml @@ -11,12 +11,15 @@
@if(Model.WorkspacePage!=null){}
+@await Component.InvokeAsync("StoryElementReferences", new { entityType = PlotLine.Data.StoryElementType.Character, entityId = c.CharacterID })
@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 5c6962dd..8bc294b4 100644 --- a/PlotLine/Views/Characters/_WorkspaceGallery.cshtml +++ b/PlotLine/Views/Characters/_WorkspaceGallery.cshtml @@ -1,5 +1,5 @@ @model CharacterDetailViewModel - + +@section Scripts { + +} diff --git a/PlotLine/Views/Shared/Components/StoryElementReferences/Default.cshtml b/PlotLine/Views/Shared/Components/StoryElementReferences/Default.cshtml new file mode 100644 index 00000000..a6140a74 --- /dev/null +++ b/PlotLine/Views/Shared/Components/StoryElementReferences/Default.cshtml @@ -0,0 +1,114 @@ +@using PlotLine.Data +@model StoryElementReferenceList +@{ + var scope = Model.Scope; + var routes = new Dictionary + { + ["entityType"] = scope.EntityType.ToString(), + ["entityId"] = scope.EntityID.ToString() + }; + var isCharacter = scope.EntityType == StoryElementType.Character; +} +
+
+

References

+ Refresh references +
+ @if (TempData["ReferenceSaved"] is string saved) + { + + } + @if (TempData["ReferenceError"] is string error) + { + + } + + @foreach (var kind in new[] { "Characteristic", "Image", "Attachment" }) + { + var label = kind switch { "Characteristic" => "Key characteristics", "Image" => "Images", _ => "Attachments" }; + if (kind == "Image" && isCharacter) + { +
+

@label

+ Open character gallery +
+ continue; + } + + var items = Model.Items.Where(item => item.Kind == kind).ToList(); +
+

@label

+ @if (items.Count == 0) + { +

No @label.ToLowerInvariant() yet.

+ } + @foreach (var item in items) + { +
+ @if (item.OriginalFileName is not null) + { + var fileUrl = Url.Action("Download", "StoryElementReferences", + new { entityType = scope.EntityType, entityId = scope.EntityID, referenceId = item.ReferenceID }); + + @if (kind == "Image") + { + @(item.Note.Length > 0 ? item.Note : item.OriginalFileName) + } + @item.OriginalFileName + + } + @if (item.Note.Length > 0) + { +

@item.Note

+ } + @if (Model.Access.CanEdit) + { +
+ Edit or remove + + + + + + + +
+ } +
+ } + + @if (Model.Access.CanEdit) + { +
+ Add @kind.ToLowerInvariant() +
+ + @if (kind != "Characteristic") + { + + } + + +
+
+ } +
+ } +
diff --git a/PlotLine/Views/StoryAssets/Details.cshtml b/PlotLine/Views/StoryAssets/Details.cshtml index 216fd1ab..acbd1aac 100644 --- a/PlotLine/Views/StoryAssets/Details.cshtml +++ b/PlotLine/Views/StoryAssets/Details.cshtml @@ -118,6 +118,7 @@ +@await Component.InvokeAsync("StoryElementReferences", new { entityType = PlotLine.Data.StoryElementType.Asset, entityId = Model.Asset.StoryAssetID })

Events across scenes

@if (!Model.Events.Any()) @@ -164,3 +165,7 @@ }
+ +@section Scripts { + +} diff --git a/PlotLine/wwwroot/js/story-element-references.js b/PlotLine/wwwroot/js/story-element-references.js new file mode 100644 index 00000000..c3ce4805 --- /dev/null +++ b/PlotLine/wwwroot/js/story-element-references.js @@ -0,0 +1,55 @@ +(() => { + let panel = document.querySelector('[data-story-element-references]'); + if (!panel) return; + + let connection; + let request; + async function refresh() { + if (panel.querySelector('details[open]') || panel.contains(document.activeElement)) return; + request?.abort(); + const controller = new AbortController(); + request = controller; + + try { + const response = await fetch(panel.dataset.refreshUrl, { cache: 'no-store', signal: controller.signal }); + if (!response.ok || response.redirected) return; + const html = await response.text(); + const updated = new DOMParser().parseFromString(html, 'text/html').querySelector('[data-story-element-references]'); + if (!updated || controller.signal.aborted || panel.querySelector('details[open]') || + panel.contains(document.activeElement)) return; + panel.replaceWith(updated); + panel = updated; + } catch { + // The explicit refresh link remains available when a background request fails. + } + } + + function connect(candidate) { + if (!candidate || connection) return; + connection = candidate; + connection.on('ContextInvalidated', hint => { + if (Number(hint.projectId) === Number(panel.dataset.projectId) && + ['characters', 'locations', 'assets'].includes(hint.kind)) void refresh(); + }); + connection.onreconnected(refresh); + } + + function openGallery() { + const gallery = document.querySelector('details#character-gallery'); + if (gallery) gallery.open = true; + } + + document.addEventListener('click', event => { + if (event.target.closest('[data-open-reference-gallery]')) openGallery(); + }); + document.addEventListener('submit', event => { + if (!event.defaultPrevented && event.target.matches('[data-story-reference-form]')) { + delete event.target.dataset.workspaceDirty; + } + }); + if (location.hash === '#character-gallery') openGallery(); + + document.addEventListener('pd-presence-connection', event => connect(event.detail)); + document.addEventListener('pd-presence-ready', () => connect(window.PlotDirectorPresenceConnection)); + connect(window.PlotDirectorPresenceConnection); +})();