Refine shared story element references and attachments

This commit is contained in:
Codex 2026-12-06 15:24:24 +00:00
parent fb56794224
commit 5a1950c79c
22 changed files with 942 additions and 187 deletions

View File

@ -1,3 +1,4 @@
using System.IO.Compression;
using System.Text.Json;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
@ -11,7 +12,7 @@ internal static class StoryElementReferenceTests
{
public static async Task Run()
{
var guest = new StoryElementReferencesController(new Guest(), null!, null!, null!, null!, null!, null!);
var guest = new StoryElementReferencesController(new Guest(), null!, null!, null!, null!, null!, null!, null!);
foreach (var entity in Enum.GetValues<StoryElementType>())
{
Check(await guest.List(entity, 1) is NotFoundResult, "Reference lists require authentication.");
@ -22,6 +23,19 @@ internal static class StoryElementReferenceTests
"Removing references requires authentication.");
}
Check(StoryElementAttachmentPolicy.IsImage("reference.PNG"), "Image routing is case insensitive.");
Check(StoryElementAttachmentPolicy.IsAudio("interview.wav", "RIFF0000WAVE"u8), "WAV has an audio type.");
Check(!StoryElementAttachmentPolicy.IsAudio("video.wav", "RIFF0000AVI "u8), "A renamed video is rejected.");
Check(StoryElementAttachmentPolicy.IsAllowedDocument("notes.csv", "name,description"u8.ToArray()), "CSV text is accepted.");
Check(StoryElementAttachmentPolicy.IsAllowedDocument("plan.pdf", "%PDF-1.7"u8.ToArray()), "PDF is accepted.");
Check(!StoryElementAttachmentPolicy.IsAllowedDocument("setup.txt", [77, 90, 0, 0]), "A binary renamed to text is rejected.");
Check(!StoryElementAttachmentPolicy.IsAllowedDocument("setup.js", "alert(1)"u8.ToArray()), "Scripts are rejected.");
Check(StoryElementAttachmentPolicy.IsAllowedDocument("notes.docx", OfficeFile("word/document.xml")), "Word documents are accepted.");
Check(StoryElementAttachmentPolicy.IsAllowedDocument("plan.xlsx", OfficeFile("xl/workbook.xml")), "Excel workbooks are accepted.");
Check(!StoryElementAttachmentPolicy.IsAllowedDocument("notes.docx", OfficeFile("word/document.xml", "word/vbaProject.bin")),
"An Office archive with a macro project is rejected.");
Check(!StoryElementAttachmentPolicy.IsAllowedDocument("archive.zip", OfficeFile("word/document.xml")), "ZIP uploads are rejected.");
var legacy = new ProjectBackupExport { Project = new() { ProjectID = 4 } };
var legacyJson = JsonSerializer.Serialize(legacy);
Check(!legacyJson.Contains("\"StoryElementReferences\"", StringComparison.Ordinal),
@ -29,6 +43,10 @@ internal static class StoryElementReferenceTests
Check(JsonSerializer.Serialize(JsonSerializer.Deserialize<ProjectBackupExport>(legacyJson)) == legacyJson,
"Reading and reserializing a legacy package must preserve its fingerprint.");
const string oldReference = """{"ReferenceID":1,"CharacterID":7,"LocationID":null,"StoryAssetID":null,"Kind":"Characteristic","Note":"Left-handed","StoragePath":null,"OriginalFileName":null}""";
Check(JsonSerializer.Serialize(JsonSerializer.Deserialize<ProjectBackupStoryElementReference>(oldReference)) == oldReference,
"Older backups with references retain their serialized fingerprint.");
string root = Directory.CreateTempSubdirectory("plotdirector-reference-test-").FullName;
try
{
@ -53,10 +71,10 @@ internal static class StoryElementReferenceTests
StoryElementReferences =
[
new() { ReferenceID = 1, CharacterID = 7, Kind = "Characteristic", Note = "Left-handed" },
new() { ReferenceID = 2, LocationID = 7, Kind = "Image", Note = "Doorway",
new() { ReferenceID = 2, LocationID = 7, Kind = "Image", Note = "Doorway", IsPrimary = true,
OriginalFileName = "Sketch.png", StoragePath = uploads.GetPublicPath(folder, "image.blob") },
new() { ReferenceID = 3, StoryAssetID = 7, Kind = "Attachment",
OriginalFileName = "Document.txt", StoragePath = uploads.GetPublicPath(folder, "document.blob") }
OriginalFileName = "Document.txt", Title = "Research notes", StoragePath = uploads.GetPublicPath(folder, "document.blob") }
]
}
};
@ -64,6 +82,8 @@ internal static class StoryElementReferenceTests
var restored = JsonSerializer.Deserialize<ProjectBackupExport>(JsonSerializer.Serialize(backup))!;
Check(ProjectBackupFiles.Validate(restored) is null, "All uploaded reference bytes survive serialization.");
var items = restored.Data.StoryElementReferences!;
Check(items[1].IsPrimary == true && items[2].Title == "Research notes",
"Primary-image selection and attachment titles survive backup serialization.");
Check(items[0].Note == "Left-handed" && items[0].StoragePath is null, "Notes are independent of files.");
Check(!StoryElementReferenceStorage.ValidBackupImage(attachment), "Arbitrary attachments cannot serve as images.");
using (await files.StageAsync(restored, importingCopy: true))
@ -85,7 +105,18 @@ internal static class StoryElementReferenceTests
Directory.Delete(root, recursive: true);
}
Console.WriteLine("PASS story element reference authentication, image normalization and portable file round-trip");
Console.WriteLine("PASS reference authentication, attachment validation and backup round-trip");
}
private static byte[] OfficeFile(params string[] parts)
{
using var bytes = new MemoryStream();
using (var zip = new ZipArchive(bytes, ZipArchiveMode.Create, leaveOpen: true))
{
zip.CreateEntry("[Content_Types].xml");
foreach (var part in parts) zip.CreateEntry(part);
}
return bytes.ToArray();
}
private static void Check(bool condition, string message)

View File

@ -2,6 +2,7 @@ using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using PlotLine.Data;
using PlotLine.Services;
using PlotLine.ViewModels;
namespace PlotLine.Controllers;
@ -13,6 +14,7 @@ public sealed class StoryElementReferencesController(
IUploadStorageService storage,
IProjectCollaborationRepository collaboration,
ISubscriptionService subscriptions,
ICharacterService characters,
ContextSavedData savedData,
ILogger<StoryElementReferencesController> logger) : Controller
{
@ -23,11 +25,13 @@ public sealed class StoryElementReferencesController(
{
if (!ModelState.IsValid || currentUser.UserId is not int userId) return NotFound();
var model = await references.ListAsync(userId, new(entityType, entityId));
return model is null ? NotFound() : PartialView("Components/StoryElementReferences/Default", model);
return model is null ? NotFound() : PartialView("Components/StoryElementReferences/Default",
new StoryElementReferenceWorkspace(model,
await StoryElementReferenceWorkspace.ReadStorageAsync(model, userId, collaboration, subscriptions)));
}
[HttpGet]
public async Task<IActionResult> Download(StoryElementType entityType, int entityId, int referenceId)
public async Task<IActionResult> Download(StoryElementType entityType, int entityId, int referenceId, bool save = false)
{
if (!ModelState.IsValid || currentUser.UserId is not int userId) return NotFound();
var entry = await references.FileAsync(userId, new(entityType, entityId), referenceId);
@ -37,15 +41,26 @@ public sealed class StoryElementReferencesController(
try { stream = System.IO.File.OpenRead(path); }
catch (IOException) { return NotFound(); }
Response.Headers.XContentTypeOptions = "nosniff";
return entry.Kind == "Image"
? File(stream, "image/webp")
: File(stream, "application/octet-stream", entry.OriginalFileName);
if (save) return File(stream, "application/octet-stream", entry.OriginalFileName);
if (entry.Kind == "Image") return File(stream, "image/webp");
var header = new byte[320];
var length = await stream.ReadAtLeastAsync(header, header.Length, false);
stream.Position = 0;
var audioType = StoryElementAttachmentPolicy.AudioType(entry.OriginalFileName);
if (audioType is not null && StoryElementAttachmentPolicy.IsAudio(entry.OriginalFileName, header.AsSpan(0, length)))
return File(stream, audioType, enableRangeProcessing: true);
if (StoryElementAttachmentPolicy.IsPdf(entry.OriginalFileName, header.AsSpan(0, length)))
{
Response.Headers.ContentSecurityPolicy = "sandbox; default-src 'none'";
return File(stream, "application/pdf", enableRangeProcessing: true);
}
return File(stream, "application/octet-stream", entry.OriginalFileName);
}
[HttpPost]
[ValidateAntiForgeryToken]
[RequestSizeLimit(11L * 1024 * 1024)]
public async Task<IActionResult> Add(StoryElementType entityType, int entityId, string kind,
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();
@ -60,13 +75,28 @@ public sealed class StoryElementReferencesController(
return await Finish(scope, await references.ChangeAsync(userId, scope, "add", null, null, kind, note));
}
if (kind is not ("Image" or "Attachment") || (kind == "Image" && entityType == StoryElementType.Character) ||
upload is null || upload.Length is <= 0 or > MapReferenceImageService.MaxUploadBytes)
return Return(scope, "Enter a characteristic or select a file up to 10 MB.");
if (upload is null || upload.Length is <= 0 or > MapReferenceImageService.MaxUploadBytes)
return Return(scope, "Enter a characteristic or select a non-empty file up to 10 MB.");
var filename = Path.GetFileName(upload.FileName.Replace('\\', '/'));
if (string.IsNullOrWhiteSpace(filename) || filename.Length > 300 || filename.Any(char.IsControl))
return Return(scope, "Choose a file with a valid name up to 300 characters.");
kind = StoryElementAttachmentPolicy.IsImage(filename) ? "Image" : "Attachment";
if (kind == "Image" && entityType == StoryElementType.Character)
{
try
{
var result = await characters.UploadCharacterImageAsync(new CharacterImageUploadViewModel
{
CharacterID = entityId, ImageUpload = upload, Caption = note
});
if (!result.Succeeded) return Return(scope, result.ErrorMessage ?? "The image could not be saved.");
await savedData.Activity(list.Access.ProjectID, scope.EntityType.ToString(), scope.EntityID);
return Success(scope);
}
catch (SubscriptionLimitException exception) { return Return(scope, exception.Message); }
}
var owner = await collaboration.GetOwnerUserIdAsync(list.Access.ProjectID);
if (owner is null) return NotFound();
@ -74,6 +104,7 @@ public sealed class StoryElementReferencesController(
var storagePath = storage.GetPublicPath(StorageFolder, filenameOnDisk);
var physicalPath = storage.GetFilePath(StorageFolder, filenameOnDisk);
long size;
long? storageLimit;
try
{
using var content = new MemoryStream();
@ -81,14 +112,20 @@ public sealed class StoryElementReferencesController(
var bytes = kind == "Image"
? MapReferenceImageService.Normalize(content.ToArray(), filename).ImageData!
: content.ToArray();
if (kind == "Attachment" && !StoryElementAttachmentPolicy.IsAudio(filename, bytes) &&
!StoryElementAttachmentPolicy.IsAllowedDocument(filename, bytes))
return Return(scope, "Unsupported file or file contents. Choose an image, audio file, PDF, text file, DOCX or XLSX.");
size = bytes.LongLength;
var quota = await subscriptions.CanUploadFileAsync(owner.Value, size);
if (!quota.Allowed) return Return(scope, quota.Message ?? "The project storage limit would be exceeded.");
if (!quota.Allowed)
return Return(scope, owner.Value == userId ? quota.Message : "The project storage allowance would be exceeded.");
storageLimit = quota.MaximumAllowedBytes >= 999999L * 1024 * 1024 ? null : quota.MaximumAllowedBytes;
storage.GetDirectory(StorageFolder);
await using var file = new FileStream(physicalPath, FileMode.CreateNew, FileAccess.Write);
await file.WriteAsync(bytes);
}
catch (InvalidDataException exception) { return Return(scope, exception.Message); }
catch (SubscriptionLimitException exception) { return Return(scope, exception.Message); }
catch (IOException exception)
{
logger.LogWarning(exception, "Could not write a story element reference upload.");
@ -97,7 +134,7 @@ public sealed class StoryElementReferencesController(
}
// Retain the file on an uncertain database outcome so a committed reference stays usable.
var change = await references.ChangeAsync(userId, scope, "add", null, null, kind, note, storagePath, filename, size);
var change = await references.ChangeAsync(userId, scope, "add", null, null, kind, note, storagePath, filename, size, storageLimitBytes: storageLimit);
if (change?.Changed != true) RemoveFile(storagePath);
return await Finish(scope, change);
}
@ -105,13 +142,15 @@ public sealed class StoryElementReferencesController(
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Change(StoryElementType entityType, int entityId, int referenceId,
string operation, string? version, string? note)
string operation, string? version, string? note, string? title = null)
{
if (!ModelState.IsValid || currentUser.UserId is not int userId ||
operation is not ("edit" or "delete" or "caption")) return NotFound();
operation is not ("edit" or "delete" or "caption" or "primary" or "clear")) return NotFound();
var scope = new StoryElementReferenceScope(entityType, entityId);
note = (note ?? "").Trim();
if (note.Length > 500) return Return(scope, "Use 500 characters or fewer.");
title = title?.Trim();
if (title?.Length > 160) return Return(scope, "Use 160 characters or fewer for the title.");
byte[]? expectedVersion = null;
if (operation != "caption")
{
@ -119,7 +158,7 @@ public sealed class StoryElementReferencesController(
if (version is null || !Convert.TryFromBase64String(version, expectedVersion, out int written) || written != 8)
return BadRequest();
}
var change = await references.ChangeAsync(userId, scope, operation, referenceId, expectedVersion, null, note);
var change = await references.ChangeAsync(userId, scope, operation, referenceId, expectedVersion, null, note, title: string.IsNullOrWhiteSpace(title) ? null : title);
if (change?.StoragePath is string path) RemoveFile(path);
return await Finish(scope, change);
}
@ -127,16 +166,29 @@ public sealed class StoryElementReferencesController(
private async Task<IActionResult> Finish(StoryElementReferenceScope scope, StoryElementReferenceChange? change)
{
if (change is null) return NotFound();
if (change.QuotaExceeded) return Return(scope, "This upload would exceed the account storage allowance.");
if (!change.Changed)
return Return(scope, "The reference changed or the note is empty. Review the saved references and try again.");
await savedData.Activity(change.ProjectID, scope.EntityType.ToString(), scope.EntityID);
return Success(scope);
}
private IActionResult Success(StoryElementReferenceScope scope)
{
if (WantsJson) return Ok(new { message = "References updated." });
TempData["ReferenceSaved"] = "References updated.";
return Return(scope);
}
private bool WantsJson => Request.Headers["X-Requested-With"] == "XMLHttpRequest";
private IActionResult Return(StoryElementReferenceScope scope, string? error = null)
{
if (error is not null) TempData["ReferenceError"] = error;
if (error is not null)
{
if (WantsJson) return BadRequest(new { message = error });
TempData["ReferenceError"] = error;
}
return RedirectToAction("Details", scope.DetailsController, new { id = scope.EntityID, tab = "reference" },
scope.EntityType == StoryElementType.Character && Request.Form["operation"] == "caption"
? "character-gallery" : "story-element-references");

View File

@ -16,8 +16,8 @@ public sealed record StoryElementReferenceScope(StoryElementType EntityType, int
};
}
public sealed record StoryElementReference(int ReferenceID, string Kind, string Note, string? OriginalFileName, byte[] Version);
public sealed record StoryElementReferenceAccess(int ProjectID, string EntityName, bool CanEdit);
public sealed record StoryElementReference(int ReferenceID, string Kind, string Note, string? OriginalFileName, byte[] Version, string? Title, bool IsPrimary);
public sealed record StoryElementReferenceAccess(int ProjectID, string EntityName, bool CanEdit, string? LegacyImagePath);
public sealed record StoryElementReferenceList(StoryElementReferenceScope Scope,
StoryElementReferenceAccess Access, IReadOnlyList<StoryElementReference> Items);
public sealed record StoryElementReferenceFile(string Kind, string StoragePath, string OriginalFileName);
@ -26,6 +26,7 @@ public sealed class StoryElementReferenceChange
public int ProjectID { get; init; }
public bool Changed { get; init; }
public string? StoragePath { get; init; }
public bool QuotaExceeded { get; init; }
}
public sealed class StoryElementReferenceRepository(ISqlConnectionFactory connections)
@ -52,14 +53,15 @@ public sealed class StoryElementReferenceRepository(ISqlConnectionFactory connec
public async Task<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)
string? storagePath = null, string? originalFileName = null, long? fileSizeBytes = null,
string? title = null, long? storageLimitBytes = 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
StoragePath = storagePath, OriginalFileName = originalFileName, FileSizeBytes = fileSizeBytes, Title = title, StorageLimitBytes = storageLimitBytes
}, commandType: CommandType.StoredProcedure);
}
}

View File

@ -301,6 +301,10 @@ public sealed class ProjectBackupStoryElementReference
public int? CharacterID { get; set; }
public int? LocationID { get; set; }
public int? StoryAssetID { get; set; }
[System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull)]
public string? Title { get; set; }
[System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull)]
public bool? IsPrimary { get; set; }
public string Kind { get; set; } = "";
public string Note { get; set; } = "";
public string? StoragePath { get; set; }

View File

@ -142,8 +142,13 @@ internal static class ProjectBackupGraphValidation
return $"Project backup {entity.Collection}.{link.Column} references a missing or foreign {link.TargetCollection} record.";
}
}
var primaryReferenceOwners = new HashSet<(int? LocationID, int? StoryAssetID)>();
foreach (var reference in backup.Data.StoryElementReferences ?? [])
{
if (reference.Title?.Length > 160 ||
(reference.IsPrimary.HasValue && (reference.IsPrimary != true || reference.Kind != "Image" ||
reference.CharacterID.HasValue || !primaryReferenceOwners.Add((reference.LocationID, reference.StoryAssetID)))))
return "Project backup contains invalid attachment metadata.";
if (new[] { reference.CharacterID, reference.LocationID, reference.StoryAssetID }.Count(id => id.HasValue) != 1 ||
reference.Note is null || reference.Note.Length > 500)
return "Project backup contains an invalid story element reference.";

View File

@ -22,7 +22,7 @@ internal static partial class ProjectBackupStoredFieldContract
["CharacterAttributeTypes"]=("CharacterAttributeTypeID,ProjectID,AttributeName,DataType,IsNormallyStable,SortOrder,IsActive","ProjectID"),
["CharacterEnrichmentEvidence"]=("CharacterEnrichmentEvidenceID,CharacterEnrichmentRunID,CharacterID,SceneID,FieldName,Value,Evidence,Confidence,Source,CreatedUtc","SceneID,Value,Evidence"),
["CharacterEnrichmentRuns"]=("CharacterEnrichmentRunID,ProjectID,BookID,UserID,StoryIntelligenceBookPipelineID,CharacterResolutionVersion,Status,TotalCharacters,ProcessedCharacters,CurrentStage,CurrentMessage,QueuedUtc,StartedUtc,CompletedUtc,FailedUtc,AttemptCount,Model,InputTokens,OutputTokens,TotalTokens,DurationMs,ErrorMessage,ErrorDetail,IsCurrent,UpdatedUtc,CharacterID","StoryIntelligenceBookPipelineID,CurrentStage,CurrentMessage,StartedUtc,CompletedUtc,FailedUtc,Model,InputTokens,OutputTokens,TotalTokens,DurationMs,ErrorMessage,ErrorDetail,CharacterID"),
["StoryElementReferences"]=("ReferenceID,CharacterID,LocationID,StoryAssetID,Kind,Note,StoragePath,OriginalFileName","CharacterID,LocationID,StoryAssetID,StoragePath,OriginalFileName"),
["StoryElementReferences"]=("ReferenceID,CharacterID,LocationID,StoryAssetID,Kind,Note,StoragePath,OriginalFileName,Title,IsPrimary","CharacterID,LocationID,StoryAssetID,StoragePath,OriginalFileName,Title,IsPrimary"),
["CharacterImages"]=("CharacterImageID,CharacterID,ProjectID,ImagePath,ThumbnailPath,Caption,SortOrder,UploadedDateUTC,IsDeleted,DeletedDateUTC","Caption,DeletedDateUTC"),
["CharacterIntelligenceEvidenceEvents"]=("CharacterIntelligenceEvidenceEventID,CharacterIntelligenceProfileID,SceneResultID,FieldName,PreviousValue,NewValue,Evidence,Confidence,IsContradiction,Source,CreatedUtc","PreviousValue,NewValue,Evidence"),
["CharacterIntelligenceProfiles"]=("CharacterIntelligenceProfileID,ImportSessionID,ProjectID,BookID,CanonicalIdentityKey,CanonicalName,ProfileJson,Confidence,NarrativeImportance,IsRecurring,EvidenceVersion,LastUpdatedSceneResultID,CreatedUtc,UpdatedUtc","NarrativeImportance,LastUpdatedSceneResultID"),

View File

@ -0,0 +1,72 @@
using System.IO.Compression;
using System.Text;
namespace PlotLine.Services;
public static class StoryElementAttachmentPolicy
{
public const string AcceptedExtensions = ".png,.jpg,.jpeg,.webp,.mp3,.wav,.flac,.ogg,.pdf,.txt,.csv,.tsv,.docx,.xlsx";
public static bool IsImage(string filename) => Extension(filename) is ".png" or ".jpg" or ".jpeg" or ".webp";
public static string? AudioType(string filename) => Extension(filename) switch
{
".mp3" => "audio/mpeg",
".wav" => "audio/wav",
".flac" => "audio/flac",
".ogg" => "audio/ogg",
_ => null
};
public static bool IsAudio(string filename, ReadOnlySpan<byte> bytes) => Extension(filename) switch
{
".mp3" => bytes.Length >= 4 && (bytes.StartsWith("ID3"u8) ||
(bytes[0] == 0xff && (bytes[1] & 0xe6) == 0xe2)),
".wav" => bytes.Length >= 12 && bytes.StartsWith("RIFF"u8) && bytes[8..].StartsWith("WAVE"u8),
".flac" => bytes.StartsWith("fLaC"u8),
".ogg" => bytes.Length > 27 && bytes.StartsWith("OggS"u8) &&
bytes.Length > 27 + bytes[26] &&
(bytes[(27 + bytes[26])..].StartsWith("OpusHead"u8) ||
bytes[(27 + bytes[26])..].StartsWith("\x01vorbis"u8)),
_ => false
};
public static bool IsPdf(string filename, ReadOnlySpan<byte> bytes) =>
Extension(filename) == ".pdf" && bytes.StartsWith("%PDF-"u8);
public static bool IsAllowedDocument(string filename, byte[] bytes) => Extension(filename) switch
{
".pdf" => IsPdf(filename, bytes),
".txt" or ".csv" or ".tsv" => IsText(bytes),
".docx" => IsOfficeDocument(bytes, "word/document.xml"),
".xlsx" => IsOfficeDocument(bytes, "xl/workbook.xml"),
_ => false
};
private static string Extension(string filename) => Path.GetExtension(filename).ToLowerInvariant();
private static bool IsText(byte[] bytes)
{
try
{
return new UTF8Encoding(false, true).GetString(bytes)
.All(character => !char.IsControl(character) || character is '\r' or '\n' or '\t');
}
catch (DecoderFallbackException) { return false; }
}
private static bool IsOfficeDocument(byte[] bytes, string mainPart)
{
try
{
using var archive = new ZipArchive(new MemoryStream(bytes), ZipArchiveMode.Read);
return archive.GetEntry("[Content_Types].xml") is not null &&
archive.GetEntry(mainPart) is not null &&
!archive.Entries.Any(entry =>
entry.Name.Equals("vbaProject.bin", StringComparison.OrdinalIgnoreCase) ||
entry.FullName.Contains("/embeddings/", StringComparison.OrdinalIgnoreCase) ||
entry.FullName.Contains("/activeX/", StringComparison.OrdinalIgnoreCase));
}
catch (InvalidDataException) { return false; }
}
}

View File

@ -0,0 +1,19 @@
using PlotLine.Data;
using PlotLine.Models;
using PlotLine.ViewModels;
namespace PlotLine.Services;
public sealed record StoryElementReferenceWorkspace(StoryElementReferenceList References, StorageUsage? Storage,
CharacterDetailViewModel? CharacterGallery = null, int GalleryPages = 1)
{
public static async Task<StorageUsage?> ReadStorageAsync(StoryElementReferenceList references,
int userId, IProjectCollaborationRepository collaboration, ISubscriptionService subscriptions)
{
// Account-level totals belong to the account owner, even on a shared project.
var owner = await collaboration.GetOwnerUserIdAsync(references.Access.ProjectID);
if (owner != userId) return null;
try { return await subscriptions.GetStorageUsageAsync(owner.Value); }
catch (SubscriptionLimitException) { return null; }
}
}

View File

@ -0,0 +1,189 @@
SET ANSI_NULLS ON;
GO
SET QUOTED_IDENTIFIER ON;
SET ANSI_PADDING ON;
SET ANSI_WARNINGS ON;
SET ARITHABORT ON;
SET CONCAT_NULL_YIELDS_NULL ON;
SET NUMERIC_ROUNDABORT OFF;
GO
IF COL_LENGTH(N'dbo.StoryElementReferences', N'Title') IS NULL
ALTER TABLE dbo.StoryElementReferences ADD Title nvarchar(160) NULL;
IF COL_LENGTH(N'dbo.StoryElementReferences', N'IsPrimary') IS NULL
ALTER TABLE dbo.StoryElementReferences ADD IsPrimary bit NULL;
GO
IF OBJECT_ID(N'dbo.CK_StoryElementReferences_Primary', N'C') IS NULL
ALTER TABLE dbo.StoryElementReferences ADD CONSTRAINT CK_StoryElementReferences_Primary
CHECK (IsPrimary IS NULL OR (IsPrimary = 1 AND Kind = 'Image' AND CharacterID IS NULL));
GO
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'dbo.StoryElementReferences')
AND name = N'UX_StoryElementReferences_PrimaryLocation')
CREATE UNIQUE INDEX UX_StoryElementReferences_PrimaryLocation ON dbo.StoryElementReferences(LocationID)
WHERE LocationID IS NOT NULL AND IsPrimary = 1;
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'dbo.StoryElementReferences')
AND name = N'UX_StoryElementReferences_PrimaryAsset')
CREATE UNIQUE INDEX UX_StoryElementReferences_PrimaryAsset ON dbo.StoryElementReferences(StoryAssetID)
WHERE StoryAssetID IS NOT NULL AND IsPrimary = 1;
GO
CREATE OR ALTER PROCEDURE dbo.StoryElementReference_Access
@UserID int, @EntityType varchar(12), @EntityID int, @Action varchar(12),
@ReferenceID int = NULL, @Version binary(8) = NULL, @Kind varchar(14) = NULL,
@Note nvarchar(500) = NULL, @StoragePath nvarchar(1000) = NULL,
@OriginalFileName nvarchar(300) = NULL, @FileSizeBytes bigint = NULL,
@Title nvarchar(160) = NULL, @StorageLimitBytes bigint = NULL
AS
BEGIN
SET NOCOUNT ON;
SET XACT_ABORT ON;
DECLARE @ProjectID int, @EntityName nvarchar(300), @CanEdit bit, @OwnerID int,
@CharacterID int, @LocationID int, @AssetID int, @LegacyImagePath nvarchar(1000);
BEGIN TRY
BEGIN TRANSACTION;
IF @EntityType = 'Character'
BEGIN
SET @CharacterID = @EntityID;
SELECT @ProjectID = ProjectID, @EntityName = CharacterName
FROM dbo.Characters WITH (HOLDLOCK) WHERE CharacterID = @EntityID AND IsArchived = 0;
END
ELSE IF @EntityType = 'Location'
BEGIN
SET @LocationID = @EntityID;
SELECT @ProjectID = ProjectID, @EntityName = LocationName
FROM dbo.Locations WITH (HOLDLOCK) WHERE LocationID = @EntityID AND IsArchived = 0;
END
ELSE IF @EntityType = 'Asset'
BEGIN
SET @AssetID = @EntityID;
SELECT @ProjectID = ProjectID, @EntityName = AssetName, @LegacyImagePath = ImagePath
FROM dbo.StoryAssets WITH (HOLDLOCK) WHERE StoryAssetID = @EntityID AND IsArchived = 0;
END
SELECT @CanEdit = CONVERT(bit, MAX(CASE WHEN a.AccessRole IN (N'Owner', N'Collaborator') THEN 1 ELSE 0 END))
FROM dbo.ProjectUserAccess a WITH (HOLDLOCK)
INNER JOIN dbo.Projects p WITH (HOLDLOCK) ON p.ProjectID = a.ProjectID AND p.IsArchived = 0
WHERE a.ProjectID = @ProjectID AND a.UserID = @UserID AND a.IsActive = 1;
IF @CanEdit IS NULL OR (@Action NOT IN ('list', 'file') AND @CanEdit = 0)
BEGIN
IF @Action = 'list'
SELECT @ProjectID AS ProjectID, @EntityName AS EntityName, @CanEdit AS CanEdit,
@LegacyImagePath AS LegacyImagePath WHERE 1 = 0;
COMMIT;
RETURN;
END
IF @Action = 'list'
BEGIN
SELECT @ProjectID AS ProjectID, @EntityName AS EntityName, @CanEdit AS CanEdit, @LegacyImagePath AS LegacyImagePath;
SELECT ReferenceID, Kind, Note, OriginalFileName, Version, Title, CONVERT(bit, COALESCE(IsPrimary, 0)) AS IsPrimary
FROM dbo.StoryElementReferences
WHERE CharacterID = @CharacterID OR LocationID = @LocationID OR StoryAssetID = @AssetID
ORDER BY ReferenceID;
END
ELSE IF @Action = 'file'
BEGIN
SELECT Kind, StoragePath, OriginalFileName
FROM dbo.StoryElementReferences
WHERE ReferenceID = @ReferenceID AND StoragePath IS NOT NULL
AND (CharacterID = @CharacterID OR LocationID = @LocationID OR StoryAssetID = @AssetID);
END
ELSE IF @Action = 'add'
BEGIN
IF @StoragePath IS NOT NULL
BEGIN
SELECT TOP (1) @OwnerID = UserID FROM dbo.ProjectUserAccess WITH (HOLDLOCK)
WHERE ProjectID = @ProjectID AND AccessRole = N'Owner' AND IsActive = 1
ORDER BY ProjectUserAccessID;
IF @OwnerID IS NULL THROW 51010, 'Project owner unavailable.', 1;
IF @StorageLimitBytes IS NOT NULL AND @FileSizeBytes >
@StorageLimitBytes - (SELECT COALESCE(SUM(FileSizeBytes), 0)
FROM dbo.UserFile WITH (UPDLOCK, HOLDLOCK) WHERE UserID = @OwnerID AND IsDeleted = 0)
BEGIN
SELECT @ProjectID AS ProjectID, CONVERT(bit, 0) AS Changed, CONVERT(bit, 1) AS QuotaExceeded;
COMMIT;
RETURN;
END
END
INSERT dbo.StoryElementReferences (CharacterID, LocationID, StoryAssetID, Kind, Note, StoragePath, OriginalFileName)
VALUES (@CharacterID, @LocationID, @AssetID, @Kind, @Note, @StoragePath, @OriginalFileName);
IF @StoragePath IS NOT NULL
INSERT dbo.UserFile (UserID, ProjectID, EntityType, EntityID, FileName, OriginalFileName, ContentType, FileSizeBytes, StoragePath)
VALUES (@OwnerID, @ProjectID, N'StoryElementReference', CONVERT(int, SCOPE_IDENTITY()),
RIGHT(@StoragePath, CHARINDEX('/', REVERSE(@StoragePath)) - 1), @OriginalFileName,
CASE @Kind WHEN 'Image' THEN N'image/webp' ELSE N'application/octet-stream' END, @FileSizeBytes, @StoragePath);
SELECT @ProjectID AS ProjectID, CONVERT(bit, 1) AS Changed;
END
ELSE IF @Action = 'caption'
BEGIN
UPDATE dbo.CharacterImages SET Caption = NULLIF(@Note, N'')
WHERE CharacterImageID = @ReferenceID AND CharacterID = @CharacterID AND ProjectID = @ProjectID AND IsDeleted = 0;
SELECT @ProjectID AS ProjectID, CONVERT(bit, @@ROWCOUNT) AS Changed;
END
ELSE IF @Action IN ('primary', 'clear')
BEGIN
DECLARE @LockResult int, @Resource nvarchar(255) = CONCAT(N'StoryReferencePrimary:', @EntityType, N':', @EntityID);
EXEC @LockResult = sys.sp_getapplock @Resource = @Resource, @LockMode = 'Exclusive',
@LockOwner = 'Transaction', @LockTimeout = 5000;
IF @LockResult < 0 THROW 51010, 'Primary image selection is busy.', 1;
DECLARE @ImageID int;
SELECT @ImageID = ReferenceID FROM dbo.StoryElementReferences WITH (UPDLOCK)
WHERE ReferenceID = @ReferenceID AND Version = @Version AND Kind = 'Image'
AND (@Action = 'primary' OR IsPrimary = 1)
AND (LocationID = @LocationID OR StoryAssetID = @AssetID);
IF @ImageID IS NOT NULL
BEGIN
UPDATE dbo.StoryElementReferences
SET IsPrimary = NULL
WHERE IsPrimary = 1 AND (LocationID = @LocationID OR StoryAssetID = @AssetID);
IF @Action = 'primary'
UPDATE dbo.StoryElementReferences SET IsPrimary = 1 WHERE ReferenceID = @ImageID;
END
SELECT @ProjectID AS ProjectID, CONVERT(bit, CASE WHEN @ImageID IS NULL THEN 0 ELSE 1 END) AS Changed;
END
ELSE IF @Action = 'edit'
BEGIN
UPDATE dbo.StoryElementReferences SET Note = @Note, Title = @Title
WHERE ReferenceID = @ReferenceID AND Version = @Version
AND (Kind <> 'Characteristic' OR LEN(@Note) > 0)
AND (CharacterID = @CharacterID OR LocationID = @LocationID OR StoryAssetID = @AssetID);
SELECT @ProjectID AS ProjectID, CONVERT(bit, @@ROWCOUNT) AS Changed;
END
ELSE IF @Action = 'delete'
BEGIN
DECLARE @Removed TABLE (StoragePath nvarchar(1000));
DELETE dbo.StoryElementReferences
OUTPUT deleted.StoragePath INTO @Removed
WHERE ReferenceID = @ReferenceID AND Version = @Version
AND (CharacterID = @CharacterID OR LocationID = @LocationID OR StoryAssetID = @AssetID);
SELECT @ProjectID AS ProjectID, CONVERT(bit, COUNT(*)) AS Changed, MAX(StoragePath) AS StoragePath
FROM @Removed;
END
COMMIT;
END TRY
BEGIN CATCH
IF XACT_STATE() <> 0 ROLLBACK;
THROW;
END CATCH
END;
GO
CREATE OR ALTER PROCEDURE dbo.StoryElementReference_Backup @ProjectID int
AS
BEGIN
SET NOCOUNT ON;
SELECT r.ReferenceID, r.CharacterID, r.LocationID, r.StoryAssetID,
r.Kind, r.Note, r.StoragePath, r.OriginalFileName, r.Title, r.IsPrimary
FROM dbo.StoryElementReferences r
LEFT JOIN dbo.Characters c ON c.CharacterID = r.CharacterID
LEFT JOIN dbo.Locations l ON l.LocationID = r.LocationID
LEFT JOIN dbo.StoryAssets a ON a.StoryAssetID = r.StoryAssetID
WHERE COALESCE(c.ProjectID, l.ProjectID, a.ProjectID) = @ProjectID
ORDER BY r.ReferenceID;
END;
GO

View File

@ -1,16 +1,21 @@
using Microsoft.AspNetCore.Mvc;
using PlotLine.Data;
using PlotLine.Services;
using PlotLine.ViewModels;
namespace PlotLine.ViewComponents;
public sealed class StoryElementReferencesViewComponent(
ICurrentUserService currentUser, StoryElementReferenceRepository references) : ViewComponent
ICurrentUserService currentUser, StoryElementReferenceRepository references,
IProjectCollaborationRepository collaboration, ISubscriptionService subscriptions) : ViewComponent
{
public async Task<IViewComponentResult> InvokeAsync(StoryElementType entityType, int entityId)
public async Task<IViewComponentResult> InvokeAsync(StoryElementType entityType, int entityId,
CharacterDetailViewModel? characterGallery = null, int galleryPages = 1)
{
if (currentUser.UserId is not int userId) return Content("");
var model = await references.ListAsync(userId, new(entityType, entityId));
return model is null ? Content("") : View(model);
return model is null ? Content("") : View(new StoryElementReferenceWorkspace(model,
await StoryElementReferenceWorkspace.ReadStorageAsync(model, userId, collaboration, subscriptions),
characterGallery, galleryPages));
}
}

View File

@ -17,6 +17,8 @@
@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{
<link rel="stylesheet" href="~/css/story-element-references.css" asp-append-version="true" />
<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,10 +1,6 @@
@model CharacterDetailViewModel
<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>
<p class="muted mb-0">Keep portraits, full-body references, clothing notes, expressions, and inspiration images together.</p>
</div>
@if (Model.WorkspaceCanEdit && !string.IsNullOrWhiteSpace(Model.Character.AvatarImagePath))
{
<form asp-action="RemoveAvatar" method="post" class="archive-button-form" data-confirm-message="Remove this character avatar?&#10;&#10;The gallery images will be kept." asp-controller="Characters">
@ -14,19 +10,6 @@
}
</div>
<form hidden="@(!Model.WorkspaceCanEdit)" asp-action="UploadImage" method="post" enctype="multipart/form-data" data-character-gallery-upload class="character-gallery-upload mb-3" asp-controller="Characters">
<input type="hidden" name="CharacterID" value="@Model.Character.CharacterID" />
<div>
<label class="form-label" for="ImageUpload">Add image</label>
<input class="form-control" id="ImageUpload" name="ImageUpload" type="file" accept=".jpg,.jpeg,.png,.webp,image/jpeg,image/png,image/webp" />
</div>
<div>
<label class="form-label" for="Caption">Caption</label>
<input class="form-control" id="Caption" name="Caption" maxlength="500" placeholder="Optional description" />
</div>
<button class="btn btn-primary" type="submit">Upload</button>
</form>
@if (!Model.Images.Any())
{
<p class="muted">No gallery images yet.</p>
@ -38,7 +21,7 @@
{
var isAvatarSource = Model.Character.AvatarSourceCharacterImageID == image.CharacterImageID;
<article class="character-gallery-card">
<img src="@image.ThumbnailPath" alt="" loading="lazy" />
<a href="@image.ImagePath" target="_blank" rel="noopener"><img src="@image.ThumbnailPath" alt="@(image.Caption ?? "Character reference")" loading="lazy" /></a>
<div class="character-gallery-card__body">
<strong>@(string.IsNullOrWhiteSpace(image.Caption) ? "Character reference" : image.Caption)</strong>
<span class="muted">Uploaded @image.UploadedDateUTC.ToLocalTime().ToString("yyyy-MM-dd")</span>

View File

@ -5,8 +5,9 @@
<partial name="/Views/Characters/_WorkspaceProfile.cshtml" model="Model.Profile"/>
<section class="plain-card"><h2>Recent recorded changes</h2>@if(!Model.Entries.Any()){<p class="muted">No changes recorded yet.</p>}else{foreach(var entry in Model.Entries){<p><strong>@entry.Heading</strong> · @entry.State <span class="small">@entry.BookDisplayTitle · @entry.SceneTitle</span></p>}}<a data-workspace-go="evolution" href="?tab=evolution">Explore evolution</a></section>
}else if(q.Tab=="reference"){
@await Component.InvokeAsync("StoryElementReferences", new { entityType = PlotLine.Data.StoryElementType.Character, entityId = c.CharacterID })
<details id="character-gallery" data-workspace-gallery><summary>Portraits and reference gallery (@Model.Total)</summary><div data-gallery-content>@{Model.Profile.Images=Model.Images;}<partial name="/Views/Characters/_WorkspaceGallery.cshtml" model="Model.Profile"/>@if(totalPages>1){<button type="button" class="btn btn-outline-secondary" data-gallery-page="2">More gallery images</button>}</div></details>
Model.Profile.Images=Model.Images;
@await Component.InvokeAsync("StoryElementReferences", new { entityType = PlotLine.Data.StoryElementType.Character,
entityId = c.CharacterID, characterGallery = Model.Profile, galleryPages = totalPages })
}else if(q.Tab=="gallery"){
Model.Profile.Images=Model.Images;<partial name="/Views/Characters/_WorkspaceGallery.cshtml" model="Model.Profile"/>
<div class="button-row">@if(q.Page>1){<button type="button" class="btn btn-outline-secondary" data-gallery-page="@(q.Page-1)">Previous images</button>}<span>Page @q.Page of @totalPages</span>@if(q.Page<totalPages){<button type="button" class="btn btn-outline-secondary" data-gallery-page="@(q.Page+1)">Next images</button>}</div>

View File

@ -29,6 +29,7 @@
<div class="location-page">
<div data-pd-context="location" data-pd-context-id="@Model.Location.LocationID" data-pd-context-label="@Model.Location.LocationName" data-pwa-help class="page-heading compact">
<span class="visual-avatar visual-avatar--lg" data-reference-primary-preview hidden><img alt="" /></span>
<partial name="_LocationIdentity" model="@((Model.Location.LocationName, (string?)Model.Project.ProjectName, Model.Location.LocationPath, "locations.details"))" />
<div data-pwa-context="Manage" class="button-row">
<a class="btn btn-outline-primary" asp-action="Index" asp-route-projectId="@Model.Project.ProjectID">All locations</a>
@ -238,6 +239,7 @@
@section Scripts {
<script src="~/js/location-geography.js" asp-append-version="true" defer></script>
<link rel="stylesheet" href="~/css/story-element-references.css" asp-append-version="true" />
<script src="~/js/story-element-references.js" asp-append-version="true"></script>
<script>
(() => {

View File

@ -128,6 +128,7 @@
@section Scripts {
<partial name="_ValidationScriptsPartial" />
<link rel="stylesheet" href="~/css/story-element-references.css" asp-append-version="true" />
<script src="~/js/story-element-references.js" asp-append-version="true"></script>
<script>
$(function () {

View File

@ -1,111 +1,177 @@
@using PlotLine.Data
@model StoryElementReferenceList
@using PlotLine.Services
@model StoryElementReferenceWorkspace
@{
var scope = Model.Scope;
var references = Model.References;
var scope = references.Scope;
var routes = new Dictionary<string, string>
{
["entityType"] = scope.EntityType.ToString(),
["entityId"] = scope.EntityID.ToString()
};
var isCharacter = scope.EntityType == StoryElementType.Character;
var referenceTab = scope.EntityType is StoryElementType.Character or StoryElementType.Location ? "reference" : null;
var refreshUrl = Url.Action("Details", scope.DetailsController, new { id = scope.EntityID, tab = referenceTab },
protocol: null, host: null, fragment: "story-element-references");
var refreshUrl = scope.EntityType == StoryElementType.Character && Model.CharacterGallery is not null
? Url.Action("Tab", "CharacterWorkspace", new { id = scope.EntityID, tab = "reference" })
: Url.Action("List", "StoryElementReferences", new { entityType = scope.EntityType, entityId = scope.EntityID });
string? FileUrl(StoryElementReference item, bool save = false) => Url.Action("Download", "StoryElementReferences",
new { entityType = scope.EntityType, entityId = scope.EntityID, referenceId = item.ReferenceID, save });
var editable = references.Access.CanEdit;
var tabs = new[] { "Images", "Audio", "Documents" };
var primary = references.Items.FirstOrDefault(item => item.IsPrimary);
}
<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" href="@refreshUrl">Refresh references</a>
</div>
<section id="story-element-references" class="reference-workspace"
data-story-element-references data-project-id="@references.Access.ProjectID"
data-reference-key="@scope.EntityType-@scope.EntityID" data-refresh-url="@refreshUrl"
data-primary-image="@(primary is null ? null : FileUrl(primary))"
aria-label="Reference workspace">
@if (TempData["ReferenceSaved"] is string saved)
{
<span hidden data-toast-message="success">@saved</span>
}
@if (TempData["ReferenceError"] is string error)
@if (scope.EntityType == StoryElementType.Asset && TempData["AssetImageSaved"] is string legacySaved)
{
<p class="alert alert-warning" role="alert">@error</p>
<span hidden data-toast-message="success">@legacySaved</span>
}
@foreach (var kind in new[] { "Characteristic", "Image", "Attachment" })
@if (scope.EntityType == StoryElementType.Asset && TempData["ImageError"] is string legacyError)
{
var label = kind switch { "Characteristic" => "Key characteristics", "Image" => "Images", _ => "Attachments" };
if (kind == "Image" && isCharacter)
{
continue;
}
var items = Model.Items.Where(item => item.Kind == kind).ToList();
<div class="mt-3">
<h3>@label</h3>
@if (items.Count == 0)
<p class="alert alert-warning" role="alert">@legacyError</p>
}
<p class="alert alert-warning" role="alert" data-reference-error hidden="@(TempData.Peek("ReferenceError") is null)">@TempData["ReferenceError"]</p>
<div class="reference-workspace__panes">
<section class="reference-workspace__pane" data-reference-scroll aria-labelledby="reference-characteristics">
<h2 id="reference-characteristics">Key characteristics</h2>
@if (editable)
{
<p class="muted">No @label.ToLowerInvariant() yet.</p>
<form asp-controller="StoryElementReferences" asp-action="Add" asp-all-route-data="routes" method="post"
data-story-reference-form class="reference-workspace__quick-add">
<input type="hidden" name="kind" value="Characteristic" />
<input class="form-control form-control-sm" name="note" placeholder="Add a characteristic"
aria-label="New characteristic" maxlength="500" required />
<button class="btn btn-primary btn-sm">Add</button>
</form>
}
@foreach (var item in items)
@foreach (var item in references.Items.Where(item => item.Kind == "Characteristic"))
{
<article class="border rounded p-2 mb-2">
@if (item.OriginalFileName is not null)
<article class="reference-workspace__row">
<span class="text-break">@item.Note</span>
@if (editable)
{
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>
<partial name="Components/StoryElementReferences/_ReferenceActions" model="(item, routes)" />
}
</article>
}
@if (Model.Access.CanEdit)
@if (!references.Items.Any(item => item.Kind == "Characteristic"))
{
<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>
<p class="muted small">No characteristics yet.</p>
}
</div>
}
</section>
<div class="reference-workspace__divider" role="separator" aria-label="Resize characteristics"
aria-orientation="vertical" tabindex="0" aria-valuemin="25" aria-valuemax="70"
aria-valuenow="40" data-reference-divider></div>
<section class="reference-workspace__pane" data-reference-scroll aria-labelledby="reference-attachments">
<div class="d-flex flex-wrap align-items-baseline justify-content-between gap-2">
<h2 id="reference-attachments">Attachments</h2>
@if (Model.Storage is not null)
{
<small class="muted" title="Account storage used and subscription allowance">Storage @Model.Storage.DisplayLabel</small>
}
</div>
<div class="reference-workspace__tabs" role="tablist" aria-label="Attachment type">
@foreach (var tab in tabs)
{
<button type="button" class="btn btn-sm" role="tab" id="reference-tab-@tab"
aria-controls="reference-panel-@tab" aria-selected="@(tab == "Images" ? "true" : "false")"
tabindex="@(tab == "Images" ? 0 : -1)" data-reference-tab="@tab">@tab</button>
}
</div>
@foreach (var tab in tabs)
{
var items = references.Items.Where(item => item.Kind != "Characteristic" &&
tab == (item.Kind == "Image" ? "Images" :
StoryElementAttachmentPolicy.AudioType(item.OriginalFileName ?? "") is not null ? "Audio" : "Documents")).ToList();
<section role="tabpanel" id="reference-panel-@tab" aria-labelledby="reference-tab-@tab"
data-reference-tab-panel="@tab" hidden="@(tab != "Images")">
@if (editable)
{
<form asp-controller="StoryElementReferences" asp-action="Add" asp-all-route-data="routes" method="post"
enctype="multipart/form-data" class="reference-workspace__drop" data-story-reference-form data-reference-upload>
<label class="form-label mb-0">
Drop files here or browse <small class="muted">(up to 10 MB each)</small>
<input class="form-control form-control-sm" type="file" name="upload"
accept="@StoryElementAttachmentPolicy.AcceptedExtensions" required />
</label>
<button class="btn btn-primary btn-sm">Upload</button>
</form>
}
@if (tab == "Images" && Model.CharacterGallery is not null)
{
<div id="character-gallery" data-workspace-gallery data-gallery-content>
<partial name="/Views/Characters/_WorkspaceGallery.cshtml" model="Model.CharacterGallery" />
@if (Model.GalleryPages > 1)
{
<button type="button" class="btn btn-outline-secondary btn-sm" data-gallery-page="2">More gallery images</button>
}
</div>
}
@if (tab == "Images" && references.Access.LegacyImagePath is string legacyImage)
{
<article class="reference-workspace__row">
<a href="@legacyImage" target="_blank" rel="noopener">
<img class="reference-workspace__preview" src="@legacyImage" alt="Existing asset image" loading="lazy" />
</a>
<span>@(primary is null ? "Primary image" : "Previous asset image")</span>
@if (editable)
{
<form asp-controller="StoryAssets" asp-action="SaveImage" asp-route-id="@scope.EntityID" method="post">
<button class="btn btn-outline-danger btn-sm" name="operation" value="remove">Remove</button>
</form>
}
</article>
}
@if (items.Count == 0 && (tab != "Images" || Model.CharacterGallery is null && references.Access.LegacyImagePath is null))
{
<p class="muted small mt-2">No @tab.ToLowerInvariant() yet.</p>
}
<div class="@(tab == "Images" ? "reference-workspace__gallery" : null)">
@foreach (var item in items)
{
var url = FileUrl(item);
<article class="reference-workspace__file">
@if (tab == "Images")
{
<a href="@url" target="_blank" rel="noopener">
<img class="reference-workspace__preview" src="@url" alt="@(item.Note.Length > 0 ? item.Note : item.OriginalFileName)" loading="lazy" />
</a>
}
<strong class="text-break">@(item.Title ?? item.OriginalFileName)</strong>
@if (item.IsPrimary)
{
<small class="muted">Primary image</small>
}
@if (item.Note.Length > 0)
{
<p class="mb-1 text-break">@item.Note</p>
}
@if (tab == "Audio")
{
<audio controls preload="none" src="@url">Use Download to play this file.</audio>
}
<div class="d-flex align-items-center flex-wrap gap-2">
@if (tab == "Documents")
{
<a href="@url" target="_blank" rel="noopener">Open</a>
}
<a href="@FileUrl(item, true)">Download</a>
<button type="button" class="btn btn-outline-secondary btn-sm" data-reference-copy="@url" hidden>Copy link</button>
@if (editable)
{
<partial name="Components/StoryElementReferences/_ReferenceActions" model="(item, routes)" />
}
</div>
</article>
}
</div>
</section>
}
</section>
</div>
</section>

View File

@ -0,0 +1,39 @@
@using PlotLine.Data
@model (StoryElementReference Item, Dictionary<string, string> Routes)
@{
var item = Model.Item;
var version = Convert.ToBase64String(item.Version);
var noteLabel = item.Kind switch { "Characteristic" => "Characteristic", "Image" => "Caption", _ => "Description" };
}
<details class="reference-workspace__edit">
<summary>Edit</summary>
<form asp-controller="StoryElementReferences" asp-action="Change" asp-all-route-data="Model.Routes"
method="post" data-story-reference-form>
<input type="hidden" name="referenceId" value="@item.ReferenceID" />
<input type="hidden" name="version" value="@version" />
@if (item.Kind == "Attachment")
{
<label class="form-label d-block">Title
<input class="form-control form-control-sm" name="title" maxlength="160" value="@item.Title" placeholder="@item.OriginalFileName" />
</label>
}
<label class="form-label d-block">@noteLabel
<textarea class="form-control form-control-sm" name="note" maxlength="500" rows="2"
required="@(item.Kind == "Characteristic")">@item.Note</textarea>
</label>
<button class="btn btn-primary btn-sm" name="operation" value="edit">Save</button>
</form>
</details>
<form asp-controller="StoryElementReferences" asp-action="Change" asp-all-route-data="Model.Routes"
method="post" data-story-reference-form>
<input type="hidden" name="referenceId" value="@item.ReferenceID" />
<input type="hidden" name="version" value="@version" />
@if (item.Kind == "Image" && Model.Routes["entityType"] != "Character")
{
<button class="btn btn-outline-secondary btn-sm" name="operation" value="@(item.IsPrimary ? "clear" : "primary")">
@(item.IsPrimary ? "Clear primary" : "Set primary")
</button>
}
<button class="btn btn-outline-danger btn-sm" name="operation" value="delete"
aria-label="Delete @(item.Title ?? item.OriginalFileName ?? item.Note)">Delete</button>
</form>

View File

@ -65,7 +65,6 @@
</div>
<div class="tab-pane @(activeTab == "reference" ? "active" : null)" id="asset-panel-reference" role="tabpanel"
aria-labelledby="asset-tab-reference" tabindex="0">
<partial name="_AssetPrimaryImage" model="@((Model.Asset.StoryAssetID, Model.Asset.AssetName, Model.Asset.ImagePath, Model.Asset.ThumbnailPath))" />
@await Component.InvokeAsync("StoryElementReferences", new { entityType = PlotLine.Data.StoryElementType.Asset, entityId = Model.Asset.StoryAssetID })
</div>
<div class="tab-pane @(activeTab == "dependencies" ? "active" : null)" id="asset-panel-dependencies" role="tabpanel"
@ -187,5 +186,6 @@
</div>
@section Scripts {
<link rel="stylesheet" href="~/css/story-element-references.css" asp-append-version="true" />
<script src="~/js/story-element-references.js" asp-append-version="true"></script>
}

View File

@ -1,6 +1,10 @@
@model (AvatarViewModel Avatar, string? ProjectName, string? Kind, string HelpKey)
<partial name="_Avatar" model="Model.Avatar" />
@if (Model.HelpKey == "storyAssets.details")
{
<span class="visual-avatar visual-avatar--xl" data-reference-primary-preview hidden><img alt="" /></span>
}
<div>
<p class="eyebrow">@(Model.ProjectName is string projectName ? $"{projectName} · Story asset" : "Story asset")</p>
<h1>@Model.Avatar.DisplayName <help-icon key="@Model.HelpKey" /></h1>

View File

@ -1,30 +0,0 @@
@model (int Id, string Name, string? ImagePath, string? ThumbnailPath)
<section class="plain-card mb-3" aria-labelledby="asset-primary-image-heading">
<h2 id="asset-primary-image-heading">Asset image</h2>
@if (TempData["ImageError"] is string imageError)
{
<div class="alert alert-warning" role="alert">@imageError</div>
}
@if (TempData["AssetImageSaved"] is string imageSaved)
{
<span hidden data-toast-message="success">@imageSaved</span>
}
<div class="visual-image-editor flex-wrap">
<partial name="_Avatar" model="@(new AvatarViewModel { DisplayName = Model.Name, ImagePath = Model.ImagePath, ThumbnailPath = Model.ThumbnailPath, Size = "lg", Lazy = false })" />
<form asp-action="SaveImage" method="post" enctype="multipart/form-data" class="visual-image-editor__controls mw-100">
<input type="hidden" name="id" value="@Model.Id" />
<label for="asset-primary-image-upload" class="form-label">Upload image</label>
<input id="asset-primary-image-upload" name="upload" class="form-control" type="file"
accept=".jpg,.jpeg,.png,.webp,image/jpeg,image/png,image/webp" aria-describedby="asset-primary-image-format" />
<div id="asset-primary-image-format" class="form-text">JPG, PNG or WebP. A 128 × 128 thumbnail is generated automatically.</div>
<div class="button-row mt-2">
<button class="btn btn-outline-primary" type="submit" name="operation" value="upload">Save image</button>
@if (!string.IsNullOrWhiteSpace(Model.ImagePath) || !string.IsNullOrWhiteSpace(Model.ThumbnailPath))
{
<button class="btn btn-outline-secondary" type="submit" name="operation" value="remove">Remove image</button>
}
</div>
</form>
</div>
</section>

View File

@ -0,0 +1,89 @@
.reference-workspace__panes {
display: grid;
grid-template-columns: minmax(0, var(--reference-divider, 40%)) .75rem minmax(0, 1fr);
min-height: 21rem;
height: min(65vh, 48rem);
}
.reference-workspace__pane {
overflow: auto;
padding: .75rem;
}
.reference-workspace__pane h2 { font-size: 1.15rem; }
.reference-workspace__divider {
cursor: col-resize;
touch-action: none;
position: relative;
}
.reference-workspace__divider::after {
content: "";
position: absolute;
inset: 0 calc(50% - 1px);
background: currentColor;
opacity: .25;
}
.reference-workspace__divider:is(:hover, :focus-visible)::after { opacity: .8; }
.reference-workspace__quick-add,
.reference-workspace__row,
.reference-workspace__tabs,
.reference-workspace__drop {
display: flex;
align-items: center;
gap: .5rem;
}
.reference-workspace__row,
.reference-workspace__file {
padding: .5rem 0;
border-bottom: 1px solid var(--bs-border-color, #aab3be);
}
.reference-workspace__row { flex-wrap: wrap; }
.reference-workspace__row > span { flex: 1 1 8rem; }
.reference-workspace__row > .reference-workspace__edit[open] { flex-basis: 100%; }
.reference-workspace__edit form { padding: .5rem 0; }
.reference-workspace__tabs { flex-wrap: wrap; margin-bottom: .5rem; }
.reference-workspace__tabs [aria-selected="true"] { border-color: currentColor; font-weight: 600; }
.reference-workspace__drop {
flex-wrap: wrap;
padding: .75rem;
border: 1px dashed currentColor;
border-radius: .4rem;
}
.reference-workspace__drop[data-drag-over] { outline: 2px solid currentColor; }
.reference-workspace__drop label { flex: 1 1 13rem; }
.reference-workspace__gallery {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(min(100%, 11rem), 1fr));
gap: .5rem 1rem;
}
.reference-workspace__file { min-width: 0; }
.reference-workspace__file audio { display: block; max-width: 100%; margin: .35rem 0; }
.reference-workspace__preview {
display: block;
width: 100%;
max-width: 15rem;
height: 8rem;
object-fit: contain;
}
.reference-workspace .character-gallery-card > a img {
display: block;
width: 100%;
height: 8rem;
object-fit: contain;
}
@media (max-width: 700px) {
.reference-workspace__panes { display: block; height: auto; }
.reference-workspace__pane { max-height: 65vh; }
.reference-workspace__divider { display: none; }
}
[data-reference-primary-preview][hidden],
.visual-avatar:has(+ [data-reference-primary-preview])[hidden],
.reference-workspace [hidden] { display: none !important; }

View File

@ -1,37 +1,256 @@
(() => {
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;
const workspace = '[data-story-element-references]';
const options = { 'X-Requested-With': 'XMLHttpRequest' };
const states = new WeakMap();
function remember(panel) {
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;
const { tab, width } = states.get(panel);
localStorage.setItem('pd.reference.' + panel.dataset.referenceKey, JSON.stringify({ tab, width }));
} catch {
// The explicit refresh link remains available when a background request fails.
// A restricted browser can still use the current layout.
}
}
function select(panel, name, focus = false) {
states.get(panel).tab = name;
for (const button of panel.querySelectorAll('[data-reference-tab]')) {
const active = button.dataset.referenceTab === name;
button.setAttribute('aria-selected', String(active));
button.tabIndex = active ? 0 : -1;
if (active && focus) button.focus();
}
for (const section of panel.querySelectorAll('[data-reference-tab-panel]')) {
section.hidden = section.dataset.referenceTabPanel !== name;
}
}
function resize(panel, value) {
const width = Math.round(Math.max(25, Math.min(70, value)));
states.get(panel).width = width;
panel.style.setProperty('--reference-divider', width + '%');
panel.querySelector('[data-reference-divider]').setAttribute('aria-valuenow', String(width));
}
function mount(panel) {
if (states.has(panel)) return;
let saved;
try { saved = JSON.parse(localStorage.getItem('pd.reference.' + panel.dataset.referenceKey)); } catch {}
states.set(panel, { busy: false, refreshRequest: null });
select(panel, ['Images', 'Audio', 'Documents'].includes(saved?.tab) ? saved.tab : 'Images');
if (navigator.clipboard) {
for (const button of panel.querySelectorAll('[data-reference-copy]')) button.hidden = false;
}
resize(panel, Number.isFinite(saved?.width) ? saved.width : 40);
for (const input of panel.querySelectorAll('[data-reference-upload] input[type=file]')) input.multiple = true;
const source = panel.dataset.primaryImage;
const display = document.querySelector('[data-reference-primary-preview]');
if (display) {
display.hidden = !source;
const image = display.querySelector('img');
if (source) image.setAttribute('src', source);
else image.removeAttribute('src');
if (display.previousElementSibling?.classList.contains('visual-avatar')) {
display.previousElementSibling.hidden = !!source;
}
}
}
function error(panel, message) {
const region = panel.querySelector('[data-reference-error]');
region.textContent = message;
region.hidden = !message;
}
function isEditing(panel) {
return panel.contains(document.activeElement) || !!panel.querySelector('details[open], input[type=file]:valid');
}
async function refresh(panel, afterSave = false) {
const state = states.get(panel);
if (!panel.isConnected || (!afterSave && (state.refreshRequest || state.busy || isEditing(panel)))) return;
state.refreshRequest?.abort();
const request = new AbortController();
state.refreshRequest = request;
try {
const signal = AbortSignal.any([request.signal, AbortSignal.timeout(15000)]);
const response = await fetch(panel.dataset.refreshUrl, { cache: 'no-store', signal });
if (!response.ok || response.redirected) throw new Error();
const html = new DOMParser().parseFromString(await response.text(), 'text/html');
const updated = html.querySelector(workspace);
if (!updated) throw new Error();
if (request.signal.aborted || !panel.isConnected || (!afterSave && (state.busy || isEditing(panel)))) return;
const scroll = [...panel.querySelectorAll('[data-reference-scroll]')].map(pane => pane.scrollTop);
remember(panel);
panel.replaceWith(updated);
mount(updated);
updated.querySelectorAll('[data-reference-scroll]').forEach((pane, index) => pane.scrollTop = scroll[index]);
return updated;
} finally {
if (state.refreshRequest === request) state.refreshRequest = null;
}
}
async function post(form, data) {
const response = await fetch(form.action, {
method: 'POST', body: data, headers: options, signal: AbortSignal.timeout(45000)
});
const json = response.headers.get('content-type')?.includes('application/json') && await response.json();
if (response.status === 400 && json?.message) return json.message;
if (!response.ok || response.redirected || !json?.message) throw new Error();
return null;
}
async function save(panel, form, submitter, files) {
mount(panel);
const state = states.get(panel);
if (state.busy) return;
state.busy = true;
panel.setAttribute('aria-busy', 'true');
error(panel, '');
let saved = 0;
let current = panel;
const issues = [];
const quickAdd = form.matches('.reference-workspace__quick-add');
try {
if (files) {
for (const file of files) {
if (file.size === 0 || file.size > 10 * 1024 * 1024) {
issues.push(file.name + ' must be non-empty and no larger than 10 MB.');
continue;
}
const data = new FormData(form);
data.set('upload', file);
const message = await post(form, data);
if (message) issues.push(file.name + ' — ' + message);
else saved++;
}
} else {
const message = await post(form, new FormData(form, submitter));
if (message) issues.push(message);
else saved++;
}
} catch {
issues.push('The last change could not be confirmed. Refresh the workspace before retrying.');
}
if (saved) {
try {
current = await refresh(panel, true) ?? panel;
if (current === panel && panel.isConnected) throw new Error();
delete form.dataset.workspaceDirty;
if (quickAdd) current.querySelector('.reference-workspace__quick-add input[name=note]')?.focus();
window.PlotDirector?.toast?.success(files ? `${saved} file${saved === 1 ? '' : 's'} added.` : 'References updated.');
} catch {
issues.push('Changes were saved. Refresh the page to see them.');
}
}
state.busy = false;
panel.removeAttribute('aria-busy');
if (issues.length) error(current, issues.join(' '));
}
document.addEventListener('click', event => {
const copy = event.target.closest('[data-reference-copy]');
if (copy) {
const url = new URL(copy.dataset.referenceCopy, location.href);
void navigator.clipboard.writeText(url.href).then(
() => window.PlotDirector?.toast?.success('Attachment link copied.'),
() => window.PlotDirector?.toast?.error('The attachment link could not be copied.'));
return;
}
const button = event.target.closest('[data-reference-tab]');
if (!button) return;
const panel = button.closest(workspace);
mount(panel);
select(panel, button.dataset.referenceTab);
remember(panel);
});
document.addEventListener('keydown', event => {
const control = event.target.closest('[data-reference-tab], [data-reference-divider]');
if (!control || !['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) return;
const panel = control.closest(workspace);
mount(panel);
event.preventDefault();
const previous = event.key === 'ArrowLeft';
if (control.hasAttribute('data-reference-divider')) {
resize(panel, event.key === 'Home' ? 25 : event.key === 'End' ? 70 :
states.get(panel).width + (previous ? -2 : 2));
} else {
const tabs = ['Images', 'Audio', 'Documents'];
const index = tabs.indexOf(control.dataset.referenceTab);
select(panel, tabs[event.key === 'Home' ? 0 : event.key === 'End' ? 2 : (index + (previous ? 2 : 1)) % 3], true);
}
remember(panel);
});
document.addEventListener('pointerdown', event => {
const divider = event.target.closest('[data-reference-divider]');
if (!divider || event.button !== 0) return;
const panel = divider.closest(workspace);
mount(panel);
const bounds = divider.parentElement.getBoundingClientRect();
const move = pointer => {
if (pointer.pointerId === event.pointerId) resize(panel, (pointer.clientX - bounds.left) / bounds.width * 100);
};
divider.setPointerCapture(event.pointerId);
divider.addEventListener('pointermove', move);
divider.addEventListener('lostpointercapture', () => {
divider.removeEventListener('pointermove', move);
remember(panel);
}, { once: true });
});
document.addEventListener('submit', event => {
const form = event.target;
const panel = form.closest(workspace);
if (!panel || !form.matches('[data-story-reference-form]')) return;
event.preventDefault();
const input = form.querySelector('input[type=file]');
void save(panel, form, event.submitter, input ? [...input.files] : null);
});
document.addEventListener('dragover', event => {
const form = event.target.closest('[data-reference-upload]');
if (!form || !event.dataTransfer.types.includes('Files')) return;
event.preventDefault();
form.setAttribute('data-drag-over', '');
});
document.addEventListener('dragleave', event => {
const form = event.target.closest('[data-reference-upload]');
if (form && !form.contains(event.relatedTarget)) form.removeAttribute('data-drag-over');
});
document.addEventListener('drop', event => {
const form = event.target.closest('[data-reference-upload]');
if (!form || !event.dataTransfer.files.length) return;
event.preventDefault();
form.removeAttribute('data-drag-over');
void save(form.closest(workspace), form, null, [...event.dataTransfer.files]);
});
function mountVisible() {
document.querySelectorAll(workspace).forEach(mount);
}
mountVisible();
const characterPanel = document.querySelector('[data-workspace-panel]');
if (characterPanel) new MutationObserver(mountVisible).observe(characterPanel, { childList: true, subtree: true });
let connection;
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();
const update = projectId => document.querySelectorAll(workspace).forEach(panel => {
if (projectId == null || Number(panel.dataset.projectId) === Number(projectId)) {
void refresh(panel).catch(() => {});
}
});
connection.onreconnected(refresh);
connection.on('ContextInvalidated', hint => {
if (['characters', 'locations', 'assets'].includes(hint.kind)) update(hint.projectId);
});
connection.onreconnected(() => update());
}
document.addEventListener('pd-presence-connection', event => connect(event.detail));