From 3f36a214ec6aea369db8e3d7ee2be29460d3a3bc Mon Sep 17 00:00:00 2001 From: "Seb H." <138793908+SebHenn@users.noreply.github.com> Date: Thu, 19 Nov 2026 19:54:17 +0100 Subject: [PATCH 1/7] M28, first part: a staged folder that cannot be removed no longer breaks the import page Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Seb H. <138793908+SebHenn@users.noreply.github.com> --- src/Commonage.Web/Import/ImportStaging.cs | 6 ++-- tests/Commonage.Tests/ImportStagingTests.cs | 33 +++++++++++++++++++++ 2 files changed, 36 insertions(+), 3 deletions(-) create mode 100644 tests/Commonage.Tests/ImportStagingTests.cs diff --git a/src/Commonage.Web/Import/ImportStaging.cs b/src/Commonage.Web/Import/ImportStaging.cs index 367f0a4..2705341 100644 --- a/src/Commonage.Web/Import/ImportStaging.cs +++ b/src/Commonage.Web/Import/ImportStaging.cs @@ -39,7 +39,7 @@ public void Delete(Guid id) if (Directory.Exists(DirectoryOf(id))) Directory.Delete(DirectoryOf(id), recursive: true); } - catch (IOException) + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) { // Left over, and removed with the next old one. } @@ -57,9 +57,9 @@ public void DeleteOld(TimeSpan age, DateTime now) if (now - Directory.GetLastWriteTimeUtc(directory) > age) Directory.Delete(directory, recursive: true); } - catch (IOException) + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) { - // In use, so it is not old. + // In use or not ours to remove, so it stays, and one such folder must not stop the page or the others from being cleared. } } } diff --git a/tests/Commonage.Tests/ImportStagingTests.cs b/tests/Commonage.Tests/ImportStagingTests.cs new file mode 100644 index 0000000..9ade38c --- /dev/null +++ b/tests/Commonage.Tests/ImportStagingTests.cs @@ -0,0 +1,33 @@ +using Commonage.Web.Import; + +namespace Commonage.Tests; + +public sealed class ImportStagingTests : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), "staging-" + Guid.NewGuid().ToString("N")); + + public void Dispose() + { + foreach (var file in Directory.EnumerateFiles(_root, "*", SearchOption.AllDirectories)) + File.SetAttributes(file, FileAttributes.Normal); + Directory.Delete(_root, recursive: true); + } + + [Fact] + public void A_folder_that_cannot_be_removed_stays_and_the_other_old_ones_are_still_cleared() + { + var staging = new ImportStaging(_root); + var stuck = staging.Create(); + var other = staging.Create(); + // A read-only file stops Windows from deleting its folder, which is an UnauthorizedAccessException, not an IOException. + var readOnly = Path.Combine(staging.DirectoryOf(stuck), "sheet.csv"); + File.WriteAllText(readOnly, "a"); + File.SetAttributes(readOnly, FileAttributes.ReadOnly); + File.WriteAllText(staging.CsvPath(other), "b"); + + var exception = Record.Exception(() => staging.DeleteOld(TimeSpan.FromDays(1), DateTime.UtcNow.AddDays(3))); + + Assert.Null(exception); + Assert.False(Directory.Exists(staging.DirectoryOf(other))); + } +} From e169ab2d5161caba2e7dd491a930625e5808e4f1 Mon Sep 17 00:00:00 2001 From: "Seb H." <138793908+SebHenn@users.noreply.github.com> Date: Thu, 19 Nov 2026 20:17:31 +0100 Subject: [PATCH 2/7] M28, second part: read Commonage's own export (reading, limits, drafts only) Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Seb H. <138793908+SebHenn@users.noreply.github.com> --- src/Commonage.Web/Audit/AuditLog.cs | 12 +- src/Commonage.Web/Audit/AuditText.cs | 6 +- src/Commonage.Web/Domain/ArchiveItem.cs | 6 + src/Commonage.Web/Domain/AuditEntry.cs | 2 + src/Commonage.Web/Import/ExportImport.cs | 798 ++++++++++++++++++ src/Commonage.Web/Import/ExportReading.cs | 197 +++++ src/Commonage.Web/Import/ImportLock.cs | 8 + src/Commonage.Web/Import/ImportStaging.cs | 5 + src/Commonage.Web/Import/ItemImport.cs | 2 +- .../Pages/Admin/Items/Import.cshtml.cs | 7 +- src/Commonage.Web/Program.cs | 2 + 11 files changed, 1032 insertions(+), 13 deletions(-) create mode 100644 src/Commonage.Web/Import/ExportImport.cs create mode 100644 src/Commonage.Web/Import/ExportReading.cs create mode 100644 src/Commonage.Web/Import/ImportLock.cs diff --git a/src/Commonage.Web/Audit/AuditLog.cs b/src/Commonage.Web/Audit/AuditLog.cs index 470af55..21d85fe 100644 --- a/src/Commonage.Web/Audit/AuditLog.cs +++ b/src/Commonage.Web/Audit/AuditLog.cs @@ -43,20 +43,20 @@ public void RecordRevision(ArchiveItem item, RevisionField field, string? oldVal }); } - public void Record(AuditAction action, string? subject, ArchiveItem? item = null) + public AuditEntry Record(AuditAction action, string? subject, ArchiveItem? item = null) { var user = httpContextAccessor.HttpContext?.User; var signedIn = user?.Identity?.IsAuthenticated == true; - Add(action, subject, item, signedIn ? user!.FindFirstValue(ClaimTypes.NameIdentifier) : null, signedIn ? user!.Identity!.Name : null); + return Add(action, subject, item, signedIn ? user!.FindFirstValue(ClaimTypes.NameIdentifier) : null, signedIn ? user!.Identity!.Name : null); } /// For what an account does while it logs in, before the request knows who it is. public void RecordFor(Microsoft.AspNetCore.Identity.IdentityUser account, AuditAction action, string? subject) => Add(action, subject, null, account.Id, account.UserName); - private void Add(AuditAction action, string? subject, ArchiveItem? item, string? userId, string? userName) + private AuditEntry Add(AuditAction action, string? subject, ArchiveItem? item, string? userId, string? userName) { - db.AuditEntries.Add(new AuditEntry + var entry = new AuditEntry { At = clock.GetUtcNow().UtcDateTime, UserId = userId, @@ -64,6 +64,8 @@ private void Add(AuditAction action, string? subject, ArchiveItem? item, string? Action = action, ArchiveItem = item, Subject = subject is { Length: > AuditEntry.SubjectMaxLength } ? subject[..AuditEntry.SubjectMaxLength] : subject, - }); + }; + db.AuditEntries.Add(entry); + return entry; } } diff --git a/src/Commonage.Web/Audit/AuditText.cs b/src/Commonage.Web/Audit/AuditText.cs index 67429d9..5407696 100644 --- a/src/Commonage.Web/Audit/AuditText.cs +++ b/src/Commonage.Web/Audit/AuditText.cs @@ -79,6 +79,8 @@ public static class AuditText AuditAction.TagDeleted => localizer["Deleted the unused tag"], AuditAction.UnusedTagsDeleted => localizer["Deleted all unused tags"], AuditAction.ItemsImported => localizer["Imported items from a spreadsheet"], + AuditAction.ArchiveImported => localizer["Imported items from a Commonage export"], + AuditAction.CollectionCreatedByImport => localizer["Created the collection while importing"], _ => action.ToString(), }; @@ -86,7 +88,7 @@ public static class AuditText { AuditAction.ItemCreated or AuditAction.ItemChanged or AuditAction.ItemFieldRestored or AuditAction.ItemPublished or AuditAction.ItemUnpublished or AuditAction.ItemMediaLevelChanged or AuditAction.ItemPublicFromChanged or AuditAction.ItemDeleted or AuditAction.ItemMovedToBin or AuditAction.ItemRestored or AuditAction.ItemPurged - or AuditAction.ItemMovedToBinAfterKeptTime or AuditAction.ItemsImported => AuditKind.Items, + or AuditAction.ItemMovedToBinAfterKeptTime or AuditAction.ItemsImported or AuditAction.ArchiveImported => AuditKind.Items, AuditAction.PhotosAdded or AuditAction.PhotosArranged or AuditAction.PhotoDeleted or AuditAction.PhotoMovedToBin or AuditAction.PhotoRestored or AuditAction.PhotoPurged or AuditAction.PreviewRetried => AuditKind.Photos, AuditAction.ContributionReceived or AuditAction.ContributionAccepted or AuditAction.ContributionRejected @@ -95,7 +97,7 @@ or AuditAction.ContributionLinkCreated or AuditAction.ContributionLinkChanged or AuditAction.VisitorNoteReceived or AuditAction.VisitorNoteHandled or AuditAction.VisitorNoteReopened or AuditAction.VisitorNoteDetailsRemoved or AuditAction.VisitorNoteDeleted => AuditKind.Contributions, AuditAction.CollectionCreated or AuditAction.CollectionChanged or AuditAction.CollectionMoved - or AuditAction.CollectionDeleted => AuditKind.Collections, + or AuditAction.CollectionDeleted or AuditAction.CollectionCreatedByImport => AuditKind.Collections, AuditAction.TagChanged or AuditAction.TagsMerged or AuditAction.TagDeleted or AuditAction.UnusedTagsDeleted => AuditKind.Tags, AuditAction.AccountCreated or AuditAction.AccountRoleChanged or AuditAction.AccountNameChanged or AuditAction.AccountDisabled or AuditAction.AccountEnabled or AuditAction.AccountDeleted or AuditAction.SetupLinkCreated or AuditAction.PasswordChanged diff --git a/src/Commonage.Web/Domain/ArchiveItem.cs b/src/Commonage.Web/Domain/ArchiveItem.cs index 34fdb2b..9ca7f4e 100644 --- a/src/Commonage.Web/Domain/ArchiveItem.cs +++ b/src/Commonage.Web/Domain/ArchiveItem.cs @@ -208,6 +208,12 @@ public bool TrySetDate(string? text) return true; } + /// + /// Sets the date as written together with the earliest and latest day it stands for, when those come from somewhere that + /// already knows them, such as an export. Nothing is read from here. + /// + public void SetDateRange(string text, DateOnly from, DateOnly to) => (DateText, DateFrom, DateTo) = (text.Trim(), from, to); + private void MarkReviewed(DateTime now) { if (Contribution is not null && Status == ItemStatus.Submitted) diff --git a/src/Commonage.Web/Domain/AuditEntry.cs b/src/Commonage.Web/Domain/AuditEntry.cs index 897aff3..1c362e8 100644 --- a/src/Commonage.Web/Domain/AuditEntry.cs +++ b/src/Commonage.Web/Domain/AuditEntry.cs @@ -62,6 +62,8 @@ public enum AuditAction ItemsImported, AccountNameChanged, ItemFieldRestored, + ArchiveImported, + CollectionCreatedByImport, } /// diff --git a/src/Commonage.Web/Import/ExportImport.cs b/src/Commonage.Web/Import/ExportImport.cs new file mode 100644 index 0000000..ce2192e --- /dev/null +++ b/src/Commonage.Web/Import/ExportImport.cs @@ -0,0 +1,798 @@ +using System.Globalization; +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; +using Commonage.Web.Audit; +using Commonage.Web.Data; +using Commonage.Web.Domain; +using Commonage.Web.Export; +using Commonage.Web.Media; +using Commonage.Web.Pages.Admin.Items; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Localization; +using Microsoft.Extensions.Options; + +namespace Commonage.Web.Import; + +/// Why a whole export could not be read at all. +public enum ExportRefusal +{ + None, + NotZip, + NoArchiveJson, + ArchiveJsonTooLarge, + NotAnExport, + VersionNotUnderstood, + NotReadable, + TooMany, + TooMuchData, +} + +public enum ExportIssueKind +{ + // Wrong: keeps the item out of the import. + ValueUnknown, + ValueInvalid, + TooLong, + DateUnreadable, + RightsUnknown, + TagTooLong, + TooManyTags, + CollectionMissing, + CollectionAmbiguous, + TooManyNewCollections, + FilePathInvalid, + FileMissing, + FileUnreadable, + FileTooLarge, + + // Not wrong, and not imported: the item is left out. + ItemRejected, + ItemWithdrawn, + NoConsentToShare, + ItemAlreadyThere, + ItemAlreadyThereDifferentText, + SameAsEarlierItem, + AllFilesAlreadyThere, + + // Only worth saying: the item is imported without this, or in spite of it. + FileMarkedProblem, + FileChecksumMismatch, + FileAlreadyThere, + FileInEarlierItem, + DateMismatch, +} + +public enum ExportIssueSeverity +{ + Problem, + LeftOut, + Note, +} + +/// is the name of the property in the export, what it holds (shortened), for the reader to find it. +public record ExportIssue(ExportIssueKind Kind, string? Field = null, string? Value = null, string? Detail = null, UploadError? Upload = null) +{ + public ExportIssueSeverity Severity => Kind switch + { + <= ExportIssueKind.FileTooLarge => ExportIssueSeverity.Problem, + <= ExportIssueKind.AllFilesAlreadyThere => ExportIssueSeverity.LeftOut, + _ => ExportIssueSeverity.Note, + }; +} + +public record PlannedExportFile(SourceEntry Entry, ExaminedUpload Examined, string Name, string? AltText, string? Caption, int Rotation); + +public record PlannedTag(string Name, TagKind Kind); + +public record PlannedNewCollection(string Key, string Title, string? Description); + +public class PlannedExportItem +{ + public int Number { get; init; } + public string Title { get; set; } = ""; + public string? Status { get; set; } + public int? CollectionId { get; set; } + public string? NewCollectionKey { get; set; } + public string? CollectionTitle { get; set; } + public string? CollectionDescription { get; set; } + public string? Description { get; set; } + public string? DateText { get; set; } + public DateOnly? DateFrom { get; set; } + public DateOnly? DateTo { get; set; } + public List Tags { get; } = []; + public string? RightsUri { get; set; } + public string? RightsHolder { get; set; } + public string? Credit { get; set; } + public string? ReferenceNumber { get; set; } + public string? OriginalLocation { get; set; } + public bool NeedsTranscription { get; set; } + public bool HelpWanted { get; set; } + public MediaLevel MediaLevel { get; set; } + public DateOnly? PublicFrom { get; set; } + public List Issues { get; } = []; + public List Files { get; } = []; + + public bool HasProblem => Issues.Any(i => i.Severity == ExportIssueSeverity.Problem); + public bool IsLeftOut => !HasProblem && Issues.Any(i => i.Severity == ExportIssueSeverity.LeftOut); + public bool IsReady => !HasProblem && !IsLeftOut; +} + +public class ExportPlan +{ + public ExportRefusal Refusal { get; init; } + public int? FoundVersion { get; init; } + public int Version { get; init; } + public IReadOnlyList Items { get; init; } = []; + public IReadOnlyList NewCollections { get; init; } = []; + + public IEnumerable Ready => Items.Where(i => i.IsReady); + public int ReadyFileCount => Ready.Sum(i => i.Files.Count); + public long ReadyBytes => Ready.SelectMany(i => i.Files).Sum(f => f.Entry.Length); + public bool CanImport => Refusal == ExportRefusal.None && Ready.Any(); +} + +public record ExportImportResult(int Items, int Files, int FilesFailed, int CollectionsCreated); + +/// +/// Brings the ZIP file of Commonage's own export into the archive as drafts. only looks and changes +/// nothing, so it is also the dry run. What of the export is read and what is left out, and why, is in +/// . This class only ever adds; nothing that is there is changed or taken away. +/// +public partial class ExportImport( + CommonageDbContext db, + MediaUploadService uploads, + AuditLog audit, + IStringLocalizer localizer, + IOptions uploadOptions, + TimeProvider clock) +{ + public const int MinVersion = 4; + public const int MaxItems = 20_000; + public const int MaxCollections = 5_000; + public const int MaxTags = 50_000; + public const int MaxFilesPerItem = 500; + public const int MaxTagsPerItemRead = 200; + + /// A run creates at most this many collections, so a file full of invented ones cannot flood the list. + public const int MaxNewCollections = 50; + + public const long MaxArchiveJsonBytes = 256L * 1024 * 1024; + public const long MaxUncompressedBytes = 8L * 1024 * 1024 * 1024; + public const string ArchiveJsonPath = "archive.json"; + public const int AltTextMax = 1000; + private const int MaxDepth = 24; + + [GeneratedRegex(@"^files/(?[0-9]{1,9})/(?[0-9]{1,9})-[^/]{1,300}$", RegexOptions.CultureInvariant | RegexOptions.ExplicitCapture)] + private static partial Regex FilePathPattern(); + + private static readonly int[] Rotations = [0, 90, 180, 270]; + + public async Task PlanAsync(IImportSource source, CancellationToken cancellationToken) + { + if (source.Entries.Sum(e => e.Length) > MaxUncompressedBytes) + return Refuse(ExportRefusal.TooMuchData); + var jsonEntry = source.Entries.FirstOrDefault(e => e.Path == ArchiveJsonPath); + if (jsonEntry is null) + return Refuse(ExportRefusal.NoArchiveJson); + + ImportedArchive? archive; + var limits = new ReadLimits(); + try + { + await using var stream = await source.OpenSeekableAsync(jsonEntry, MaxArchiveJsonBytes, cancellationToken); + var head = new byte[16384]; + var read = await stream.ReadAtLeastAsync(head, head.Length, throwOnEndOfStream: false, cancellationToken); + var (format, version) = Sniff(head.AsSpan(0, read), final: read < head.Length); + if (format != ArchiveExporter.Format) + return Refuse(ExportRefusal.NotAnExport); + if (version is null or < MinVersion or > ArchiveExporter.Version) + return Refuse(ExportRefusal.VersionNotUnderstood, version); + + stream.Position = 0; + archive = await JsonSerializer.DeserializeAsync(stream, ReadOptions(limits), cancellationToken); + } + catch (EntryTooLargeException) + { + return Refuse(ExportRefusal.ArchiveJsonTooLarge); + } + catch (JsonException) + { + return Refuse(limits.TooMany ? ExportRefusal.TooMany : ExportRefusal.NotReadable); + } + catch (Exception exception) when (exception is InvalidDataException or IOException) + { + return Refuse(ExportRefusal.NotReadable); + } + + if (archive is null) + return Refuse(ExportRefusal.NotReadable); + + var entriesByPath = source.Entries.ToDictionary(e => e.Path, StringComparer.Ordinal); + var exportedCollections = new Dictionary(); + foreach (var collection in archive.Collections ?? []) + { + if (collection?.Id is { } collectionId) + exportedCollections.TryAdd(collectionId, collection); + } + + var tagKinds = new Dictionary(StringComparer.Ordinal); + foreach (var tag in archive.Tags ?? []) + { + if (Text(tag?.Name) is { } tagName) + tagKinds.TryAdd(Tag.Normalize(tagName), tag!.Kind); + } + + var existingCollections = (await db.Collections.AsNoTracking().Select(c => new { c.Id, c.Title }).ToListAsync(cancellationToken)) + .GroupBy(c => Key(c.Title), StringComparer.OrdinalIgnoreCase) + .ToDictionary(g => g.Key, g => g.Select(c => c.Id).ToList(), StringComparer.OrdinalIgnoreCase); + var existingItems = (await db.ArchiveItems.AsNoTracking() + .Where(i => i.Title != "") + .Select(i => new { i.Id, i.CollectionId, i.Title, i.DateText }) + .ToListAsync(cancellationToken)) + .GroupBy(i => ItemKey(i.CollectionId.ToString(CultureInfo.InvariantCulture), i.Title, i.DateText), StringComparer.OrdinalIgnoreCase) + .ToDictionary(g => g.Key, g => g.Select(i => i.Id).ToList(), StringComparer.OrdinalIgnoreCase); + + var items = new List(); + var earlierItemOfKey = new Dictionary(StringComparer.OrdinalIgnoreCase); + var earlierItemOfFile = new Dictionary(StringComparer.OrdinalIgnoreCase); + var usedPaths = new HashSet(StringComparer.Ordinal); + var newCollections = new Dictionary(StringComparer.OrdinalIgnoreCase); + var today = DateOnly.FromDateTime(clock.GetUtcNow().UtcDateTime); + long bytesRead = 0; + var number = 0; + + foreach (var exported in archive.Items ?? []) + { + cancellationToken.ThrowIfCancellationRequested(); + number++; + var item = exported ?? new ImportedItem(); + var planned = new PlannedExportItem { Number = number, Status = Shorten(item.Status) }; + planned.Title = Shorten(Text(item.Title)) ?? ""; + items.Add(planned); + + // What decides whether the item is imported at all is looked at first; nothing else of a left-out item is examined. + if (!TryEnum(item.Status, out ItemStatus status)) + planned.Issues.Add(new ExportIssue(ExportIssueKind.ValueUnknown, "status", Shorten(item.Status))); + else if (status == ItemStatus.Rejected) + planned.Issues.Add(new ExportIssue(ExportIssueKind.ItemRejected, "status")); + else if (status == ItemStatus.Withdrawn) + planned.Issues.Add(new ExportIssue(ExportIssueKind.ItemWithdrawn, "status")); + if (item.Contribution is { ConsentCoversSharing: false }) + planned.Issues.Add(new ExportIssue(ExportIssueKind.NoConsentToShare, "contribution")); + if (planned.Issues.Count > 0) + continue; + + string? Limited(string field, string? value, int max, ExportIssueKind kind = ExportIssueKind.TooLong) + { + var text = Text(value); + if (text is not null && text.Length > max) + { + Issue(planned, kind, field, Shorten(text), max.ToString(CultureInfo.InvariantCulture)); + return null; + } + + return text; + } + + planned.Title = Limited("title", item.Title, ItemImport.TitleMax) ?? planned.Title; + planned.Description = Limited("description", item.Description, ItemImport.DescriptionMax); + planned.RightsHolder = Limited("rightsHolder", item.RightsHolder, ItemImport.HolderMax); + planned.Credit = Limited("credit", item.Credit, ItemImport.CreditMax); + planned.ReferenceNumber = Limited("referenceNumber", item.ReferenceNumber, ItemImport.ReferenceMax); + planned.OriginalLocation = Limited("originalLocation", item.OriginalLocation, ItemImport.LocationMax); + planned.NeedsTranscription = item.NeedsTranscription == true; + planned.HelpWanted = item.HelpWanted == true; + + planned.RightsUri = Text(item.RightsUri); + if (planned.RightsUri is not null && !RightsOptions.IsKnown(planned.RightsUri)) + Issue(planned, ExportIssueKind.RightsUnknown, "rightsUri", Shorten(planned.RightsUri)); + + if (item.MediaLevel is null) + planned.MediaLevel = MediaLevel.Everything; + else if (TryEnum(item.MediaLevel, out MediaLevel level)) + planned.MediaLevel = level; + else + Issue(planned, ExportIssueKind.ValueUnknown, "mediaLevel", Shorten(item.MediaLevel)); + + if (item.PublicFrom is not null) + { + if (TryDay(item.PublicFrom, out var day) && day.Year >= 1900 && day.Year <= today.Year + 200) + planned.PublicFrom = day; + else + Issue(planned, ExportIssueKind.ValueInvalid, "publicFrom", Shorten(item.PublicFrom)); + } + + PlanDate(planned, item.Date); + PlanTags(planned, item, tagKinds); + PlanCollection(planned, item, exportedCollections, existingCollections); + + if (!HasProblem(planned)) + { + var bytes = await PlanFilesAsync(planned, item, source, entriesByPath, usedPaths, earlierItemOfFile, bytesRead, cancellationToken); + if (bytes < 0) + return Refuse(ExportRefusal.TooMuchData); + bytesRead = bytes; + } + + if (!HasProblem(planned) && planned.Title.Length > 0 && (planned.CollectionId is not null || planned.NewCollectionKey is not null)) + { + var collectionKey = planned.CollectionId?.ToString(CultureInfo.InvariantCulture) ?? "new:" + planned.NewCollectionKey; + var key = ItemKey(collectionKey, planned.Title, planned.DateText); + if (planned.CollectionId is not null && existingItems.TryGetValue(key, out var sameIds)) + { + var theirs = await db.ArchiveItems.AsNoTracking().Where(i => sameIds.Contains(i.Id)).Select(i => i.Description).ToListAsync(cancellationToken); + var same = theirs.Any(d => string.Equals(Key(d ?? ""), Key(planned.Description ?? ""), StringComparison.Ordinal)); + Issue(planned, same ? ExportIssueKind.ItemAlreadyThere : ExportIssueKind.ItemAlreadyThereDifferentText, "title", Shorten(planned.Title)); + } + else if (!earlierItemOfKey.TryAdd(key, number)) + Issue(planned, ExportIssueKind.SameAsEarlierItem, "title", Shorten(planned.Title), earlierItemOfKey[key].ToString(CultureInfo.InvariantCulture)); + } + + if (planned.IsReady && planned.NewCollectionKey is { } newKey && !newCollections.ContainsKey(newKey)) + { + if (newCollections.Count >= MaxNewCollections) + Issue(planned, ExportIssueKind.TooManyNewCollections, "collectionId", null, MaxNewCollections.ToString(CultureInfo.InvariantCulture)); + else + newCollections[newKey] = new PlannedNewCollection(newKey, planned.CollectionTitle!, planned.CollectionDescription); + } + } + + return new ExportPlan { Version = ArchiveExporter.Version, Items = items, NewCollections = newCollections.Values.ToList() }; + } + + private static bool HasProblem(PlannedExportItem planned) => planned.Issues.Any(i => i.Severity == ExportIssueSeverity.Problem); + + private static ExportPlan Refuse(ExportRefusal refusal, int? foundVersion = null) => new() { Refusal = refusal, FoundVersion = foundVersion }; + + private static void Issue(PlannedExportItem planned, ExportIssueKind kind, string? field = null, string? value = null, string? detail = null, UploadError? upload = null) => + planned.Issues.Add(new ExportIssue(kind, field, value, detail, upload)); + + /// + /// The exported earliest and latest day are used when they are real, because the text may be in a vocabulary this version + /// does not read; the text stays as the display text. Without usable days the text has to be readable. + /// + private static void PlanDate(PlannedExportItem planned, ImportedDate? date) + { + var text = Text(date?.Text); + if (text is null) + return; + if (text.Length > DateRange.MaxTextLength) + { + Issue(planned, ExportIssueKind.DateUnreadable, "date", Shorten(text)); + return; + } + + var readable = DateRange.TryParse(text, out var parsed); + if (TryDay(date!.From, out var from) && TryDay(date.To, out var to) && from <= to) + { + planned.DateText = text; + planned.DateFrom = from; + planned.DateTo = to; + if (readable && (parsed.From != from || parsed.To != to)) + Issue(planned, ExportIssueKind.DateMismatch, "date", Shorten(text)); + } + else if (readable) + { + planned.DateText = text; + planned.DateFrom = parsed.From; + planned.DateTo = parsed.To; + } + else + { + Issue(planned, ExportIssueKind.DateUnreadable, "date", Shorten(text)); + } + } + + private static void PlanTags(PlannedExportItem planned, ImportedItem item, Dictionary tagKinds) + { + var seen = new HashSet(StringComparer.Ordinal); + foreach (var raw in item.Tags ?? []) + { + if (Text(raw) is not { } name) + continue; + if (name.Length > Tag.MaxLength) + { + Issue(planned, ExportIssueKind.TagTooLong, "tags", Shorten(name), Tag.MaxLength.ToString(CultureInfo.InvariantCulture)); + continue; + } + + var normalized = Tag.Normalize(name); + if (!seen.Add(normalized)) + continue; + var kind = TagKind.Topic; + if (tagKinds.TryGetValue(normalized, out var written) && written is not null && !TryEnum(written, out kind)) + { + Issue(planned, ExportIssueKind.ValueUnknown, "tags", Shorten(name)); + continue; + } + + planned.Tags.Add(new PlannedTag(name, kind)); + } + + if (planned.Tags.Count > ItemFields.MaxTagsPerItem) + Issue(planned, ExportIssueKind.TooManyTags, "tags", null, ItemFields.MaxTagsPerItem.ToString(CultureInfo.InvariantCulture)); + } + + private static void PlanCollection( + PlannedExportItem planned, ImportedItem item, Dictionary exported, Dictionary> existing) + { + if (item.CollectionId is not { } id || !exported.TryGetValue(id, out var collection) || Text(collection.Title) is not { } title) + { + Issue(planned, ExportIssueKind.CollectionMissing, "collectionId"); + return; + } + + if (title.Length > ItemImport.TitleMax) + { + Issue(planned, ExportIssueKind.TooLong, "collection", Shorten(title), ItemImport.TitleMax.ToString(CultureInfo.InvariantCulture)); + return; + } + + planned.CollectionTitle = title; + if (existing.TryGetValue(Key(title), out var matches)) + { + if (matches.Count == 1) + planned.CollectionId = matches[0]; + else + Issue(planned, ExportIssueKind.CollectionAmbiguous, "collection", Shorten(title)); + return; + } + + var description = Text(collection.Description); + if (description is not null && description.Length > ItemImport.DescriptionMax) + { + Issue(planned, ExportIssueKind.TooLong, "collection", Shorten(title), ItemImport.DescriptionMax.ToString(CultureInfo.InvariantCulture)); + return; + } + + planned.NewCollectionKey = Key(title); + planned.CollectionDescription = description; + } + + /// + /// Looks at each file of the item. Returns the bytes read so far including this item's, or -1 when the total budget is used up. + /// A path is only a key into the ZIP file; it must have the form the export writes and belong to this item and this file. + /// + private async Task PlanFilesAsync( + PlannedExportItem planned, ImportedItem item, IImportSource source, Dictionary entries, HashSet usedPaths, + Dictionary earlierItemOfFile, long bytesRead, CancellationToken cancellationToken) + { + var files = (item.Files ?? []).OfType() + .OrderBy(f => f.Position ?? int.MaxValue).ThenBy(f => f.Id ?? int.MaxValue).ToList(); + var alreadyThere = 0; + var seen = 0; + foreach (var file in files) + { + var shown = Shorten(Text(file.OriginalFileName) ?? ""); + if (!string.IsNullOrEmpty(file.Problem)) + { + Issue(planned, ExportIssueKind.FileMarkedProblem, "files", shown); + continue; + } + + var match = file.Path is null ? null : FilePathPattern().Match(file.Path); + if (match is not { Success: true } + || file.Id is not { } fileId || item.Id is not { } itemId + || match.Groups["item"].Value != itemId.ToString(CultureInfo.InvariantCulture) + || match.Groups["file"].Value != fileId.ToString(CultureInfo.InvariantCulture) + || !usedPaths.Add(file.Path!)) + { + Issue(planned, ExportIssueKind.FilePathInvalid, "files", shown); + continue; + } + + if (file.Rotation is { } rotation && !Rotations.Contains(rotation)) + { + Issue(planned, ExportIssueKind.ValueInvalid, "rotation", shown); + continue; + } + + var altText = Text(file.AltText); + var caption = Text(file.Caption); + if (altText is { Length: > AltTextMax } || caption is { Length: > MediaFile.MaxCaptionLength }) + { + Issue(planned, ExportIssueKind.TooLong, "files", shown, (altText is { Length: > AltTextMax } ? AltTextMax : MediaFile.MaxCaptionLength).ToString(CultureInfo.InvariantCulture)); + continue; + } + + if (!entries.TryGetValue(file.Path!, out var entry)) + { + Issue(planned, ExportIssueKind.FileMissing, "files", shown); + continue; + } + + ExaminedUpload examined; + try + { + await using var content = await source.OpenSeekableAsync(entry, uploadOptions.Value.MaxFileSizeBytes, cancellationToken); + bytesRead += content.Length; + if (bytesRead > MaxUncompressedBytes) + return -1; + examined = await uploads.ExamineAsync(content, content.Length, documents: true, cancellationToken); + } + catch (EntryTooLargeException) + { + Issue(planned, ExportIssueKind.FileTooLarge, "files", shown); + continue; + } + catch (Exception exception) when (exception is InvalidDataException or IOException) + { + Issue(planned, ExportIssueKind.FileUnreadable, "files", shown, upload: UploadError.UnsupportedFormat); + continue; + } + + if (examined.Error != UploadError.None) + { + Issue(planned, ExportIssueKind.FileUnreadable, "files", shown, upload: examined.Error); + continue; + } + + seen++; + if (!string.Equals(examined.Sha256, file.Sha256, StringComparison.OrdinalIgnoreCase)) + { + Issue(planned, ExportIssueKind.FileChecksumMismatch, "files", shown); + continue; + } + + if (earlierItemOfFile.TryGetValue(examined.Sha256!, out var earlier)) + { + Issue(planned, ExportIssueKind.FileInEarlierItem, "files", shown, earlier.ToString(CultureInfo.InvariantCulture)); + continue; + } + + if (await uploads.FindIdenticalAsync(examined, cancellationToken: cancellationToken) is { } same) + { + alreadyThere++; + Issue(planned, ExportIssueKind.FileAlreadyThere, "files", shown, ArchiveItem.ShownTitle(localizer, same.ItemTitle)); + continue; + } + + earlierItemOfFile[examined.Sha256!] = planned.Number; + planned.Files.Add(new PlannedExportFile(entry, examined, Text(file.OriginalFileName) ?? entry.Name, altText, caption, file.Rotation ?? 0)); + } + + // Every photo of the item is in the archive already: the item is, too, whatever its title says now. + if (alreadyThere > 0 && planned.Files.Count == 0 && !HasProblem(planned) && alreadyThere == seen) + Issue(planned, ExportIssueKind.AllFilesAlreadyThere, "files"); + return bytesRead; + } + + // Titles, tags and collections are compared in NFC and ordinally ignoring case, so that a title written on a Mac (decomposed) + // and the server's culture make no difference. + private static string Key(string text) => text.Normalize(NormalizationForm.FormC).Trim(); + + private static string ItemKey(string collection, string title, string? date) => $"{collection}\u001f{Key(title)}\u001f{Key(date ?? "")}"; + + /// Trimmed, in NFC, and null when there is nothing in it. + private static string? Text(string? value) => ItemFields.Clean(value)?.Normalize(NormalizationForm.FormC); + + private static string? Shorten(string? value) => value is null ? null : value.Length <= 80 ? value : value[..80] + "…"; + + /// A name of the enum, written as such. A number, or a name with other letters, is not one. + private static bool TryEnum(string? value, out T result) where T : struct, Enum + { + result = default; + return value is not null && !char.IsDigit(value.FirstOrDefault()) && Enum.TryParse(value, ignoreCase: false, out result) && Enum.IsDefined(result); + } + + private static bool TryDay(string? value, out DateOnly day) + { + day = default; + return value is not null && DateOnly.TryParseExact(value, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out day); + } + + /// The format and version, which the exporter writes first, found without reading the rest. + private static (string? Format, int? Version) Sniff(ReadOnlySpan bytes, bool final) + { + string? format = null; + int? version = null; + if (bytes.StartsWith(""u8.ToArray()) || bytes.StartsWith(new byte[] { 0xEF, 0xBB, 0xBF })) + bytes = bytes[3..]; + try + { + var reader = new Utf8JsonReader(bytes, final, default); + if (!reader.Read() || reader.TokenType != JsonTokenType.StartObject) + return (null, null); + while (reader.Read() && reader.TokenType == JsonTokenType.PropertyName) + { + var name = reader.GetString(); + if (!reader.Read()) + break; + if (name == "format" && reader.TokenType == JsonTokenType.String) + format = reader.GetString(); + else if (name == "version" && reader.TokenType == JsonTokenType.Number && reader.TryGetInt32(out var number)) + version = number; + else if (reader.TokenType is JsonTokenType.StartObject or JsonTokenType.StartArray && !reader.TrySkip()) + break; + if (format is not null && version is not null) + break; + } + } + catch (JsonException) + { + } + + return (format, version); + } + + private static JsonSerializerOptions ReadOptions(ReadLimits limits) => new() + { + MaxDepth = MaxDepth, + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + Converters = + { + new CappedListConverter(MaxItems, limits), + new CappedListConverter(MaxCollections, limits), + new CappedListConverter(MaxTags, limits), + new CappedListConverter(MaxFilesPerItem, limits), + new CappedListConverter(MaxTagsPerItemRead, limits), + }, + }; + + /// Imports the items of a plan that are in order, as drafts. A file that is no longer what the dry run saw is left out and counted. + public async Task RunAsync(ExportPlan plan, IImportSource source, CancellationToken cancellationToken) + { + // The entry is added before the first save, so an import that stops half way still has its line in the log. + var logged = audit.Record(AuditAction.ArchiveImported, null); + var now = clock.GetUtcNow().UtcDateTime; + var created = new Dictionary(StringComparer.OrdinalIgnoreCase); + var position = (await db.Collections.MaxAsync(c => (int?)c.Position, cancellationToken) ?? -1) + 1; + foreach (var planned in plan.NewCollections) + { + var collection = new Collection { Title = planned.Title, Description = planned.Description, CreatedAt = now, Position = position++ }; + created[planned.Key] = collection; + db.Collections.Add(collection); + audit.Record(AuditAction.CollectionCreatedByImport, planned.Title); + } + + await db.SaveChangesAsync(cancellationToken); + var loggedId = logged.Id; + var newCollectionIds = created.ToDictionary(c => c.Key, c => c.Value.Id, StringComparer.OrdinalIgnoreCase); + + var items = 0; + var files = 0; + var failed = 0; + var tags = new Dictionary(StringComparer.Ordinal); + foreach (var row in plan.Ready) + { + cancellationToken.ThrowIfCancellationRequested(); + // Everything tracked is looked after at every save, which gets slow with thousands of items. + if (items > 0 && items % 100 == 0) + { + db.ChangeTracker.Clear(); + tags.Clear(); + } + + var stamp = clock.GetUtcNow().UtcDateTime; + var item = new ArchiveItem + { + Title = row.Title, + Description = row.Description, + Status = ItemStatus.Draft, + MediaLevel = row.MediaLevel, + PublicFrom = row.PublicFrom, + CollectionId = row.CollectionId ?? newCollectionIds[row.NewCollectionKey!], + RightsUri = row.RightsUri, + RightsHolder = row.RightsHolder, + Credit = row.Credit, + ReferenceNumber = row.ReferenceNumber, + OriginalLocation = row.OriginalLocation, + NeedsTranscription = row.NeedsTranscription, + HelpWanted = row.HelpWanted, + CreatedAt = stamp, + UpdatedAt = stamp, + }; + if (row.DateText is not null) + item.SetDateRange(row.DateText, row.DateFrom!.Value, row.DateTo!.Value); + + var missing = row.Tags.Where(t => !tags.ContainsKey(Tag.Normalize(t.Name))).ToList(); + if (missing.Count > 0) + { + var normalized = missing.Select(t => Tag.Normalize(t.Name)).ToList(); + foreach (var found in await db.Tags.Where(t => normalized.Contains(t.NormalizedName)).ToListAsync(cancellationToken)) + tags[found.NormalizedName] = found; + // A tag that is there keeps its kind: the archive's own choice wins over what an export says. + foreach (var tag in missing.Where(t => !tags.ContainsKey(Tag.Normalize(t.Name)))) + tags[Tag.Normalize(tag.Name)] = new Tag { Name = tag.Name, NormalizedName = Tag.Normalize(tag.Name), Kind = tag.Kind }; + } + + item.SetTags(row.Tags.Select(t => tags[Tag.Normalize(t.Name)]).ToList()); + + db.ArchiveItems.Add(item); + audit.Record(AuditAction.ItemCreated, item.Title, item); + await db.SaveChangesAsync(cancellationToken); + items++; + + var added = 0; + foreach (var planned in row.Files) + { + try + { + await using var content = await source.OpenSeekableAsync(planned.Entry, uploadOptions.Value.MaxFileSizeBytes, cancellationToken); + var examined = await uploads.ExamineAsync(content, content.Length, documents: true, cancellationToken); + if (examined.Error != UploadError.None || examined.Sha256 != planned.Examined.Sha256) + { + failed++; + continue; + } + + var stored = await uploads.StoreAsync(item, content, planned.Name, content.Length, examined, cancellationToken); + files++; + added++; + if (planned.AltText is not null || planned.Caption is not null || planned.Rotation != 0) + { + stored.AltText = planned.AltText; + stored.Caption = planned.Caption; + stored.Rotation = planned.Rotation; + await db.SaveChangesAsync(cancellationToken); + } + } + catch (Exception exception) when (exception is EntryTooLargeException or InvalidDataException or IOException) + { + failed++; + } + } + + if (added > 0) + { + audit.Record(AuditAction.PhotosAdded, item.Title, item); + await db.SaveChangesAsync(cancellationToken); + } + } + + // How many came in, as numbers only, so the line reads the same in every language. + db.ChangeTracker.Clear(); + var line = await db.AuditEntries.FirstAsync(e => e.Id == loggedId, cancellationToken); + line.Subject = $"{items} / {files}"; + await db.SaveChangesAsync(cancellationToken); + return new ExportImportResult(items, files, failed, created.Count); + } + + /// The message for a refused export, in the reader's language. + public static string Describe(IStringLocalizer localizer, ExportRefusal refusal, int? foundVersion) => refusal switch + { + ExportRefusal.NotZip => localizer["This is not a ZIP file, or it holds too many files."], + ExportRefusal.NoArchiveJson => localizer["This ZIP file is not a Commonage export: it has no archive.json."], + ExportRefusal.ArchiveJsonTooLarge => localizer["The file archive.json in this export is too large to read."], + ExportRefusal.NotAnExport => localizer["This is not a Commonage export."], + ExportRefusal.VersionNotUnderstood => + localizer["This export has the format version {0}. This archive reads the versions {1} to {2}.", foundVersion?.ToString(CultureInfo.InvariantCulture) ?? "?", MinVersion, ArchiveExporter.Version], + ExportRefusal.NotReadable => localizer["The file archive.json in this export could not be read."], + ExportRefusal.TooMany => localizer["This export holds more items, files, tags or collections than one import can read."], + ExportRefusal.TooMuchData => localizer["This export holds more data than one import can read."], + _ => "", + }; + + /// The message for one thing found in an item. The field and the value are shown beside it, never built into it. + public static string Describe(IStringLocalizer localizer, ExportIssue issue) => issue.Kind switch + { + ExportIssueKind.ValueUnknown => localizer["This value is not one this archive knows."], + ExportIssueKind.ValueInvalid => localizer["This value is not valid."], + ExportIssueKind.TooLong => localizer["This text can be at most {1} characters long.", "", issue.Detail!], + ExportIssueKind.DateUnreadable => localizer["This date could not be understood. Please include a year, for example: 1953, 12.03.1953, circa 1950, 1950s, 1950–1955."], + ExportIssueKind.RightsUnknown => localizer["This is not one of the archive's rights statements. Write its web address as an export does, or leave the cell empty."], + ExportIssueKind.TagTooLong => localizer.Plural("A tag can be at most {0, plural, one {# character} other {# characters}} long.", int.Parse(issue.Detail!, CultureInfo.InvariantCulture)), + ExportIssueKind.TooManyTags => localizer.Plural("An item can have at most {0, plural, one {# tag} other {# tags}}.", int.Parse(issue.Detail!, CultureInfo.InvariantCulture)), + ExportIssueKind.CollectionMissing => localizer["The collection of this item is not in the export."], + ExportIssueKind.CollectionAmbiguous => localizer["More than one collection has this name. Rename one of them first."], + ExportIssueKind.TooManyNewCollections => localizer.Plural("One import creates at most {0, plural, one {# collection} other {# collections}}. Import again for the rest.", int.Parse(issue.Detail!, CultureInfo.InvariantCulture)), + ExportIssueKind.FilePathInvalid => localizer["The place of this file in the ZIP file is not the one an export writes."], + ExportIssueKind.FileMissing => localizer["This file is not in the ZIP file."], + ExportIssueKind.FileUnreadable => UploadErrorMessages.Describe(localizer, issue.Upload ?? UploadError.UnsupportedFormat, issue.Value ?? ""), + ExportIssueKind.FileTooLarge => localizer["This file is too large."], + ExportIssueKind.ItemRejected => localizer["Left out: it was rejected in the other archive."], + ExportIssueKind.ItemWithdrawn => localizer["Left out: its contributor withdrew their consent in the other archive."], + ExportIssueKind.NoConsentToShare => localizer["Left out: its contributor did not agree to it being shared further."], + ExportIssueKind.ItemAlreadyThere => localizer["An item with this title and date is already in this collection."], + ExportIssueKind.ItemAlreadyThereDifferentText => localizer["An item with this title and date is already in this collection, with a different description. It is not changed."], + ExportIssueKind.SameAsEarlierItem => localizer["The same title and date as item {0}, in the same collection.", issue.Detail!], + ExportIssueKind.AllFilesAlreadyThere => localizer["Every photo of this item is already in the archive."], + ExportIssueKind.FileMarkedProblem => localizer["The other archive could not export this file, so it is left out."], + ExportIssueKind.FileChecksumMismatch => localizer["This file does not match its checksum, so it is left out."], + ExportIssueKind.FileAlreadyThere => localizer["The archive already has this file: {0}", issue.Detail!], + ExportIssueKind.FileInEarlierItem => localizer["The same file as in item {0}.", issue.Detail!], + ExportIssueKind.DateMismatch => localizer["The days in the export differ from what this text means here. The days of the export are used."], + _ => issue.Kind.ToString(), + }; +} diff --git a/src/Commonage.Web/Import/ExportReading.cs b/src/Commonage.Web/Import/ExportReading.cs new file mode 100644 index 0000000..045fc6b --- /dev/null +++ b/src/Commonage.Web/Import/ExportReading.cs @@ -0,0 +1,197 @@ +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Commonage.Web.Import; + +/// What the importer does with one property of the export. +public enum ExportFieldDecision +{ + /// Read, checked and kept in the archive. + Read, + + /// Read only to decide something, or only to find the way to something else; never kept. + ReadForDecision, + + /// Not read: the property has no place in the classes below, so it is skipped while the file is read. + Dropped, +} + +public record ExportFieldRule(ExportFieldDecision Decision, string Why); + +/// +/// A decision for every property the export writes: read, read only for a decision, or dropped, each with its reason. A test +/// fails when the exporter gains a property that is not listed here, so a new field is never carried over, or lost, by accident. +/// The classes and the like hold exactly the properties that are not dropped. +/// +public static class ExportImportTable +{ + private const string OtherArchive = "A setting or text of the other archive; a backup restores those, an import does not."; + private const string Personal = "A contributor's details and consent were given to the other archive for that archive, so they stay there."; + private const string NotTrusted = "Made again here, or not trusted from outside."; + + public static readonly IReadOnlyDictionary Fields = Build(); + + private static Dictionary Build() + { + var table = new Dictionary(); + void Add(string type, ExportFieldDecision decision, string why, params string[] names) + { + foreach (var name in names) + table.Add($"{type}.{name}", new ExportFieldRule(decision, why)); + } + + Add("ExportSettings", ExportFieldDecision.Dropped, OtherArchive, + "DefaultLanguage", "ContentLanguage", "OtherContentLanguages", "AccentColor", "TimeZone", "DefaultRightsUri", "AllowSearchEngines", + "RequireTwoFactor", "LargePhotos", "PrivacyReviewed", "ImprintNotNeeded", "RestoreTestedAt", "ActivityLogKeptYears", + "RejectedKeptMonths", "AcceptVisitorNotes", "Logo", "Texts"); + Add("ExportText", ExportFieldDecision.Dropped, OtherArchive, "Language", "Kind", "Text"); + + Add("ExportCollection", ExportFieldDecision.ReadForDecision, "Only the key that the items of the export name their collection by.", "Id"); + Add("ExportCollection", ExportFieldDecision.Read, "Collections are matched by title, and created with this when there is none.", "Title", "Description"); + Add("ExportCollection", ExportFieldDecision.Dropped, NotTrusted, "CreatedAt", "Position", "Sort", "CoverFileId"); + + Add("ExportTag", ExportFieldDecision.Read, "Tags are matched by name, and created with this kind when there is none.", "Name", "Kind"); + + Add("ExportItem", ExportFieldDecision.ReadForDecision, "Only the key that the files of the item are checked against.", "Id"); + Add("ExportItem", ExportFieldDecision.ReadForDecision, "Only says which collection of the export the item is in.", "CollectionId"); + Add("ExportItem", ExportFieldDecision.ReadForDecision, + "Rejected and withdrawn items are left out, so a withdrawal is not undone. Whatever the status, an item arrives as a draft.", "Status"); + Add("ExportItem", ExportFieldDecision.Read, "Comes with the item.", + "Title", "Description", "Date", "Tags", "RightsUri", "RightsHolder", "Credit", "ReferenceNumber", "OriginalLocation", + "NeedsTranscription", "HelpWanted", "Files"); + Add("ExportItem", ExportFieldDecision.Read, "Kept, so that what a curator held back in one archive is not lost by moving it. Shown in the dry run.", "MediaLevel", "PublicFrom"); + Add("ExportItem", ExportFieldDecision.Dropped, "Made again: the item is new here, and a draft.", "CreatedAt", "UpdatedAt", "PublishedAt", "RejectedOrWithdrawnAt"); + Add("ExportItem", ExportFieldDecision.Dropped, "Names or describes who gave the item to the other archive, or what that archive's curators wrote to each other.", "ReceivedFrom", "ReceivedOn", "InternalNotes"); + Add("ExportItem", ExportFieldDecision.ReadForDecision, + "Only whether the contributor agreed to the item being shared further; an item without that agreement is left out. Nothing else of it is read.", "Contribution"); + Add("ExportItem", ExportFieldDecision.Dropped, "Notes from visitors are for the curators of the archive they were sent to.", "Notes"); + + Add("ExportDate", ExportFieldDecision.Read, "The text is kept as written; the earliest and latest day are used when they are sane.", "Text", "From", "To"); + + Add("ExportContribution", ExportFieldDecision.ReadForDecision, "Decides whether the item is imported at all.", "ConsentCoversSharing"); + Add("ExportContribution", ExportFieldDecision.Dropped, Personal, + "ContributorName", "ContributorEmail", "ShowName", "Rights", "RightsHolder", "ConsentText", "Reuse", "ReferenceCode", "SubmittedAt", + "ReviewedAt", "PersonalDetailsRemovedAt", "ContributionLink"); + + Add("ExportNote", ExportFieldDecision.Dropped, "Notes from visitors are for the curators of the archive they were sent to.", + "Kind", "Message", "Name", "Email", "ReceivedAt", "HandledAt", "PersonalDetailsRemovedAt"); + + Add("ExportFile", ExportFieldDecision.ReadForDecision, "Only the key that the path of the file is checked against.", "Id"); + Add("ExportFile", ExportFieldDecision.Read, "Comes with the photo; the path is only a key into the ZIP file and never a path on disk.", + "Path", "OriginalFileName", "Sha256", "AltText", "Caption", "Position", "Rotation"); + Add("ExportFile", ExportFieldDecision.ReadForDecision, "A file the export itself marked as missing or damaged is left out.", "Problem"); + Add("ExportFile", ExportFieldDecision.Dropped, "Found out again from the file itself: what a ZIP file claims about a file is not trusted.", "ContentType", "SizeBytes", "PageCount"); + Add("ExportFile", ExportFieldDecision.Dropped, NotTrusted, "UploadedAt"); + return table; + } +} + +// What is read of archive.json. A property that is not here is skipped by the reader, not stored; ExportImportTable says which +// and why. Strings stay strings until they are checked, so that a value this version does not know is one line in the dry +// run and not an exception. + +public sealed class ImportedArchive +{ + public string? Format { get; set; } + public int? Version { get; set; } + public List? Collections { get; set; } + public List? Tags { get; set; } + public List? Items { get; set; } +} + +public sealed class ImportedCollection +{ + public int? Id { get; set; } + public string? Title { get; set; } + public string? Description { get; set; } +} + +public sealed class ImportedTag +{ + public string? Name { get; set; } + public string? Kind { get; set; } +} + +public sealed class ImportedItem +{ + public int? Id { get; set; } + public int? CollectionId { get; set; } + public string? Title { get; set; } + public string? Description { get; set; } + public string? Status { get; set; } + public ImportedDate? Date { get; set; } + public List? Tags { get; set; } + public string? RightsUri { get; set; } + public string? RightsHolder { get; set; } + public string? Credit { get; set; } + public string? ReferenceNumber { get; set; } + public string? OriginalLocation { get; set; } + public bool? NeedsTranscription { get; set; } + public bool? HelpWanted { get; set; } + public string? MediaLevel { get; set; } + public string? PublicFrom { get; set; } + public ImportedContribution? Contribution { get; set; } + public List? Files { get; set; } +} + +public sealed class ImportedDate +{ + public string? Text { get; set; } + public string? From { get; set; } + public string? To { get; set; } +} + +/// The one thing read of a contribution. Its names, email address, consent text and the rest are never read. +public sealed class ImportedContribution +{ + public bool? ConsentCoversSharing { get; set; } +} + +public sealed class ImportedFile +{ + public int? Id { get; set; } + public string? Path { get; set; } + public string? OriginalFileName { get; set; } + public string? Sha256 { get; set; } + public string? AltText { get; set; } + public string? Caption { get; set; } + public int? Position { get; set; } + public int? Rotation { get; set; } + public string? Problem { get; set; } +} + +/// What went wrong while counting: tells a list that was too long from a file that is not JSON. +internal sealed class ReadLimits +{ + public bool TooMany { get; set; } +} + +/// +/// Reads a JSON array into a list and stops at once when it holds more than elements, so that a file +/// made of a hundred million empty items never becomes a hundred million objects. +/// +internal sealed class CappedListConverter(int max, ReadLimits limits) : JsonConverter> +{ + public override List? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + if (reader.TokenType == JsonTokenType.Null) + return null; + if (reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + var list = new List(); + while (reader.Read() && reader.TokenType != JsonTokenType.EndArray) + { + if (list.Count >= max) + { + limits.TooMany = true; + throw new JsonException(); + } + + list.Add(JsonSerializer.Deserialize(ref reader, options)!); + } + + return list; + } + + public override void Write(Utf8JsonWriter writer, List value, JsonSerializerOptions options) => throw new NotSupportedException(); +} diff --git a/src/Commonage.Web/Import/ImportLock.cs b/src/Commonage.Web/Import/ImportLock.cs new file mode 100644 index 0000000..3eaf2be --- /dev/null +++ b/src/Commonage.Web/Import/ImportLock.cs @@ -0,0 +1,8 @@ +namespace Commonage.Web.Import; + +/// An import runs one at a time, whatever it reads: two of them would each be sure that an item is not there yet. +public static class ImportLock +{ + /// Taken with WaitAsync(0) and released in a finally. + public static readonly SemaphoreSlim OneAtATime = new(1, 1); +} diff --git a/src/Commonage.Web/Import/ImportStaging.cs b/src/Commonage.Web/Import/ImportStaging.cs index 2705341..f092796 100644 --- a/src/Commonage.Web/Import/ImportStaging.cs +++ b/src/Commonage.Web/Import/ImportStaging.cs @@ -28,6 +28,11 @@ public Guid Create() public string ZipPath(Guid id) => Path.Combine(DirectoryOf(id), "scans.zip"); + /// Where the ZIP file of an export waits while it is read into the archive. + public string ExportPath(Guid id) => Path.Combine(DirectoryOf(id), "export.zip"); + + public bool ExportExists(Guid id) => File.Exists(ExportPath(id)); + public string WorkDirectory(Guid id) => Path.Combine(DirectoryOf(id), "work"); public bool Exists(Guid id) => File.Exists(CsvPath(id)); diff --git a/src/Commonage.Web/Import/ItemImport.cs b/src/Commonage.Web/Import/ItemImport.cs index 73cb9b6..f12c14c 100644 --- a/src/Commonage.Web/Import/ItemImport.cs +++ b/src/Commonage.Web/Import/ItemImport.cs @@ -102,7 +102,7 @@ public class ItemImport( "collection", "title", "date", "tags", "description", "rights", "rights_holder", "credit", "reference_number", "original_location", "files", ]; - private const int TitleMax = 300, DescriptionMax = 20000, HolderMax = 300, CreditMax = 300, ReferenceMax = 100, LocationMax = 300; + public const int TitleMax = 300, DescriptionMax = 20000, HolderMax = 300, CreditMax = 300, ReferenceMax = 100, LocationMax = 300; /// The template: the columns, in order, and no rows. public static string TemplateCsv() => string.Join(',', Columns) + "\r\n"; diff --git a/src/Commonage.Web/Pages/Admin/Items/Import.cshtml.cs b/src/Commonage.Web/Pages/Admin/Items/Import.cshtml.cs index 53f9cca..3df8510 100644 --- a/src/Commonage.Web/Pages/Admin/Items/Import.cshtml.cs +++ b/src/Commonage.Web/Pages/Admin/Items/Import.cshtml.cs @@ -26,9 +26,6 @@ public class ImportModel( TimeProvider clock, IStringLocalizer localizer) : PageModel { - /// An import runs one at a time: two of them would each be sure that an item is not there yet. - private static readonly SemaphoreSlim OneAtATime = new(1, 1); - /// How many problems the page lists. The rest is counted. public const int ShownIssues = 200; @@ -132,7 +129,7 @@ public async Task OnPostImportAsync(CancellationToken cancellatio return RedirectToPage(); } - if (!await OneAtATime.WaitAsync(0, cancellationToken)) + if (!await ImportLock.OneAtATime.WaitAsync(0, cancellationToken)) { TempData["Error"] = localizer["Another import is running. Please wait until it has finished."].Value; return RedirectToPage(); @@ -165,7 +162,7 @@ public async Task OnPostImportAsync(CancellationToken cancellatio } finally { - OneAtATime.Release(); + ImportLock.OneAtATime.Release(); } } diff --git a/src/Commonage.Web/Program.cs b/src/Commonage.Web/Program.cs index b74a349..4529579 100644 --- a/src/Commonage.Web/Program.cs +++ b/src/Commonage.Web/Program.cs @@ -85,6 +85,7 @@ builder.Services.AddSingleton(new LocalFileStorage(storageRoot)); builder.Services.AddSingleton(new ImportStaging(storageRoot)); builder.Services.AddScoped(); +builder.Services.AddScoped(); builder.Services.Configure(builder.Configuration.GetSection("Uploads")); builder.Services.AddSingleton(); PdfTools.RemoveStaleCopies(); @@ -129,6 +130,7 @@ options.Conventions.AuthorizePage(page, Policies.ManageArchive); options.Conventions.AuthorizeFolder("/Admin/Users", Policies.Administer); options.Conventions.AuthorizePage("/Admin/Export", Policies.Administer); + options.Conventions.AuthorizePage("/Admin/ImportArchive", Policies.Administer); options.Conventions.AuthorizePage("/Admin/Activity", Policies.Administer); options.Conventions.AuthorizePage("/Admin/Settings", Policies.Administer); options.Conventions.AuthorizePage("/Admin/System", Policies.Administer); From b508aa61d605dde726f2f9d931acdccc9c4f2500 Mon Sep 17 00:00:00 2001 From: "Seb H." <138793908+SebHenn@users.noreply.github.com> Date: Thu, 19 Nov 2026 20:17:31 +0100 Subject: [PATCH 3/7] M28, second part: import page for exports, German texts and tests Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Seb H. <138793908+SebHenn@users.noreply.github.com> --- src/Commonage.Web/Pages/Admin/Export.cshtml | 1 + .../Pages/Admin/ImportArchive.cshtml | 128 +++++ .../Pages/Admin/ImportArchive.cshtml.cs | 161 ++++++ .../Resources/SharedResource.de.resx | 47 ++ .../Resources/SharedResource.resx | 47 ++ .../AccessibilityTests.cs | 2 +- tests/Commonage.Tests/ExportImportTests.cs | 522 ++++++++++++++++++ 7 files changed, 907 insertions(+), 1 deletion(-) create mode 100644 src/Commonage.Web/Pages/Admin/ImportArchive.cshtml create mode 100644 src/Commonage.Web/Pages/Admin/ImportArchive.cshtml.cs create mode 100644 tests/Commonage.Tests/ExportImportTests.cs diff --git a/src/Commonage.Web/Pages/Admin/Export.cshtml b/src/Commonage.Web/Pages/Admin/Export.cshtml index 9f80ce4..ff52077 100644 --- a/src/Commonage.Web/Pages/Admin/Export.cshtml +++ b/src/Commonage.Web/Pages/Admin/Export.cshtml @@ -21,4 +21,5 @@ +

@T["Read an export into this archive"]

diff --git a/src/Commonage.Web/Pages/Admin/ImportArchive.cshtml b/src/Commonage.Web/Pages/Admin/ImportArchive.cshtml new file mode 100644 index 0000000..b0466dc --- /dev/null +++ b/src/Commonage.Web/Pages/Admin/ImportArchive.cshtml @@ -0,0 +1,128 @@ +@page +@model Commonage.Web.Pages.Admin.ImportArchiveModel +@using Commonage.Web.Import +@{ + ViewData["Title"] = T["Import an export"]; + var plan = Model.Plan; + var shown = Commonage.Web.Pages.Admin.ImportArchiveModel.ShownIssues; +} + + + +

@ViewData["Title"]

+ +@if (plan is { Refusal: not ExportRefusal.None }) +{ + +} + +@if (plan is { Refusal: ExportRefusal.None }) +{ +
+

@T["The dry run"]

+

@T["Nothing has been imported yet. This is what would happen."]

+
    +
  • @T["Items read: {0}", plan.Items.Count]
  • +
  • @T["Items that can be imported: {0}", plan.Ready.Count()]
  • +
  • @T["Photos that would be added: {0}", plan.ReadyFileCount]
  • +
  • @T["Collections that would be created: {0}", plan.NewCollections.Count]
  • +
  • @T["Items with problems, which are left out: {0}", plan.Items.Count(i => i.HasProblem)]
  • +
  • @T["Items left out on purpose: {0}", plan.Items.Count(i => i.IsLeftOut)]
  • +
+ + @if (plan.Ready.Any(i => i.MediaLevel != Commonage.Web.Domain.MediaLevel.Everything || i.PublicFrom is not null)) + { +

@T["Some items keep what the other archive chose for what visitors get of them, or the day from which they are public. They arrive as drafts either way."]

+ } + + @foreach (var (heading, rows, why) in new[] + { + (T["Problems"].Value, Model.Problems, T["What is wrong"].Value), + (T["Left out"].Value, Model.LeftOut, T["Why"].Value), + (T["Good to know"].Value, Model.Notes, T["What happens"].Value), + }) + { + var list = rows.ToList(); + if (list.Count == 0) + { + continue; + } + +

@heading

+
+ + + + + + + + + + + + + @foreach (var (item, issue) in list.Take(shown)) + { + + + + + + + + } + +
@heading
@T["Item"]@T["Title"]@T["Field"]@T["What the export says"]@why
@item.Number@item.Title@issue.Field@issue.Value@Model.Describe(issue)
+
+ @if (list.Count > shown) + { +

@T["More lines than are listed here: {0}", list.Count - shown]

+ } + } + +
+ @if (plan.CanImport) + { +
+ + +
+ } +
+ + +
+
+ @if (plan.CanImport) + { +

@T["Imported items become drafts, whatever they were in the other archive. A large import takes a while: keep this page open. If it breaks off, run it again: what is already there is left out."]

+ } +
+} +else if (!Model.CanUpload) +{ +

@T["The disk is nearly full, so no photos can be added at the moment. Tell the person who runs the server."]

+} +else +{ +
+

@T["Reads the ZIP file that the export of a Commonage archive makes, to merge two archives or to start a new one from another. Every item becomes a draft, and nothing is imported before you have seen a dry run."]

+

@T["What is left out: the names, email addresses and consent texts of contributors, notes from visitors, internal notes, who gave an item, users, settings, and the activity log. Items that were rejected or withdrawn, or whose contributor did not agree to sharing, are not imported. An item that is already here is never changed."]

+

@T["Import from a spreadsheet instead"]

+ +
+ +
+ + + +
+ + +
+} diff --git a/src/Commonage.Web/Pages/Admin/ImportArchive.cshtml.cs b/src/Commonage.Web/Pages/Admin/ImportArchive.cshtml.cs new file mode 100644 index 0000000..d28e1d7 --- /dev/null +++ b/src/Commonage.Web/Pages/Admin/ImportArchive.cshtml.cs @@ -0,0 +1,161 @@ +using Commonage.Web.Import; +using Commonage.Web.Operations; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.RazorPages; +using Microsoft.Extensions.Localization; + +namespace Commonage.Web.Pages.Admin; + +/// +/// Reads the ZIP file of another Commonage archive's export, or one this archive made, into this archive as drafts. First a +/// dry run lists what would come in and what would not; only after that does an admin choose to go on. The page names the +/// titles of items that are not published here, so it is never cached. +/// +[AcceptsUploads] +[RequestSizeLimit(ImportStaging.MaxZipBytes)] +[RequestFormLimits(MultipartBodyLengthLimit = ImportStaging.MaxZipBytes)] +public class ImportArchiveModel( + ExportImport import, + ImportStaging staging, + ArchiveHealth health, + TimeProvider clock, + IStringLocalizer localizer) : PageModel +{ + /// How many lines a list on the page shows. The rest is counted. + public const int ShownIssues = 200; + + [BindProperty] + public Guid? StagingId { get; set; } + + public ExportPlan? Plan { get; private set; } + public bool CanUpload => health.CanAcceptUploads(); + + public IEnumerable<(PlannedExportItem Item, ExportIssue Issue)> Problems => IssuesOf(ExportIssueSeverity.Problem); + public IEnumerable<(PlannedExportItem Item, ExportIssue Issue)> LeftOut => IssuesOf(ExportIssueSeverity.LeftOut); + public IEnumerable<(PlannedExportItem Item, ExportIssue Issue)> Notes => IssuesOf(ExportIssueSeverity.Note); + + private IEnumerable<(PlannedExportItem, ExportIssue)> IssuesOf(ExportIssueSeverity severity) => + Plan!.Items.SelectMany(i => i.Issues.Where(x => x.Severity == severity).Select(x => (i, x))); + + public string Describe(ExportIssue issue) => ExportImport.Describe(localizer, issue); + + public string DescribeRefusal() => ExportImport.Describe(localizer, Plan!.Refusal, Plan.FoundVersion); + + public void OnGet() + { + NoStore(); + staging.DeleteOld(TimeSpan.FromDays(1), clock.GetUtcNow().UtcDateTime); + } + + /// The dry run: keeps what was sent, reads it and shows what would happen. + public async Task OnPostAsync(IFormFile? export, CancellationToken cancellationToken) + { + NoStore(); + if (export is null || export.Length == 0) + ModelState.AddModelError("export", localizer["Please choose the ZIP file of an export."]); + if (!ModelState.IsValid) + return Page(); + + staging.DeleteOld(TimeSpan.FromDays(1), clock.GetUtcNow().UtcDateTime); + var id = staging.Create(); + try + { + await using var target = System.IO.File.Create(staging.ExportPath(id)); + await export!.CopyToAsync(target, cancellationToken); + await target.FlushAsync(cancellationToken); + } + catch + { + staging.Delete(id); + throw; + } + + // The ZIP file is closed before it is deleted, which Windows needs. + using (var source = ImportSources.OpenZip(staging.ExportPath(id), staging.WorkDirectory(id))) + { + try + { + Plan = source is null + ? new ExportPlan { Refusal = ExportRefusal.NotZip } + : await import.PlanAsync(source, cancellationToken); + } + catch + { + source?.Dispose(); + staging.Delete(id); + throw; + } + } + + if (Plan.Refusal != ExportRefusal.None) + { + staging.Delete(id); + return Page(); + } + + StagingId = id; + return Page(); + } + + public async Task OnPostImportAsync(CancellationToken cancellationToken) + { + if (StagingId is not { } id || !staging.ExportExists(id)) + { + TempData["Error"] = localizer["The files for this import are no longer there. Please choose them again."].Value; + return RedirectToPage(); + } + + if (!await ImportLock.OneAtATime.WaitAsync(0, cancellationToken)) + { + TempData["Error"] = localizer["Another import is running. Please wait until it has finished."].Value; + return RedirectToPage(); + } + + try + { + using var source = ImportSources.OpenZip(staging.ExportPath(id), staging.WorkDirectory(id)); + if (source is null) + { + TempData["Error"] = localizer["The files for this import are no longer there. Please choose them again."].Value; + return RedirectToPage(); + } + + // Looked at again, because the archive may have changed since the dry run. + var plan = await import.PlanAsync(source, cancellationToken); + if (!plan.CanImport) + { + TempData["Error"] = localizer["There is nothing left to import."].Value; + source.Dispose(); + staging.Delete(id); + return RedirectToPage(); + } + + if (!health.CanAcceptUploads(plan.ReadyBytes)) + { + TempData["Error"] = localizer["The disk is nearly full, so no photos can be added at the moment. Tell the person who runs the server."].Value; + return RedirectToPage(); + } + + var result = await import.RunAsync(plan, source, cancellationToken); + source.Dispose(); + staging.Delete(id); + TempData["Message"] = localizer["Drafts created: {0}. Photos added: {1}. Previews are being created.", result.Items, result.Files].Value; + if (result.FilesFailed > 0) + TempData["Error"] = localizer["Photos that could not be added, because the files had changed: {0}", result.FilesFailed].Value; + return LocalRedirect(Items.AddManyModel.DraftsUrl); + } + finally + { + ImportLock.OneAtATime.Release(); + } + } + + public IActionResult OnPostCancel() + { + if (StagingId is { } id) + staging.Delete(id); + return RedirectToPage(); + } + + private void NoStore() => Response.Headers.CacheControl = "private, no-store"; +} diff --git a/src/Commonage.Web/Resources/SharedResource.de.resx b/src/Commonage.Web/Resources/SharedResource.de.resx index c5dd7b9..ee35522 100644 --- a/src/Commonage.Web/Resources/SharedResource.de.resx +++ b/src/Commonage.Web/Resources/SharedResource.de.resx @@ -1029,4 +1029,51 @@ Nur als Datensatz gezeigt Unter Sperrfrist Besucher sehen dieses Foto noch nicht oder gar nicht + Ein Objekt mit diesem Titel und Datum ist in dieser Sammlung schon vorhanden, mit anderer Beschreibung. Es wird nicht geändert. + Export prüfen + Sammlungen, die angelegt würden: {0} + Sammlung beim Import angelegt + Jedes Foto dieses Objekts ist schon im Archiv. + Feld + Gut zu wissen + Export einlesen + Stattdessen aus einer Tabelle importieren + Eingelesene Objekte werden Entwürfe, was auch immer sie im anderen Archiv waren. Ein großer Import dauert eine Weile: Lassen Sie diese Seite offen. Bricht er ab, starten Sie ihn erneut: Was schon da ist, wird ausgelassen. + Objekte aus einem Commonage-Export eingelesen + Absichtlich ausgelassene Objekte: {0} + Gelesene Objekte: {0} + Objekte, die importiert werden können: {0} + Objekte mit Problemen, die ausgelassen werden: {0} + Ausgelassen + Ausgelassen: Es wurde im anderen Archiv abgelehnt. + Ausgelassen: Die Person, die es beigetragen hat, hat der Weitergabe nicht zugestimmt. + Ausgelassen: Die Person, die es beigetragen hat, hat ihre Einwilligung im anderen Archiv zurückgezogen. + Weitere Zeilen, die hier nicht aufgelistet sind: {0} + Ein Import legt höchstens {0, plural, one {# Sammlung} other {# Sammlungen}} an. Importieren Sie erneut für den Rest. + Bitte wählen Sie die ZIP-Datei eines Exports. + Einen Export in dieses Archiv einlesen + Liest die ZIP-Datei, die der Export eines Commonage-Archivs erzeugt, um zwei Archive zusammenzuführen oder ein neues aus einem anderen zu beginnen. Jedes Objekt wird ein Entwurf, und nichts wird importiert, bevor Sie einen Probelauf gesehen haben. + Manche Objekte behalten, was das andere Archiv dafür festgelegt hat, was Besucher davon bekommen, oder den Tag, ab dem sie öffentlich sind. Sie kommen in jedem Fall als Entwürfe an. + Die Sammlung dieses Objekts ist nicht im Export. + Die Tage im Export weichen von dem ab, was dieser Text hier bedeutet. Die Tage des Exports werden verwendet. + Die Datei archive.json in diesem Export konnte nicht gelesen werden. + Die Datei archive.json in diesem Export ist zu groß zum Lesen. + Das andere Archiv konnte diese Datei nicht exportieren, daher wird sie ausgelassen. + Der Ort dieser Datei in der ZIP-Datei ist nicht der, den ein Export schreibt. + Dieselbe Datei wie in Objekt {0}. + Derselbe Titel und dasselbe Datum wie Objekt {0}, in derselben Sammlung. + Diese ZIP-Datei ist kein Commonage-Export: Sie enthält keine archive.json. + Dieser Export hat die Formatversion {0}. Dieses Archiv liest die Versionen {1} bis {2}. + Dieser Export enthält mehr Daten, als ein Import lesen kann. + Dieser Export enthält mehr Objekte, Dateien, Schlagwörter oder Sammlungen, als ein Import lesen kann. + Diese Datei passt nicht zu ihrer Prüfsumme, daher wird sie ausgelassen. + Diese Datei ist nicht in der ZIP-Datei. + Das ist kein Commonage-Export. + Diesen Wert kennt dieses Archiv nicht. + Dieser Wert ist ungültig. + Was geschieht + Was ausgelassen wird: Namen, E-Mail-Adressen und Einwilligungstexte der Beitragenden, Hinweise von Besuchern, interne Notizen, wer ein Objekt gegeben hat, Konten, Einstellungen und das Aktivitätsprotokoll. Abgelehnte oder zurückgezogene Objekte und solche, bei denen die Person der Weitergabe nicht zugestimmt hat, werden nicht importiert. Ein Objekt, das schon hier ist, wird nie geändert. + Was der Export sagt + ZIP-Datei eines Exports + {0, plural, one {Das eine Objekt importieren, das in Ordnung ist} other {Die # Objekte importieren, die in Ordnung sind}} diff --git a/src/Commonage.Web/Resources/SharedResource.resx b/src/Commonage.Web/Resources/SharedResource.resx index acf75a7..416c89a 100644 --- a/src/Commonage.Web/Resources/SharedResource.resx +++ b/src/Commonage.Web/Resources/SharedResource.resx @@ -69,6 +69,7 @@ Always An item can have at most {0, plural, one {# tag} other {# tags}}.Has a count. Write a form for each one your language needs, in ICU MessageFormat. An item with this tag was changed at the same moment. Nothing was changed; please try again. + An item with this title and date is already in this collection, with a different description. It is not changed. An item with this title and date is already in this collection. Another import is running. Please wait until it has finished. Anyone can ask for their details, or what they sent in, to be changed or removed. The contact page says how to reach the archive. Backups keep older copies until they are replaced.Part of the privacy text an archive starts with. Please have a second translator review it. @@ -118,6 +119,7 @@ Changed their password Changed what visitors get of the item Check the contribution, complete the details below, then publish it, accept it as a draft or reject it. + Check the export Check the spreadsheet Checks Choose @@ -136,6 +138,7 @@ Collection for rows that name none Collection: {0} Collections + Collections that would be created: {0} Colour of buttons and links Column Columns that are not imported: {0} @@ -176,6 +179,7 @@ Created new recovery codes Created the account Created the collection + Created the collection while importing Created the contribution link Created the item Creating preview… @@ -248,6 +252,7 @@ Enable account Enabled the account Encrypted with COMMONAGE_LOGIN_KEY + Every photo of this item is already in the archive. Every place named in the archive, with how many items show it. Everyone Everyone named in the archive, with how many items they appear in. @@ -262,6 +267,7 @@ Export, settings and the log itself Exported the archive Exported the archive with contributors' personal data + Field File names in the ZIP file or folder, separated by semicolons. A name is enough when it is only there once; otherwise write the path. Files in the ZIP file or folder that no row names: {0} Filter @@ -299,6 +305,7 @@ Go on to managing the archive Go to the drafts without a title Go to the start page + Good to know Handbook Help from visitors Helper @@ -316,7 +323,11 @@ If the contributor asks If you do not know yet, choosing that it is not checked is honest. A free licence is only yours to give for what you hold the rights to. Import a spreadsheet + Import an export Import from a spreadsheet + Import from a spreadsheet instead + Imported items become drafts, whatever they were in the other archive. A large import takes a while: keep this page open. If it breaks off, run it again: what is already there is left out. + Imported items from a Commonage export Imported items from a spreadsheet Imported rows become drafts, whatever the spreadsheet says. A large import takes a while: keep this page open. If it breaks off, run it again: what is already there is left out. Imprint @@ -339,7 +350,11 @@ Items chosen: {0} Items found: {0} Items in the bin: {0} + Items left out on purpose: {0} + Items read: {0} Items that already have one, which is then replaced: {0}. + Items that can be imported: {0} + Items with problems, which are left out: {0} Items: {0} JPEG, PNG, TIFF, WebP, AVIF or GIF, at most {0} MB. It is also used as the browser tab's icon. JPEG, PNG, TIFF, WebP, AVIF, GIF or PDF. The original file is kept unchanged and is only visible to curators. @@ -360,11 +375,15 @@ Later: {0} Leave empty to take an embargo away. Leave this field empty + Left out Left out, because a recording has no transcript yet: {0}. Left out, because the archive already has them: {0} Left out, because they are not drafts: {0}. A contribution needs a decision of its own, on its own page. Left out, because they have no title yet: {0}. Left out, because they would be there twice + Left out: it was rejected in the other archive. + Left out: its contributor did not agree to it being shared further. + Left out: its contributor withdrew their consent in the other archive. Let search engines list this archive Let visitors open photos at a large size Letters @@ -399,6 +418,7 @@ Merged two tags into one More about it More from {0} + More lines than are listed here: {0} More problems than are listed here: {0} More than one collection has this name. Rename one of them first. Move many to a collection @@ -475,6 +495,7 @@ Oldest first On each contribution you can remove their name and email address, mark it as withdrawn, or move the item to the bin and delete it there for good. Backups keep older copies until they are replaced. On the contribution form, the title, date and description you type stay in your own browser for three days or until you send them, so that nothing is lost if you have to stop. They reach the archive only when you send the form, and you can clear them at any time.Part of the privacy text an archive starts with. Please have a second translator review it. + One import creates at most {0, plural, one {# collection} other {# collections}}. Import again for the rest.Has a count. Write a form for each one your language needs, in ICU MessageFormat. Only a tag that no item has can be deleted. To move its items to another tag, merge it. Only an empty collection can be deleted. Move its items to another collection first. Only an empty collection can be deleted: without items, also in the bin, and without contribution links that send material to it. @@ -538,6 +559,7 @@ Please choose one of the statements. Please choose one of the time zones. Please choose one of the times. + Please choose the ZIP file of an export. Please choose the photos again. Please choose the spreadsheet, saved as CSV. Please choose what you would like to tell us. @@ -590,7 +612,9 @@ Publish: {0} Published Published the item + Read an export into this archive Read the privacy text and adapt it + Reads the ZIP file that the export of a Commonage archive makes, to merge two archives or to start a new one from another. Every item becomes a draft, and nothing is imported before you have seen a dry run. Received from Received when Recently added @@ -682,6 +706,7 @@ Six digits. Without your phone, type one of your recovery codes instead. Each one works once. Skip to content Software + Some items keep what the other archive chose for what visitors get of them, or the day from which they are public. They arrive as drafts either way. Some items wait for someone who knows more about them. Someone else changed one of these items just now, so nothing was changed. Please try again. Someone else changed this item while you were working on it @@ -736,6 +761,7 @@ The authenticator app is turned off for this account. The person logs in with their password now. The bin is empty. The collection is empty, so it can be deleted. + The collection of this item is not in the export. The collection “{0}” is deleted. The collection's public page The collection's public page then shows the heading of this link and a button to it, while the link is open. Without this, only the people you give the link to know it exists. Turn it on only if anyone may send something in. @@ -757,6 +783,7 @@ The current password is incorrect. The date can be at most {0, plural, one {# character} other {# characters}} long.Has a count. Write a form for each one your language needs, in ICU MessageFormat. The date can be at most {1} characters long. + The days in the export differ from what this text means here. The days of the export are used. The description can be at most {1} characters long. The disk is filling up, or uploads have already stopped. The disk is filling up. Free disk space (GB): {0}. Uploads stop before it is full. @@ -766,6 +793,8 @@ The earlier text is back. The email address can be at most {1} characters long. The email address or password is incorrect. + The file archive.json in this export could not be read. + The file archive.json in this export is too large to read. The files for this import are no longer there. Please choose them again. The first photo The first row of the spreadsheet must name the columns. None of them is one this import knows. Download the template to see them. @@ -794,6 +823,7 @@ The note is open again. The old app no longer works. Set up the new one now: this archive requires it. The original files exactly as they were uploaded, in one folder per item: + The other archive could not export this file, so it is left out. The password can be at most {1} characters long. The password is not right. The password must be at least {0, plural, one {# character} other {# characters}} long.Has a count. Write a form for each one your language needs, in ICU MessageFormat. @@ -806,10 +836,13 @@ The photo is in the bin. You can restore it there for {0, plural, one {# day} other {# days}}.Has a count. Write a form for each one your language needs, in ICU MessageFormat. The photo is restored. The photo visitors see for the collection. They only see a photo while its item is published; until then, and without a choice, they see the first photo of the collection. + The place of this file in the ZIP file is not the one an export writes. The record only, without pictures and recordings The request could not be processed + The same file as in item {0}. The same file as in row {0}. The same items as a table, for spreadsheet programs. It is UTF-8. Cells that start with =, +, - or @ get a leading apostrophe, so a spreadsheet never runs them as formulas; archive.json has the exact text. + The same title and date as item {0}, in the same collection. The same title and date as row {0}, in the same collection. The server's clock The spreadsheet could not be read: a quotation mark is never closed. @@ -838,6 +871,7 @@ These photos are too much to send with the form. Save the item first, then add them: they are sent one at a time there. They hold the contributor's name and email address, and material that will not be published. Afterwards they go to the bin, and are deleted for good 30 days later. This ZIP file holds a copy of a community archive made with Commonage. You need no special software to use it. + This ZIP file is not a Commonage export: it has no archive.json. This account is disabled. Please ask an admin. This archive cannot take in anything new at the moment, because its storage is full. Please try again later. This archive keeps rejected and withdrawn contributions for a set time. This one goes to the bin on {0}. @@ -849,11 +883,17 @@ This date could not be understood. Please include a year, for example: 1953, 12.03.1953, circa 1950, 1950s, 1950–1955. This describes what Commonage itself stores. It is a template and not legal advice: adapt it to what your group does. This draft has no title yet, and cannot be published without one. Give it a title that says what the photo shows. + This export has the format version {0}. This archive reads the versions {1} to {2}. + This export holds more data than one import can read. + This export holds more items, files, tags or collections than one import can read. + This file does not match its checksum, so it is left out. This file is not in the ZIP file or the folder. + This file is not in the ZIP file. This file is too large. This folder is not there any more. This form belongs to {0}. This is a demo archive. Everything in it, people and pictures included, is made up. + This is not a Commonage export. This is not a ZIP file, or it holds too many files. This is not one of the archive's rights statements. Write its web address as an export does, or leave the cell empty. This is your own account. Another admin can change its role, disable or delete it. @@ -871,6 +911,8 @@ This text can be at most {1} characters long. This text cannot be put back: the field would be empty or no longer reads as valid. This text was started on this device earlier. If it is not yours, clear it. + This value is not one this archive knows. + This value is not valid. Through the decades Tick all on this page Time zone @@ -933,6 +975,8 @@ What changed What do you know about it? (optional) What does it show? + What happens + What is left out: the names, email addresses and consent texts of contributors, notes from visitors, internal notes, who gave an item, users, settings, and the activity log. Items that were rejected or withdrawn, or whose contributor did not agree to sharing, are not imported. An item that is already here is never changed. What is new in {0} What is wrong What may others do with it? @@ -940,6 +984,7 @@ What needs attention What others may do with this item. Choose a free licence only if whoever holds the rights really gave it. What the cell says + What the export says What this means What visitors get What visitors sent through “Do you know more about this?” on an item. It is not shown publicly: write what is worth keeping into the item, then mark the note as dealt with. @@ -987,6 +1032,7 @@ Your password is set. You can log in now. Your recovery codes Your reference: {0}. Please note it down: you can quote it if you want to ask about what you sent, or have it taken down. No email will follow. + ZIP file of an export ZIP file with the scans (optional) accessed {0} may be named publicly @@ -1005,6 +1051,7 @@ {0, plural, one {For # month after the decision} other {For # months after the decision}}Has a count. Write a form for each one your language needs, in ICU MessageFormat. {0, plural, one {For # year} other {For # years}}Has a count. Write a form for each one your language needs, in ICU MessageFormat. {0, plural, one {For one photo, no preview could be made.} other {For # photos, no preview could be made.}} Visitors do not see them. A file the archive cannot read will fail again; the original stays safe either way, and curators can download it from the item.Has a count. Write a form for each one your language needs, in ICU MessageFormat. + {0, plural, one {Import the one item that is in order} other {Import the # items that are in order}}Has a count. Write a form for each one your language needs, in ICU MessageFormat. {0, plural, one {Import the one row that is in order} other {Import the # rows that are in order}}Has a count. Write a form for each one your language needs, in ICU MessageFormat. {0, plural, one {On one item} other {On # items}}Has a count. Write a form for each one your language needs, in ICU MessageFormat. {0, plural, one {One database change has not been made yet.} other {# database changes have not been made yet.}} They are made when the archive starts.Has a count. Write a form for each one your language needs, in ICU MessageFormat. diff --git a/tests/Commonage.BrowserTests/AccessibilityTests.cs b/tests/Commonage.BrowserTests/AccessibilityTests.cs index e3944b1..0fe67bf 100644 --- a/tests/Commonage.BrowserTests/AccessibilityTests.cs +++ b/tests/Commonage.BrowserTests/AccessibilityTests.cs @@ -14,7 +14,7 @@ public static TheoryData PublicPages() => Widths( public static TheoryData CuratorPages() => Widths( "/Admin", "/Admin?status=Submitted", "/Admin/Items/Edit/11", "/Admin/Items/Edit", "/Admin/Items/AddMany", "/Admin/Items/Import", "/Admin/Items/Edit/1", "/Admin/Items/Preview/1", "/Admin/Collections", "/Admin/Collections/Edit/1", "/Admin/Collections/Edit", "/Admin/Tags", "/Admin/Tags/Edit/1", "/Admin/Notes", "/Admin/Notes?show=All", "/Admin/Contributions", "/Admin/Contributions/Poster/1", - "/Admin/Contributors?q=a", "/Admin/Bin", "/Admin/Settings", "/Admin/Users", "/Admin/Activity", "/Admin/Activity?what=Items", "/Admin/Export", "/Admin/System", "/Account/Password", "/Account/TwoFactor"); + "/Admin/Contributors?q=a", "/Admin/Bin", "/Admin/Settings", "/Admin/Users", "/Admin/Activity", "/Admin/Activity?what=Items", "/Admin/Export", "/Admin/ImportArchive", "/Admin/System", "/Account/Password", "/Account/TwoFactor"); private static TheoryData Widths(params string[] paths) { diff --git a/tests/Commonage.Tests/ExportImportTests.cs b/tests/Commonage.Tests/ExportImportTests.cs new file mode 100644 index 0000000..ad71edf --- /dev/null +++ b/tests/Commonage.Tests/ExportImportTests.cs @@ -0,0 +1,522 @@ +using System.IO.Compression; +using System.Net; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; +using Commonage.Web.Data; +using Commonage.Web.Domain; +using Commonage.Web.Export; +using Commonage.Web.Import; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.EntityFrameworkCore; + +namespace Commonage.Tests; + +/// Reading an export of Commonage's own back in: as drafts, without anyone's personal details, and never more than once. +[Collection(nameof(AppCollection))] +public partial class ExportImportTests(CommonageAppFactory app) +{ + private const string Page = "/Admin/ImportArchive"; + + private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web); + + private static byte[] NewPhoto() => [.. TestData.Photo, .. Guid.NewGuid().ToByteArray()]; + + private static string Sha(byte[] bytes) => Convert.ToHexStringLower(SHA256.HashData(bytes)); + + private static async Task CuratorAsync(WebApplicationFactory archive) + { + var client = archive.CreateClient(); + await Browser.LogInAsCuratorAsync(client); + return client; + } + + private static byte[] Zip(params (string Name, byte[] Content)[] files) + { + using var stream = new MemoryStream(); + using (var zip = new ZipArchive(stream, ZipArchiveMode.Create, leaveOpen: true)) + { + foreach (var (name, content) in files) + { + using var entry = zip.CreateEntry(name).Open(); + entry.Write(content); + } + } + + return stream.ToArray(); + } + + private static byte[] ArchiveJson(object[] items, object[]? collections = null, int version = 8, string format = "commonage-export") => + JsonSerializer.SerializeToUtf8Bytes(new { format, version, collections = collections ?? [], tags = Array.Empty(), items }, Json); + + private static object Collection(int id, string title) => new { id, title, description = (string?)null }; + + private static object File(int id, int item, string name, byte[] content, string? sha = null, string? path = null) => new + { + id, + path = path ?? $"files/{item}/{id}-{name}", + originalFileName = name, + sha256 = sha ?? Sha(content), + position = 0, + rotation = 0, + problem = (string?)null, + }; + + private static object Item(int id, string title, int collectionId = 1, string status = "Published", object? date = null, + object? contribution = null, object[]? files = null, string? mediaLevel = null, string? publicFrom = null, string? description = null) => new + { + id, + collectionId, + title, + description, + status, + date, + tags = Array.Empty(), + mediaLevel, + publicFrom, + contribution, + files = files ?? [], + }; + + private static async Task DryRunAsync(HttpClient client, byte[] zip) + { + var page = await client.GetStringAsync(Page); + using var form = new MultipartFormDataContent + { + { new StringContent(Browser.Token(page)), "__RequestVerificationToken" }, + { new ByteArrayContent(zip), "export", "export.zip" }, + }; + var response = await client.PostAsync(Page, form); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Contains("no-store", response.Headers.CacheControl?.ToString()); + return await response.Content.ReadAsStringAsync(); + } + + private static async Task ImportAsync(HttpClient client, string dryRunHtml) + { + var id = StagingIdPattern().Match(dryRunHtml).Groups[1].Value; + Assert.NotEmpty(id); + var response = await client.PostAsync($"{Page}?handler=Import", new FormUrlEncodedContent(new Dictionary + { + ["__RequestVerificationToken"] = Browser.Token(dryRunHtml), + ["StagingId"] = id, + })); + response.EnsureSuccessStatusCode(); + } + + [GeneratedRegex(@"name=""StagingId""[^>]*value=""([^""]+)""")] + private static partial Regex StagingIdPattern(); + + private async Task RunAsync(HttpClient client, byte[] zip) + { + var html = await DryRunAsync(client, zip); + if (StagingIdPattern().IsMatch(html) && html.Contains("handler=Import")) + await ImportAsync(client, html); + return html; + } + + private Task> ItemsAsync(string titleContains) => + app.WithDbAsync(db => db.ArchiveItems.IgnoreQueryFilters().Include(i => i.MediaFiles).Include(i => i.Collection) + .Where(i => i.Title.Contains(titleContains)).OrderBy(i => i.Id).ToListAsync()); + + private static string Word() => TestData.UniqueWord("Exportword"); + + [Fact] + public async Task An_export_of_this_app_comes_back_as_drafts_without_a_single_personal_detail() + { + await using var from = await app.NewArchiveAsync(); + using var source = await CuratorAsync(from); + var word = Word(); + var contribution = await from.CreateContributionAsync(ItemStatus.Published, name: "Erika Zeppelin", email: "zeppelin@example.org"); + var photo = NewPhoto(); + await Browser.UploadAsync(source, $"/Admin/Items/Edit/{contribution.Id}", "Upload", "mill.jpg", photo); + await from.WithDbAsync(async db => + { + var item = await db.ArchiveItems.Include(i => i.Contribution).SingleAsync(i => i.Id == contribution.Id); + item.Title = $"{word} Mill"; + item.Description = "The old mill in spring"; + item.MediaLevel = MediaLevel.RecordOnly; + item.PublicFrom = new DateOnly(2099, 6, 1); + item.SetDateRange("Spring 1953", new DateOnly(1953, 3, 1), new DateOnly(1953, 5, 31)); + item.ReceivedFrom = "Aunt Frieda Hohenzollern"; + item.InternalNotes = "Do not tell anyone about the cellar"; + item.Contribution!.ConsentCoversSharing = true; + item.Contribution.ConsentText = "I, Erika Zeppelin, agree to everything."; + db.VisitorNotes.Add(new VisitorNote + { + ArchiveItemId = item.Id, Message = "A note from Gustav Visitor", Name = "Gustav Visitor", Email = "gustav@example.org", ReceivedAt = DateTime.UtcNow, + }); + return await db.SaveChangesAsync(); + }); + var originalSha = await from.WithDbAsync(db => db.MediaFiles.Where(f => f.ArchiveItemId == contribution.Id).Select(f => f.Sha256).SingleAsync()); + var response = await Browser.PostFormAsync(source, "/Admin/Export", new() { ["IncludePersonalData"] = "true" }); + var export = await response.Content.ReadAsByteArrayAsync(); + Assert.Contains("zeppelin@example.org", Encoding.UTF8.GetString(ReadEntry(export, "archive.json"))); + + await using var into = await app.NewArchiveAsync(); + using var target = await CuratorAsync(into); + var html = await DryRunAsync(target, export); + await ImportAsync(target, html); + + var items = await into.WithDbAsync(db => db.ArchiveItems.IgnoreQueryFilters().Include(i => i.MediaFiles).ToListAsync()); + var imported = Assert.Single(items); + Assert.Equal($"{word} Mill", imported.Title); + Assert.Equal("The old mill in spring", imported.Description); + Assert.Equal(ItemStatus.Draft, imported.Status); + Assert.Null(imported.PublishedAt); + Assert.Equal(MediaLevel.RecordOnly, imported.MediaLevel); + Assert.Equal(new DateOnly(2099, 6, 1), imported.PublicFrom); + Assert.Equal("Spring 1953", imported.DateText); + Assert.Equal(new DateOnly(1953, 3, 1), imported.DateFrom); + Assert.Equal(new DateOnly(1953, 5, 31), imported.DateTo); + Assert.Equal(originalSha, Assert.Single(imported.MediaFiles).Sha256); + Assert.Null(imported.ReceivedFrom); + Assert.Null(imported.InternalNotes); + Assert.Null(imported.Contribution); + + var everything = await into.WithDbAsync(async db => + string.Join('\n', await db.Contributions.Select(c => c.ContributorName + c.ContributorEmail + c.ConsentText).ToListAsync()) + + string.Join('\n', await db.VisitorNotes.Select(n => n.Message + n.Name + n.Email).ToListAsync()) + + string.Join('\n', await db.AuditEntries.Select(a => a.UserName + a.Subject + a.Action).ToListAsync()) + + string.Join('\n', await db.ArchiveItems.IgnoreQueryFilters().Select(i => i.ReceivedFrom + i.InternalNotes + i.Description + i.RightsHolder).ToListAsync())); + var activity = await target.GetStringAsync("/Admin/Activity"); + foreach (var secret in new[] { "Zeppelin", "zeppelin@example.org", "agree to everything", "Gustav", "gustav@example.org", "Hohenzollern", "cellar" }) + { + Assert.DoesNotContain(secret, everything); + Assert.DoesNotContain(secret, html); + Assert.DoesNotContain(secret, activity); + } + + Assert.Contains("Imported items from a Commonage export", activity); + var actions = await into.WithDbAsync(db => db.AuditEntries.Select(e => e.Action).ToListAsync()); + Assert.Contains(AuditAction.ArchiveImported, actions); + Assert.Contains(AuditAction.ItemCreated, actions); + Assert.Contains(AuditAction.PhotosAdded, actions); + + // The second run finds everything there and offers nothing. + var again = await DryRunAsync(target, export); + Assert.DoesNotContain("handler=Import", again); + Assert.Single(await into.WithDbAsync(db => db.ArchiveItems.IgnoreQueryFilters().ToListAsync())); + } + + [Theory] + [InlineData(4)] + [InlineData(8)] + public async Task Versions_four_to_the_current_one_are_read(int version) + { + using var curator = await CuratorAsync(app); + var word = Word(); + var json = ArchiveJson([Item(1, $"{word} Barn")], [Collection(1, $"{word} Collection")], version); + + await RunAsync(curator, Zip(("archive.json", json))); + + var item = Assert.Single(await ItemsAsync(word)); + Assert.Equal(ItemStatus.Draft, item.Status); + } + + [Theory] + [InlineData(3, "format version 3")] + [InlineData(9, "format version 9")] + public async Task Other_versions_and_other_files_are_refused_with_a_sentence(int version, string expected) + { + using var curator = await CuratorAsync(app); + var word = Word(); + + var html = await DryRunAsync(curator, Zip(("archive.json", ArchiveJson([Item(1, $"{word} X")], null, version)))); + + Assert.Contains(expected, html); + Assert.Empty(await ItemsAsync(word)); + Assert.DoesNotContain("handler=Import", html); + + var other = await DryRunAsync(curator, Zip(("archive.json", ArchiveJson([], null, 8, "something-else")))); + Assert.Contains("This is not a Commonage export.", other); + var plain = await DryRunAsync(curator, Zip(("readme.txt", "hi"u8.ToArray()))); + Assert.Contains("has no archive.json", plain); + } + + [Fact] + public async Task A_file_with_the_wrong_checksum_is_left_out_and_not_stored() + { + using var curator = await CuratorAsync(app); + var word = Word(); + var photo = NewPhoto(); + var json = ArchiveJson( + [Item(1, $"{word} Barn", files: [File(7, 1, "barn.jpg", photo, sha: Sha([1, 2, 3]))])], + [Collection(1, $"{word} Collection")]); + + var html = await RunAsync(curator, Zip(("archive.json", json), ("files/1/7-barn.jpg", photo))); + + Assert.Contains("does not match its checksum", html); + var item = Assert.Single(await ItemsAsync(word)); + Assert.Empty(item.MediaFiles); + } + + [Fact] + public async Task Names_that_climb_out_of_the_folder_are_never_looked_up_and_never_stored() + { + using var curator = await CuratorAsync(app); + var word = Word(); + var photo = NewPhoto(); + var json = ArchiveJson( + [Item(1, $"{word} Barn", files: [File(7, 1, "barn.jpg", photo, path: "files/1/../../evil.jpg")]), + Item(2, $"{word} Shed", files: [File(8, 2, "shed.jpg", photo, path: "files/2/8-shed.jpg/../../x.jpg")])], + [Collection(1, $"{word} Collection")]); + + var html = await RunAsync(curator, Zip(("archive.json", json), ("evil.jpg", photo), ("x.jpg", photo))); + + Assert.Contains("not the one an export writes", html); + Assert.All(await ItemsAsync(word), item => Assert.Empty(item.MediaFiles)); + } + + [Fact] + public async Task An_entry_that_lies_about_its_size_does_not_get_a_file_stored_or_break_the_page() + { + using var curator = await CuratorAsync(app); + var word = Word(); + var photo = NewPhoto(); + var json = ArchiveJson( + [Item(1, $"{word} Barn", files: [File(7, 1, "barn.jpg", photo)])], + [Collection(1, $"{word} Collection")]); + var zip = Zip(("archive.json", json), ("files/1/7-barn.jpg", photo)); + LieAboutSize(zip, "files/1/7-barn.jpg", 10); + + await RunAsync(curator, zip); + + Assert.All(await ItemsAsync(word), item => Assert.Empty(item.MediaFiles)); + } + + [Fact] + public async Task An_archive_json_that_inflates_beyond_the_limit_is_refused_while_it_is_read() + { + using var curator = await CuratorAsync(app); + using var stream = new MemoryStream(); + using (var zip = new ZipArchive(stream, ZipArchiveMode.Create, leaveOpen: true)) + { + using var entry = zip.CreateEntry("archive.json", CompressionLevel.SmallestSize).Open(); + entry.Write("{\"format\":\"commonage-export\",\"version\":8,\"items\":["u8); + var spaces = new byte[1024 * 1024]; + Array.Fill(spaces, (byte)' '); + for (var i = 0; i < 260; i++) + entry.Write(spaces); + entry.Write("]}"u8); + } + + Assert.True(stream.Length < 5 * 1024 * 1024, "the test file is meant to be small"); + var html = await DryRunAsync(curator, stream.ToArray()); + + Assert.Contains("too large to read", html); + Assert.DoesNotContain("handler=Import", html); + } + + [Fact] + public async Task Whatever_the_status_an_item_arrives_as_a_draft_and_keeps_what_visitors_get_and_when() + { + using var curator = await CuratorAsync(app); + var word = Word(); + var json = ArchiveJson( + [Item(1, $"{word} Embargoed", mediaLevel: "RecordOnly", publicFrom: "2099-06-01"), + Item(2, $"{word} Accepted", status: "Submitted"), + Item(3, $"{word} Wrong day", publicFrom: "1066-01-01"), + Item(4, $"{word} Unknown level", mediaLevel: "Everything-and-more"), + Item(5, $"{word} Unknown status", status: "Banana")], + [Collection(1, $"{word} Collection")]); + + var html = await RunAsync(curator, Zip(("archive.json", json))); + + var items = await ItemsAsync(word); + Assert.All(items, item => Assert.Equal(ItemStatus.Draft, item.Status)); + Assert.All(items, item => Assert.Null(item.PublishedAt)); + var embargoed = items.Single(i => i.Title.EndsWith("Embargoed")); + Assert.Equal(MediaLevel.RecordOnly, embargoed.MediaLevel); + Assert.Equal(new DateOnly(2099, 6, 1), embargoed.PublicFrom); + Assert.Equal(MediaLevel.Everything, items.Single(i => i.Title.EndsWith("Accepted")).MediaLevel); + Assert.Equal(2, items.Count); + Assert.Contains("This value is not valid.", html); + Assert.Contains("This value is not one this archive knows.", html); + } + + [Fact] + public async Task Rejected_withdrawn_and_unconsented_items_are_left_out_and_listed_with_a_reason() + { + using var curator = await CuratorAsync(app); + var word = Word(); + var json = ArchiveJson( + [Item(1, $"{word} Fine"), + Item(2, $"{word} Rejected", status: "Rejected"), + Item(3, $"{word} Withdrawn", status: "Withdrawn"), + Item(4, $"{word} No consent", contribution: new { consentCoversSharing = false }), + Item(5, $"{word} Consent", contribution: new { consentCoversSharing = true })], + [Collection(1, $"{word} Collection")]); + + var html = await RunAsync(curator, Zip(("archive.json", json))); + + Assert.Equal([$"{word} Consent", $"{word} Fine"], (await ItemsAsync(word)).Select(i => i.Title).Order().ToArray()); + Assert.Contains("it was rejected in the other archive", html); + Assert.Contains("withdrew their consent", html); + Assert.Contains("did not agree to it being shared further", html); + } + + [Fact] + public async Task A_second_run_of_the_same_export_adds_nothing() + { + using var curator = await CuratorAsync(app); + var word = Word(); + var zip = Zip(("archive.json", ArchiveJson([Item(1, $"{word} Barn"), Item(2, $"{word} Shed")], [Collection(1, $"{word} Collection")]))); + + await RunAsync(curator, zip); + var second = await RunAsync(curator, zip); + + Assert.Equal(2, (await ItemsAsync(word)).Count); + Assert.DoesNotContain("handler=Import", second); + Assert.Single((await ItemsAsync(word)).Select(i => i.CollectionId).Distinct()); + } + + [Fact] + public async Task Titles_are_compared_after_normalising_so_a_decomposed_title_is_the_same_item() + { + using var curator = await CuratorAsync(app); + var word = Word(); + var collection = Collection(1, $"{word} Collection"); + await RunAsync(curator, Zip(("archive.json", ArchiveJson([Item(1, $"{word} Café")], [collection])))); + + var again = await RunAsync(curator, Zip(("archive.json", ArchiveJson([Item(1, $"{word} CAFÉ")], [collection])))); + + Assert.Single(await ItemsAsync(word)); + Assert.DoesNotContain("handler=Import", again); + } + + [Fact] + public async Task Titles_in_any_script_arrive_as_written() + { + using var curator = await CuratorAsync(app); + var word = Word(); + string[] titles = [$"春祭り {word}", $"مهرجان الحصاد {word}", $"Праздник урожая {word}"]; + var json = ArchiveJson(titles.Select((t, i) => Item(i + 1, t, description: t)).ToArray(), [Collection(1, $"{word} 収穫")]); + + await RunAsync(curator, Zip(("archive.json", json))); + + var items = await ItemsAsync(word); + Assert.Equal(titles.Order(StringComparer.Ordinal), items.Select(i => i.Title).Order(StringComparer.Ordinal)); + Assert.All(items, item => Assert.Equal(item.Title, item.Description)); + Assert.All(items, item => Assert.Equal($"{word} 収穫", item.Collection.Title)); + } + + [Fact] + public async Task A_date_text_nobody_can_read_still_arrives_with_its_exported_days() + { + using var curator = await CuratorAsync(app); + var word = Word(); + var json = ArchiveJson( + [Item(1, $"{word} Barn", date: new { text = "around the time of the old mill", from = "1950-01-01", to = "1959-12-31" })], + [Collection(1, $"{word} Collection")]); + + await RunAsync(curator, Zip(("archive.json", json))); + + var item = Assert.Single(await ItemsAsync(word)); + Assert.Equal(new DateOnly(1950, 1, 1), item.DateFrom); + Assert.Equal(new DateOnly(1959, 12, 31), item.DateTo); + Assert.Equal("around the time of the old mill", item.DateText); + } + + [Fact] + public async Task Only_an_admin_may_use_the_page() + { + using var admin = await CuratorAsync(app); + var (curator, _, _, _) = await app.CreateAccountAsync(admin); + using var anonymous = app.CreateClient(new() { AllowAutoRedirect = false }); + + Assert.Equal(HttpStatusCode.Forbidden, (await curator.GetAsync(Page)).StatusCode); + Assert.Equal(HttpStatusCode.OK, (await admin.GetAsync(Page)).StatusCode); + Assert.Equal(HttpStatusCode.Redirect, (await anonymous.GetAsync(Page)).StatusCode); + curator.Dispose(); + } + + [Fact] + public void Every_property_of_the_export_has_a_decision_and_the_reader_holds_exactly_what_is_not_dropped() + { + var assembly = typeof(ArchiveExporter).Assembly; + string[] types = ["ExportSettings", "ExportText", "ExportCollection", "ExportTag", "ExportItem", "ExportDate", "ExportContribution", "ExportNote", "ExportFile"]; + var missing = new List(); + var found = new HashSet(); + foreach (var name in types) + { + var type = assembly.GetTypes().Single(t => t.Name == name && t.Namespace == typeof(ArchiveExporter).Namespace); + foreach (var property in type.GetProperties().Where(p => p.DeclaringType == type)) + { + var key = $"{name}.{property.Name}"; + found.Add(key); + if (!ExportImportTable.Fields.ContainsKey(key)) + missing.Add(key); + } + } + + Assert.True(missing.Count == 0, "The export has properties that ExportImportTable has no decision for:\n" + string.Join('\n', missing)); + Assert.True(ExportImportTable.Fields.Keys.All(found.Contains), "ExportImportTable decides about a property that the export no longer has."); + + (string Export, Type Imported)[] pairs = + [ + ("ExportCollection", typeof(ImportedCollection)), ("ExportTag", typeof(ImportedTag)), ("ExportItem", typeof(ImportedItem)), + ("ExportDate", typeof(ImportedDate)), ("ExportContribution", typeof(ImportedContribution)), ("ExportFile", typeof(ImportedFile)), + ]; + foreach (var (export, imported) in pairs) + { + var wanted = ExportImportTable.Fields + .Where(f => f.Key.StartsWith(export + ".") && f.Value.Decision != ExportFieldDecision.Dropped) + .Select(f => f.Key[(export.Length + 1)..]).Order(StringComparer.Ordinal).ToArray(); + var held = imported.GetProperties().Select(p => p.Name).Order(StringComparer.Ordinal).ToArray(); + Assert.Equal(wanted, held); + } + + var contribution = ExportImportTable.Fields.Where(f => f.Key.StartsWith("ExportContribution.") && f.Value.Decision != ExportFieldDecision.Dropped).ToList(); + Assert.Equal("ExportContribution.ConsentCoversSharing", Assert.Single(contribution).Key); + } + + [Fact] + public void The_importer_never_publishes_deletes_or_reads_around_the_filters() + { + var folder = Path.Combine(SourceRoot(), "Import"); + string[] forbidden = ["ItemStatus.Published", ".Publish(", "PublishedAt", "SetPublicFrom", ".Remove(", "RemoveRange", "ExecuteDelete", "ExecuteUpdate", "IgnoreQueryFilters", "DateTime.UtcNow", "DateTime.Now"]; + var offences = new List(); + // ExportReading.cs only names the dropped properties, among them PublishedAt, so it is the importer that is read. + foreach (var file in new[] { "ExportImport.cs" }) + { + var text = System.IO.File.ReadAllText(Path.Combine(folder, file)); + offences.AddRange(forbidden.Where(text.Contains).Select(f => $"{file}: {f}")); + } + + Assert.True(offences.Count == 0, "The importer must make drafts, only insert, and use the clock it is given:\n" + string.Join('\n', offences)); + } + + private static string SourceRoot() + { + var directory = new DirectoryInfo(AppContext.BaseDirectory); + while (directory is not null && !Directory.Exists(Path.Combine(directory.FullName, "src", "Commonage.Web"))) + directory = directory.Parent; + return Path.Combine(directory?.FullName ?? throw new InvalidOperationException("Source folder not found."), "src", "Commonage.Web"); + } + + private static byte[] ReadEntry(byte[] zip, string path) + { + using var archive = new ZipArchive(new MemoryStream(zip)); + using var stream = archive.GetEntry(path)!.Open(); + using var copy = new MemoryStream(); + stream.CopyTo(copy); + return copy.ToArray(); + } + + /// Changes the size that the directory of the ZIP file gives for one entry, as a made-up file would. + private static void LieAboutSize(byte[] zip, string name, uint size) + { + var nameBytes = Encoding.UTF8.GetBytes(name); + for (var i = 0; i + 46 + nameBytes.Length <= zip.Length; i++) + { + if (BitConverter.ToUInt32(zip, i) != 0x02014b50 || !zip.AsSpan(i + 46, nameBytes.Length).SequenceEqual(nameBytes)) + continue; + BitConverter.GetBytes(size).CopyTo(zip, i + 24); + return; + } + + throw new InvalidOperationException("Entry not found."); + } +} From 6e0bf8b7283da2c89acb18c5df4dd8e83fbfbf08 Mon Sep 17 00:00:00 2001 From: "Seb H." <138793908+SebHenn@users.noreply.github.com> Date: Thu, 19 Nov 2026 20:17:31 +0100 Subject: [PATCH 4/7] M28, second part: docs for reading an export Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Seb H. <138793908+SebHenn@users.noreply.github.com> --- CHANGELOG.md | 6 ++++++ docs/curator-handbook.md | 16 ++++++++++++++++ docs/handbuch-kuratoren.md | 18 ++++++++++++++++++ docs/operations.md | 11 +++++++++++ docs/security.md | 1 + 5 files changed, 52 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index f662c5c..1c64b30 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,12 @@ version may change things that need attention when updating, and these notes say ### For curators +- **Read an export into an archive.** "Read an export into this archive" on the Export page (admins) takes the ZIP file of a Commonage + export, from this archive or another, and makes a draft of each item, with its photos, tags, collection, date, "What visitors + get" and "Public from". A dry run comes first. What a contributor or visitor gave to the other archive stays there: names, + email addresses, consent texts, visitor notes, internal notes and who gave an item are never read. Items that were rejected or + withdrawn, or whose contributor did not agree to sharing, are left out and listed with the reason. An item that is already + here (same collection, title and date) is never changed. Reads export format versions 4 to 8. - A published item can have an **embargo**: set "Public from" on the item, and until the start of that day (in the archive's time zone) it is as hidden as a draft, everywhere, including its pictures. Lists, feeds and the start page put the item where it belongs on the day it opens. Exports of published items leave out items still under embargo (export format version 8). diff --git a/docs/curator-handbook.md b/docs/curator-handbook.md index e06eabc..22775b5 100644 --- a/docs/curator-handbook.md +++ b/docs/curator-handbook.md @@ -148,6 +148,22 @@ First you see a dry run. It changes nothing and lists unreadable dates, collecti and rows that would be there twice. Fix the spreadsheet and check again, or import the rows that are in order and deal with the rest later. Everything imported is a draft. If it breaks off, run it again: what is already there is left out. +## Reading an export + +Admins can read the ZIP file of a Commonage export into an archive, to merge two archives or to start a new one from another: +**Read an export into this archive** on the Export page. A dry run comes first and changes nothing. + +What arrives: the title, description, date, tags, collection, rights, "What visitors get" and "Public from" of each item, and its +photos. Everything arrives as a **draft**, whatever it was in the other archive, so you decide what to publish. A collection +that does not exist here is created (at most 50 in one go; import again for the rest). A tag that exists here keeps the kind it +has here. + +What does not arrive, and why: the names, email addresses and consent texts of contributors, notes from visitors, internal +notes and who gave an item belong to the other archive and its promises. Items that were rejected or withdrawn there, and items +whose contributor did not agree to sharing, are left out and listed. Items in the other archive's bin are not in its export, so +they are not seen. An item that is already here (same collection, title and date) is not changed, and a photo that is already +here is not added a second time. Run the same export again after a break-off: what is there is left out. + ## A box full of photos **Add many photos** on the item list makes one draft from each photo. Enter what they share first: the collection, and if diff --git a/docs/handbuch-kuratoren.md b/docs/handbuch-kuratoren.md index 90caecc..1427fdd 100644 --- a/docs/handbuch-kuratoren.md +++ b/docs/handbuch-kuratoren.md @@ -151,6 +151,24 @@ bestätigen. Jeder geänderte Eintrag bekommt eine Zeile in seinem Verlauf. Beim Veröffentlichen von vielen werden nur Entwürfe mit Titel genommen. Über Beiträge wird einzeln entschieden. Rückgängig machen lässt sich eine Änderung an vielen nicht, also probieren Sie sie im Zweifel erst an wenigen aus. +## Einen Export einlesen + +Admins können die ZIP-Datei eines Commonage-Exports in ein Archiv einlesen, um zwei Archive zusammenzuführen oder ein neues aus +einem anderen zu beginnen: **Einen Export in dieses Archiv einlesen** auf der Seite Export. Zuerst kommt ein Probelauf, der nichts +ändert. + +Was ankommt: Titel, Beschreibung, Datum, Schlagwörter, Sammlung, Rechte, "Was Besucher bekommen" und "Öffentlich ab" jedes Eintrags +und seine Fotos. Alles kommt als **Entwurf** an, was es im anderen Archiv auch war; was veröffentlicht wird, entscheiden Sie. Eine +Sammlung, die es hier nicht gibt, wird angelegt (höchstens 50 auf einmal; importieren Sie erneut für den Rest). Ein Schlagwort, +das es hier gibt, behält die Art, die es hier hat. + +Was nicht ankommt, und warum: Namen, E-Mail-Adressen und Einwilligungstexte der Beitragenden, Hinweise von Besuchern, interne +Notizen und wer einen Eintrag gegeben hat gehören dem anderen Archiv und dem, was dort versprochen wurde. Abgelehnte oder +zurückgezogene Einträge und solche, bei denen die Person der Weitergabe nicht zugestimmt hat, werden ausgelassen und aufgelistet. +Einträge im Papierkorb des anderen Archivs stehen nicht in dessen Export und werden deshalb nicht gesehen. Ein Eintrag, der schon +hier ist (gleiche Sammlung, gleicher Titel, gleiches Datum), wird nicht geändert, und ein Foto, das schon hier ist, wird nicht +noch einmal hinzugefügt. Starten Sie denselben Export nach einem Abbruch erneut: Was da ist, wird ausgelassen. + ## Eine Tabelle voller Einträge Liegt das Archiv schon in einer Tabelle vor, macht **Tabelle importieren** unter Archiv verwalten aus jeder Zeile einen Entwurf. diff --git a/docs/operations.md b/docs/operations.md index dd8b9f5..bcb69e9 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -232,6 +232,17 @@ or email address, including items in the bin. On each item, curators can: Backups still contain removed data until they are replaced. Delete backups you no longer need. +## Reading an export + +Admins can read the ZIP file of a Commonage export on the page **Read an export into this archive** (linked from Export). The +file is kept in `import-staging` on the media volume until the import is done, or a day. It shares the one-at-a-time lock with +the spreadsheet import and runs inside one web request, so the reverse proxy needs the same long timeout. Limits: a ZIP of at most +4 GB; `archive.json` at most 256 MB when unpacked, counted as it is read; at most 20,000 items, 5,000 collections, 50,000 tags and +500 files per item; at most 8 GB of files in all; at most 50 new collections per run. The format versions 4 to 8 are read. Every +item is a draft, and the activity log records the run ("Imported items from a Commonage export", with counts only) and each +new collection, never a title of the other archive's contributors or their details. The database is only added to: nothing is +changed or removed, so a run that breaks off can be run again. + ## Export "Manage archive" → "Export" (admins) downloads the whole archive as one ZIP file. It needs no Commonage to read, so diff --git a/docs/security.md b/docs/security.md index 95b31bc..28616ae 100644 --- a/docs/security.md +++ b/docs/security.md @@ -27,6 +27,7 @@ vulnerability, see [SECURITY.md](../SECURITY.md). | Staff names and last login | `StaffProfiles` holds an optional display name and the time of the last login per account, written after a successful login (password, authenticator code or recovery code). Read only on the admin-only Accounts pages, never on a public page, feed or link preview, and not in the export or the activity log (which keeps the email address). Changing a name is logged. The row goes with the account (cascade). `AccountTests`. | | Helpers | The `Helper` role (policy `Describe`) reaches only the item list, the item form, "Add many photos", the preview and the generated pictures under `/admin/media` (not the original). Everything else under `/Admin` needs `ManageArchive` (curator or admin) or `Administer`. A helper only gets draft items, in the list, the form, the preview and the pictures, never published, submitted, rejected or withdrawn ones: what visitors see changes only through a curator, and no contribution or contributor name or email reaches a helper (the contribution is not even loaded). The start page counts, the "already in the archive" file check and the reference-number check show a helper drafts only. Publishing, unpublishing, accepting, rejecting, deleting, withdrawing and removing a photo are refused with 403 on the server, not only hidden. Accepted: a helper can read "received from" and the internal notes of the items they open; the handbook says so. `HelperTests` (including a test that lists every `/Admin` address a helper can reach), `AccountTests`. | | Import | Only curators (the `/Admin` policy). The sheet and ZIP are kept in `import-staging` on the media volume, which is never served by path, for a day at most. A sheet is read as strict UTF-8, at most 20 MB and 100,000 rows; a ZIP at most 4 GB and 200,000 entries; every entry is counted as it is unpacked into a temporary file, and a name inside it is never used in a path. A folder to import from is chosen from a listing of `import/`, links and hidden files are skipped. Files go through the same checks as an upload. One import at a time. Everything imported is a draft; the activity log records each item and the import, never the spreadsheet or the contributors' details. `ImportTests`. | +| Reading an export | Admins only (`Administer`), the dry run is `private, no-store`. Same staging folder, one-at-a-time lock and file checks as the spreadsheet import; the ZIP is at most 4 GB and 200,000 entries, `archive.json` at most 256 MB counted as it is unpacked (a ZIP entry's declared size is not trusted), parsed with a depth limit and capped lists (20,000 items, 5,000 collections, 50,000 tags, 500 files per item), at most 8 GB of files in all and 50 new collections per run. A file is taken only under the exact path `files//-`, unique, never by name and never as a path on disk; its type and size are found from the bytes and its sha256 must match. Unknown values are lines in the dry run, not exceptions. **Decision on consent:** a contributor's name, email address, consent text, rights statement and reference code, visitor notes, internal notes and received-from are never deserialised or stored (`ExportImportTable` decides every property of the export, and `ExportImportTests` fails when the exporter gains one without a decision); only whether the contributor agreed to sharing is read, and an item without that agreement, or one rejected or withdrawn, is left out. Everything arrives as a draft, whatever its status, and the code only inserts (a test reads the source for publishing, removing and unfiltered queries). `ExportImportTests`. | | Earlier texts | `ItemRevisions` keeps what a title, description, date, credit, original location or reference number said before a change, with the account that changed it (its name at the time) and when. The fields are a fixed list (`RevisionField`): never a contributor's name or email, the internal notes or where an item was received from, so removing a contributor's details never has to touch it. Who changed it is forgotten on the activity log's schedule (`ActivityLogKeptYears`); the text itself stays with the item. Shown on the item's admin page only; a curator may restore, a helper only reads. The rows go with their item (cascade, hidden while it is in the bin) and are not exported. `RevisionTests`, `ExportTests`. | | Recordings | Only curators can add a recording (MP3, M4A, WAV, FLAC, recognised by their first bytes); contribution links refuse them. Visitors hear only a copy made by the app itself (`AudioTools`, no outside program): the sound is copied byte for byte, and ID3v2/ID3v1/APE tags (MP3), `udta`, `meta`, `uuid` and padding boxes and the dates in the headers (M4A), every chunk except `fmt `, `fact` and `data` (WAV), and every block except stream info and the seek table (FLAC) are left out. A file that is not built as its type says (impossible sizes, missing parts, fragmented M4A) fails and has no copy, so nothing is ever served untouched. The parser is managed code reading sizes against the file's length, with the header of an M4A limited to 64 MB; it runs on the single preview queue and a failure marks only that file. Served for published items only, from `/media/{id}/audio` with range requests, with its own copy (`audio/…` key); the original is only at `/admin/media/{id}/original` for curators. Accepted: the sound itself may contain a voice that identifies someone, which is what an oral history is; curators decide what to publish. `AudioTests`. | | PDF files | Only curators can add a PDF; contribution links refuse it. A PDF is recognised by `%PDF-` and read by poppler (`pdfinfo`, `pdftoppm`), a large C++ parser, so it runs as separate processes, never inside the app: each call has a time limit (`Uploads:PdfTimeoutSeconds`, 60) and is killed with its children when it takes longer, the size of the drawn picture is set by us with `-scale-to` whatever size the page claims, at most 300 pages are drawn, and no part of the file or its name reaches a command line (arguments are passed as a list, the file is copied to a random name in an owner-only temporary folder that is removed afterwards). Pages are served only for published items; the PDF stays private. Accepted: a hostile PDF made by a curator could still exploit poppler, which runs with the app's rights in the container; build with `WITH_PDF=false` to remove it. `poppler-utils` comes from the distribution at build time and is not pinned to a version, so a rebuild of the same commit can ship another poppler (accepted; the base image digest is pinned). The text of a PDF (`pdftotext`, same limits, control characters removed, at most 200,000 characters) is only matched by search, never shown, and it is in the index only while the item is not in the bin and the PDF is not in the bin; a draft is found only by curators, as before. The preview queue is single, so a very long PDF delays other previews (at most 60 s per page); copies of a PDF left by a stopped app are removed at the next start. | From bc270d7e09a160c8108ebbda73b565c39f8780fe Mon Sep 17 00:00:00 2001 From: "Seb H." <138793908+SebHenn@users.noreply.github.com> Date: Thu, 19 Nov 2026 20:34:54 +0100 Subject: [PATCH 5/7] M28, second part: fix review findings in the export import - An item whose contribution does not say yes (no key, null) is left out, like a no. - A file that cannot be stored costs only that file: counted, no error text shown; the PhotosAdded line is written in a finally; the run no longer takes the request's token. - Cap on files in all of archive.json, and on recorded dry-run lines (the rest is counted and shown). - The staged ZIP and its folder are owner-only where the system has such modes. - Path regex ends with \z; "at most N characters" through T.Plural; handbooks and security.md updated. Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Seb H. <138793908+SebHenn@users.noreply.github.com> --- CHANGELOG.md | 2 +- docs/curator-handbook.md | 6 +- docs/operations.md | 10 +- docs/security.md | 2 +- src/Commonage.Web/Import/ExportImport.cs | 142 +++++++++++++----- src/Commonage.Web/Import/ExportReading.cs | 11 +- src/Commonage.Web/Import/ImportStaging.cs | 19 ++- .../Pages/Admin/ImportArchive.cshtml | 5 + .../Pages/Admin/ImportArchive.cshtml.cs | 7 +- .../Resources/SharedResource.de.resx | 10 +- .../Resources/SharedResource.resx | 6 +- tests/Commonage.Tests/ExportImportTests.cs | 104 +++++++++++++ tests/Commonage.Tests/ImportStagingTests.cs | 37 +++++ 13 files changed, 307 insertions(+), 54 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1c64b30..9c90de9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,7 +12,7 @@ version may change things that need attention when updating, and these notes say get" and "Public from". A dry run comes first. What a contributor or visitor gave to the other archive stays there: names, email addresses, consent texts, visitor notes, internal notes and who gave an item are never read. Items that were rejected or withdrawn, or whose contributor did not agree to sharing, are left out and listed with the reason. An item that is already - here (same collection, title and date) is never changed. Reads export format versions 4 to 8. + here (same collection, title and date) is never changed, and is not given photos it lacks. A photo that cannot be stored is counted and the item stays a draft with the others. Reads export format versions 4 to 8. - A published item can have an **embargo**: set "Public from" on the item, and until the start of that day (in the archive's time zone) it is as hidden as a draft, everywhere, including its pictures. Lists, feeds and the start page put the item where it belongs on the day it opens. Exports of published items leave out items still under embargo (export format version 8). diff --git a/docs/curator-handbook.md b/docs/curator-handbook.md index 22775b5..03c2a51 100644 --- a/docs/curator-handbook.md +++ b/docs/curator-handbook.md @@ -162,7 +162,11 @@ What does not arrive, and why: the names, email addresses and consent texts of c notes and who gave an item belong to the other archive and its promises. Items that were rejected or withdrawn there, and items whose contributor did not agree to sharing, are left out and listed. Items in the other archive's bin are not in its export, so they are not seen. An item that is already here (same collection, title and date) is not changed, and a photo that is already -here is not added a second time. Run the same export again after a break-off: what is there is left out. +here is not added a second time. A credit or rights holder that a curator typed into an item travels with it, so check them before you publish. +Run the same export again after a break-off: what is there is left out. That also holds for an item that arrived without all +its photos (a photo could not be stored, which the page after the import says): it stays a draft with the photos +that did arrive, and the import never adds to an item that is already here. Add the missing photos by hand, or put the draft in +the bin and run the import again. ## A box full of photos diff --git a/docs/operations.md b/docs/operations.md index bcb69e9..a473165 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -238,10 +238,16 @@ Admins can read the ZIP file of a Commonage export on the page **Read an export file is kept in `import-staging` on the media volume until the import is done, or a day. It shares the one-at-a-time lock with the spreadsheet import and runs inside one web request, so the reverse proxy needs the same long timeout. Limits: a ZIP of at most 4 GB; `archive.json` at most 256 MB when unpacked, counted as it is read; at most 20,000 items, 5,000 collections, 50,000 tags and -500 files per item; at most 8 GB of files in all; at most 50 new collections per run. The format versions 4 to 8 are read. Every +500 files per item and 100,000 files in all; at most 8 GB of files in all; at most 50 new collections per run; the dry run keeps +at most 10,000 lines and counts the rest. The format versions 4 to 8 are read. Every item is a draft, and the activity log records the run ("Imported items from a Commonage export", with counts only) and each new collection, never a title of the other archive's contributors or their details. The database is only added to: nothing is -changed or removed, so a run that breaks off can be run again. +changed or removed, so a run that breaks off can be run again. A file that cannot be stored (a full disk, a broken ZIP entry) is +counted and shown, never explained with the system's own error text; its item stays a draft with the photos that did arrive and the +activity log has the line for those. The import never adds to an item that is already there, so such an item is not completed by +running again: add the photos by hand, or put the draft in the bin and run the import again. Items from the export carry the +credit and rights holder a curator typed in. The run does not stop when the browser tab is closed. The ZIP file waits in a folder +only the account running the app can read (on Linux and macOS). ## Export diff --git a/docs/security.md b/docs/security.md index 28616ae..570f498 100644 --- a/docs/security.md +++ b/docs/security.md @@ -27,7 +27,7 @@ vulnerability, see [SECURITY.md](../SECURITY.md). | Staff names and last login | `StaffProfiles` holds an optional display name and the time of the last login per account, written after a successful login (password, authenticator code or recovery code). Read only on the admin-only Accounts pages, never on a public page, feed or link preview, and not in the export or the activity log (which keeps the email address). Changing a name is logged. The row goes with the account (cascade). `AccountTests`. | | Helpers | The `Helper` role (policy `Describe`) reaches only the item list, the item form, "Add many photos", the preview and the generated pictures under `/admin/media` (not the original). Everything else under `/Admin` needs `ManageArchive` (curator or admin) or `Administer`. A helper only gets draft items, in the list, the form, the preview and the pictures, never published, submitted, rejected or withdrawn ones: what visitors see changes only through a curator, and no contribution or contributor name or email reaches a helper (the contribution is not even loaded). The start page counts, the "already in the archive" file check and the reference-number check show a helper drafts only. Publishing, unpublishing, accepting, rejecting, deleting, withdrawing and removing a photo are refused with 403 on the server, not only hidden. Accepted: a helper can read "received from" and the internal notes of the items they open; the handbook says so. `HelperTests` (including a test that lists every `/Admin` address a helper can reach), `AccountTests`. | | Import | Only curators (the `/Admin` policy). The sheet and ZIP are kept in `import-staging` on the media volume, which is never served by path, for a day at most. A sheet is read as strict UTF-8, at most 20 MB and 100,000 rows; a ZIP at most 4 GB and 200,000 entries; every entry is counted as it is unpacked into a temporary file, and a name inside it is never used in a path. A folder to import from is chosen from a listing of `import/`, links and hidden files are skipped. Files go through the same checks as an upload. One import at a time. Everything imported is a draft; the activity log records each item and the import, never the spreadsheet or the contributors' details. `ImportTests`. | -| Reading an export | Admins only (`Administer`), the dry run is `private, no-store`. Same staging folder, one-at-a-time lock and file checks as the spreadsheet import; the ZIP is at most 4 GB and 200,000 entries, `archive.json` at most 256 MB counted as it is unpacked (a ZIP entry's declared size is not trusted), parsed with a depth limit and capped lists (20,000 items, 5,000 collections, 50,000 tags, 500 files per item), at most 8 GB of files in all and 50 new collections per run. A file is taken only under the exact path `files//-`, unique, never by name and never as a path on disk; its type and size are found from the bytes and its sha256 must match. Unknown values are lines in the dry run, not exceptions. **Decision on consent:** a contributor's name, email address, consent text, rights statement and reference code, visitor notes, internal notes and received-from are never deserialised or stored (`ExportImportTable` decides every property of the export, and `ExportImportTests` fails when the exporter gains one without a decision); only whether the contributor agreed to sharing is read, and an item without that agreement, or one rejected or withdrawn, is left out. Everything arrives as a draft, whatever its status, and the code only inserts (a test reads the source for publishing, removing and unfiltered queries). `ExportImportTests`. | +| Reading an export | Admins only (`Administer`), the dry run is `private, no-store`. Same staging folder, one-at-a-time lock and file checks as the spreadsheet import; the ZIP is at most 4 GB and 200,000 entries, `archive.json` at most 256 MB counted as it is unpacked (a ZIP entry's declared size is not trusted), parsed with a depth limit and capped lists (20,000 items, 5,000 collections, 50,000 tags, 500 files per item, 100,000 files in all), at most 8 GB of files in all, 50 new collections per run and 10,000 recorded lines in the dry run (the rest is counted). A file is taken only under the exact path `files//-`, unique, never by name and never as a path on disk; its type and size are found from the bytes and its sha256 must match. Unknown values are lines in the dry run, not exceptions. **Decision on consent:** a contributor's name, email address, consent text, rights statement and reference code, visitor notes, internal notes and received-from are never deserialised or stored (`ExportImportTable` decides every property of the export, and `ExportImportTests` fails when the exporter gains one without a decision); only whether the contributor agreed to sharing is read, and an item with a contribution that does not say yes (no, null or no answer at all), or one rejected or withdrawn, is left out. The ZIP is staged in a folder and file only the app's account can read (Linux and macOS), and a file that cannot be stored costs only that file, counted without the error text; the run is not cancelled by closing the tab. Everything arrives as a draft, whatever its status, and the code only inserts (a test reads the source for publishing, removing and unfiltered queries). `ExportImportTests`. | | Earlier texts | `ItemRevisions` keeps what a title, description, date, credit, original location or reference number said before a change, with the account that changed it (its name at the time) and when. The fields are a fixed list (`RevisionField`): never a contributor's name or email, the internal notes or where an item was received from, so removing a contributor's details never has to touch it. Who changed it is forgotten on the activity log's schedule (`ActivityLogKeptYears`); the text itself stays with the item. Shown on the item's admin page only; a curator may restore, a helper only reads. The rows go with their item (cascade, hidden while it is in the bin) and are not exported. `RevisionTests`, `ExportTests`. | | Recordings | Only curators can add a recording (MP3, M4A, WAV, FLAC, recognised by their first bytes); contribution links refuse them. Visitors hear only a copy made by the app itself (`AudioTools`, no outside program): the sound is copied byte for byte, and ID3v2/ID3v1/APE tags (MP3), `udta`, `meta`, `uuid` and padding boxes and the dates in the headers (M4A), every chunk except `fmt `, `fact` and `data` (WAV), and every block except stream info and the seek table (FLAC) are left out. A file that is not built as its type says (impossible sizes, missing parts, fragmented M4A) fails and has no copy, so nothing is ever served untouched. The parser is managed code reading sizes against the file's length, with the header of an M4A limited to 64 MB; it runs on the single preview queue and a failure marks only that file. Served for published items only, from `/media/{id}/audio` with range requests, with its own copy (`audio/…` key); the original is only at `/admin/media/{id}/original` for curators. Accepted: the sound itself may contain a voice that identifies someone, which is what an oral history is; curators decide what to publish. `AudioTests`. | | PDF files | Only curators can add a PDF; contribution links refuse it. A PDF is recognised by `%PDF-` and read by poppler (`pdfinfo`, `pdftoppm`), a large C++ parser, so it runs as separate processes, never inside the app: each call has a time limit (`Uploads:PdfTimeoutSeconds`, 60) and is killed with its children when it takes longer, the size of the drawn picture is set by us with `-scale-to` whatever size the page claims, at most 300 pages are drawn, and no part of the file or its name reaches a command line (arguments are passed as a list, the file is copied to a random name in an owner-only temporary folder that is removed afterwards). Pages are served only for published items; the PDF stays private. Accepted: a hostile PDF made by a curator could still exploit poppler, which runs with the app's rights in the container; build with `WITH_PDF=false` to remove it. `poppler-utils` comes from the distribution at build time and is not pinned to a version, so a rebuild of the same commit can ship another poppler (accepted; the base image digest is pinned). The text of a PDF (`pdftotext`, same limits, control characters removed, at most 200,000 characters) is only matched by search, never shown, and it is in the index only while the item is not in the bin and the PDF is not in the bin; a draft is found only by curators, as before. The preview queue is single, so a very long PDF delays other previews (at most 60 s per page); copies of a PDF left by a stopped app are removed at the next start. | diff --git a/src/Commonage.Web/Import/ExportImport.cs b/src/Commonage.Web/Import/ExportImport.cs index ce2192e..ca9c8f4 100644 --- a/src/Commonage.Web/Import/ExportImport.cs +++ b/src/Commonage.Web/Import/ExportImport.cs @@ -87,8 +87,20 @@ public record PlannedTag(string Name, TagKind Kind); public record PlannedNewCollection(string Key, string Title, string? Description); -public class PlannedExportItem +/// How many more lines the dry run records, and how many were found beyond that. +public sealed class IssueBudget(int limit) { + private int _remaining = limit; + + public int Omitted { get; set; } + + public bool TryTake() => _remaining > 0 && _remaining-- > 0; +} + +public class PlannedExportItem(IssueBudget? budget = null) +{ + private readonly List _issues = []; + public int Number { get; init; } public string Title { get; set; } = ""; public string? Status { get; set; } @@ -110,9 +122,22 @@ public class PlannedExportItem public bool HelpWanted { get; set; } public MediaLevel MediaLevel { get; set; } public DateOnly? PublicFrom { get; set; } - public List Issues { get; } = []; + public IReadOnlyList Issues => _issues; public List Files { get; } = []; + /// + /// Keeps the issue while the plan's budget lasts. An item always keeps one issue of the kind that decides about it (a problem, + /// or a reason to leave it out), so that what is not listed never changes what happens to the item. + /// + public void AddIssue(ExportIssue issue) + { + var decides = issue.Severity != ExportIssueSeverity.Note && !_issues.Any(i => i.Severity == issue.Severity); + if (decides || budget is null || budget.TryTake()) + _issues.Add(issue); + else + budget.Omitted++; + } + public bool HasProblem => Issues.Any(i => i.Severity == ExportIssueSeverity.Problem); public bool IsLeftOut => !HasProblem && Issues.Any(i => i.Severity == ExportIssueSeverity.LeftOut); public bool IsReady => !HasProblem && !IsLeftOut; @@ -126,6 +151,9 @@ public class ExportPlan public IReadOnlyList Items { get; init; } = []; public IReadOnlyList NewCollections { get; init; } = []; + /// Lines found beyond , which are counted and not listed. + public int IssuesNotListed { get; init; } + public IEnumerable Ready => Items.Where(i => i.IsReady); public int ReadyFileCount => Ready.Sum(i => i.Files.Count); public long ReadyBytes => Ready.SelectMany(i => i.Files).Sum(f => f.Entry.Length); @@ -152,6 +180,12 @@ public partial class ExportImport( public const int MaxCollections = 5_000; public const int MaxTags = 50_000; public const int MaxFilesPerItem = 500; + + /// Files in all of archive.json, so that thousands of items with hundreds of files each cannot become millions of objects. + public const int MaxTotalFiles = 100_000; + + /// Lines of the dry run that are kept. What is found beyond this is only counted; each item keeps what decides about it. + public const int MaxIssues = 10_000; public const int MaxTagsPerItemRead = 200; /// A run creates at most this many collections, so a file full of invented ones cannot flood the list. @@ -163,7 +197,7 @@ public partial class ExportImport( public const int AltTextMax = 1000; private const int MaxDepth = 24; - [GeneratedRegex(@"^files/(?[0-9]{1,9})/(?[0-9]{1,9})-[^/]{1,300}$", RegexOptions.CultureInvariant | RegexOptions.ExplicitCapture)] + [GeneratedRegex(@"^files/(?[0-9]{1,9})/(?[0-9]{1,9})-[^/]{1,300}\z", RegexOptions.CultureInvariant | RegexOptions.ExplicitCapture)] private static partial Regex FilePathPattern(); private static readonly int[] Rotations = [0, 90, 180, 270]; @@ -241,25 +275,27 @@ public async Task PlanAsync(IImportSource source, CancellationToken var today = DateOnly.FromDateTime(clock.GetUtcNow().UtcDateTime); long bytesRead = 0; var number = 0; + var budget = new IssueBudget(MaxIssues); foreach (var exported in archive.Items ?? []) { cancellationToken.ThrowIfCancellationRequested(); number++; var item = exported ?? new ImportedItem(); - var planned = new PlannedExportItem { Number = number, Status = Shorten(item.Status) }; + var planned = new PlannedExportItem(budget) { Number = number, Status = Shorten(item.Status) }; planned.Title = Shorten(Text(item.Title)) ?? ""; items.Add(planned); // What decides whether the item is imported at all is looked at first; nothing else of a left-out item is examined. if (!TryEnum(item.Status, out ItemStatus status)) - planned.Issues.Add(new ExportIssue(ExportIssueKind.ValueUnknown, "status", Shorten(item.Status))); + planned.AddIssue(new ExportIssue(ExportIssueKind.ValueUnknown, "status", Shorten(item.Status))); else if (status == ItemStatus.Rejected) - planned.Issues.Add(new ExportIssue(ExportIssueKind.ItemRejected, "status")); + planned.AddIssue(new ExportIssue(ExportIssueKind.ItemRejected, "status")); else if (status == ItemStatus.Withdrawn) - planned.Issues.Add(new ExportIssue(ExportIssueKind.ItemWithdrawn, "status")); - if (item.Contribution is { ConsentCoversSharing: false }) - planned.Issues.Add(new ExportIssue(ExportIssueKind.NoConsentToShare, "contribution")); + planned.AddIssue(new ExportIssue(ExportIssueKind.ItemWithdrawn, "status")); + // Only a contribution that says yes counts: one without the answer (no key, or null) is left out like a no. + if (item.Contribution is not null && item.Contribution.ConsentCoversSharing != true) + planned.AddIssue(new ExportIssue(ExportIssueKind.NoConsentToShare, "contribution")); if (planned.Issues.Count > 0) continue; @@ -338,7 +374,7 @@ public async Task PlanAsync(IImportSource source, CancellationToken } } - return new ExportPlan { Version = ArchiveExporter.Version, Items = items, NewCollections = newCollections.Values.ToList() }; + return new ExportPlan { Version = ArchiveExporter.Version, Items = items, NewCollections = newCollections.Values.ToList(), IssuesNotListed = budget.Omitted }; } private static bool HasProblem(PlannedExportItem planned) => planned.Issues.Any(i => i.Severity == ExportIssueSeverity.Problem); @@ -346,7 +382,7 @@ public async Task PlanAsync(IImportSource source, CancellationToken private static ExportPlan Refuse(ExportRefusal refusal, int? foundVersion = null) => new() { Refusal = refusal, FoundVersion = foundVersion }; private static void Issue(PlannedExportItem planned, ExportIssueKind kind, string? field = null, string? value = null, string? detail = null, UploadError? upload = null) => - planned.Issues.Add(new ExportIssue(kind, field, value, detail, upload)); + planned.AddIssue(new ExportIssue(kind, field, value, detail, upload)); /// /// The exported earliest and latest day are used when they are real, because the text may be in a vocabulary this version @@ -625,12 +661,16 @@ private static (string? Format, int? Version) Sniff(ReadOnlySpan bytes, bo new CappedListConverter(MaxItems, limits), new CappedListConverter(MaxCollections, limits), new CappedListConverter(MaxTags, limits), - new CappedListConverter(MaxFilesPerItem, limits), + new CappedListConverter(MaxFilesPerItem, limits, MaxTotalFiles), new CappedListConverter(MaxTagsPerItemRead, limits), }, }; - /// Imports the items of a plan that are in order, as drafts. A file that is no longer what the dry run saw is left out and counted. + /// + /// Imports the items of a plan that are in order, as drafts. A file that is no longer what the dry run saw, or that cannot be + /// stored, is left out and counted; its item stays a draft with the photos that did arrive. The caller passes a token that + /// closing the browser does not cancel, so that a run is never cut off between an item and its photos. + /// public async Task RunAsync(ExportPlan plan, IImportSource source, CancellationToken cancellationToken) { // The entry is added before the first save, so an import that stops half way still has its line in the log. @@ -705,39 +745,53 @@ public async Task RunAsync(ExportPlan plan, IImportSource so items++; var added = 0; - foreach (var planned in row.Files) + try { - try + foreach (var planned in row.Files) { - await using var content = await source.OpenSeekableAsync(planned.Entry, uploadOptions.Value.MaxFileSizeBytes, cancellationToken); - var examined = await uploads.ExamineAsync(content, content.Length, documents: true, cancellationToken); - if (examined.Error != UploadError.None || examined.Sha256 != planned.Examined.Sha256) + var stored = false; + try { - failed++; - continue; + await using var content = await source.OpenSeekableAsync(planned.Entry, uploadOptions.Value.MaxFileSizeBytes, cancellationToken); + var examined = await uploads.ExamineAsync(content, content.Length, documents: true, cancellationToken); + if (examined.Error != UploadError.None || examined.Sha256 != planned.Examined.Sha256) + { + failed++; + continue; + } + + var file = await uploads.StoreAsync(item, content, planned.Name, content.Length, examined, cancellationToken); + stored = true; + files++; + added++; + if (planned.AltText is not null || planned.Caption is not null || planned.Rotation != 0) + { + file.AltText = planned.AltText; + file.Caption = planned.Caption; + file.Rotation = planned.Rotation; + await db.SaveChangesAsync(cancellationToken); + } } - - var stored = await uploads.StoreAsync(item, content, planned.Name, content.Length, examined, cancellationToken); - files++; - added++; - if (planned.AltText is not null || planned.Caption is not null || planned.Rotation != 0) + catch (Exception exception) { - stored.AltText = planned.AltText; - stored.Caption = planned.Caption; - stored.Rotation = planned.Rotation; - await db.SaveChangesAsync(cancellationToken); + // Whatever went wrong with one file (a full disk, a lost connection, a broken ZIP entry) costs that file only: + // it is counted, and what was thrown is never shown, because it can hold paths. A stop is not a failure. + DiscardUnsaved(item); + if (exception is OperationCanceledException) + throw; + if (!stored) + failed++; } } - catch (Exception exception) when (exception is EntryTooLargeException or InvalidDataException or IOException) - { - failed++; - } } - - if (added > 0) + finally { - audit.Record(AuditAction.PhotosAdded, item.Title, item); - await db.SaveChangesAsync(cancellationToken); + // Also when the loop is cut short: the photos that did arrive are in the log. + if (added > 0) + { + audit.Record(AuditAction.PhotosAdded, item.Title, item); + await db.SaveChangesAsync(CancellationToken.None); + } } } @@ -749,6 +803,14 @@ public async Task RunAsync(ExportPlan plan, IImportSource so return new ExportImportResult(items, files, failed, created.Count); } + /// Forgets a photo that was never saved, so that the next save does not try it again and fail with it. + private void DiscardUnsaved(ArchiveItem item) + { + foreach (var entry in db.ChangeTracker.Entries().Where(e => e.State is EntityState.Added or EntityState.Modified).ToList()) + entry.State = entry.State == EntityState.Added ? EntityState.Detached : EntityState.Unchanged; + item.MediaFiles.RemoveAll(f => f.Id == 0); + } + /// The message for a refused export, in the reader's language. public static string Describe(IStringLocalizer localizer, ExportRefusal refusal, int? foundVersion) => refusal switch { @@ -769,7 +831,7 @@ public async Task RunAsync(ExportPlan plan, IImportSource so { ExportIssueKind.ValueUnknown => localizer["This value is not one this archive knows."], ExportIssueKind.ValueInvalid => localizer["This value is not valid."], - ExportIssueKind.TooLong => localizer["This text can be at most {1} characters long.", "", issue.Detail!], + ExportIssueKind.TooLong => localizer.Plural("This text can be at most {0, plural, one {# character} other {# characters}} long.", int.Parse(issue.Detail!, CultureInfo.InvariantCulture)), ExportIssueKind.DateUnreadable => localizer["This date could not be understood. Please include a year, for example: 1953, 12.03.1953, circa 1950, 1950s, 1950–1955."], ExportIssueKind.RightsUnknown => localizer["This is not one of the archive's rights statements. Write its web address as an export does, or leave the cell empty."], ExportIssueKind.TagTooLong => localizer.Plural("A tag can be at most {0, plural, one {# character} other {# characters}} long.", int.Parse(issue.Detail!, CultureInfo.InvariantCulture)), @@ -784,8 +846,8 @@ public async Task RunAsync(ExportPlan plan, IImportSource so ExportIssueKind.ItemRejected => localizer["Left out: it was rejected in the other archive."], ExportIssueKind.ItemWithdrawn => localizer["Left out: its contributor withdrew their consent in the other archive."], ExportIssueKind.NoConsentToShare => localizer["Left out: its contributor did not agree to it being shared further."], - ExportIssueKind.ItemAlreadyThere => localizer["An item with this title and date is already in this collection."], - ExportIssueKind.ItemAlreadyThereDifferentText => localizer["An item with this title and date is already in this collection, with a different description. It is not changed."], + ExportIssueKind.ItemAlreadyThere => localizer["An item with this title and date is already in this collection. It is not changed, and photos it lacks are not added."], + ExportIssueKind.ItemAlreadyThereDifferentText => localizer["An item with this title and date is already in this collection, with a different description. It is not changed, and photos it lacks are not added."], ExportIssueKind.SameAsEarlierItem => localizer["The same title and date as item {0}, in the same collection.", issue.Detail!], ExportIssueKind.AllFilesAlreadyThere => localizer["Every photo of this item is already in the archive."], ExportIssueKind.FileMarkedProblem => localizer["The other archive could not export this file, so it is left out."], diff --git a/src/Commonage.Web/Import/ExportReading.cs b/src/Commonage.Web/Import/ExportReading.cs index 045fc6b..f76a03c 100644 --- a/src/Commonage.Web/Import/ExportReading.cs +++ b/src/Commonage.Web/Import/ExportReading.cs @@ -164,13 +164,16 @@ public sealed class ImportedFile internal sealed class ReadLimits { public bool TooMany { get; set; } + + /// Elements read so far of the lists that have a limit for all of them together. + public int Counted { get; set; } } /// /// Reads a JSON array into a list and stops at once when it holds more than elements, so that a file /// made of a hundred million empty items never becomes a hundred million objects. /// -internal sealed class CappedListConverter(int max, ReadLimits limits) : JsonConverter> +internal sealed class CappedListConverter(int max, ReadLimits limits, int? totalMax = null) : JsonConverter> { public override List? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { @@ -187,6 +190,12 @@ internal sealed class CappedListConverter(int max, ReadLimits limits) : JsonC throw new JsonException(); } + if (totalMax is { } total && ++limits.Counted > total) + { + limits.TooMany = true; + throw new JsonException(); + } + list.Add(JsonSerializer.Deserialize(ref reader, options)!); } diff --git a/src/Commonage.Web/Import/ImportStaging.cs b/src/Commonage.Web/Import/ImportStaging.cs index f092796..1f7606c 100644 --- a/src/Commonage.Web/Import/ImportStaging.cs +++ b/src/Commonage.Web/Import/ImportStaging.cs @@ -18,10 +18,27 @@ public sealed class ImportStaging(string storageRoot) public Guid Create() { var id = Guid.NewGuid(); - Directory.CreateDirectory(DirectoryOf(id)); + // Owner-only where the system has such permissions: what waits here may hold what the archive does not publish. + if (OperatingSystem.IsWindows()) + Directory.CreateDirectory(DirectoryOf(id)); + else + Directory.CreateDirectory(DirectoryOf(id), OwnerOnlyDirectory); return id; } + internal const UnixFileMode OwnerOnlyDirectory = UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute; + + internal const UnixFileMode OwnerOnlyFile = UnixFileMode.UserRead | UnixFileMode.UserWrite; + + /// A new file that only the account running the app can read, for what visitors and other curators must not get at. + public static FileStream CreateOwnerOnlyFile(string path) + { + var options = new FileStreamOptions { Mode = FileMode.Create, Access = FileAccess.Write, Share = FileShare.None }; + if (!OperatingSystem.IsWindows()) + options.UnixCreateMode = OwnerOnlyFile; + return new FileStream(path, options); + } + public string DirectoryOf(Guid id) => Path.Combine(Waiting, id.ToString("N")); public string CsvPath(Guid id) => Path.Combine(DirectoryOf(id), "sheet.csv"); diff --git a/src/Commonage.Web/Pages/Admin/ImportArchive.cshtml b/src/Commonage.Web/Pages/Admin/ImportArchive.cshtml index b0466dc..9620594 100644 --- a/src/Commonage.Web/Pages/Admin/ImportArchive.cshtml +++ b/src/Commonage.Web/Pages/Admin/ImportArchive.cshtml @@ -85,6 +85,11 @@ } } + @if (plan.IssuesNotListed > 0) + { +

@T.Plural("{0, plural, one {And # more thing found, which is not listed.} other {And # more things found, which are not listed.}}", plan.IssuesNotListed)

+ } +
@if (plan.CanImport) { diff --git a/src/Commonage.Web/Pages/Admin/ImportArchive.cshtml.cs b/src/Commonage.Web/Pages/Admin/ImportArchive.cshtml.cs index d28e1d7..c8b28c2 100644 --- a/src/Commonage.Web/Pages/Admin/ImportArchive.cshtml.cs +++ b/src/Commonage.Web/Pages/Admin/ImportArchive.cshtml.cs @@ -60,7 +60,7 @@ public async Task OnPostAsync(IFormFile? export, CancellationToke var id = staging.Create(); try { - await using var target = System.IO.File.Create(staging.ExportPath(id)); + await using var target = ImportStaging.CreateOwnerOnlyFile(staging.ExportPath(id)); await export!.CopyToAsync(target, cancellationToken); await target.FlushAsync(cancellationToken); } @@ -136,12 +136,13 @@ public async Task OnPostImportAsync(CancellationToken cancellatio return RedirectToPage(); } - var result = await import.RunAsync(plan, source, cancellationToken); + // Closing the tab must not stop the run between an item and its photos, so it is not given the request's token. + var result = await import.RunAsync(plan, source, CancellationToken.None); source.Dispose(); staging.Delete(id); TempData["Message"] = localizer["Drafts created: {0}. Photos added: {1}. Previews are being created.", result.Items, result.Files].Value; if (result.FilesFailed > 0) - TempData["Error"] = localizer["Photos that could not be added, because the files had changed: {0}", result.FilesFailed].Value; + TempData["Error"] = localizer["Photos that could not be added: {0}. Their items stay drafts with the photos that did arrive. Add the missing photos by hand, or put the draft in the bin and run the import again.", result.FilesFailed].Value; return LocalRedirect(Items.AddManyModel.DraftsUrl); } finally diff --git a/src/Commonage.Web/Resources/SharedResource.de.resx b/src/Commonage.Web/Resources/SharedResource.de.resx index ee35522..35f75ee 100644 --- a/src/Commonage.Web/Resources/SharedResource.de.resx +++ b/src/Commonage.Web/Resources/SharedResource.de.resx @@ -914,7 +914,7 @@ Dieser Link ist geschlossen Dieser Link ist geschlossen. Das Plakat würde die Leute auf eine Seite schicken, die das sagt. Öffnen Sie zuerst den Link. Zum Archiv - Ein Objekt mit diesem Titel und Datum ist in dieser Sammlung schon vorhanden. + Ein Objekt mit diesem Titel und Datum ist in dieser Sammlung schon vorhanden. Es wird nicht geändert, und fehlende Fotos werden nicht ergänzt. Es läuft gerade ein anderer Import. Bitte warten Sie, bis er fertig ist. Wie sonst auch: 1953, 12.03.1953, um 1950, 1950er, 1950–1955. Tabelle prüfen @@ -942,7 +942,7 @@ Keine Es wurde noch nichts importiert. So würde es ablaufen. Oder ein Ordner auf dem Server - Fotos, die nicht hinzugefügt werden konnten, weil sich die Dateien geändert hatten: {0} + Fotos, die nicht hinzugefügt werden konnten: {0}. Ihre Objekte bleiben Entwürfe mit den Fotos, die angekommen sind. Fügen Sie die fehlenden Fotos von Hand hinzu, oder legen Sie den Entwurf in den Papierkorb und starten Sie den Import erneut. Fotos, die hinzugefügt würden: {0} Bitte wählen Sie entweder eine ZIP-Datei oder einen Ordner, nicht beides. Bitte wählen Sie die Tabelle, als CSV gespeichert. @@ -1029,7 +1029,7 @@ Nur als Datensatz gezeigt Unter Sperrfrist Besucher sehen dieses Foto noch nicht oder gar nicht - Ein Objekt mit diesem Titel und Datum ist in dieser Sammlung schon vorhanden, mit anderer Beschreibung. Es wird nicht geändert. + Ein Objekt mit diesem Titel und Datum ist in dieser Sammlung schon vorhanden, mit anderer Beschreibung. Es wird nicht geändert, und fehlende Fotos werden nicht ergänzt. Export prüfen Sammlungen, die angelegt würden: {0} Sammlung beim Import angelegt @@ -1076,4 +1076,8 @@ Was der Export sagt ZIP-Datei eines Exports {0, plural, one {Das eine Objekt importieren, das in Ordnung ist} other {Die # Objekte importieren, die in Ordnung sind}} + Dieser Text darf höchstens {0, plural, one {# Zeichen} other {# Zeichen}} lang sein. + {0, plural, one {Und # weiterer Fund, der nicht aufgelistet ist.} other {Und # weitere Funde, die nicht aufgelistet sind.}} + Ein Objekt mit diesem Titel und Datum ist in dieser Sammlung schon vorhanden. + Fotos, die nicht hinzugefügt werden konnten, weil sich die Dateien geändert hatten: {0} diff --git a/src/Commonage.Web/Resources/SharedResource.resx b/src/Commonage.Web/Resources/SharedResource.resx index 416c89a..f782b65 100644 --- a/src/Commonage.Web/Resources/SharedResource.resx +++ b/src/Commonage.Web/Resources/SharedResource.resx @@ -69,8 +69,9 @@ Always An item can have at most {0, plural, one {# tag} other {# tags}}.Has a count. Write a form for each one your language needs, in ICU MessageFormat. An item with this tag was changed at the same moment. Nothing was changed; please try again. - An item with this title and date is already in this collection, with a different description. It is not changed. + An item with this title and date is already in this collection, with a different description. It is not changed, and photos it lacks are not added. An item with this title and date is already in this collection. + An item with this title and date is already in this collection. It is not changed, and photos it lacks are not added. Another import is running. Please wait until it has finished. Anyone can ask for their details, or what they sent in, to be changed or removed. The contact page says how to reach the archive. Backups keep older copies until they are replaced.Part of the privacy text an archive starts with. Please have a second translator review it. Anyone with a contribution link can send in photos and stories for a collection. Share it with a group, put it in a newsletter or on a poster. What people send in waits for your review and is never public before you publish it. @@ -539,6 +540,7 @@ Photos of this item Photos on their way Photos that could not be added, because the files had changed: {0} + Photos that could not be added: {0}. Their items stay drafts with the photos that did arrive. Add the missing photos by hand, or put the draft in the bin and run the import again. Photos that would be added: {0} Photos uploaded: {0}. Previews are being created. Photos: {0} @@ -908,6 +910,7 @@ This reference number is already used by another item. This reference number is already used by: {0} This site only sets the cookies it needs: one for the chosen language, one to protect forms, and one to keep curators logged in. There are no analytics and no third-party services. Visitors' addresses are held in memory for a short time, to limit abuse of forms and logins.Part of the privacy text an archive starts with. Please have a second translator review it. + This text can be at most {0, plural, one {# character} other {# characters}} long.Has a count. Write a form for each one your language needs, in ICU MessageFormat. This text can be at most {1} characters long. This text cannot be put back: the field would be empty or no longer reads as valid. This text was started on this device earlier. If it is not yours, clear it. @@ -1047,6 +1050,7 @@ {0, plural, one {# note from visitors to deal with} other {# notes from visitors to deal with}}Has a count. Write a form for each one your language needs, in ICU MessageFormat. {0, plural, one {# of them is not published yet} other {# of them are not published yet}}Has a count. Write a form for each one your language needs, in ICU MessageFormat. {0, plural, one {A visitor sent a note about this item.} other {Visitors sent # notes about this item.}}Has a count. Write a form for each one your language needs, in ICU MessageFormat. + {0, plural, one {And # more thing found, which is not listed.} other {And # more things found, which are not listed.}}Has a count. Write a form for each one your language needs, in ICU MessageFormat. {0, plural, one {Delete the unused tag} other {Delete the # unused tags}}Has a count. Write a form for each one your language needs, in ICU MessageFormat. {0, plural, one {For # month after the decision} other {For # months after the decision}}Has a count. Write a form for each one your language needs, in ICU MessageFormat. {0, plural, one {For # year} other {For # years}}Has a count. Write a form for each one your language needs, in ICU MessageFormat. diff --git a/tests/Commonage.Tests/ExportImportTests.cs b/tests/Commonage.Tests/ExportImportTests.cs index ad71edf..4d738cd 100644 --- a/tests/Commonage.Tests/ExportImportTests.cs +++ b/tests/Commonage.Tests/ExportImportTests.cs @@ -8,8 +8,11 @@ using Commonage.Web.Domain; using Commonage.Web.Export; using Commonage.Web.Import; +using Commonage.Web.Media; using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.AspNetCore.TestHost; using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; namespace Commonage.Tests; @@ -357,6 +360,107 @@ public async Task Rejected_withdrawn_and_unconsented_items_are_left_out_and_list Assert.Contains("did not agree to it being shared further", html); } + [Fact] + public async Task A_contribution_that_does_not_say_yes_is_left_out_whether_it_says_no_nothing_or_null() + { + using var curator = await CuratorAsync(app); + var word = Word(); + var json = ArchiveJson( + [Item(1, $"{word} Fine"), + Item(2, $"{word} No key", contribution: new { }), + Item(3, $"{word} Null answer", contribution: new { consentCoversSharing = (bool?)null }), + Item(4, $"{word} Other keys only", contribution: new { showName = true })], + [Collection(1, $"{word} Collection")]); + + var html = await RunAsync(curator, Zip(("archive.json", json))); + + Assert.Equal([$"{word} Fine"], (await ItemsAsync(word)).Select(i => i.Title)); + Assert.Equal(3, Regex.Matches(html, "did not agree to it being shared further").Count); + } + + [Fact] + public async Task A_photo_that_cannot_be_stored_costs_only_that_photo_and_the_item_stays_a_draft_with_the_others() + { + var word = Word(); + var storage = new StorageThatFailsOnOriginal(app.Services.GetRequiredService(), failOn: 2); + await using var archive = await app.NewArchiveAsync(b => b.ConfigureTestServices(services => services.AddSingleton(storage))); + using var curator = await CuratorAsync(archive); + byte[][] photos = [NewPhoto(), NewPhoto(), NewPhoto()]; + var json = ArchiveJson( + [Item(1, $"{word} Barn", files: [File(7, 1, "a.jpg", photos[0]), File(8, 1, "b.jpg", photos[1]), File(9, 1, "c.jpg", photos[2])])], + [Collection(1, $"{word} Collection")]); + var zip = Zip(("archive.json", json), ("files/1/7-a.jpg", photos[0]), ("files/1/8-b.jpg", photos[1]), ("files/1/9-c.jpg", photos[2])); + + var dryRun = await DryRunAsync(curator, zip); + var response = await curator.PostAsync($"{Page}?handler=Import", new FormUrlEncodedContent(new Dictionary + { + ["__RequestVerificationToken"] = Browser.Token(dryRun), + ["StagingId"] = StagingIdPattern().Match(dryRun).Groups[1].Value, + })); + var body = await response.Content.ReadAsStringAsync(); + + response.EnsureSuccessStatusCode(); + Assert.Contains("Photos that could not be added: 1", body); + Assert.DoesNotContain("secret-disk-path", body); + var item = Assert.Single(await archive.WithDbAsync(db => db.ArchiveItems.IgnoreQueryFilters().Include(i => i.MediaFiles).ToListAsync())); + Assert.Equal(ItemStatus.Draft, item.Status); + Assert.Equal([Sha(photos[0]), Sha(photos[2])], item.MediaFiles.OrderBy(f => f.Position).Select(f => f.Sha256)); + var actions = await archive.WithDbAsync(db => db.AuditEntries.Select(e => e.Action).ToListAsync()); + Assert.Contains(AuditAction.PhotosAdded, actions); + Assert.Equal(1, ImportLock.OneAtATime.CurrentCount); + + // The item is there now, so a second run does not top it up, and the dry run says so. + var again = await DryRunAsync(curator, zip); + Assert.DoesNotContain("handler=Import", again); + Assert.Contains("photos it lacks are not added", again); + Assert.Equal(2, (await archive.WithDbAsync(db => db.MediaFiles.CountAsync()))); + } + + private sealed class StorageThatFailsOnOriginal(IFileStorage real, int failOn) : IFileStorage + { + private int _originals; + + public Task SaveAsync(string key, Stream content, CancellationToken cancellationToken = default) => + key.StartsWith("originals/", StringComparison.Ordinal) && Interlocked.Increment(ref _originals) == failOn + ? throw new IOException("secret-disk-path is full.") + : real.SaveAsync(key, content, cancellationToken); + + public Stream OpenRead(string key) => real.OpenRead(key); + + public void Delete(string key) => real.Delete(key); + } + + private static object[] EmptyFiles(int count) => Enumerable.Repeat(new { }, count).ToArray(); + + [Fact] + public async Task More_files_in_all_than_the_cap_are_refused_even_when_no_item_has_too_many() + { + using var curator = await CuratorAsync(app); + var word = Word(); + var items = Enumerable.Range(1, ExportImport.MaxTotalFiles / ExportImport.MaxFilesPerItem + 1) + .Select(i => Item(i, $"{word} {i}", files: EmptyFiles(ExportImport.MaxFilesPerItem))).ToArray(); + + var html = await DryRunAsync(curator, Zip(("archive.json", ArchiveJson(items, [Collection(1, $"{word} Collection")])))); + + Assert.Contains("more items, files, tags or collections than one import can read", html); + Assert.DoesNotContain("handler=Import", html); + } + + [Fact] + public async Task A_dry_run_stops_recording_lines_at_a_limit_counts_the_rest_and_still_leaves_out_every_item_with_a_problem() + { + using var curator = await CuratorAsync(app); + var word = Word(); + var items = Enumerable.Range(1, ExportImport.MaxTotalFiles / ExportImport.MaxFilesPerItem) + .Select(i => Item(i, $"{word} {i}", files: EmptyFiles(ExportImport.MaxFilesPerItem))).ToArray(); + + var html = await DryRunAsync(curator, Zip(("archive.json", ArchiveJson(items, [Collection(1, $"{word} Collection")])))); + + Assert.Contains("more things found, which are not listed", html); + Assert.Contains($"Items with problems, which are left out: {items.Length}", html); + Assert.DoesNotContain("handler=Import", html); + } + [Fact] public async Task A_second_run_of_the_same_export_adds_nothing() { diff --git a/tests/Commonage.Tests/ImportStagingTests.cs b/tests/Commonage.Tests/ImportStagingTests.cs index 9ade38c..b144ca5 100644 --- a/tests/Commonage.Tests/ImportStagingTests.cs +++ b/tests/Commonage.Tests/ImportStagingTests.cs @@ -2,6 +2,16 @@ namespace Commonage.Tests; +/// A test about Unix permissions: skipped on Windows, which has no such mode bits (files there get their folder's access list). +public sealed class UnixFactAttribute : FactAttribute +{ + public UnixFactAttribute() + { + if (OperatingSystem.IsWindows()) + Skip = "Unix file modes do not exist on Windows."; + } +} + public sealed class ImportStagingTests : IDisposable { private readonly string _root = Path.Combine(Path.GetTempPath(), "staging-" + Guid.NewGuid().ToString("N")); @@ -13,6 +23,33 @@ public void Dispose() Directory.Delete(_root, recursive: true); } + [UnixFact] + [System.Runtime.Versioning.UnsupportedOSPlatform("windows")] + public void What_waits_for_the_import_can_only_be_read_by_the_account_running_the_app() + { + var staging = new ImportStaging(_root); + var id = staging.Create(); + using (var file = ImportStaging.CreateOwnerOnlyFile(staging.ExportPath(id))) + file.WriteByte(1); + + Assert.Equal(UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute, File.GetUnixFileMode(staging.DirectoryOf(id))); + Assert.Equal(UnixFileMode.UserRead | UnixFileMode.UserWrite, File.GetUnixFileMode(staging.ExportPath(id))); + } + + [Fact] + public void A_file_made_owner_only_is_still_written_and_replaced_on_every_system() + { + var staging = new ImportStaging(_root); + var id = staging.Create(); + for (var round = 1; round <= 2; round++) + { + using var file = ImportStaging.CreateOwnerOnlyFile(staging.ExportPath(id)); + file.WriteByte((byte)round); + } + + Assert.Equal([(byte)2], File.ReadAllBytes(staging.ExportPath(id))); + } + [Fact] public void A_folder_that_cannot_be_removed_stays_and_the_other_old_ones_are_still_cleared() { From 7c7b3a5973c5ab6e610b91b13612c69a492d5bda Mon Sep 17 00:00:00 2001 From: "Seb H." <138793908+SebHenn@users.noreply.github.com> Date: Thu, 19 Nov 2026 20:58:06 +0100 Subject: [PATCH 6/7] M28, second part: harden how the export import fails Stop a run after 5 failures in a row or when the app shuts down, and say how many items were not tried. Delete the stored original when its save fails and the .uploading file when a copy fails. Store alt text, caption and rotation in the photo's one save. Write the summary and photo lines in finally paths, log swallowed file errors by type, catch only store failures per file, and release the lock and remove staging when a run ends unexpectedly. Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Seb H. <138793908+SebHenn@users.noreply.github.com> --- CHANGELOG.md | 1 + docs/curator-handbook.md | 8 +- docs/handbuch-kuratoren.md | 9 +- docs/operations.md | 10 + src/Commonage.Web/Audit/AuditText.cs | 3 +- src/Commonage.Web/Domain/AuditEntry.cs | 1 + src/Commonage.Web/Import/ExportImport.cs | 250 +++++++++++------ src/Commonage.Web/Media/IFileStorage.cs | 22 +- src/Commonage.Web/Media/MediaUploadService.cs | 29 +- .../Pages/Admin/ImportArchive.cshtml.cs | 27 +- .../Resources/SharedResource.de.resx | 3 + .../Resources/SharedResource.resx | 3 + tests/Commonage.Tests/ExportImportTests.cs | 262 +++++++++++++++++- tests/Commonage.Tests/FileStorageTests.cs | 17 ++ 14 files changed, 537 insertions(+), 108 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9c90de9..73e8989 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ version may change things that need attention when updating, and these notes say email addresses, consent texts, visitor notes, internal notes and who gave an item are never read. Items that were rejected or withdrawn, or whose contributor did not agree to sharing, are left out and listed with the reason. An item that is already here (same collection, title and date) is never changed, and is not given photos it lacks. A photo that cannot be stored is counted and the item stays a draft with the others. Reads export format versions 4 to 8. +- A run that keeps failing (a full disk, a lost database) or that meets a shutdown stops and says how many items it did not try; each draft that lacks photos has a line in the activity log. A very large import may outlast the browser's wait; its result is in the activity log. - A published item can have an **embargo**: set "Public from" on the item, and until the start of that day (in the archive's time zone) it is as hidden as a draft, everywhere, including its pictures. Lists, feeds and the start page put the item where it belongs on the day it opens. Exports of published items leave out items still under embargo (export format version 8). diff --git a/docs/curator-handbook.md b/docs/curator-handbook.md index 03c2a51..60c2568 100644 --- a/docs/curator-handbook.md +++ b/docs/curator-handbook.md @@ -166,7 +166,13 @@ here is not added a second time. A credit or rights holder that a curator typed Run the same export again after a break-off: what is there is left out. That also holds for an item that arrived without all its photos (a photo could not be stored, which the page after the import says): it stays a draft with the photos that did arrive, and the import never adds to an item that is already here. Add the missing photos by hand, or put the draft in -the bin and run the import again. +the bin and run the import again. The activity log has a line for each draft that did not get all its photos. + +A very large import can take longer than your browser or the server in front of it waits, and the page may then show an error or +nothing at all while the import goes on. Do not start it again: wait, and look at the activity log, where the run's line ("Imported +items from a Commonage export") appears with the number of items and photos when it is done. If the disk or the database keeps +failing, or the server is shut down, the import stops early after the items it has done and the page says how many it did not try; +choose the same file again for the rest. ## A box full of photos diff --git a/docs/handbuch-kuratoren.md b/docs/handbuch-kuratoren.md index 1427fdd..ed84ae9 100644 --- a/docs/handbuch-kuratoren.md +++ b/docs/handbuch-kuratoren.md @@ -167,7 +167,14 @@ Notizen und wer einen Eintrag gegeben hat gehören dem anderen Archiv und dem, w zurückgezogene Einträge und solche, bei denen die Person der Weitergabe nicht zugestimmt hat, werden ausgelassen und aufgelistet. Einträge im Papierkorb des anderen Archivs stehen nicht in dessen Export und werden deshalb nicht gesehen. Ein Eintrag, der schon hier ist (gleiche Sammlung, gleicher Titel, gleiches Datum), wird nicht geändert, und ein Foto, das schon hier ist, wird nicht -noch einmal hinzugefügt. Starten Sie denselben Export nach einem Abbruch erneut: Was da ist, wird ausgelassen. +noch einmal hinzugefügt. Starten Sie denselben Export nach einem Abbruch erneut: Was da ist, wird ausgelassen. Für jeden Entwurf, der +nicht alle seine Fotos bekommen hat, steht eine Zeile im Aktivitätsprotokoll. + +Bei einem sehr großen Import kann der Browser oder der Server davor länger warten, als er will, und die Seite zeigt dann einen Fehler +oder nichts, während der Import weiterläuft. Starten Sie ihn nicht noch einmal: Warten Sie und sehen Sie ins Aktivitätsprotokoll, wo +die Zeile des Laufs ("Objekte aus einem Commonage-Export eingelesen") mit der Zahl der Einträge und Fotos erscheint, wenn er fertig +ist. Fällt der Datenträger oder die Datenbank immer wieder aus oder wird der Server heruntergefahren, endet der Import vorzeitig nach +den Einträgen, die er geschafft hat, und die Seite nennt, wie viele er nicht versucht hat; wählen Sie dieselbe Datei erneut für den Rest. ## Eine Tabelle voller Einträge diff --git a/docs/operations.md b/docs/operations.md index a473165..46dcbe9 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -249,6 +249,16 @@ running again: add the photos by hand, or put the draft in the bin and run the i credit and rights holder a curator typed in. The run does not stop when the browser tab is closed. The ZIP file waits in a folder only the account running the app can read (on Linux and macOS). +How a run fails: only a failed file or save (`IOException`, the ZIP reader's errors, `DbUpdateException`, `NpgsqlException`) is +counted and survived; the warning in the application log names only the exception type and the item's number in the export, never a +file name or message. After 5 failures in a row (a full disk or a lost database) the run stops and creates no further items; it +also stops between items when the app is shutting down. The page then says how many items were not tried, and the same file can be +chosen again for the rest. Any other exception ends the run, but the lock is released, the staged copy removed and the run's line in +the activity log ("items / photos") and the "Added photos" lines are written first. A photo whose save fails has its stored original +removed again. Each draft that lacks photos has a line "Could not add every photo of this item while importing" in the activity +log. A very large import can outlast the browser's or the reverse proxy's wait, so the page may time out while the import goes on; +the result is the line in the activity log. + ## Export "Manage archive" → "Export" (admins) downloads the whole archive as one ZIP file. It needs no Commonage to read, so diff --git a/src/Commonage.Web/Audit/AuditText.cs b/src/Commonage.Web/Audit/AuditText.cs index 5407696..4c9bd5f 100644 --- a/src/Commonage.Web/Audit/AuditText.cs +++ b/src/Commonage.Web/Audit/AuditText.cs @@ -81,6 +81,7 @@ public static class AuditText AuditAction.ItemsImported => localizer["Imported items from a spreadsheet"], AuditAction.ArchiveImported => localizer["Imported items from a Commonage export"], AuditAction.CollectionCreatedByImport => localizer["Created the collection while importing"], + AuditAction.ImportPhotosMissing => localizer["Could not add every photo of this item while importing"], _ => action.ToString(), }; @@ -90,7 +91,7 @@ AuditAction.ItemCreated or AuditAction.ItemChanged or AuditAction.ItemFieldResto or AuditAction.ItemDeleted or AuditAction.ItemMovedToBin or AuditAction.ItemRestored or AuditAction.ItemPurged or AuditAction.ItemMovedToBinAfterKeptTime or AuditAction.ItemsImported or AuditAction.ArchiveImported => AuditKind.Items, AuditAction.PhotosAdded or AuditAction.PhotosArranged or AuditAction.PhotoDeleted or AuditAction.PhotoMovedToBin - or AuditAction.PhotoRestored or AuditAction.PhotoPurged or AuditAction.PreviewRetried => AuditKind.Photos, + or AuditAction.PhotoRestored or AuditAction.PhotoPurged or AuditAction.PreviewRetried or AuditAction.ImportPhotosMissing => AuditKind.Photos, AuditAction.ContributionReceived or AuditAction.ContributionAccepted or AuditAction.ContributionRejected or AuditAction.ContributionWithdrawn or AuditAction.ContributorDetailsRemoved or AuditAction.ContributorDetailsChanged or AuditAction.ContributionLinkCreated or AuditAction.ContributionLinkChanged diff --git a/src/Commonage.Web/Domain/AuditEntry.cs b/src/Commonage.Web/Domain/AuditEntry.cs index 1c362e8..bfe01ed 100644 --- a/src/Commonage.Web/Domain/AuditEntry.cs +++ b/src/Commonage.Web/Domain/AuditEntry.cs @@ -64,6 +64,7 @@ public enum AuditAction ItemFieldRestored, ArchiveImported, CollectionCreatedByImport, + ImportPhotosMissing, } /// diff --git a/src/Commonage.Web/Import/ExportImport.cs b/src/Commonage.Web/Import/ExportImport.cs index ca9c8f4..cc12327 100644 --- a/src/Commonage.Web/Import/ExportImport.cs +++ b/src/Commonage.Web/Import/ExportImport.cs @@ -9,8 +9,11 @@ using Commonage.Web.Media; using Commonage.Web.Pages.Admin.Items; using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Localization; +using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; +using Npgsql; namespace Commonage.Web.Import; @@ -160,7 +163,8 @@ public class ExportPlan public bool CanImport => Refusal == ExportRefusal.None && Ready.Any(); } -public record ExportImportResult(int Items, int Files, int FilesFailed, int CollectionsCreated); +/// are the items left when the run stopped early; those that could not be created. +public record ExportImportResult(int Items, int Files, int FilesFailed, int CollectionsCreated, int ItemsFailed = 0, int ItemsNotTried = 0); /// /// Brings the ZIP file of Commonage's own export into the archive as drafts. only looks and changes @@ -173,9 +177,14 @@ public partial class ExportImport( AuditLog audit, IStringLocalizer localizer, IOptions uploadOptions, - TimeProvider clock) + TimeProvider clock, + IHostApplicationLifetime lifetime, + ILogger logger) { public const int MinVersion = 4; + + /// A run stops after this many failures in a row: a full disk or a lost database fails every file, and each item would only become an empty draft. + public const int StopAfterFailures = 5; public const int MaxItems = 20_000; public const int MaxCollections = 5_000; public const int MaxTags = 50_000; @@ -668,8 +677,10 @@ private static (string? Format, int? Version) Sniff(ReadOnlySpan bytes, bo /// /// Imports the items of a plan that are in order, as drafts. A file that is no longer what the dry run saw, or that cannot be - /// stored, is left out and counted; its item stays a draft with the photos that did arrive. The caller passes a token that - /// closing the browser does not cancel, so that a run is never cut off between an item and its photos. + /// stored, is left out and counted; its item stays a draft with the photos that did arrive. Within one item the run is not + /// cut off by a token, so that it never stops between an item and its photos; between items it stops when the app is shutting + /// down, and after failures in a row (a full disk or a lost database), so that it does not go + /// on creating empty drafts. What was done is in the activity log whichever way the run ends. /// public async Task RunAsync(ExportPlan plan, IImportSource source, CancellationToken cancellationToken) { @@ -690,119 +701,180 @@ public async Task RunAsync(ExportPlan plan, IImportSource so var loggedId = logged.Id; var newCollectionIds = created.ToDictionary(c => c.Key, c => c.Value.Id, StringComparer.OrdinalIgnoreCase); + var ready = plan.Ready.ToList(); + var tried = 0; var items = 0; var files = 0; var failed = 0; + var itemsFailed = 0; + var streak = 0; var tags = new Dictionary(StringComparer.Ordinal); - foreach (var row in plan.Ready) + Exception? error = null; + try { - cancellationToken.ThrowIfCancellationRequested(); - // Everything tracked is looked after at every save, which gets slow with thousands of items. - if (items > 0 && items % 100 == 0) + foreach (var row in ready) { - db.ChangeTracker.Clear(); - tags.Clear(); - } + cancellationToken.ThrowIfCancellationRequested(); + if (lifetime.ApplicationStopping.IsCancellationRequested || streak >= StopAfterFailures) + break; + tried++; + // Everything tracked is looked after at every save, which gets slow with thousands of items. + if (tried > 1 && tried % 100 == 1) + { + db.ChangeTracker.Clear(); + tags.Clear(); + } - var stamp = clock.GetUtcNow().UtcDateTime; - var item = new ArchiveItem - { - Title = row.Title, - Description = row.Description, - Status = ItemStatus.Draft, - MediaLevel = row.MediaLevel, - PublicFrom = row.PublicFrom, - CollectionId = row.CollectionId ?? newCollectionIds[row.NewCollectionKey!], - RightsUri = row.RightsUri, - RightsHolder = row.RightsHolder, - Credit = row.Credit, - ReferenceNumber = row.ReferenceNumber, - OriginalLocation = row.OriginalLocation, - NeedsTranscription = row.NeedsTranscription, - HelpWanted = row.HelpWanted, - CreatedAt = stamp, - UpdatedAt = stamp, - }; - if (row.DateText is not null) - item.SetDateRange(row.DateText, row.DateFrom!.Value, row.DateTo!.Value); - - var missing = row.Tags.Where(t => !tags.ContainsKey(Tag.Normalize(t.Name))).ToList(); - if (missing.Count > 0) - { - var normalized = missing.Select(t => Tag.Normalize(t.Name)).ToList(); - foreach (var found in await db.Tags.Where(t => normalized.Contains(t.NormalizedName)).ToListAsync(cancellationToken)) - tags[found.NormalizedName] = found; - // A tag that is there keeps its kind: the archive's own choice wins over what an export says. - foreach (var tag in missing.Where(t => !tags.ContainsKey(Tag.Normalize(t.Name)))) - tags[Tag.Normalize(tag.Name)] = new Tag { Name = tag.Name, NormalizedName = Tag.Normalize(tag.Name), Kind = tag.Kind }; - } + var stamp = clock.GetUtcNow().UtcDateTime; + var item = new ArchiveItem + { + Title = row.Title, + Description = row.Description, + Status = ItemStatus.Draft, + MediaLevel = row.MediaLevel, + PublicFrom = row.PublicFrom, + CollectionId = row.CollectionId ?? newCollectionIds[row.NewCollectionKey!], + RightsUri = row.RightsUri, + RightsHolder = row.RightsHolder, + Credit = row.Credit, + ReferenceNumber = row.ReferenceNumber, + OriginalLocation = row.OriginalLocation, + NeedsTranscription = row.NeedsTranscription, + HelpWanted = row.HelpWanted, + CreatedAt = stamp, + UpdatedAt = stamp, + }; + if (row.DateText is not null) + item.SetDateRange(row.DateText, row.DateFrom!.Value, row.DateTo!.Value); + + try + { + var missing = row.Tags.Where(t => !tags.ContainsKey(Tag.Normalize(t.Name))).ToList(); + if (missing.Count > 0) + { + var normalized = missing.Select(t => Tag.Normalize(t.Name)).ToList(); + foreach (var found in await db.Tags.Where(t => normalized.Contains(t.NormalizedName)).ToListAsync(cancellationToken)) + tags[found.NormalizedName] = found; + // A tag that is there keeps its kind: the archive's own choice wins over what an export says. + foreach (var tag in missing.Where(t => !tags.ContainsKey(Tag.Normalize(t.Name)))) + tags[Tag.Normalize(tag.Name)] = new Tag { Name = tag.Name, NormalizedName = Tag.Normalize(tag.Name), Kind = tag.Kind }; + } - item.SetTags(row.Tags.Select(t => tags[Tag.Normalize(t.Name)]).ToList()); + item.SetTags(row.Tags.Select(t => tags[Tag.Normalize(t.Name)]).ToList()); + + db.ArchiveItems.Add(item); + audit.Record(AuditAction.ItemCreated, item.Title, item); + await db.SaveChangesAsync(cancellationToken); + } + catch (Exception exception) when (IsStoreFailure(exception)) + { + logger.LogWarning("The import could not create item {Number}: {ExceptionType}", row.Number, exception.GetType().Name); + // What the failed save left tracked would fail the next one, too. The run's own line is read again at the end. + db.ChangeTracker.Clear(); + tags.Clear(); + itemsFailed++; + streak++; + continue; + } - db.ArchiveItems.Add(item); - audit.Record(AuditAction.ItemCreated, item.Title, item); - await db.SaveChangesAsync(cancellationToken); - items++; + items++; - var added = 0; - try - { - foreach (var planned in row.Files) + var added = 0; + var failedHere = 0; + Exception? itemError = null; + try { - var stored = false; - try + foreach (var planned in row.Files) { - await using var content = await source.OpenSeekableAsync(planned.Entry, uploadOptions.Value.MaxFileSizeBytes, cancellationToken); - var examined = await uploads.ExamineAsync(content, content.Length, documents: true, cancellationToken); - if (examined.Error != UploadError.None || examined.Sha256 != planned.Examined.Sha256) + try + { + await using var content = await source.OpenSeekableAsync(planned.Entry, uploadOptions.Value.MaxFileSizeBytes, cancellationToken); + var examined = await uploads.ExamineAsync(content, content.Length, documents: true, cancellationToken); + if (examined.Error != UploadError.None || examined.Sha256 != planned.Examined.Sha256) + { + failed++; + failedHere++; + continue; + } + + await uploads.StoreAsync(item, content, planned.Name, content.Length, examined, cancellationToken, planned.AltText, planned.Caption, planned.Rotation); + files++; + added++; + streak = 0; + } + catch (Exception exception) when (IsStoreFailure(exception) || exception is InvalidDataException or EntryTooLargeException) { + // Whatever went wrong with one file (a full disk, a lost connection, a broken ZIP entry) costs that file only: + // it is counted, and what was thrown is never shown, because it can hold paths. Anything else stops the run. + DiscardUnsaved(item); + logger.LogWarning("The import could not add a file to item {Number}: {ExceptionType}", row.Number, exception.GetType().Name); failed++; - continue; + failedHere++; + if (IsStoreFailure(exception) && ++streak >= StopAfterFailures) + break; } - - var file = await uploads.StoreAsync(item, content, planned.Name, content.Length, examined, cancellationToken); - stored = true; - files++; - added++; - if (planned.AltText is not null || planned.Caption is not null || planned.Rotation != 0) + catch { - file.AltText = planned.AltText; - file.Caption = planned.Caption; - file.Rotation = planned.Rotation; - await db.SaveChangesAsync(cancellationToken); + DiscardUnsaved(item); + throw; } } - catch (Exception exception) + } + catch (Exception exception) + { + itemError = exception; + throw; + } + finally + { + // Also when the loop is cut short: the photos that did arrive, and the ones that did not, are in the log. + try + { + if (added > 0) + audit.Record(AuditAction.PhotosAdded, item.Title, item); + if (failedHere > 0) + audit.Record(AuditAction.ImportPhotosMissing, item.Title, item); + if (added > 0 || failedHere > 0) + await db.SaveChangesAsync(CancellationToken.None); + } + catch (Exception exception) when (itemError is not null || IsStoreFailure(exception)) { - // Whatever went wrong with one file (a full disk, a lost connection, a broken ZIP entry) costs that file only: - // it is counted, and what was thrown is never shown, because it can hold paths. A stop is not a failure. - DiscardUnsaved(item); - if (exception is OperationCanceledException) - throw; - if (!stored) - failed++; + // This must not hide what stopped the loop, and a database that is gone is the same failure as any other. + logger.LogWarning("The import could not write the log lines of item {Number}: {ExceptionType}", row.Number, exception.GetType().Name); + db.ChangeTracker.Clear(); + tags.Clear(); + streak++; } } } - finally + } + catch (Exception exception) + { + error = exception; + throw; + } + finally + { + // How many came in, as numbers only, so the line reads the same in every language. Written whichever way the run ends. + try { - // Also when the loop is cut short: the photos that did arrive are in the log. - if (added > 0) - { - audit.Record(AuditAction.PhotosAdded, item.Title, item); - await db.SaveChangesAsync(CancellationToken.None); - } + db.ChangeTracker.Clear(); + var line = await db.AuditEntries.FirstAsync(e => e.Id == loggedId, CancellationToken.None); + line.Subject = $"{items} / {files}"; + await db.SaveChangesAsync(CancellationToken.None); + } + catch (Exception exception) when (error is not null) + { + logger.LogWarning("The import could not write its summary line: {ExceptionType}", exception.GetType().Name); } } - // How many came in, as numbers only, so the line reads the same in every language. - db.ChangeTracker.Clear(); - var line = await db.AuditEntries.FirstAsync(e => e.Id == loggedId, cancellationToken); - line.Subject = $"{items} / {files}"; - await db.SaveChangesAsync(cancellationToken); - return new ExportImportResult(items, files, failed, created.Count); + return new ExportImportResult(items, files, failed, created.Count, itemsFailed, ready.Count - tried); } + /// What a full disk, a broken file system or a lost database throws. Anything else is not something the run can go on after. + private static bool IsStoreFailure(Exception exception) => exception is IOException or DbUpdateException or NpgsqlException; + /// Forgets a photo that was never saved, so that the next save does not try it again and fail with it. private void DiscardUnsaved(ArchiveItem item) { diff --git a/src/Commonage.Web/Media/IFileStorage.cs b/src/Commonage.Web/Media/IFileStorage.cs index fa48cbe..ac78ded 100644 --- a/src/Commonage.Web/Media/IFileStorage.cs +++ b/src/Commonage.Web/Media/IFileStorage.cs @@ -40,12 +40,28 @@ public async Task SaveAsync(string key, Stream content, CancellationToken cancel // Write to a temporary file first so a crash never leaves a half-written file under the real key. var temporaryPath = path + ".uploading"; - await using (var target = File.Create(temporaryPath)) + try { - await content.CopyToAsync(target, cancellationToken); + await using (var target = File.Create(temporaryPath)) + { + await content.CopyToAsync(target, cancellationToken); + } + + File.Move(temporaryPath, path, overwrite: true); } + catch + { + // A full disk or a lost stream must not leave a half-written file behind that nothing will ever remove. + try + { + File.Delete(temporaryPath); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + } - File.Move(temporaryPath, path, overwrite: true); + throw; + } } // FileShare.Delete lets a curator delete a file while it is being read, for example by the preview generator or an diff --git a/src/Commonage.Web/Media/MediaUploadService.cs b/src/Commonage.Web/Media/MediaUploadService.cs index f3fa7b0..4614b07 100644 --- a/src/Commonage.Web/Media/MediaUploadService.cs +++ b/src/Commonage.Web/Media/MediaUploadService.cs @@ -119,8 +119,10 @@ public async Task StoreAsync(ArchiveItem item, IFormFile upload, Exam return await StoreAsync(item, content, upload.FileName, upload.Length, examined, cancellationToken); } - /// The same for a file that is not an upload, such as one from an import. - public async Task StoreAsync(ArchiveItem item, Stream content, string fileName, long length, ExaminedUpload examined, CancellationToken cancellationToken = default) + /// The same for a file that is not an upload, such as one from an import. The text and the turn are saved with the file, in one save. When that save fails, the stored original is removed again. + public async Task StoreAsync( + ArchiveItem item, Stream content, string fileName, long length, ExaminedUpload examined, CancellationToken cancellationToken = default, + string? altText = null, string? caption = null, int rotation = 0) { // After everything else, also what is in the bin, because it may come back to its place. var last = await db.MediaFiles.IgnoreQueryFilters().Where(f => f.ArchiveItemId == item.Id).MaxAsync(f => (int?)f.Position, cancellationToken); @@ -135,11 +137,30 @@ public async Task StoreAsync(ArchiveItem item, Stream content, string StorageId = Guid.NewGuid(), Status = ProcessingStatus.Pending, UploadedAt = DateTime.UtcNow, + AltText = altText, + Caption = caption, + Rotation = rotation, }; content.Position = 0; await storage.SaveAsync(file.OriginalKey, content, cancellationToken); - db.MediaFiles.Add(file); - await db.SaveChangesAsync(cancellationToken); + try + { + db.MediaFiles.Add(file); + await db.SaveChangesAsync(cancellationToken); + } + catch + { + // The file is stored but nothing in the database knows it, so nothing would ever remove it. + try + { + storage.Delete(file.OriginalKey); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + } + + throw; + } queue.Enqueue(file.Id); return file; diff --git a/src/Commonage.Web/Pages/Admin/ImportArchive.cshtml.cs b/src/Commonage.Web/Pages/Admin/ImportArchive.cshtml.cs index c8b28c2..879d10f 100644 --- a/src/Commonage.Web/Pages/Admin/ImportArchive.cshtml.cs +++ b/src/Commonage.Web/Pages/Admin/ImportArchive.cshtml.cs @@ -111,9 +111,11 @@ public async Task OnPostImportAsync(CancellationToken cancellatio return RedirectToPage(); } + IImportSource? source = null; + var started = false; try { - using var source = ImportSources.OpenZip(staging.ExportPath(id), staging.WorkDirectory(id)); + source = ImportSources.OpenZip(staging.ExportPath(id), staging.WorkDirectory(id)); if (source is null) { TempData["Error"] = localizer["The files for this import are no longer there. Please choose them again."].Value; @@ -125,8 +127,7 @@ public async Task OnPostImportAsync(CancellationToken cancellatio if (!plan.CanImport) { TempData["Error"] = localizer["There is nothing left to import."].Value; - source.Dispose(); - staging.Delete(id); + started = true; return RedirectToPage(); } @@ -136,17 +137,29 @@ public async Task OnPostImportAsync(CancellationToken cancellatio return RedirectToPage(); } - // Closing the tab must not stop the run between an item and its photos, so it is not given the request's token. + // Closing the tab must not stop the run between an item and its photos, so it is not given the request's token. A very + // large import can outlast what a browser or a proxy waits for; it goes on, and the activity log has the result. + // Whatever way it ends, the copy is of no more use: what came in is there, and a second run would find it so. + started = true; var result = await import.RunAsync(plan, source, CancellationToken.None); - source.Dispose(); - staging.Delete(id); TempData["Message"] = localizer["Drafts created: {0}. Photos added: {1}. Previews are being created.", result.Items, result.Files].Value; + var problems = new List(); if (result.FilesFailed > 0) - TempData["Error"] = localizer["Photos that could not be added: {0}. Their items stay drafts with the photos that did arrive. Add the missing photos by hand, or put the draft in the bin and run the import again.", result.FilesFailed].Value; + problems.Add(localizer["Photos that could not be added: {0}. Their items stay drafts with the photos that did arrive. Add the missing photos by hand, or put the draft in the bin and run the import again.", result.FilesFailed].Value); + if (result.ItemsFailed > 0) + problems.Add(localizer.Plural("{0, plural, one {# item} other {# items}} could not be created.", result.ItemsFailed)); + if (result.ItemsNotTried > 0) + problems.Add(localizer.Plural("The import stopped early, because the disk or the database kept failing, or the server was shutting down. {0, plural, one {# item was} other {# items were}} not tried. What came in stays as drafts. Choose the same file again for the rest.", result.ItemsNotTried)); + if (problems.Count > 0) + TempData["Error"] = string.Join(" ", problems); return LocalRedirect(Items.AddManyModel.DraftsUrl); } finally { + // The ZIP file is closed before its folder is removed, which Windows needs. + source?.Dispose(); + if (started) + staging.Delete(id); ImportLock.OneAtATime.Release(); } } diff --git a/src/Commonage.Web/Resources/SharedResource.de.resx b/src/Commonage.Web/Resources/SharedResource.de.resx index 35f75ee..5079d50 100644 --- a/src/Commonage.Web/Resources/SharedResource.de.resx +++ b/src/Commonage.Web/Resources/SharedResource.de.resx @@ -1033,6 +1033,9 @@ Export prüfen Sammlungen, die angelegt würden: {0} Sammlung beim Import angelegt + Beim Import konnten nicht alle Fotos dieses Objekts hinzugefügt werden + {0, plural, one {# Objekt konnte} other {# Objekte konnten}} nicht angelegt werden. + Der Import wurde vorzeitig beendet, weil der Datenträger oder die Datenbank immer wieder ausfiel oder der Server heruntergefahren wurde. {0, plural, one {# Objekt wurde} other {# Objekte wurden}} nicht versucht. Was angekommen ist, bleibt als Entwurf. Wählen Sie dieselbe Datei erneut für den Rest. Jedes Foto dieses Objekts ist schon im Archiv. Feld Gut zu wissen diff --git a/src/Commonage.Web/Resources/SharedResource.resx b/src/Commonage.Web/Resources/SharedResource.resx index f782b65..80c2f34 100644 --- a/src/Commonage.Web/Resources/SharedResource.resx +++ b/src/Commonage.Web/Resources/SharedResource.resx @@ -169,6 +169,7 @@ Correct these details Corrected the contributor's details Correction + Could not add every photo of this item while importing Cover Create a new setup link Create account @@ -802,6 +803,7 @@ The first row of the spreadsheet must name the columns. None of them is one this import knows. Download the template to see them. The format is described in docs/operations.md of the Commonage source code. The heading contributors see, for example: Share your photos of the Mill Street flood + The import stopped early, because the disk or the database kept failing, or the server was shutting down. {0, plural, one {# item was} other {# items were}} not tried. What came in stays as drafts. Choose the same file again for the rest.Has a count. Write a form for each one your language needs, in ICU MessageFormat. The introduction can be at most {1} characters long. The item is deleted for good. The item is in the bin. You can restore it there for {0, plural, one {# day} other {# days}}.Has a count. Write a form for each one your language needs, in ICU MessageFormat. @@ -1047,6 +1049,7 @@ {0, plural, one {# item asks visitors for help} other {# items ask visitors for help}}Has a count. Write a form for each one your language needs, in ICU MessageFormat. {0, plural, one {# item waits for a transcription} other {# items wait for a transcription}}Has a count. Write a form for each one your language needs, in ICU MessageFormat. {0, plural, one {# item} other {# items}}Has a count. Write a form for each one your language needs, in ICU MessageFormat. + {0, plural, one {# item} other {# items}} could not be created.Has a count. Write a form for each one your language needs, in ICU MessageFormat. {0, plural, one {# note from visitors to deal with} other {# notes from visitors to deal with}}Has a count. Write a form for each one your language needs, in ICU MessageFormat. {0, plural, one {# of them is not published yet} other {# of them are not published yet}}Has a count. Write a form for each one your language needs, in ICU MessageFormat. {0, plural, one {A visitor sent a note about this item.} other {Visitors sent # notes about this item.}}Has a count. Write a form for each one your language needs, in ICU MessageFormat. diff --git a/tests/Commonage.Tests/ExportImportTests.cs b/tests/Commonage.Tests/ExportImportTests.cs index 4d738cd..946d312 100644 --- a/tests/Commonage.Tests/ExportImportTests.cs +++ b/tests/Commonage.Tests/ExportImportTests.cs @@ -12,7 +12,9 @@ using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.AspNetCore.TestHost; using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; namespace Commonage.Tests; @@ -55,14 +57,17 @@ private static byte[] ArchiveJson(object[] items, object[]? collections = null, private static object Collection(int id, string title) => new { id, title, description = (string?)null }; - private static object File(int id, int item, string name, byte[] content, string? sha = null, string? path = null) => new + private static object File(int id, int item, string name, byte[] content, string? sha = null, string? path = null, + string? altText = null, string? caption = null, int rotation = 0) => new { id, path = path ?? $"files/{item}/{id}-{name}", originalFileName = name, sha256 = sha ?? Sha(content), position = 0, - rotation = 0, + rotation, + altText, + caption, problem = (string?)null, }; @@ -430,6 +435,259 @@ public Task SaveAsync(string key, Stream content, CancellationToken cancellation public void Delete(string key) => real.Delete(key); } + /// Stores through the real storage, but fails the saves of originals that the script names, and tells what was saved and removed. + private sealed class ScriptedStorage(IFileStorage real, Func failure, Action? afterSave = null) : IFileStorage + { + private int _originals; + + public List Saved { get; } = []; + + public List Deleted { get; } = []; + + public async Task SaveAsync(string key, Stream content, CancellationToken cancellationToken = default) + { + if (!key.StartsWith("originals/", StringComparison.Ordinal)) + { + await real.SaveAsync(key, content, cancellationToken); + return; + } + + var number = Interlocked.Increment(ref _originals); + if (failure(number) is { } exception) + throw exception; + await real.SaveAsync(key, content, cancellationToken); + Saved.Add(key); + afterSave?.Invoke(number); + } + + public Stream OpenRead(string key) => real.OpenRead(key); + + public bool Exists(string key) => real.Exists(key); + + public void Delete(string key) + { + Deleted.Add(key); + real.Delete(key); + } + } + + /// Makes the save of a new photo fail the way a lost database connection does. + private sealed class FailingPhotoSave : SaveChangesInterceptor + { + public override ValueTask> SavingChangesAsync( + DbContextEventData eventData, InterceptionResult result, CancellationToken cancellationToken = default) => + eventData.Context!.ChangeTracker.Entries().Any(e => e.State == EntityState.Added) + ? throw new DbUpdateException("secret-db-detail") + : base.SavingChangesAsync(eventData, result, cancellationToken); + } + + private sealed class FakeLifetime : IHostApplicationLifetime + { + public CancellationTokenSource Stopping { get; } = new(); + + public CancellationToken ApplicationStarted => CancellationToken.None; + + public CancellationToken ApplicationStopping => Stopping.Token; + + public CancellationToken ApplicationStopped => CancellationToken.None; + + public void StopApplication() => Stopping.Cancel(); + } + + private static string Copy(string word, int number) => $"{word} {number}"; + + private (byte[] Zip, byte[][] Photos) ManyItems(string word, int items, int filesPerItem = 1) + { + var photos = Enumerable.Range(0, items * filesPerItem).Select(_ => NewPhoto()).ToArray(); + var entries = new List<(string, byte[])>(); + var all = new List(); + for (var i = 1; i <= items; i++) + { + var files = new List(); + for (var f = 1; f <= filesPerItem; f++) + { + var photo = photos[(i - 1) * filesPerItem + f - 1]; + var id = i * 100 + f; + files.Add(File(id, i, $"p{id}.jpg", photo)); + entries.Add(($"files/{i}/{id}-p{id}.jpg", photo)); + } + + all.Add(Item(i, Copy(word, i), files: [.. files])); + } + + return (Zip([("archive.json", ArchiveJson([.. all], [Collection(1, $"{word} Collection")])), .. entries]), photos); + } + + private static async Task RunDirectAsync(WebApplicationFactory archive, byte[] zip, IHostApplicationLifetime? lifetime = null) + { + var folder = Path.Combine(Path.GetTempPath(), "commonage-tests", Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(folder); + try + { + var zipPath = Path.Combine(folder, "export.zip"); + await System.IO.File.WriteAllBytesAsync(zipPath, zip); + using var source = ImportSources.OpenZip(zipPath, Path.Combine(folder, "work"))!; + using var scope = archive.Services.CreateScope(); + var import = lifetime is null + ? scope.ServiceProvider.GetRequiredService() + : ActivatorUtilities.CreateInstance(scope.ServiceProvider, lifetime); + var plan = await import.PlanAsync(source, CancellationToken.None); + Assert.True(plan.CanImport); + return await import.RunAsync(plan, source, CancellationToken.None); + } + finally + { + Directory.Delete(folder, recursive: true); + } + } + + private static Task PostImportAsync(HttpClient client, string dryRunHtml) => + client.PostAsync($"{Page}?handler=Import", new FormUrlEncodedContent(new Dictionary + { + ["__RequestVerificationToken"] = Browser.Token(dryRunHtml), + ["StagingId"] = StagingIdPattern().Match(dryRunHtml).Groups[1].Value, + })); + + private Task SummaryAsync(WebApplicationFactory archive) => + archive.WithDbAsync(db => db.AuditEntries.Where(e => e.Action == AuditAction.ArchiveImported).Select(e => e.Subject).SingleAsync()); + + [Fact] + public async Task A_run_that_keeps_failing_stops_instead_of_creating_empty_drafts_and_says_how_many_items_it_did_not_try() + { + var word = Word(); + var storage = new ScriptedStorage(app.Services.GetRequiredService(), _ => new IOException("secret-disk-path is full.")); + await using var archive = await app.NewArchiveAsync(b => b.ConfigureTestServices(services => services.AddSingleton(storage))); + using var curator = await CuratorAsync(archive); + var (zip, _) = ManyItems(word, ExportImport.StopAfterFailures + 3); + + var dryRun = await DryRunAsync(curator, zip); + var response = await PostImportAsync(curator, dryRun); + var body = await response.Content.ReadAsStringAsync(); + + response.EnsureSuccessStatusCode(); + Assert.Contains("The import stopped early", body); + Assert.Contains("3 items were not tried", body); + Assert.DoesNotContain("secret-disk-path", body); + Assert.Equal(ExportImport.StopAfterFailures, await archive.WithDbAsync(db => db.ArchiveItems.CountAsync())); + Assert.Equal($"{ExportImport.StopAfterFailures} / 0", await SummaryAsync(archive)); + } + + [Fact] + public async Task One_good_file_between_failures_keeps_a_run_going() + { + var word = Word(); + var storage = new ScriptedStorage(app.Services.GetRequiredService(), n => n % 2 == 1 ? new IOException("Full.") : null); + await using var archive = await app.NewArchiveAsync(b => b.ConfigureTestServices(services => services.AddSingleton(storage))); + var (zip, _) = ManyItems(word, ExportImport.StopAfterFailures * 2); + + var result = await RunDirectAsync(archive, zip); + + Assert.Equal(ExportImport.StopAfterFailures * 2, result.Items); + Assert.Equal(0, result.ItemsNotTried); + Assert.Equal(ExportImport.StopAfterFailures, result.FilesFailed); + } + + [Fact] + public async Task A_run_stops_between_items_when_the_app_is_shutting_down() + { + var word = Word(); + var lifetime = new FakeLifetime(); + var storage = new ScriptedStorage(app.Services.GetRequiredService(), _ => null, afterSave: n => + { + if (n == 1) + lifetime.Stopping.Cancel(); + }); + await using var archive = await app.NewArchiveAsync(b => b.ConfigureTestServices(services => services.AddSingleton(storage))); + var (zip, photos) = ManyItems(word, 3); + + var result = await RunDirectAsync(archive, zip, lifetime); + + Assert.Equal(1, result.Items); + Assert.Equal(1, result.Files); + Assert.Equal(2, result.ItemsNotTried); + Assert.Equal([Sha(photos[0])], await archive.WithDbAsync(db => db.MediaFiles.Select(f => f.Sha256).ToListAsync())); + Assert.Equal("1 / 1", await SummaryAsync(archive)); + } + + [Fact] + public async Task A_run_that_is_cut_short_after_an_added_photo_still_logs_the_photos_and_the_summary_and_rethrows_the_real_error() + { + var word = Word(); + var storage = new ScriptedStorage(app.Services.GetRequiredService(), n => n == 2 ? new InvalidOperationException("Not a disk problem.") : null); + await using var archive = await app.NewArchiveAsync(b => b.ConfigureTestServices(services => services.AddSingleton(storage))); + var (zip, _) = ManyItems(word, 1, filesPerItem: 2); + + var thrown = await Assert.ThrowsAsync(() => RunDirectAsync(archive, zip)); + + Assert.Equal("Not a disk problem.", thrown.Message); + var actions = await archive.WithDbAsync(db => db.AuditEntries.Select(e => e.Action).ToListAsync()); + Assert.Contains(AuditAction.PhotosAdded, actions); + Assert.Equal("1 / 1", await SummaryAsync(archive)); + Assert.Equal(1, await archive.WithDbAsync(db => db.MediaFiles.CountAsync())); + } + + [Fact] + public async Task The_lock_is_released_and_the_copy_removed_when_a_run_fails_in_a_way_that_is_not_a_failed_file() + { + var word = Word(); + var storage = new ScriptedStorage(app.Services.GetRequiredService(), _ => new InvalidOperationException("secret-bug-detail")); + await using var archive = await app.NewArchiveAsync(b => b.ConfigureTestServices(services => services.AddSingleton(storage))); + using var curator = await CuratorAsync(archive); + var (zip, _) = ManyItems(word, 2); + var dryRun = await DryRunAsync(curator, zip); + var id = Guid.Parse(StagingIdPattern().Match(dryRun).Groups[1].Value); + + var response = await PostImportAsync(curator, dryRun); + + Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); + Assert.Equal(1, ImportLock.OneAtATime.CurrentCount); + Assert.False(archive.Services.GetRequiredService().ExportExists(id)); + Assert.Equal("1 / 0", await SummaryAsync(archive)); + } + + [Fact] + public async Task A_photo_whose_save_fails_leaves_no_stored_original_and_is_counted_and_logged_against_its_item() + { + var word = Word(); + var storage = new ScriptedStorage(app.Services.GetRequiredService(), _ => null); + var failing = new FailingPhotoSave(); + await using var archive = await app.NewArchiveAsync(b => b.ConfigureTestServices(services => + { + services.AddSingleton(storage); + services.ConfigureDbContext(options => options.AddInterceptors(failing)); + })); + var (zip, _) = ManyItems(word, 1); + + var result = await RunDirectAsync(archive, zip); + + Assert.Equal(new ExportImportResult(1, 0, 1, 1), result); + var key = Assert.Single(storage.Saved); + Assert.Equal([key], storage.Deleted); + Assert.False(storage.Exists(key)); + var line = await archive.WithDbAsync(db => db.AuditEntries.Where(e => e.Action == AuditAction.ImportPhotosMissing).SingleAsync()); + Assert.Equal(Copy(word, 1), line.Subject); + Assert.NotNull(line.ArchiveItemId); + Assert.DoesNotContain(AuditAction.PhotosAdded, await archive.WithDbAsync(db => db.AuditEntries.Select(e => e.Action).ToListAsync())); + Assert.Equal("1 / 0", await SummaryAsync(archive)); + } + + [Fact] + public async Task The_text_and_the_turn_of_a_photo_are_stored_with_it_in_one_save() + { + var word = Word(); + await using var archive = await app.NewArchiveAsync(); + var photo = NewPhoto(); + var json = ArchiveJson( + [Item(1, $"{word} Barn", files: [File(7, 1, "a.jpg", photo, altText: "A red barn", caption: "Before the fire", rotation: 90)])], + [Collection(1, $"{word} Collection")]); + + var result = await RunDirectAsync(archive, Zip(("archive.json", json), ("files/1/7-a.jpg", photo))); + + Assert.Equal(new ExportImportResult(1, 1, 0, 1), result); + var stored = await archive.WithDbAsync(db => db.MediaFiles.SingleAsync()); + Assert.Equal(("A red barn", "Before the fire", 90), (stored.AltText, stored.Caption, stored.Rotation)); + } + private static object[] EmptyFiles(int count) => Enumerable.Repeat(new { }, count).ToArray(); [Fact] diff --git a/tests/Commonage.Tests/FileStorageTests.cs b/tests/Commonage.Tests/FileStorageTests.cs index f749b28..ed231ea 100644 --- a/tests/Commonage.Tests/FileStorageTests.cs +++ b/tests/Commonage.Tests/FileStorageTests.cs @@ -29,6 +29,23 @@ public void Keys_cannot_point_outside_the_storage_directory() Assert.Throws(() => storage.OpenRead("../secrets.txt")); } + [Fact] + public async Task A_copy_that_fails_leaves_no_half_written_file_behind() + { + var storage = new LocalFileStorage(_root); + + await Assert.ThrowsAsync(() => storage.SaveAsync("originals/abc", new StreamThatFails())); + + Assert.False(storage.Exists("originals/abc")); + Assert.Empty(Directory.EnumerateFiles(_root, "*", SearchOption.AllDirectories)); + } + + private sealed class StreamThatFails : MemoryStream + { + public override ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) => + throw new IOException("The disk is full."); + } + public void Dispose() { if (Directory.Exists(_root)) From af2dae7fe783977bb88bc2d8ae55cd1234e60877 Mon Sep 17 00:00:00 2001 From: "Seb H." <138793908+SebHenn@users.noreply.github.com> Date: Sun, 22 Nov 2026 20:15:44 +0100 Subject: [PATCH 7/7] M28, second part: delete a stored original after a failed save only when no row exists A save that throws may still have committed (a dropped connection), so the original is removed only when a fresh look finds no row; the entry is detached. Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Seb H. <138793908+SebHenn@users.noreply.github.com> --- src/Commonage.Web/Media/MediaUploadService.cs | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/Commonage.Web/Media/MediaUploadService.cs b/src/Commonage.Web/Media/MediaUploadService.cs index 4614b07..8ed6923 100644 --- a/src/Commonage.Web/Media/MediaUploadService.cs +++ b/src/Commonage.Web/Media/MediaUploadService.cs @@ -150,12 +150,18 @@ public async Task StoreAsync( } catch { - // The file is stored but nothing in the database knows it, so nothing would ever remove it. + // The file is stored; if the save failed, nothing in the database knows it and nothing would ever remove it. + // A failed save can still have been committed (a dropped connection), so the file goes only when a fresh + // look shows no row for it. If that look fails too, an orphan file is better than a lost original. + db.Entry(file).State = EntityState.Detached; try { - storage.Delete(file.OriginalKey); + var committed = await db.MediaFiles.IgnoreQueryFilters().AsNoTracking() + .AnyAsync(m => m.StorageId == file.StorageId, CancellationToken.None); + if (!committed) + storage.Delete(file.OriginalKey); } - catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or DbUpdateException or InvalidOperationException or Npgsql.NpgsqlException) { }