Add shared story element references

This commit is contained in:
Codex 2026-12-05 17:22:38 +00:00
parent 8c54850647
commit d089f2d7b5
24 changed files with 892 additions and 13 deletions

View File

@ -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;}

View File

@ -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<StoryElementType>())
{
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<ProjectBackupExport>(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<ProjectBackupExport>(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!;
}
}

View File

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

View File

@ -158,6 +158,10 @@ public sealed class ProjectBackupRepository(ISqlConnectionFactory connectionFact
}
data.StoryElementReferences = (await connection.QueryAsync<ProjectBackupStoryElementReference>(
"dbo.StoryElementReference_Backup", new { ProjectID = projectId },
commandType: CommandType.StoredProcedure, transaction: transaction)).ToList();
data.SceneThreads = (await connection.QueryAsync<SceneThread>(
"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),

View File

@ -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<StoryElementReference> 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<StoryElementReferenceList?> 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<StoryElementReferenceAccess>();
return access is null ? null : new(scope, access, (await results.ReadAsync<StoryElementReference>()).AsList());
}
public async Task<StoryElementReferenceFile?> FileAsync(int userId, StoryElementReferenceScope scope, int referenceId)
{
using var connection = connections.CreateConnection();
return await connection.QuerySingleOrDefaultAsync<StoryElementReferenceFile>(Procedure,
new { UserID = userId, EntityType = scope.EntityType.ToString(), scope.EntityID, Action = "file", ReferenceID = referenceId },
commandType: CommandType.StoredProcedure);
}
public async Task<StoryElementReferenceChange?> 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<StoryElementReferenceChange>(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);
}
}

View File

@ -62,6 +62,8 @@ public sealed class ProjectBackupData
public IReadOnlyList<ProjectBackupOnboardingManuscriptBuildSceneMap> OnboardingManuscriptBuildSceneMap { get; set; } = [];
public IReadOnlyList<ProjectBackupOnboardingManuscriptBuildCharacterMap> OnboardingManuscriptBuildCharacterMap { get; set; } = [];
[System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull)]
public IReadOnlyList<ProjectBackupStoryElementReference>? StoryElementReferences { get; set; }
public IReadOnlyList<CharacterImage> CharacterImages { get; set; } = [];
public IReadOnlyList<ProjectBackupCompanionSceneAsset> WordCompanionSceneAssets { get; set; } = [];
public IReadOnlyList<ProjectBackupCompanionSceneLocation> 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;

View File

@ -290,6 +290,7 @@ public class Program
builder.Services.AddScoped<IWriterWorkspaceService, WriterWorkspaceService>();
builder.Services.AddScoped<IWritingScheduleService, WritingScheduleService>();
builder.Services.AddScoped<IStorageService, StorageService>();
builder.Services.AddScoped<StoryElementReferenceRepository>();
builder.Services.AddSingleton<IUploadStorageService, UploadStorageService>();
builder.Services.AddScoped<IExportService, ExportService>();
builder.Services.AddScoped<IProjectBackupFiles, ProjectBackupFiles>();
@ -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<IUploadStorageService>();
app.UseStaticFiles(new StaticFileOptions

View File

@ -9,10 +9,10 @@ namespace PlotLine.Services;
public static class BookBackupGraph
{
public static readonly JsonSerializerOptions Json = new() { PropertyNameCaseInsensitive = true };
internal static readonly HashSet<string> 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<string> 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<string, string> 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<object>().ToArray();
internal static object[] Rows(ProjectBackupExport b, string c) => ((IEnumerable?)typeof(ProjectBackupData).GetProperty(c)!.GetValue(b.Data))?.Cast<object>().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<object> 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); }

View File

@ -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<VisualIdentityImageResult> SaveCharacterAvatarAsync(CharacterAvatarCropViewModel model)

View File

@ -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);

View File

@ -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);

View File

@ -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<object>().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)))

View File

@ -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<object?>().Any(item=>item is null)))
if (typeof(ProjectBackupData).GetProperties().Any(property => ((System.Collections.IEnumerable?)property.GetValue(data))?.Cast<object?>().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)

View File

@ -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"),

View File

@ -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; }
}
}

View File

@ -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

View File

@ -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

View File

@ -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<IViewComponentResult> 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);
}
}

View File

@ -11,12 +11,15 @@
<div class="character-workspace-switch"><label>Find another character<input type="search" class="form-control" data-character-switch maxlength="120" placeholder="Name or alias"/></label><div data-character-matches></div></div>
<nav class="character-workspace-tabs" role="tablist" aria-label="Character workspace">@foreach(var tab in CharacterWorkspace.Tabs){<a role="tab" id="character-tab-@tab" aria-controls="character-workspace-panel" aria-selected="@(Model.WorkspaceTab==tab?"true":"false")" data-character-tab="@tab" href="@Url.Action("Details",new{id=c.CharacterID,tab})">@(tab=="overview"?"Overview":tab=="relationships"?"Relationships":tab=="evolution"?"Evolution":tab=="appearances"?"Appearances":"Knowledge")</a>}</nav>
<div data-workspace-status role="status"></div><section id="character-workspace-panel" data-workspace-panel role="tabpanel" tabindex="-1">@if(Model.WorkspacePage!=null){<partial name="/Views/Characters/_WorkspaceTab.cshtml" model="Model.WorkspacePage"/>}</section>
@await Component.InvokeAsync("StoryElementReferences", new { entityType = PlotLine.Data.StoryElementType.Character, entityId = c.CharacterID })
<noscript><p>Select a tab above to open its content.</p></noscript>
<dialog data-workspace-dialog aria-labelledby="character-operation-title"><div data-workspace-dialog-content></div><button type="button" data-workspace-dialog-fallback>Cancel</button></dialog>
</div>
@foreach(var key in new[]{"ImageMessage","RelationshipMessage","CharacterMessage"}){if(TempData[key] is string message){<span hidden data-toast-message="success">@message</span>}}
@if(TempData["ImageError"] is string error){<div class="alert alert-warning">@error</div>}
@section Scripts{
<script src="~/js/story-element-references.js" asp-append-version="true"></script>
<link rel="stylesheet" href="~/css/character-workspace.css" asp-append-version="true"/>
<script src="~/js/context-relationship-layout.js" asp-append-version="true"></script>
<script src="~/js/character-workspace-graph.js" asp-append-version="true"></script>

View File

@ -1,5 +1,5 @@
@model CharacterDetailViewModel
<section id="character-gallery" class="list-section mt-3">
<section class="list-section mt-3">
<div class="d-flex align-items-start justify-content-between gap-3 flex-wrap mb-3">
<div>
<h2>Character Images <help-icon key="characters.images" /></h2>
@ -48,6 +48,20 @@
}
</div>
<div class="button-row character-gallery-card__actions">
@if (Model.WorkspaceCanEdit)
{
<details>
<summary>Edit caption</summary>
<form asp-controller="StoryElementReferences" asp-action="Change" method="post" data-story-reference-form
asp-route-entityType="Character" asp-route-entityId="@Model.Character.CharacterID">
<input type="hidden" name="referenceId" value="@image.CharacterImageID" />
<label class="form-label d-block">Caption
<input class="form-control" name="note" maxlength="500" value="@image.Caption" />
</label>
<button class="btn btn-primary btn-sm" name="operation" value="caption">Save caption</button>
</form>
</details>
}
<a hidden="@(!Model.WorkspaceCanEdit)" class="btn btn-outline-primary btn-sm" asp-action="CropAvatar" asp-route-imageId="@image.CharacterImageID" asp-controller="Characters">Create Avatar</a>
<a class="btn btn-outline-secondary btn-sm" href="@image.ImagePath" target="_blank" rel="noopener">Open</a>
<form hidden="@(!Model.WorkspaceCanEdit)" asp-action="DeleteImage" method="post" class="archive-button-form" data-confirm-message="Remove this image from the character gallery?" asp-controller="Characters">

View File

@ -71,6 +71,8 @@
</div>
</section>
@await Component.InvokeAsync("StoryElementReferences", new { entityType = PlotLine.Data.StoryElementType.Location, entityId = Model.Location.LocationID })
@if (TempData["LocationMessage"] is string locationMessage)
{
<span hidden data-toast-message="info">@locationMessage</span>
@ -217,3 +219,7 @@
</div>
</section>
</div>
@section Scripts {
<script src="~/js/story-element-references.js" asp-append-version="true"></script>
}

View File

@ -0,0 +1,114 @@
@using PlotLine.Data
@model StoryElementReferenceList
@{
var scope = Model.Scope;
var routes = new Dictionary<string, string>
{
["entityType"] = scope.EntityType.ToString(),
["entityId"] = scope.EntityID.ToString()
};
var isCharacter = scope.EntityType == StoryElementType.Character;
}
<section id="story-element-references" class="list-section mt-3" aria-labelledby="story-element-reference-title"
data-story-element-references data-project-id="@Model.Access.ProjectID"
data-refresh-url="@Url.Action("List", "StoryElementReferences", new { entityType = scope.EntityType, entityId = scope.EntityID })">
<div class="d-flex flex-wrap align-items-center justify-content-between gap-2">
<h2 id="story-element-reference-title">References</h2>
<a class="btn btn-outline-secondary btn-sm" asp-controller="@scope.DetailsController" asp-action="Details"
asp-route-id="@scope.EntityID" asp-fragment="story-element-references">Refresh references</a>
</div>
@if (TempData["ReferenceSaved"] is string saved)
{
<span hidden data-toast-message="success">@saved</span>
}
@if (TempData["ReferenceError"] is string error)
{
<p class="alert alert-warning" role="alert">@error</p>
}
@foreach (var kind in new[] { "Characteristic", "Image", "Attachment" })
{
var label = kind switch { "Characteristic" => "Key characteristics", "Image" => "Images", _ => "Attachments" };
if (kind == "Image" && isCharacter)
{
<div class="mt-3">
<h3>@label</h3>
<a asp-controller="Characters" asp-action="Details" asp-route-id="@scope.EntityID"
asp-fragment="character-gallery" asp-route-tab="overview" data-open-reference-gallery>Open character gallery</a>
</div>
continue;
}
var items = Model.Items.Where(item => item.Kind == kind).ToList();
<div class="mt-3">
<h3>@label</h3>
@if (items.Count == 0)
{
<p class="muted">No @label.ToLowerInvariant() yet.</p>
}
@foreach (var item in items)
{
<article class="border rounded p-2 mb-2">
@if (item.OriginalFileName is not null)
{
var fileUrl = Url.Action("Download", "StoryElementReferences",
new { entityType = scope.EntityType, entityId = scope.EntityID, referenceId = item.ReferenceID });
<a href="@fileUrl">
@if (kind == "Image")
{
<img class="d-block rounded" src="@fileUrl" alt="@(item.Note.Length > 0 ? item.Note : item.OriginalFileName)"
loading="lazy" width="180" />
}
@item.OriginalFileName
</a>
}
@if (item.Note.Length > 0)
{
<p class="mb-2 text-break">@item.Note</p>
}
@if (Model.Access.CanEdit)
{
<details>
<summary>Edit or remove</summary>
<form asp-controller="StoryElementReferences" asp-action="Change" asp-all-route-data="routes" method="post" data-story-reference-form
class="mt-2">
<input type="hidden" name="referenceId" value="@item.ReferenceID" />
<input type="hidden" name="version" value="@Convert.ToBase64String(item.Version)" />
<label class="form-label d-block">
@(kind == "Characteristic" ? "Characteristic" : "Caption")
<textarea class="form-control" name="note" maxlength="500" rows="2">@item.Note</textarea>
</label>
<button class="btn btn-primary btn-sm" name="operation" value="edit">Save</button>
<button class="btn btn-outline-danger btn-sm" name="operation" value="delete">Remove</button>
</form>
</details>
}
</article>
}
@if (Model.Access.CanEdit)
{
<details>
<summary>Add @kind.ToLowerInvariant()</summary>
<form asp-controller="StoryElementReferences" asp-action="Add" asp-all-route-data="routes" method="post" data-story-reference-form
enctype="multipart/form-data" class="mt-2">
<input type="hidden" name="kind" value="@kind" />
@if (kind != "Characteristic")
{
<label class="form-label d-block">
File up to 10 MB
<input class="form-control" type="file" name="upload" required
accept="@(kind == "Image" ? "image/png,image/jpeg,image/webp" : null)" />
</label>
}
<label class="form-label d-block">
@(kind == "Characteristic" ? "Characteristic" : "Caption (optional)")
<textarea class="form-control" name="note" maxlength="500" rows="2" required="@(kind == "Characteristic")"></textarea>
</label>
<button class="btn btn-primary btn-sm">Add @kind.ToLowerInvariant()</button>
</form>
</details>
}
</div>
}
</section>

View File

@ -118,6 +118,7 @@
</article>
</section>
@await Component.InvokeAsync("StoryElementReferences", new { entityType = PlotLine.Data.StoryElementType.Asset, entityId = Model.Asset.StoryAssetID })
<section class="list-section mt-3">
<h2>Events across scenes <help-icon key="storyAssets.eventsAcrossScenes" /></h2>
@if (!Model.Events.Any())
@ -164,3 +165,7 @@
</div>
}
</section>
@section Scripts {
<script src="~/js/story-element-references.js" asp-append-version="true"></script>
}

View File

@ -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);
})();