From 80d07bb2b2a25d82055b3d0f3ea285dda501ed71 Mon Sep 17 00:00:00 2001 From: "Seb H." <138793908+SebHenn@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:03:53 +0100 Subject: [PATCH 1/2] M27, first part: one definition of what the public may see VisibleItems and VisibleMedia replace PublishedItems. A collection with nothing public no longer has a page or a place in the search filter. The visibility matrix and a guard test pin the rule. Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Seb H. <138793908+SebHenn@users.noreply.github.com> --- CHANGELOG.md | 2 + docs/development.md | 2 +- docs/roadmap.md | 2 + docs/security.md | 2 +- src/Commonage.Web/Data/CommonageDbContext.cs | 5 +- src/Commonage.Web/Data/Visibility.cs | 18 +++ src/Commonage.Web/Export/ArchiveExporter.cs | 2 +- src/Commonage.Web/Media/MediaEndpoints.cs | 9 +- .../Pages/Collections/Details.cshtml.cs | 4 +- src/Commonage.Web/Pages/Help.cshtml.cs | 2 +- src/Commonage.Web/Pages/Index.cshtml.cs | 10 +- .../Pages/Items/Details.cshtml.cs | 2 +- src/Commonage.Web/Pages/Items/Tell.cshtml.cs | 2 +- src/Commonage.Web/Pages/Search.cshtml.cs | 6 +- src/Commonage.Web/Pages/TagIndex.cshtml.cs | 2 +- src/Commonage.Web/Search/ItemSearch.cs | 2 +- src/Commonage.Web/Search/ItemSummary.cs | 12 +- src/Commonage.Web/Search/ItemSurroundings.cs | 4 +- src/Commonage.Web/Search/PublicFeeds.cs | 6 +- tests/Commonage.Tests/BinTests.cs | 2 +- tests/Commonage.Tests/ContributionTests.cs | 2 +- tests/Commonage.Tests/LinkInvitationTests.cs | 5 +- tests/Commonage.Tests/ReadableItemTests.cs | 2 +- tests/Commonage.Tests/VisibilityGuardTests.cs | 58 +++++++++ .../Commonage.Tests/VisibilityMatrixTests.cs | 111 ++++++++++++++++++ 25 files changed, 234 insertions(+), 40 deletions(-) create mode 100644 src/Commonage.Web/Data/Visibility.cs create mode 100644 tests/Commonage.Tests/VisibilityGuardTests.cs create mode 100644 tests/Commonage.Tests/VisibilityMatrixTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index bd4aef3..d45c9ff 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -51,6 +51,8 @@ Updating needs no picture regeneration. Migrations run by themselves at start. ### For visitors and curators +- A collection with nothing public in it, only drafts or items in the bin, no longer has a page of its own, and the search's + collection filter no longer lists it. Before, anyone who knew or guessed its number could read its title and description. - A year, decade, month or period typed into the search, such as "Mill Street 1950s", "circa 1960" or "before 1945", also finds what is dated then. The page says how it read the date. Curators' item list searches the same way. - The start page shows the archive through the decades, and the search shows the decades of what it found. Each decade opens diff --git a/docs/development.md b/docs/development.md index 2a507bc..c1be626 100644 --- a/docs/development.md +++ b/docs/development.md @@ -21,7 +21,7 @@ queue server and no build step for the front end: pages work without JavaScript, What is special about it, and easy to break by accident: -- **Only published items are public.** Public pages go through `db.PublishedItems`, and `/media` serves nothing else. +- **Only published items are public.** Public pages go through `db.VisibleItems`, and `/media` serves only `db.VisibleMedia`. - **Originals are private.** Visitors only ever see generated pictures, which carry no EXIF. So GPS positions stay private. - **A contributor's personal details stay with curators.** They are never on a public page unless a curator chose so, and never in the activity log. diff --git a/docs/roadmap.md b/docs/roadmap.md index 473a841..3a5f3ec 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -889,6 +889,8 @@ shows the years of its published items. M19 is complete. **M27 Visibility levels** - The plan is in [plan-m27-visibility.md](plan-m27-visibility.md). +- *Built (part 1):* `VisibleItems` and `VisibleMedia` replace `PublishedItems`; the matrix and guard tests are in. It found two + leaks that were already there (a collection page and the search filter naming a collection with nothing public), now fixed. - First a record without its media, then an embargo date. `PublishedItems` becomes `VisibleItems(viewer)`. Members-only waits for a group to ask, because visitor accounts are not planned. A separate plan and an adversarial privacy review come before any code, and every public page, the feed, the sitemap, link previews and the published-only export get a test with such diff --git a/docs/security.md b/docs/security.md index 61ac576..e478dc0 100644 --- a/docs/security.md +++ b/docs/security.md @@ -21,7 +21,7 @@ vulnerability, see [SECURITY.md](../SECURITY.md). | Area | Measure | |---|---| -| Access | Public pages and public image addresses read only from published items (`PublishedItems`). Admin pages are protected by policy per folder; admin-only pages (accounts, export, activity log) by a second policy. Originals and previews of unpublished items are served only to curators. What a curator chooses ahead of publishing, such as a draft's photo as a collection's cover, is passed over until its item is published. Tested in `PublicationTests`, `MediaTests`, `AccountTests`, `ExportTests`, `CollectionTests`. `EndpointAccessTests` lists every address that is open without a login, so a new one cannot be open by accident. | +| Access | Public pages and public image addresses read only from published items (`VisibleItems`, `VisibleMedia`). Admin pages are protected by policy per folder; admin-only pages (accounts, export, activity log) by a second policy. Originals and previews of unpublished items are served only to curators. What a curator chooses ahead of publishing, such as a draft's photo as a collection's cover, is passed over until its item is published. Tested in `PublicationTests`, `MediaTests`, `AccountTests`, `ExportTests`, `CollectionTests`. `EndpointAccessTests` lists every address that is open without a login, so a new one cannot be open by accident. | | Accounts | Passwords of at least 12 characters (length over forced symbols, NIST SP 800-63B). Five wrong passwords lock an account for five minutes, and one address can try 100 logins an hour. Accounts are created with one-time setup links, valid seven days. Disabling an account, or a password change, ends its logins within a minute. Admins cannot lock themselves out. An authenticator app (TOTP) can be added to each login, and admins can require it of everyone who manages the archive; wrong codes count towards the lockout like wrong passwords. Ten recovery codes, each usable once. Turning the app off or making new codes asks for the password again, and wrong passwords there and on "Change password" count towards the lockout too. Tested in `TwoFactorTests`. | | Forms | Every form carries an antiforgery token. Redirects after login and language change only go to addresses on this site. | | 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`. | diff --git a/src/Commonage.Web/Data/CommonageDbContext.cs b/src/Commonage.Web/Data/CommonageDbContext.cs index 9e127ed..989a85b 100644 --- a/src/Commonage.Web/Data/CommonageDbContext.cs +++ b/src/Commonage.Web/Data/CommonageDbContext.cs @@ -46,7 +46,10 @@ public class CommonageDbContext(DbContextOptions options) public const string FoldFunction = "commonage_fold"; /// Items the public may see. Every public page must start from this query. - public IQueryable PublishedItems => ArchiveItems.Where(i => i.Status == ItemStatus.Published); + public IQueryable VisibleItems => ArchiveItems.Where(Visibility.Item); + + /// Files the public may be given. /media and every cover or first photo start from this. + public IQueryable VisibleMedia => MediaFiles.Where(Visibility.Media); /// Items in the bin. Query filters hide them from every other query, see . public IQueryable BinnedItems => ArchiveItems.IgnoreQueryFilters().Where(i => i.DeletedAt != null); diff --git a/src/Commonage.Web/Data/Visibility.cs b/src/Commonage.Web/Data/Visibility.cs new file mode 100644 index 0000000..df9f581 --- /dev/null +++ b/src/Commonage.Web/Data/Visibility.cs @@ -0,0 +1,18 @@ +using System.Linq.Expressions; +using Commonage.Web.Domain; + +namespace Commonage.Web.Data; + +/// +/// The one definition of what the public may see. This file, and +/// are the only places that may write in a +/// query. A query that starts from a collection or a tag and reaches its items uses and . +/// +public static class Visibility +{ + /// An item visitors may see: published and, by the query filter, not in the bin. + public static readonly Expression> Item = i => i.Status == ItemStatus.Published; + + /// A file visitors may be given: it belongs to a visible item. + public static readonly Expression> Media = f => f.ArchiveItem.Status == ItemStatus.Published; +} diff --git a/src/Commonage.Web/Export/ArchiveExporter.cs b/src/Commonage.Web/Export/ArchiveExporter.cs index d09cff3..0085503 100644 --- a/src/Commonage.Web/Export/ArchiveExporter.cs +++ b/src/Commonage.Web/Export/ArchiveExporter.cs @@ -51,7 +51,7 @@ public async Task WriteAsync(Stream output, ExportOptions options, CancellationT // changes the archive while a large export is being written. Nothing is written to the database. await using var snapshot = await db.Database.BeginTransactionAsync(System.Data.IsolationLevel.RepeatableRead, cancellationToken); var collections = await db.Collections.AsNoTracking().OrderBy(c => c.Id).ToListAsync(cancellationToken); - var source = (options.PublishedOnly ? db.PublishedItems : db.ArchiveItems).AsNoTracking(); + var source = (options.PublishedOnly ? db.VisibleItems : db.ArchiveItems).AsNoTracking(); if (options.PublishedOnly) { var used = await source.Select(i => i.CollectionId).Distinct().ToListAsync(cancellationToken); diff --git a/src/Commonage.Web/Media/MediaEndpoints.cs b/src/Commonage.Web/Media/MediaEndpoints.cs index f86bf90..5646e35 100644 --- a/src/Commonage.Web/Media/MediaEndpoints.cs +++ b/src/Commonage.Web/Media/MediaEndpoints.cs @@ -55,8 +55,7 @@ private static async Task PreviewStatusAsync(string? ids, CommonageDbCo private static async Task ServePublicDerivativeAsync( int id, string variant, CommonageDbContext db, IFileStorage storage, ArchiveProfile profile, HttpContext context) { - var file = await db.PublishedItems - .SelectMany(i => i.MediaFiles) + var file = await db.VisibleMedia .FirstOrDefaultAsync(f => f.Id == id && f.Status == ProcessingStatus.Ready); if (file is null || file.IsAudio) return Results.NotFound(); @@ -77,8 +76,7 @@ private static async Task ServePublicDerivativeAsync( /// private static async Task ServePublicAudioAsync(int id, CommonageDbContext db, IFileStorage storage, HttpContext context) { - var file = await db.PublishedItems - .SelectMany(i => i.MediaFiles) + var file = await db.VisibleMedia .FirstOrDefaultAsync(f => f.Id == id && f.Status == ProcessingStatus.Ready && f.ContentType.StartsWith("audio/")); if (file is null || !storage.Exists(file.AudioKey)) return Results.NotFound(); @@ -101,8 +99,7 @@ private static async Task ServeAudioAsync(int id, CommonageDbContext db /// One page of a published PDF, drawn as a picture. The PDF itself is never served to visitors. private static async Task ServePublicPageAsync(int id, int page, CommonageDbContext db, IFileStorage storage, HttpContext context) { - var file = await db.PublishedItems - .SelectMany(i => i.MediaFiles) + var file = await db.VisibleMedia .FirstOrDefaultAsync(f => f.Id == id && f.Status == ProcessingStatus.Ready); if (file is null || page < 1 || page > (file.PageCount ?? 0)) return Results.NotFound(); diff --git a/src/Commonage.Web/Pages/Collections/Details.cshtml.cs b/src/Commonage.Web/Pages/Collections/Details.cshtml.cs index add2240..20d8bed 100644 --- a/src/Commonage.Web/Pages/Collections/Details.cshtml.cs +++ b/src/Commonage.Web/Pages/Collections/Details.cshtml.cs @@ -25,13 +25,13 @@ public record Invitation(string Title, string Token); public async Task OnGetAsync(int id, CancellationToken cancellationToken) { - var collection = await db.Collections.FindAsync([id], cancellationToken); + var collection = await db.Collections.Where(c => c.Id == id && c.Items.AsQueryable().Any(Visibility.Item)).FirstOrDefaultAsync(cancellationToken); if (collection is null) return NotFound(); Collection = collection; Years = await db.Collections.Where(c => c.Id == id).ToCards().Select(c => c.Years).FirstAsync(cancellationToken); - Items = await db.PublishedItems + Items = await db.VisibleItems .Filter(new ItemFilter(CollectionId: id)) .Sort(collection.Sort.ToItemSort(), query: null) .Select(ItemSummary.FromItem) diff --git a/src/Commonage.Web/Pages/Help.cshtml.cs b/src/Commonage.Web/Pages/Help.cshtml.cs index 0b3c924..0aeddd7 100644 --- a/src/Commonage.Web/Pages/Help.cshtml.cs +++ b/src/Commonage.Web/Pages/Help.cshtml.cs @@ -21,7 +21,7 @@ public async Task OnGetAsync(CancellationToken cancellationToken) if (!(await profile.GetAsync()).AcceptVisitorNotes) return NotFound(); - Items = await db.PublishedItems + Items = await db.VisibleItems .Where(i => i.HelpWanted) .OrderByDescending(i => i.PublishedAt) .ThenByDescending(i => i.Id) diff --git a/src/Commonage.Web/Pages/Index.cshtml.cs b/src/Commonage.Web/Pages/Index.cshtml.cs index 84d8951..42b567d 100644 --- a/src/Commonage.Web/Pages/Index.cshtml.cs +++ b/src/Commonage.Web/Pages/Index.cshtml.cs @@ -32,18 +32,18 @@ public class IndexModel(CommonageDbContext db, Commonage.Web.Operations.ArchiveP public async Task OnGetAsync() { Identity = await profile.GetAsync(); - HelpWanted = Identity.AcceptVisitorNotes && await db.PublishedItems.AnyAsync(i => i.HelpWanted); + HelpWanted = Identity.AcceptVisitorNotes && await db.VisibleItems.AnyAsync(i => i.HelpWanted); Collections = await db.LoadCollectionCardsAsync(HttpContext.RequestAborted); - Recent = await db.PublishedItems + Recent = await db.VisibleItems .OrderByDescending(i => i.PublishedAt) .ThenByDescending(i => i.Id) .Take(RecentCount) .Select(ItemSummary.FromItem) .ToListAsync(); - Decades = await DecadeTimeline.LoadAsync(db.PublishedItems, HttpContext.RequestAborted); + Decades = await DecadeTimeline.LoadAsync(db.VisibleItems, HttpContext.RequestAborted); - var popularTags = await db.PublishedItems + var popularTags = await db.VisibleItems .SelectMany(i => i.Tags) .GroupBy(t => t.Name) .OrderByDescending(g => g.Count()) @@ -52,7 +52,7 @@ public async Task OnGetAsync() .Take(MaxTags) .ToListAsync(); Tags = popularTags.Order(StringComparer.CurrentCultureIgnoreCase).ToList(); - TagKinds = await db.PublishedItems + TagKinds = await db.VisibleItems .SelectMany(i => i.Tags) .Where(t => t.Kind != Domain.TagKind.Topic) .Select(t => t.Kind) diff --git a/src/Commonage.Web/Pages/Items/Details.cshtml.cs b/src/Commonage.Web/Pages/Items/Details.cshtml.cs index 1763039..70c33d2 100644 --- a/src/Commonage.Web/Pages/Items/Details.cshtml.cs +++ b/src/Commonage.Web/Pages/Items/Details.cshtml.cs @@ -23,7 +23,7 @@ public class DetailsModel(CommonageDbContext db, ArchiveProfile profile, IString public async Task OnGetAsync(int id, CancellationToken cancellationToken) { - var item = await db.PublishedItems + var item = await db.VisibleItems .Include(i => i.Collection) .Include(i => i.Contribution) .Include(i => i.Tags.OrderBy(t => t.Name)) diff --git a/src/Commonage.Web/Pages/Items/Tell.cshtml.cs b/src/Commonage.Web/Pages/Items/Tell.cshtml.cs index d46e44a..f092e51 100644 --- a/src/Commonage.Web/Pages/Items/Tell.cshtml.cs +++ b/src/Commonage.Web/Pages/Items/Tell.cshtml.cs @@ -111,7 +111,7 @@ private async Task LoadAsync(int id, CancellationToken cancellationToken) { if (!(await profile.GetAsync()).AcceptVisitorNotes) return false; - if (await db.PublishedItems.FirstOrDefaultAsync(i => i.Id == id, cancellationToken) is not { } item) + if (await db.VisibleItems.FirstOrDefaultAsync(i => i.Id == id, cancellationToken) is not { } item) return false; Item = item; return true; diff --git a/src/Commonage.Web/Pages/Search.cshtml.cs b/src/Commonage.Web/Pages/Search.cshtml.cs index 3d65526..9001290 100644 --- a/src/Commonage.Web/Pages/Search.cshtml.cs +++ b/src/Commonage.Web/Pages/Search.cshtml.cs @@ -76,7 +76,7 @@ public async Task OnGetAsync(CancellationToken cancellationToken) var search = await db.ToSearchAsync(Text, cancellationToken); (Query, Dates) = (search.Query, search.Dates); var filter = new ItemFilter(Query, Tag, Collection, From, To, Dates); - var matches = db.PublishedItems.Filter(filter); + var matches = db.VisibleItems.Filter(filter); Results = await matches .Sort(Sort, Query) @@ -101,13 +101,13 @@ public async Task OnGetAsync(CancellationToken cancellationToken) Decades = []; } - var collections = await db.Collections.OrderBy(c => c.Title).ToListAsync(cancellationToken); + var collections = await db.Collections.Where(c => c.Items.AsQueryable().Any(Visibility.Item)).OrderBy(c => c.Title).ToListAsync(cancellationToken); CollectionOptions = new SelectList(collections, nameof(Domain.Collection.Id), nameof(Domain.Collection.Title), Collection); CollectionTitle = collections.FirstOrDefault(c => c.Id == Collection)?.Title; if (Results.TotalCount == 0) { - PopularTags = await db.PublishedItems + PopularTags = await db.VisibleItems .SelectMany(i => i.Tags) .GroupBy(t => t.Name) .OrderByDescending(g => g.Count()) diff --git a/src/Commonage.Web/Pages/TagIndex.cshtml.cs b/src/Commonage.Web/Pages/TagIndex.cshtml.cs index fd26825..022f32d 100644 --- a/src/Commonage.Web/Pages/TagIndex.cshtml.cs +++ b/src/Commonage.Web/Pages/TagIndex.cshtml.cs @@ -31,7 +31,7 @@ public async Task OnGetAsync(string kind, CancellationToken cance Kind = found; // Only what visitors can see: a name on drafts alone is not shown. - var tags = await db.PublishedItems + var tags = await db.VisibleItems .SelectMany(i => i.Tags) .Where(t => t.Kind == Kind) .GroupBy(t => t.Name) diff --git a/src/Commonage.Web/Search/ItemSearch.cs b/src/Commonage.Web/Search/ItemSearch.cs index c9b52e1..70e7b35 100644 --- a/src/Commonage.Web/Search/ItemSearch.cs +++ b/src/Commonage.Web/Search/ItemSearch.cs @@ -33,7 +33,7 @@ public record TextSearch(string? Query, IReadOnlyList Dates) /// /// Filters and sorts archive items. It never decides what the caller may see: public pages pass -/// , curator pages pass all items. +/// , curator pages pass all items. /// public static class ItemSearch { diff --git a/src/Commonage.Web/Search/ItemSummary.cs b/src/Commonage.Web/Search/ItemSummary.cs index 7ee9435..e8dd7ff 100644 --- a/src/Commonage.Web/Search/ItemSummary.cs +++ b/src/Commonage.Web/Search/ItemSummary.cs @@ -24,7 +24,7 @@ public static class CollectionCards /// Collections with published items, in the order curators gave them. public static Task> LoadCollectionCardsAsync(this CommonageDbContext db, CancellationToken cancellationToken) => db.Collections - .Where(c => c.Items.Any(i => i.Status == ItemStatus.Published)) + .Where(c => c.Items.AsQueryable().Any(Visibility.Item)) .OrderBy(c => c.Position).ThenBy(c => c.Title).ThenBy(c => c.Id) .ToCards() .ToListAsync(cancellationToken); @@ -38,19 +38,19 @@ public static IQueryable ToCards(this IQueryable col c.Id, c.Title, c.Description, - c.Items.Count(i => i.Status == ItemStatus.Published), - c.Items.Where(i => i.Status == ItemStatus.Published) + c.Items.AsQueryable().Count(Visibility.Item), + c.Items.AsQueryable().Where(Visibility.Item) .SelectMany(i => i.MediaFiles) .Where(f => f.Status == ProcessingStatus.Ready && f.Id == c.CoverMediaFileId && !f.ContentType.StartsWith("audio/")) .Select(f => (int?)f.Id) .FirstOrDefault() - ?? c.Items.Where(i => i.Status == ItemStatus.Published) + ?? c.Items.AsQueryable().Where(Visibility.Item) .SelectMany(i => i.MediaFiles) .Where(f => f.Status == ProcessingStatus.Ready && !f.ContentType.StartsWith("audio/")) .OrderBy(f => f.ArchiveItemId).ThenBy(f => f.Position).ThenBy(f => f.Id) .Select(f => (int?)f.Id) .FirstOrDefault(), new YearSpan( - c.Items.Where(i => i.Status == ItemStatus.Published).Min(i => (int?)(i.DateFrom ?? i.DateTo)!.Value.Year), - c.Items.Where(i => i.Status == ItemStatus.Published).Max(i => (int?)(i.DateTo ?? i.DateFrom)!.Value.Year)))); + c.Items.AsQueryable().Where(Visibility.Item).Min(i => (int?)(i.DateFrom ?? i.DateTo)!.Value.Year), + c.Items.AsQueryable().Where(Visibility.Item).Max(i => (int?)(i.DateTo ?? i.DateFrom)!.Value.Year)))); } diff --git a/src/Commonage.Web/Search/ItemSurroundings.cs b/src/Commonage.Web/Search/ItemSurroundings.cs index 2391058..9b4a09c 100644 --- a/src/Commonage.Web/Search/ItemSurroundings.cs +++ b/src/Commonage.Web/Search/ItemSurroundings.cs @@ -14,7 +14,7 @@ public record ItemSurroundings(ItemLink? Previous, ItemLink? Next, IReadOnlyList public static async Task LoadAsync(CommonageDbContext db, ArchiveItem item, CancellationToken cancellationToken) { - var inCollection = db.PublishedItems.Where(i => i.CollectionId == item.CollectionId && i.Id != item.Id); + var inCollection = db.VisibleItems.Where(i => i.CollectionId == item.CollectionId && i.Id != item.Id); var sort = await db.Collections.Where(c => c.Id == item.CollectionId).Select(c => c.Sort).FirstAsync(cancellationToken); // In the order of the collection's page. @@ -36,7 +36,7 @@ public static async Task LoadAsync(CommonageDbContext db, Arch if (item is { DateFrom: { } from, DateTo: { } to }) { var alreadyShown = sameCollection.Select(i => i.Id).ToList(); - sameTime = await db.PublishedItems + sameTime = await db.VisibleItems .Where(i => i.Id != item.Id && !alreadyShown.Contains(i.Id) && i.DateFrom != null && i.DateTo != null && i.DateFrom <= to && i.DateTo >= from) // Closest to the same period first, so that "summer 1953" comes before "1930–1955". .OrderBy(i => Math.Abs(i.DateFrom!.Value.DayNumber - from.DayNumber) + Math.Abs(i.DateTo!.Value.DayNumber - to.DayNumber)) diff --git a/src/Commonage.Web/Search/PublicFeeds.cs b/src/Commonage.Web/Search/PublicFeeds.cs index 8832251..067cc8a 100644 --- a/src/Commonage.Web/Search/PublicFeeds.cs +++ b/src/Commonage.Web/Search/PublicFeeds.cs @@ -64,7 +64,7 @@ private static async Task ServeFeedAsync( var address = context.Request.BaseAddress(); // What people agreed to before this existed was "this website". A feed is copied to other places, so those stay out of it. - var items = await db.PublishedItems + var items = await db.VisibleItems .Where(i => i.Contribution == null || i.Contribution.ConsentCoversSharing) .Include(i => i.MediaFiles.Where(f => f.Status == ProcessingStatus.Ready && !f.ContentType.StartsWith("audio/")).OrderBy(f => f.Position).ThenBy(f => f.Id).Take(1)) .OrderByDescending(i => i.PublishedAt).ThenByDescending(i => i.Id) @@ -123,11 +123,11 @@ private static async Task ServeSitemapAsync(HttpContext context, Common var address = context.Request.BaseAddress(); var collections = await db.Collections - .Where(c => c.Items.Any(i => i.Status == ItemStatus.Published)) + .Where(c => c.Items.AsQueryable().Any(Visibility.Item)) .OrderBy(c => c.Id) .Select(c => c.Id) .ToListAsync(cancellationToken); - var items = await db.PublishedItems + var items = await db.VisibleItems .OrderByDescending(i => i.PublishedAt).ThenByDescending(i => i.Id) .Take(MaxSitemapItems) .Select(i => new { i.Id, i.UpdatedAt }) diff --git a/tests/Commonage.Tests/BinTests.cs b/tests/Commonage.Tests/BinTests.cs index 1b0484a..e6daaa3 100644 --- a/tests/Commonage.Tests/BinTests.cs +++ b/tests/Commonage.Tests/BinTests.cs @@ -35,7 +35,7 @@ public async Task An_item_in_the_bin_is_gone_from_everywhere_until_it_is_restore await Browser.PostFormAsync(curator, $"{ItemPage(item)}?handler=Delete", new(), ItemPage(item)); Assert.Equal(HttpStatusCode.NotFound, (await visitor.GetAsync($"/items/{item.Id}")).StatusCode); - Assert.DoesNotContain(item.Title, await visitor.GetStringAsync($"/collections/{item.CollectionId}")); + Assert.Equal(HttpStatusCode.NotFound, (await visitor.GetAsync($"/collections/{item.CollectionId}")).StatusCode); Assert.DoesNotContain(item.Title, await curator.GetStringAsync("/Admin")); Assert.Contains(item.Title, await curator.GetStringAsync("/Admin/Bin")); var opened = await curator.GetAsync(ItemPage(item)); diff --git a/tests/Commonage.Tests/ContributionTests.cs b/tests/Commonage.Tests/ContributionTests.cs index a8b4bb5..aebefcd 100644 --- a/tests/Commonage.Tests/ContributionTests.cs +++ b/tests/Commonage.Tests/ContributionTests.cs @@ -54,7 +54,7 @@ public async Task A_contribution_stays_private_until_a_curator_publishes_it() Assert.Equal(HttpStatusCode.NotFound, (await visitor.GetAsync($"/items/{item.Id}")).StatusCode); Assert.Equal(HttpStatusCode.NotFound, (await visitor.GetAsync($"/media/{item.MediaFiles[0].Id}/preview")).StatusCode); - Assert.DoesNotContain("Flood in Mill Street", await visitor.GetStringAsync($"/collections/{collectionId}")); + Assert.Equal(HttpStatusCode.NotFound, (await visitor.GetAsync($"/collections/{collectionId}")).StatusCode); var waiting = await curator.GetStringAsync("/Admin?status=Submitted"); var review = await curator.GetStringAsync($"/Admin/Items/Edit/{item.Id}"); diff --git a/tests/Commonage.Tests/LinkInvitationTests.cs b/tests/Commonage.Tests/LinkInvitationTests.cs index 10d67b2..e55076e 100644 --- a/tests/Commonage.Tests/LinkInvitationTests.cs +++ b/tests/Commonage.Tests/LinkInvitationTests.cs @@ -24,7 +24,10 @@ public class LinkInvitationTests(CommonageAppFactory app) InviteOnCollectionPage = invite, CreatedAt = DateTime.UtcNow, }; - db.Add(link); + // A collection with nothing public has no page, so each one holds a published item. + var item = new ArchiveItem { Title = $"Mill {suffix}", Collection = collection, CreatedAt = DateTime.UtcNow, UpdatedAt = DateTime.UtcNow }; + item.Publish(DateTime.UtcNow); + db.AddRange(link, item); await db.SaveChangesAsync(); return (collection.Id, link.Id, link.Token); }); diff --git a/tests/Commonage.Tests/ReadableItemTests.cs b/tests/Commonage.Tests/ReadableItemTests.cs index a999cc4..ca910cc 100644 --- a/tests/Commonage.Tests/ReadableItemTests.cs +++ b/tests/Commonage.Tests/ReadableItemTests.cs @@ -297,7 +297,7 @@ public async Task Photos_go_in_the_order_curators_give_them_and_the_first_is_the Assert.True(page.IndexOf($"/media/{three}/preview", StringComparison.Ordinal) < page.IndexOf($"/media/{one}/preview", StringComparison.Ordinal)); var title = await app.WithDbAsync(db => db.ArchiveItems.Where(i => i.Id == item.Id).Select(i => i.Title).SingleAsync()); - var card = await app.WithDbAsync(db => db.PublishedItems.Where(i => i.Id == item.Id).Select(ItemSummary.FromItem).SingleAsync()); + var card = await app.WithDbAsync(db => db.VisibleItems.Where(i => i.Id == item.Id).Select(ItemSummary.FromItem).SingleAsync()); Assert.Equal(two, card.ThumbnailMediaFileId); // An open form can still be saved, and putting photos in order is one thing that happened, not many. diff --git a/tests/Commonage.Tests/VisibilityGuardTests.cs b/tests/Commonage.Tests/VisibilityGuardTests.cs new file mode 100644 index 0000000..f4efac7 --- /dev/null +++ b/tests/Commonage.Tests/VisibilityGuardTests.cs @@ -0,0 +1,58 @@ +using System.Text.RegularExpressions; + +namespace Commonage.Tests; + +/// +/// A tripwire, not a proof ( proves the behaviour): code a visitor reaches must not read +/// items by another way than VisibleItems and VisibleMedia. Needs no Docker. +/// +public partial class VisibilityGuardTests +{ + /// What a visitor's request may run: everything under these, except what the list below names. + private static readonly string[] PublicFolders = ["Pages", "Search", "Media", "Export"]; + + /// Files that read items another way on purpose, each with its reason. + private static readonly Dictionary Allowed = new() + { + ["Media/MediaEndpoints.cs"] = "the staff path (/admin/media) reads every file for curators", + ["Media/MediaProcessing.cs"] = "makes the previews of files nobody may see yet", + ["Media/FileTextIndex.cs"] = "keeps the search text of an item's PDFs in step, for staff and background work", + ["Search/AdminItemList.cs"] = "the curators' list, which sees drafts", + ["Media/MediaUploadService.cs"] = "the position of the next file counts files in the bin too", + ["Pages/Contribute/Index.cshtml.cs"] = "the contributor's own submissions, found by their link", + ["Export/ArchiveExporter.cs"] = "the full export is for admins; the published-only copy goes through VisibleItems", + }; + + [Fact] + public void Public_code_reads_items_only_through_the_visible_queries() + { + var root = SourceRoot(); + var offenders = new List(); + foreach (var folder in PublicFolders) + foreach (var file in Directory.EnumerateFiles(Path.Combine(root, folder), "*", SearchOption.AllDirectories)) + { + var relative = Path.GetRelativePath(root, file).Replace('\\', '/'); + if (relative.StartsWith("Pages/Admin/") || Allowed.ContainsKey(relative)) + continue; + if (!file.EndsWith(".cs") && !file.EndsWith(".cshtml")) + continue; + if (Forbidden().IsMatch(File.ReadAllText(file))) + offenders.Add(relative); + } + + Assert.True(offenders.Count == 0, + "These files read items without VisibleItems or VisibleMedia. Use them, or list the file in Allowed with the reason:\n" + + string.Join('\n', offenders)); + } + + [GeneratedRegex(@"ItemStatus\.Published|\bArchiveItems\b|IgnoreQueryFilters|\bdb\.MediaFiles\b")] + private static partial Regex Forbidden(); + + 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"); + } +} diff --git a/tests/Commonage.Tests/VisibilityMatrixTests.cs b/tests/Commonage.Tests/VisibilityMatrixTests.cs new file mode 100644 index 0000000..c4c2e82 --- /dev/null +++ b/tests/Commonage.Tests/VisibilityMatrixTests.cs @@ -0,0 +1,111 @@ +using System.Net; +using System.Text; +using Commonage.Web.Data; +using Commonage.Web.Domain; + +namespace Commonage.Tests; + +/// +/// What the public may see, address by address. Every item has a word of its own in its title, description, tag, credit, +/// caption and the text of its PDF, so a page that shows any part of a hidden item is caught, and not only its title. +/// A new public address that is about items goes into . +/// +[Collection(nameof(AppCollection))] +public class VisibilityMatrixTests(CommonageAppFactory app) +{ + private sealed record Marked(string Word, int ItemId, int CollectionId, int FileId); + + private static readonly string[] Addresses = + [ + "/", "/search?q={0}", "/search", "/collections", "/places", "/people", "/help", "/feed.xml", "/sitemap.xml", + ]; + + private async Task SeedAsync(string kind, Action state) + { + var word = TestData.UniqueWord(kind); + return await app.WithDbAsync(async db => + { + var now = DateTime.UtcNow; + var collection = new Collection { Title = $"Box {word}", CreatedAt = now }; + var item = new ArchiveItem + { + Title = $"Title {word}", Description = $"Words {word}", Collection = collection, CreatedAt = now, UpdatedAt = now, + Credit = $"Credit {word}", + }; + item.SetTags([new Tag { Name = $"P {word}", NormalizedName = $"p {word}", Kind = TagKind.Place }]); + var file = new MediaFile + { + ArchiveItem = item, OriginalFileName = "a.jpg", ContentType = "image/jpeg", Sha256 = new string('a', 64), + StorageId = Guid.NewGuid(), Status = ProcessingStatus.Ready, AltText = $"Alt {word}", Caption = $"Caption {word}", + ExtractedText = $"Pages {word}", + }; + item.MediaFiles.Add(file); + state(item, now); + db.AddRange(collection, item); + await db.SaveChangesAsync(); + return new Marked(word, item.Id, collection.Id, file.Id); + }); + } + + [Fact] + public async Task Only_published_items_show_up_anywhere_a_visitor_can_look() + { + var shown = await SeedAsync("shown", (i, now) => i.Publish(now)); + var draft = await SeedAsync("draft", (_, _) => { }); + var binned = await SeedAsync("binned", (i, now) => { i.Publish(now); i.MoveToBin(now); }); + using var visitor = app.CreateClient(); + + var everything = new StringBuilder(); + foreach (var marked in new[] { shown, draft, binned }) + { + foreach (var address in Addresses) + everything.Append(await TextAsync(visitor, string.Format(address, marked.Word))); + everything.Append(await TextAsync(visitor, $"/items/{marked.ItemId}")); + everything.Append(await TextAsync(visitor, $"/collections/{marked.CollectionId}")); + } + var text = everything.ToString(); + + Assert.Contains($"Title {shown.Word}", text); + foreach (var hidden in new[] { draft, binned }) + foreach (var part in new[] { "Title ", "Words ", "Credit ", "Alt ", "Caption ", "Pages ", "Box ", "P " }) + Assert.DoesNotContain(part + hidden.Word, text); + } + + [Fact] + public async Task A_collection_of_hidden_items_has_no_page_card_or_sitemap_entry() + { + var draft = await SeedAsync("onlydraft", (_, _) => { }); + using var visitor = app.CreateClient(); + + Assert.Equal(HttpStatusCode.NotFound, (await visitor.GetAsync($"/collections/{draft.CollectionId}")).StatusCode); + Assert.DoesNotContain($"/collections/{draft.CollectionId}\"", await TextAsync(visitor, "/collections")); + Assert.DoesNotContain($"/collections/{draft.CollectionId}<", await TextAsync(visitor, "/sitemap.xml")); + } + + [Fact] + public async Task The_pictures_of_hidden_items_are_not_served_to_visitors() + { + var draft = await SeedAsync("picturedraft", (_, _) => { }); + var binned = await SeedAsync("picturebinned", (i, now) => { i.Publish(now); i.MoveToBin(now); }); + using var visitor = app.CreateClient(); + + foreach (var hidden in new[] { draft, binned }) + foreach (var variant in new[] { "preview", "thumbnail", "card", "large" }) + Assert.Equal(HttpStatusCode.NotFound, (await visitor.GetAsync($"/media/{hidden.FileId}/{variant}")).StatusCode); + } + + [Fact] + public async Task A_visitor_cannot_open_the_note_form_of_a_hidden_item() + { + var draft = await SeedAsync("notedraft", (_, _) => { }); + using var visitor = app.CreateClient(); + + Assert.Equal(HttpStatusCode.NotFound, (await visitor.GetAsync($"/items/{draft.ItemId}/tell")).StatusCode); + } + + private static async Task TextAsync(HttpClient client, string address) + { + var response = await client.GetAsync(address); + return response.IsSuccessStatusCode ? await response.Content.ReadAsStringAsync() : ""; + } +} From 6daed2a604e7a063b1fe24bcdcbbe6d59b4453b8 Mon Sep 17 00:00:00 2001 From: "Seb H." <138793908+SebHenn@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:15:55 +0100 Subject: [PATCH 2/2] M27, second part: items shown as a record only An item can be public without its media: no picture, page image, recording, caption or PDF-text match for visitors. Curators choose it on the item, it is recorded in the activity log, and an export of published items leaves the files of such items out (export format version 7). Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Seb H. <138793908+SebHenn@users.noreply.github.com> --- CHANGELOG.md | 4 + docs/operations.md | 2 +- docs/security.md | 2 +- src/Commonage.Web/Audit/AuditText.cs | 3 +- .../20261119170557_ItemMediaLevel.Designer.cs | 1111 +++++++++++++++++ .../20261119170557_ItemMediaLevel.cs | 29 + .../CommonageDbContextModelSnapshot.cs | 3 + src/Commonage.Web/Data/Visibility.cs | 9 +- src/Commonage.Web/Domain/ArchiveItem.cs | 3 + src/Commonage.Web/Domain/AuditEntry.cs | 1 + src/Commonage.Web/Domain/MediaLevel.cs | 14 + src/Commonage.Web/Export/ArchiveExporter.cs | 8 +- src/Commonage.Web/Pages/Admin/Index.cshtml | 2 +- src/Commonage.Web/Pages/Admin/Index.cshtml.cs | 3 +- .../Pages/Admin/Items/Edit.cshtml | 20 + .../Pages/Admin/Items/Edit.cshtml.cs | 10 + .../Pages/Admin/Items/Preview.cshtml | 13 +- src/Commonage.Web/Pages/Items/Details.cshtml | 1 + .../Pages/Items/Details.cshtml.cs | 2 +- .../Pages/Shared/_ItemArticle.cshtml | 4 + .../Resources/SharedResource.de.resx | 8 + .../Resources/SharedResource.resx | 8 + src/Commonage.Web/Search/AdminItemList.cs | 4 +- src/Commonage.Web/Search/ItemSearch.cs | 13 +- src/Commonage.Web/Search/ItemSummary.cs | 7 +- src/Commonage.Web/Search/PublicFeeds.cs | 2 +- tests/Commonage.Tests/ExportTests.cs | 4 +- tests/Commonage.Tests/MediaLevelTests.cs | 114 ++ .../Commonage.Tests/VisibilityMatrixTests.cs | 26 + 29 files changed, 1408 insertions(+), 22 deletions(-) create mode 100644 src/Commonage.Web/Data/Migrations/20261119170557_ItemMediaLevel.Designer.cs create mode 100644 src/Commonage.Web/Data/Migrations/20261119170557_ItemMediaLevel.cs create mode 100644 src/Commonage.Web/Domain/MediaLevel.cs create mode 100644 tests/Commonage.Tests/MediaLevelTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index d45c9ff..c7ae300 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,10 @@ version may change things that need attention when updating, and these notes say ### For curators +- An item can be shown as a **record only**: visitors get its title, description, date, place and credit, but no picture, page + image or recording, and search does not find what its PDFs or captions say. Choose "What visitors get" on the item's page; + the item list shows a "Record only" badge. Exports of published items leave out the files of such items; the full export + keeps them (export format version 7). - The page of an item shows its **earlier texts**: when the title, description, date, credit, original location or reference number was changed, by whom, and what it said before, shown beside what the field says now. A curator can put an earlier text back with one button; the text it replaces is kept in turn. Texts from before this version have no history, and the history is not part of the export. diff --git a/docs/operations.md b/docs/operations.md index b299d40..36e7d5d 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -254,7 +254,7 @@ none of them most, and null if never chosen), and `otherContentLanguages`, separ `rejectedKeptMonths` are how long records are kept (null for always), and each item's `rejectedOrWithdrawnAt` is when that time started for it. -`archive.json` has `"format": "commonage-export"` and `"version": 6`. Version 6 added `pageCount` to each file (for a PDF, how many pages have a preview; the page pictures and the text read from a PDF for search are left out, because they can be made again from the file). Version 5 added `helpWanted` to each item, also in an export of published items, because the page "Can you help?" shows it. Version 4 added `tags`, each with its `name` and `kind` +`archive.json` has `"format": "commonage-export"` and `"version": 7`. Version 7 added `mediaLevel` to each item (`Everything` or `RecordOnly`). In an export of published items, the files of a record-only item are left out, because visitors never get them. Version 6 added `pageCount` to each file (for a PDF, how many pages have a preview; the page pictures and the text read from a PDF for search are left out, because they can be made again from the file). Version 5 added `helpWanted` to each item, also in an export of published items, because the page "Can you help?" shows it. Version 4 added `tags`, each with its `name` and `kind` (`Topic`, `Place` or `Person`); items still list their tags by name. Each collection also has its `position` among the others, the `sort` of its items (`RecentlyAdded`, `OldestFirst` or `NewestFirst`) and `coverFileId`, the `id` of the file chosen as its cover, or null when none is chosen or that file is not in the export. Items also have `notes`, the messages visitors sent through diff --git a/docs/security.md b/docs/security.md index e478dc0..fa51bb6 100644 --- a/docs/security.md +++ b/docs/security.md @@ -21,7 +21,7 @@ vulnerability, see [SECURITY.md](../SECURITY.md). | Area | Measure | |---|---| -| Access | Public pages and public image addresses read only from published items (`VisibleItems`, `VisibleMedia`). Admin pages are protected by policy per folder; admin-only pages (accounts, export, activity log) by a second policy. Originals and previews of unpublished items are served only to curators. What a curator chooses ahead of publishing, such as a draft's photo as a collection's cover, is passed over until its item is published. Tested in `PublicationTests`, `MediaTests`, `AccountTests`, `ExportTests`, `CollectionTests`. `EndpointAccessTests` lists every address that is open without a login, so a new one cannot be open by accident. | +| Access | Public pages and public image addresses read only from published items (`VisibleItems`, `VisibleMedia`). Admin pages are protected by policy per folder; admin-only pages (accounts, export, activity log) by a second policy. Originals and previews of unpublished items are served only to curators. An item shown as a record only (`MediaLevel.RecordOnly`) gives visitors no file, thumbnail, cover, link-preview picture or PDF-text match; `VisibleMedia` and `Visibility.ItemWithMedia` are the one place that decides, and `ItemFilter.SearchAllFileText` is off unless a curator searches. What a curator chooses ahead of publishing, such as a draft's photo as a collection's cover, is passed over until its item is published. Tested in `PublicationTests`, `MediaTests`, `AccountTests`, `ExportTests`, `CollectionTests`. `EndpointAccessTests` lists every address that is open without a login, so a new one cannot be open by accident. | | Accounts | Passwords of at least 12 characters (length over forced symbols, NIST SP 800-63B). Five wrong passwords lock an account for five minutes, and one address can try 100 logins an hour. Accounts are created with one-time setup links, valid seven days. Disabling an account, or a password change, ends its logins within a minute. Admins cannot lock themselves out. An authenticator app (TOTP) can be added to each login, and admins can require it of everyone who manages the archive; wrong codes count towards the lockout like wrong passwords. Ten recovery codes, each usable once. Turning the app off or making new codes asks for the password again, and wrong passwords there and on "Change password" count towards the lockout too. Tested in `TwoFactorTests`. | | Forms | Every form carries an antiforgery token. Redirects after login and language change only go to addresses on this site. | | 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`. | diff --git a/src/Commonage.Web/Audit/AuditText.cs b/src/Commonage.Web/Audit/AuditText.cs index 99d418c..405ff91 100644 --- a/src/Commonage.Web/Audit/AuditText.cs +++ b/src/Commonage.Web/Audit/AuditText.cs @@ -24,6 +24,7 @@ public static class AuditText AuditAction.ItemChanged => localizer["Changed the item"], AuditAction.ItemPublished => localizer["Published the item"], AuditAction.ItemUnpublished => localizer["Unpublished the item"], + AuditAction.ItemMediaLevelChanged => localizer["Changed what visitors get of the item"], AuditAction.ItemFieldRestored => localizer["Restored an earlier text of the item"], AuditAction.ItemDeleted => localizer["Deleted the item for good"], AuditAction.ItemMovedToBin => localizer["Moved the item to the bin"], @@ -82,7 +83,7 @@ public static class AuditText public static AuditKind KindOf(AuditAction action) => action switch { - AuditAction.ItemCreated or AuditAction.ItemChanged or AuditAction.ItemFieldRestored or AuditAction.ItemPublished or AuditAction.ItemUnpublished + AuditAction.ItemCreated or AuditAction.ItemChanged or AuditAction.ItemFieldRestored or AuditAction.ItemPublished or AuditAction.ItemUnpublished or AuditAction.ItemMediaLevelChanged or AuditAction.ItemDeleted or AuditAction.ItemMovedToBin or AuditAction.ItemRestored or AuditAction.ItemPurged or AuditAction.ItemMovedToBinAfterKeptTime or AuditAction.ItemsImported => AuditKind.Items, AuditAction.PhotosAdded or AuditAction.PhotosArranged or AuditAction.PhotoDeleted or AuditAction.PhotoMovedToBin diff --git a/src/Commonage.Web/Data/Migrations/20261119170557_ItemMediaLevel.Designer.cs b/src/Commonage.Web/Data/Migrations/20261119170557_ItemMediaLevel.Designer.cs new file mode 100644 index 0000000..c52d29d --- /dev/null +++ b/src/Commonage.Web/Data/Migrations/20261119170557_ItemMediaLevel.Designer.cs @@ -0,0 +1,1111 @@ +// +using System; +using Commonage.Web.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; +using NpgsqlTypes; + +#nullable disable + +namespace Commonage.Web.Data.Migrations +{ + [DbContext(typeof(CommonageDbContext))] + [Migration("20261119170557_ItemMediaLevel")] + partial class ItemMediaLevel + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.14") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("ArchiveItemTag", b => + { + b.Property("ItemsId") + .HasColumnType("integer"); + + b.Property("TagsId") + .HasColumnType("integer"); + + b.HasKey("ItemsId", "TagsId"); + + b.HasIndex("TagsId"); + + b.ToTable("ArchiveItemTag"); + }); + + modelBuilder.Entity("Commonage.Web.Domain.ArchiveItem", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CollectionId") + .HasColumnType("integer"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Credit") + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("DateFrom") + .HasColumnType("date"); + + b.Property("DateText") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("DateTo") + .HasColumnType("date"); + + b.Property("DeletedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasMaxLength(20000) + .HasColumnType("character varying(20000)"); + + b.Property("HelpWanted") + .HasColumnType("boolean"); + + b.Property("InternalNotes") + .HasMaxLength(20000) + .HasColumnType("character varying(20000)"); + + b.Property("MediaLevel") + .HasColumnType("integer"); + + b.Property("NeedsTranscription") + .HasColumnType("boolean"); + + b.Property("OriginalLocation") + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("PublishedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("ReceivedFrom") + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("ReceivedOn") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("ReferenceNumber") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("RejectedOrWithdrawnAt") + .HasColumnType("timestamp with time zone"); + + b.Property("RightsHolder") + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("RightsUri") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("SearchVector") + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("tsvector") + .HasComputedColumnSql("setweight(to_tsvector('simple', commonage_fold(coalesce(\"Title\", ''))), 'A') || setweight(to_tsvector('simple', commonage_fold(coalesce(\"TagNames\", '') || ' ' || coalesce(\"DateText\", ''))), 'B') || setweight(to_tsvector('simple', commonage_fold(coalesce(\"Description\", ''))), 'C')", true); + + b.Property("Status") + .HasColumnType("integer"); + + b.Property("TagNames") + .HasColumnType("text"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Version") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("xid") + .HasColumnName("xmin"); + + b.HasKey("Id"); + + b.HasIndex("CollectionId"); + + b.HasIndex("DateFrom"); + + b.HasIndex("DateTo"); + + b.HasIndex("ReferenceNumber") + .IsUnique(); + + b.HasIndex("SearchVector"); + + NpgsqlIndexBuilderExtensions.HasMethod(b.HasIndex("SearchVector"), "GIN"); + + b.HasIndex("Status"); + + b.ToTable("ArchiveItems"); + }); + + modelBuilder.Entity("Commonage.Web.Domain.ArchiveSettings", b => + { + b.Property("Id") + .HasColumnType("integer"); + + b.Property("AccentColor") + .HasMaxLength(7) + .HasColumnType("character varying(7)"); + + b.Property("AcceptVisitorNotes") + .HasColumnType("boolean"); + + b.Property("ActivityLogKeptYears") + .HasColumnType("integer"); + + b.Property("AllowSearchEngines") + .HasColumnType("boolean"); + + b.Property("ContentLanguage") + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("DefaultLanguage") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("DefaultRightsUri") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("ImprintNotNeeded") + .HasColumnType("boolean"); + + b.Property("LargePhotos") + .HasColumnType("boolean"); + + b.Property("LogoId") + .HasColumnType("uuid"); + + b.Property("OtherContentLanguages") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("PrivacyReviewed") + .HasColumnType("boolean"); + + b.Property("RejectedKeptMonths") + .HasColumnType("integer"); + + b.Property("RequireTwoFactor") + .HasColumnType("boolean"); + + b.Property("RestoreTestedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("TimeZone") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.HasKey("Id"); + + b.ToTable("ArchiveSettings"); + }); + + modelBuilder.Entity("Commonage.Web.Domain.ArchiveText", b => + { + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("Kind") + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.Property("Text") + .IsRequired() + .HasMaxLength(20000) + .HasColumnType("character varying(20000)"); + + b.HasKey("Language", "Kind"); + + b.ToTable("ArchiveTexts"); + }); + + modelBuilder.Entity("Commonage.Web.Domain.AuditEntry", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("ArchiveItemId") + .HasColumnType("integer"); + + b.Property("At") + .HasColumnType("timestamp with time zone"); + + b.Property("Subject") + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("UserId") + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("ArchiveItemId"); + + b.HasIndex("At"); + + b.ToTable("AuditEntries"); + }); + + modelBuilder.Entity("Commonage.Web.Domain.Collection", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CoverMediaFileId") + .HasColumnType("integer"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Position") + .HasColumnType("integer"); + + b.Property("Sort") + .HasColumnType("integer"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.HasKey("Id"); + + b.HasIndex("CoverMediaFileId"); + + b.HasIndex("Position"); + + b.ToTable("Collections"); + }); + + modelBuilder.Entity("Commonage.Web.Domain.Contribution", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ArchiveItemId") + .HasColumnType("integer"); + + b.Property("ConsentCoversSharing") + .HasColumnType("boolean"); + + b.Property("ConsentText") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("ContributionLinkId") + .HasColumnType("integer"); + + b.Property("ContributorEmail") + .HasMaxLength(254) + .HasColumnType("character varying(254)"); + + b.Property("ContributorName") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("PersonalDetailsRemovedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("ReferenceCode") + .HasMaxLength(9) + .HasColumnType("character varying(9)"); + + b.Property("Reuse") + .HasColumnType("integer"); + + b.Property("ReviewedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Rights") + .HasColumnType("integer"); + + b.Property("RightsHolder") + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("SendingFingerprint") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("ShowName") + .HasColumnType("boolean"); + + b.Property("SubmittedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("ArchiveItemId") + .IsUnique(); + + b.HasIndex("ContributionLinkId"); + + b.HasIndex("ReferenceCode") + .IsUnique(); + + b.HasIndex("SendingFingerprint") + .IsUnique(); + + b.ToTable("Contributions"); + }); + + modelBuilder.Entity("Commonage.Web.Domain.ContributionLink", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CollectionId") + .HasColumnType("integer"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Introduction") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("InviteOnCollectionPage") + .HasColumnType("boolean"); + + b.Property("IsActive") + .HasColumnType("boolean"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Token") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.HasKey("Id"); + + b.HasIndex("CollectionId"); + + b.HasIndex("Token") + .IsUnique(); + + b.ToTable("ContributionLinks"); + }); + + modelBuilder.Entity("Commonage.Web.Domain.ItemFileText", b => + { + b.Property("ArchiveItemId") + .HasColumnType("integer"); + + b.Property("SearchVector") + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("tsvector") + .HasComputedColumnSql("setweight(to_tsvector('simple', commonage_fold(coalesce(\"Text\", ''))), 'D')", true); + + b.Property("Text") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("ArchiveItemId"); + + b.HasIndex("SearchVector"); + + NpgsqlIndexBuilderExtensions.HasMethod(b.HasIndex("SearchVector"), "GIN"); + + b.ToTable("ItemFileTexts"); + }); + + modelBuilder.Entity("Commonage.Web.Domain.ItemRevision", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ArchiveItemId") + .HasColumnType("integer"); + + b.Property("At") + .HasColumnType("timestamp with time zone"); + + b.Property("Field") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.Property("OldValue") + .HasColumnType("text"); + + b.Property("UserId") + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("ArchiveItemId", "At"); + + b.ToTable("ItemRevisions"); + }); + + modelBuilder.Entity("Commonage.Web.Domain.MediaFile", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AltText") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("ArchiveItemId") + .HasColumnType("integer"); + + b.Property("Caption") + .HasColumnType("text"); + + b.Property("ContentType") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("DeletedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DerivativeVersion") + .HasColumnType("integer"); + + b.Property("ExtractedText") + .HasColumnType("text"); + + b.Property("HasLarge") + .HasColumnType("boolean"); + + b.Property("OriginalFileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("PageCount") + .HasColumnType("integer"); + + b.Property("Position") + .HasColumnType("integer"); + + b.Property("PreviewHeight") + .HasColumnType("integer"); + + b.Property("PreviewWidth") + .HasColumnType("integer"); + + b.Property("ProcessingAttempts") + .HasColumnType("integer"); + + b.Property("ProcessingError") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("RenderedRotation") + .HasColumnType("integer"); + + b.Property("Rotation") + .HasColumnType("integer"); + + b.Property("Sha256") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character(64)") + .IsFixedLength(); + + b.Property("SizeBytes") + .HasColumnType("bigint"); + + b.Property("Status") + .HasColumnType("integer"); + + b.Property("StorageId") + .HasColumnType("uuid"); + + b.Property("UploadedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("ArchiveItemId"); + + b.HasIndex("Sha256"); + + b.HasIndex("Status"); + + b.HasIndex("StorageId") + .IsUnique(); + + b.ToTable("MediaFiles"); + }); + + modelBuilder.Entity("Commonage.Web.Domain.StaffProfile", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("DisplayName") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("LastLoginAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("UserId"); + + b.ToTable("StaffProfiles"); + }); + + modelBuilder.Entity("Commonage.Web.Domain.Tag", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Kind") + .HasColumnType("integer"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("NormalizedName") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique(); + + b.ToTable("Tags"); + }); + + modelBuilder.Entity("Commonage.Web.Domain.VisitorNote", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ArchiveItemId") + .HasColumnType("integer"); + + b.Property("Email") + .HasMaxLength(254) + .HasColumnType("character varying(254)"); + + b.Property("HandledAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Kind") + .HasColumnType("integer"); + + b.Property("Message") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Name") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("PersonalDetailsRemovedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("ReceivedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("ArchiveItemId"); + + b.HasIndex("HandledAt"); + + b.ToTable("VisitorNotes"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.DataProtection.EntityFrameworkCore.DataProtectionKey", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("FriendlyName") + .HasColumnType("text"); + + b.Property("Xml") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("DataProtectionKeys"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("text"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUser", b => + { + b.Property("Id") + .HasColumnType("text"); + + b.Property("AccessFailedCount") + .HasColumnType("integer"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("boolean"); + + b.Property("LockoutEnabled") + .HasColumnType("boolean"); + + b.Property("LockoutEnd") + .HasColumnType("timestamp with time zone"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("PhoneNumber") + .HasColumnType("text"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("boolean"); + + b.Property("SecurityStamp") + .HasColumnType("text"); + + b.Property("TwoFactorEnabled") + .HasColumnType("boolean"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("ProviderKey") + .HasColumnType("text"); + + b.Property("ProviderDisplayName") + .HasColumnType("text"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("RoleId") + .HasColumnType("text"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("ArchiveItemTag", b => + { + b.HasOne("Commonage.Web.Domain.ArchiveItem", null) + .WithMany() + .HasForeignKey("ItemsId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Commonage.Web.Domain.Tag", null) + .WithMany() + .HasForeignKey("TagsId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Commonage.Web.Domain.ArchiveItem", b => + { + b.HasOne("Commonage.Web.Domain.Collection", "Collection") + .WithMany("Items") + .HasForeignKey("CollectionId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Collection"); + }); + + modelBuilder.Entity("Commonage.Web.Domain.AuditEntry", b => + { + b.HasOne("Commonage.Web.Domain.ArchiveItem", "ArchiveItem") + .WithMany() + .HasForeignKey("ArchiveItemId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("ArchiveItem"); + }); + + modelBuilder.Entity("Commonage.Web.Domain.Collection", b => + { + b.HasOne("Commonage.Web.Domain.MediaFile", null) + .WithMany() + .HasForeignKey("CoverMediaFileId") + .OnDelete(DeleteBehavior.SetNull); + }); + + modelBuilder.Entity("Commonage.Web.Domain.Contribution", b => + { + b.HasOne("Commonage.Web.Domain.ArchiveItem", "ArchiveItem") + .WithOne("Contribution") + .HasForeignKey("Commonage.Web.Domain.Contribution", "ArchiveItemId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Commonage.Web.Domain.ContributionLink", "ContributionLink") + .WithMany("Contributions") + .HasForeignKey("ContributionLinkId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("ArchiveItem"); + + b.Navigation("ContributionLink"); + }); + + modelBuilder.Entity("Commonage.Web.Domain.ContributionLink", b => + { + b.HasOne("Commonage.Web.Domain.Collection", "Collection") + .WithMany() + .HasForeignKey("CollectionId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Collection"); + }); + + modelBuilder.Entity("Commonage.Web.Domain.ItemFileText", b => + { + b.HasOne("Commonage.Web.Domain.ArchiveItem", "ArchiveItem") + .WithOne("FileText") + .HasForeignKey("Commonage.Web.Domain.ItemFileText", "ArchiveItemId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ArchiveItem"); + }); + + modelBuilder.Entity("Commonage.Web.Domain.ItemRevision", b => + { + b.HasOne("Commonage.Web.Domain.ArchiveItem", "ArchiveItem") + .WithMany() + .HasForeignKey("ArchiveItemId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ArchiveItem"); + }); + + modelBuilder.Entity("Commonage.Web.Domain.MediaFile", b => + { + b.HasOne("Commonage.Web.Domain.ArchiveItem", "ArchiveItem") + .WithMany("MediaFiles") + .HasForeignKey("ArchiveItemId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ArchiveItem"); + }); + + modelBuilder.Entity("Commonage.Web.Domain.StaffProfile", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) + .WithOne() + .HasForeignKey("Commonage.Web.Domain.StaffProfile", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Commonage.Web.Domain.VisitorNote", b => + { + b.HasOne("Commonage.Web.Domain.ArchiveItem", "ArchiveItem") + .WithMany() + .HasForeignKey("ArchiveItemId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ArchiveItem"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Commonage.Web.Domain.ArchiveItem", b => + { + b.Navigation("Contribution"); + + b.Navigation("FileText"); + + b.Navigation("MediaFiles"); + }); + + modelBuilder.Entity("Commonage.Web.Domain.Collection", b => + { + b.Navigation("Items"); + }); + + modelBuilder.Entity("Commonage.Web.Domain.ContributionLink", b => + { + b.Navigation("Contributions"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Commonage.Web/Data/Migrations/20261119170557_ItemMediaLevel.cs b/src/Commonage.Web/Data/Migrations/20261119170557_ItemMediaLevel.cs new file mode 100644 index 0000000..2d3ffc0 --- /dev/null +++ b/src/Commonage.Web/Data/Migrations/20261119170557_ItemMediaLevel.cs @@ -0,0 +1,29 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Commonage.Web.Data.Migrations +{ + /// + public partial class ItemMediaLevel : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "MediaLevel", + table: "ArchiveItems", + type: "integer", + nullable: false, + defaultValue: 0); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "MediaLevel", + table: "ArchiveItems"); + } + } +} diff --git a/src/Commonage.Web/Data/Migrations/CommonageDbContextModelSnapshot.cs b/src/Commonage.Web/Data/Migrations/CommonageDbContextModelSnapshot.cs index fcfe477..9196bf0 100644 --- a/src/Commonage.Web/Data/Migrations/CommonageDbContextModelSnapshot.cs +++ b/src/Commonage.Web/Data/Migrations/CommonageDbContextModelSnapshot.cs @@ -80,6 +80,9 @@ protected override void BuildModel(ModelBuilder modelBuilder) .HasMaxLength(20000) .HasColumnType("character varying(20000)"); + b.Property("MediaLevel") + .HasColumnType("integer"); + b.Property("NeedsTranscription") .HasColumnType("boolean"); diff --git a/src/Commonage.Web/Data/Visibility.cs b/src/Commonage.Web/Data/Visibility.cs index df9f581..0ec0e74 100644 --- a/src/Commonage.Web/Data/Visibility.cs +++ b/src/Commonage.Web/Data/Visibility.cs @@ -13,6 +13,11 @@ public static class Visibility /// An item visitors may see: published and, by the query filter, not in the bin. public static readonly Expression> Item = i => i.Status == ItemStatus.Published; - /// A file visitors may be given: it belongs to a visible item. - public static readonly Expression> Media = f => f.ArchiveItem.Status == ItemStatus.Published; + /// A visible item whose media visitors may also have. Covers and first photos come from these only. + public static readonly Expression> ItemWithMedia = + i => i.Status == ItemStatus.Published && i.MediaLevel == MediaLevel.Everything; + + /// A file visitors may be given: it belongs to a visible item that shows its media. + public static readonly Expression> Media = + f => f.ArchiveItem.Status == ItemStatus.Published && f.ArchiveItem.MediaLevel == MediaLevel.Everything; } diff --git a/src/Commonage.Web/Domain/ArchiveItem.cs b/src/Commonage.Web/Domain/ArchiveItem.cs index 8192ed5..bb30b1e 100644 --- a/src/Commonage.Web/Domain/ArchiveItem.cs +++ b/src/Commonage.Web/Domain/ArchiveItem.cs @@ -14,6 +14,9 @@ public class ArchiveItem public string? Description { get; set; } public ItemStatus Status { get; set; } + /// What visitors get of the item once it is published, see . + public MediaLevel MediaLevel { get; set; } + public int CollectionId { get; set; } public Collection Collection { get; set; } = null!; diff --git a/src/Commonage.Web/Domain/AuditEntry.cs b/src/Commonage.Web/Domain/AuditEntry.cs index 4543802..89f6488 100644 --- a/src/Commonage.Web/Domain/AuditEntry.cs +++ b/src/Commonage.Web/Domain/AuditEntry.cs @@ -7,6 +7,7 @@ public enum AuditAction ItemChanged, ItemPublished, ItemUnpublished, + ItemMediaLevelChanged, ItemDeleted, PhotosAdded, PhotoDeleted, diff --git a/src/Commonage.Web/Domain/MediaLevel.cs b/src/Commonage.Web/Domain/MediaLevel.cs new file mode 100644 index 0000000..10be754 --- /dev/null +++ b/src/Commonage.Web/Domain/MediaLevel.cs @@ -0,0 +1,14 @@ +namespace Commonage.Web.Domain; + +/// What visitors get of a published item. Stored as a number, so new levels go at the end. +public enum MediaLevel +{ + /// The record and everything attached to it: photos, pages, recordings. + Everything = 0, + + /// + /// Only the record: title, description, date, place and credit. No picture, page image or recording anywhere, and nothing + /// said about what is in them (captions, alt text, the text of PDFs). The description stays, also a recording's transcript. + /// + RecordOnly = 1, +} diff --git a/src/Commonage.Web/Export/ArchiveExporter.cs b/src/Commonage.Web/Export/ArchiveExporter.cs index 0085503..1c4ad3a 100644 --- a/src/Commonage.Web/Export/ArchiveExporter.cs +++ b/src/Commonage.Web/Export/ArchiveExporter.cs @@ -29,7 +29,7 @@ public class ArchiveExporter( ILogger logger) { public const string Format = "commonage-export"; - public const int Version = 6; + public const int Version = 7; private static readonly JsonSerializerOptions JsonOptions = new() { @@ -69,6 +69,8 @@ public async Task WriteAsync(Stream output, ExportOptions options, CancellationT { var files = await db.MediaFiles.AsNoTracking() .Where(f => batch.Contains(f.ArchiveItemId)) + // A copy of what is public holds no file of an item shown as a record only. + .Where(f => !options.PublishedOnly || f.ArchiveItem.MediaLevel == MediaLevel.Everything) .OrderBy(f => f.ArchiveItemId).ThenBy(f => f.Position).ThenBy(f => f.Id) .ToListAsync(cancellationToken); foreach (var file in files) @@ -188,7 +190,7 @@ private async IAsyncEnumerable DescribeItemsAsync( : (await db.VisitorNotes.AsNoTracking().Where(n => ids.Contains(n.ArchiveItemId)).OrderBy(n => n.Id).ToListAsync(cancellationToken)).ToLookup(n => n.ArchiveItemId); foreach (var item in items) { - var files = item.MediaFiles.OrderBy(f => f.Position).ThenBy(f => f.Id).Select(file => + var files = (options.PublishedOnly && item.MediaLevel == MediaLevel.RecordOnly ? [] : item.MediaFiles).OrderBy(f => f.Position).ThenBy(f => f.Id).Select(file => { var problem = problems.GetValueOrDefault(file.Id); return Describe(file, problem == "missing" ? null : PathOf(item.Id, file), problem); @@ -268,6 +270,7 @@ private static ExportFile Describe(MediaFile file, string? path, string? problem options.PublishedOnly || !options.IncludePersonalData ? null : item.InternalNotes, options.PublishedOnly ? null : item.NeedsTranscription, item.HelpWanted, + item.MediaLevel, item.Contribution is not { } contribution ? null : new ExportContribution( options.IncludePersonalData ? contribution.ContributorName : null, options.IncludePersonalData ? contribution.ContributorEmail : null, @@ -420,6 +423,7 @@ internal record ExportItem( string? InternalNotes, bool? NeedsTranscription, bool HelpWanted, + MediaLevel MediaLevel, ExportContribution? Contribution, IReadOnlyList? Notes, IReadOnlyList Files); diff --git a/src/Commonage.Web/Pages/Admin/Index.cshtml b/src/Commonage.Web/Pages/Admin/Index.cshtml index 9526e1e..5c3ed0f 100644 --- a/src/Commonage.Web/Pages/Admin/Index.cshtml +++ b/src/Commonage.Web/Pages/Admin/Index.cshtml @@ -219,7 +219,7 @@ else } @item.CollectionTitle - + @if (item.RecordOnly) { @T["Record only"] } @Dates.Moment(item.UpdatedAt) } diff --git a/src/Commonage.Web/Pages/Admin/Index.cshtml.cs b/src/Commonage.Web/Pages/Admin/Index.cshtml.cs index 8d50d98..fc42694 100644 --- a/src/Commonage.Web/Pages/Admin/Index.cshtml.cs +++ b/src/Commonage.Web/Pages/Admin/Index.cshtml.cs @@ -116,7 +116,8 @@ public async Task OnGetAsync(CancellationToken cancellationToken) i.MediaFiles.Count, i.Title == "" ? i.MediaFiles.OrderBy(f => f.Id).Select(f => f.OriginalFileName).FirstOrDefault() : null, // Worth a look before a decision on a contribution. Contributors are never told. - i.Status == ItemStatus.Submitted && i.MediaFiles.Any(f => db.MediaFiles.Any(other => other.Sha256 == f.Sha256 && other.ArchiveItemId != i.Id)))) + i.Status == ItemStatus.Submitted && i.MediaFiles.Any(f => db.MediaFiles.Any(other => other.Sha256 == f.Sha256 && other.ArchiveItemId != i.Id)), + i.MediaLevel == MediaLevel.RecordOnly)) .ToPagedListAsync(PageNumber, PageSize, cancellationToken); } } diff --git a/src/Commonage.Web/Pages/Admin/Items/Edit.cshtml b/src/Commonage.Web/Pages/Admin/Items/Edit.cshtml index e573efe..4dd332a 100644 --- a/src/Commonage.Web/Pages/Admin/Items/Edit.cshtml +++ b/src/Commonage.Web/Pages/Admin/Items/Edit.cshtml @@ -17,6 +17,10 @@ @if (Model.CurrentStatus is { } status) { + @if (Model.Input.MediaLevel == MediaLevel.RecordOnly) + { + @T["Record only"] + } } @if (Model.CurrentStatus == ItemStatus.Published) { @@ -257,6 +261,22 @@ + @if (mayManage) + { +
+ @T["What visitors get"] +
+ + +
+
+ + +
+
@T["Applies once the item is published. A recording's transcript in the description stays visible."]
+
+ } +
diff --git a/src/Commonage.Web/Pages/Admin/Items/Edit.cshtml.cs b/src/Commonage.Web/Pages/Admin/Items/Edit.cshtml.cs index 6e3bd32..a0226a2 100644 --- a/src/Commonage.Web/Pages/Admin/Items/Edit.cshtml.cs +++ b/src/Commonage.Web/Pages/Admin/Items/Edit.cshtml.cs @@ -174,6 +174,9 @@ public class InputModel [Display(Name = "Ask visitors for help with this item")] public bool HelpWanted { get; set; } + [Display(Name = "What visitors get")] + public MediaLevel MediaLevel { get; set; } + /// The item's version when the form was opened, to notice changes made by someone else since. public uint? Version { get; set; } } @@ -210,6 +213,7 @@ public async Task OnGetAsync(int? id, int? collectionId) InternalNotes = item.InternalNotes, NeedsTranscription = item.NeedsTranscription, HelpWanted = item.HelpWanted, + MediaLevel = item.MediaLevel, }; RightsWereProposed = item.RightsUri is null && item.Contribution is not null; await ShowStateAsync(item); @@ -343,6 +347,10 @@ public async Task OnPostAsync(int? id, string? command, string? t item.InternalNotes = Clean(Input.InternalNotes); item.NeedsTranscription = Input.NeedsTranscription; item.HelpWanted = Input.HelpWanted; + // Helpers do not decide what the public gets, as they do not publish. + var mediaLevelChanged = User.MayManage() && item.MediaLevel != Input.MediaLevel; + if (mediaLevelChanged) + item.MediaLevel = Input.MediaLevel; if ((Input.AltTexts.Count > 0 || Input.Captions.Count > 0) && id is not null) { foreach (var file in await db.MediaFiles.Where(f => f.ArchiveItemId == id).ToListAsync()) @@ -354,6 +362,8 @@ public async Task OnPostAsync(int? id, string? command, string? t } } audit.Record(isNew ? AuditAction.ItemCreated : AuditAction.ItemChanged, item.Title, item); + if (mediaLevelChanged) + audit.Record(AuditAction.ItemMediaLevelChanged, item.Title, item); switch (command) { diff --git a/src/Commonage.Web/Pages/Admin/Items/Preview.cshtml b/src/Commonage.Web/Pages/Admin/Items/Preview.cshtml index 69dc7db..0a7406c 100644 --- a/src/Commonage.Web/Pages/Admin/Items/Preview.cshtml +++ b/src/Commonage.Web/Pages/Admin/Items/Preview.cshtml @@ -7,7 +7,18 @@
- @(Model.Item.Status == ItemStatus.Published ? T["Preview. This item is public."] : T["Preview. Visitors cannot see this item."]) + @if (Model.Item.Status != ItemStatus.Published) + { + @T["Preview. Visitors cannot see this item."] + } + else if (Model.Item.MediaLevel == MediaLevel.RecordOnly) + { + @T["Preview. Visitors see the record only, without its pictures and recordings."] + } + else + { + @T["Preview. This item is public."] + } @T["Back to editing"]
diff --git a/src/Commonage.Web/Pages/Items/Details.cshtml b/src/Commonage.Web/Pages/Items/Details.cshtml index 06bebd8..bd1e9e7 100644 --- a/src/Commonage.Web/Pages/Items/Details.cshtml +++ b/src/Commonage.Web/Pages/Items/Details.cshtml @@ -6,6 +6,7 @@ ViewData["Canonical"] = Model.Address; ViewData["Citation"] = Model.Citation; ViewData["LinkPreview"] = Model.Preview; + ViewData["RecordOnly"] = Model.Item.MediaLevel == MediaLevel.RecordOnly; }
} + @if (ViewData["RecordOnly"] is true) + { +

@T["The archive shows this item as a record only. Its pictures and recordings are not shown here."]

+ }
@if (!string.IsNullOrWhiteSpace(Model.Description)) { diff --git a/src/Commonage.Web/Resources/SharedResource.de.resx b/src/Commonage.Web/Resources/SharedResource.de.resx index 26ab572..c6a0c21 100644 --- a/src/Commonage.Web/Resources/SharedResource.de.resx +++ b/src/Commonage.Web/Resources/SharedResource.de.resx @@ -1007,4 +1007,12 @@ Der frühere Text ist wieder da. Ursprünglicher Ort Dieser Text kann nicht zurückgesetzt werden: Das Feld wäre leer oder ließe sich nicht mehr lesen. + Gilt, sobald der Eintrag veröffentlicht ist. Die Abschrift einer Aufnahme in der Beschreibung bleibt sichtbar. + Geändert, was Besucher vom Eintrag bekommen + Alles: der Eintrag mit seinen Bildern und Aufnahmen + Vorschau. Besucher sehen nur den Eintrag, ohne seine Bilder und Aufnahmen. + Nur Eintrag + Das Archiv zeigt diesen Eintrag nur als Eintrag. Seine Bilder und Aufnahmen werden hier nicht gezeigt. + Nur der Eintrag, ohne Bilder und Aufnahmen + Was Besucher bekommen diff --git a/src/Commonage.Web/Resources/SharedResource.resx b/src/Commonage.Web/Resources/SharedResource.resx index c53cb7b..803c3de 100644 --- a/src/Commonage.Web/Resources/SharedResource.resx +++ b/src/Commonage.Web/Resources/SharedResource.resx @@ -74,6 +74,7 @@ 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. Anything + Applies once the item is published. A recording's transcript in the description stays visible. Apply filters Archive settings As elsewhere: 1953, 12.03.1953, circa 1950, 1950s, 1950–1955. @@ -114,6 +115,7 @@ Changed the order or direction of photos Changed the tag 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 spreadsheet Checks @@ -253,6 +255,7 @@ Everything Everything from this time Everything that is known about the collections and items, complete and exact. Dates are ISO 8601 and in UTC. Each file lists its SHA-256 checksum, so you can check that a copy is intact. + Everything: the record with its pictures and recordings Export Export the archive Export, settings and the log itself @@ -561,6 +564,7 @@ Preview Preview. This item is public. Preview. Visitors cannot see this item. + Preview. Visitors see the record only, without its pictures and recordings. Preview: {0} Previews Previews are being created. Reload the page in a moment. @@ -583,6 +587,7 @@ Received from Received when Recently added + Record only Recording of {0} Recording {0} of {1} Reference @@ -712,6 +717,7 @@ The archive did not accept this. Please reload the page and try again. Photos have to be chosen again. The archive did not accept this. Reload the page, choose the photos that are missing and try again. The archive has no collections yet. + The archive shows this item as a record only. Its pictures and recordings are not shown here. The archive's default: {0} The archive's logo, if it has one. Its name and pages are under "settings" in archive.json. The archive's storage is full @@ -788,6 +794,7 @@ 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 record only, without pictures and recordings The request could not be processed 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. @@ -920,6 +927,7 @@ 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 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. What whoever runs the server should keep an eye on. Visitors and uptime monitors that open /health learn only whether all is well, not what follows here. What would you like to tell us? diff --git a/src/Commonage.Web/Search/AdminItemList.cs b/src/Commonage.Web/Search/AdminItemList.cs index 72c366f..cb90c86 100644 --- a/src/Commonage.Web/Search/AdminItemList.cs +++ b/src/Commonage.Web/Search/AdminItemList.cs @@ -43,7 +43,7 @@ public record AdminItemFilter( /// One line of the curators' item list. public record AdminItemRow( int Id, string Title, string CollectionTitle, ItemStatus Status, DateTime UpdatedAt, int? ThumbnailMediaFileId, int PhotoCount, - string? FirstFileName = null, bool HasIdenticalFile = false); + string? FirstFileName = null, bool HasIdenticalFile = false, bool RecordOnly = false); /// The curators' item list. The edit page uses it too, to go on to the next item of the same list. public static class AdminItemList @@ -56,7 +56,7 @@ public static async Task> QueryAsync(this CommonageDbCon // A reference number is not in the search index, on purpose, so it is looked up on its own. Whoever types one wants that item. var isReference = filter.Text is { Length: > 0 } text && await db.ArchiveItems.AnyAsync(i => i.ReferenceNumber == text.Trim(), cancellationToken); var search = isReference ? TextSearch.None : await db.ToSearchAsync(filter.Text, cancellationToken); - var items = db.ArchiveItems.Filter(new ItemFilter(search.Query, filter.Tag, filter.CollectionId, Dates: search.Dates)); + var items = db.ArchiveItems.Filter(new ItemFilter(search.Query, filter.Tag, filter.CollectionId, Dates: search.Dates, SearchAllFileText: true)); if (isReference) items = items.Where(i => i.ReferenceNumber == filter.Text!.Trim()); if (filter.Status is { } status) diff --git a/src/Commonage.Web/Search/ItemSearch.cs b/src/Commonage.Web/Search/ItemSearch.cs index 70e7b35..6fa404d 100644 --- a/src/Commonage.Web/Search/ItemSearch.cs +++ b/src/Commonage.Web/Search/ItemSearch.cs @@ -18,9 +18,13 @@ public enum ItemSort /// A full-text query from , or null to match all items. /// Dates typed into the search. Each one matches what is dated within it, or has its words. +/// +/// Curators search what the PDFs of every item say. Without it, only the PDFs of items that show their media are searched: what +/// the pages of a record without its media say must not be found by a visitor. Left off by default so that a new caller is safe. +/// public record ItemFilter( string? Query = null, string? Tag = null, int? CollectionId = null, int? YearFrom = null, int? YearTo = null, - IReadOnlyList? Dates = null); + IReadOnlyList? Dates = null, bool SearchAllFileText = false); /// The full-text query for the words of the date itself, so that "1958" also finds "Team photo 1958". public record DateInSearch(SearchDate Date, string Query); @@ -42,12 +46,14 @@ public static class ItemSearch public static IQueryable Filter(this IQueryable items, ItemFilter filter) { + var searchAllFileText = filter.SearchAllFileText; if (filter.Query is { } query) { items = items.Where(i => EF.Property(i, CommonageDbContext.SearchVector) .Matches(EF.Functions.ToTsQuery(CommonageDbContext.SearchConfiguration, query)) // What the item's PDFs say. All words must be in the item's own text or all in the documents, not split between them. - || (i.FileText != null && EF.Property(i.FileText, CommonageDbContext.SearchVector) + || (i.FileText != null && (searchAllFileText || i.MediaLevel == MediaLevel.Everything) + && EF.Property(i.FileText, CommonageDbContext.SearchVector) .Matches(EF.Functions.ToTsQuery(CommonageDbContext.SearchConfiguration, query)))); } @@ -69,7 +75,8 @@ public static IQueryable Filter(this IQueryable items, && (to == null || i.DateFrom == null || i.DateFrom <= to)) || EF.Property(i, CommonageDbContext.SearchVector) .Matches(EF.Functions.ToTsQuery(CommonageDbContext.SearchConfiguration, words)) - || (i.FileText != null && EF.Property(i.FileText, CommonageDbContext.SearchVector) + || (i.FileText != null && (searchAllFileText || i.MediaLevel == MediaLevel.Everything) + && EF.Property(i.FileText, CommonageDbContext.SearchVector) .Matches(EF.Functions.ToTsQuery(CommonageDbContext.SearchConfiguration, words)))); } diff --git a/src/Commonage.Web/Search/ItemSummary.cs b/src/Commonage.Web/Search/ItemSummary.cs index e8dd7ff..6dfb675 100644 --- a/src/Commonage.Web/Search/ItemSummary.cs +++ b/src/Commonage.Web/Search/ItemSummary.cs @@ -12,7 +12,8 @@ public record ItemSummary(int Id, string Title, string? DateText, int? Thumbnail i.Id, i.Title, i.DateText, - i.MediaFiles.Where(f => f.Status == ProcessingStatus.Ready && !f.ContentType.StartsWith("audio/")).OrderBy(f => f.Position).ThenBy(f => f.Id).Select(f => (int?)f.Id).FirstOrDefault(), + // A record without its media has no picture, also not as a thumbnail. + i.MediaLevel != MediaLevel.Everything ? null : i.MediaFiles.Where(f => f.Status == ProcessingStatus.Ready && !f.ContentType.StartsWith("audio/")).OrderBy(f => f.Position).ThenBy(f => f.Id).Select(f => (int?)f.Id).FirstOrDefault(), i.Collection.Title); } @@ -39,12 +40,12 @@ public static IQueryable ToCards(this IQueryable col c.Title, c.Description, c.Items.AsQueryable().Count(Visibility.Item), - c.Items.AsQueryable().Where(Visibility.Item) + c.Items.AsQueryable().Where(Visibility.ItemWithMedia) .SelectMany(i => i.MediaFiles) .Where(f => f.Status == ProcessingStatus.Ready && f.Id == c.CoverMediaFileId && !f.ContentType.StartsWith("audio/")) .Select(f => (int?)f.Id) .FirstOrDefault() - ?? c.Items.AsQueryable().Where(Visibility.Item) + ?? c.Items.AsQueryable().Where(Visibility.ItemWithMedia) .SelectMany(i => i.MediaFiles) .Where(f => f.Status == ProcessingStatus.Ready && !f.ContentType.StartsWith("audio/")) .OrderBy(f => f.ArchiveItemId).ThenBy(f => f.Position).ThenBy(f => f.Id) diff --git a/src/Commonage.Web/Search/PublicFeeds.cs b/src/Commonage.Web/Search/PublicFeeds.cs index 067cc8a..d998c47 100644 --- a/src/Commonage.Web/Search/PublicFeeds.cs +++ b/src/Commonage.Web/Search/PublicFeeds.cs @@ -66,7 +66,7 @@ private static async Task ServeFeedAsync( // What people agreed to before this existed was "this website". A feed is copied to other places, so those stay out of it. var items = await db.VisibleItems .Where(i => i.Contribution == null || i.Contribution.ConsentCoversSharing) - .Include(i => i.MediaFiles.Where(f => f.Status == ProcessingStatus.Ready && !f.ContentType.StartsWith("audio/")).OrderBy(f => f.Position).ThenBy(f => f.Id).Take(1)) + .Include(i => i.MediaFiles.Where(f => f.Status == ProcessingStatus.Ready && f.ArchiveItem.MediaLevel == MediaLevel.Everything && !f.ContentType.StartsWith("audio/")).OrderBy(f => f.Position).ThenBy(f => f.Id).Take(1)) .OrderByDescending(i => i.PublishedAt).ThenByDescending(i => i.Id) .Take(FeedLength) .AsNoTracking() diff --git a/tests/Commonage.Tests/ExportTests.cs b/tests/Commonage.Tests/ExportTests.cs index 1c72d92..0182a29 100644 --- a/tests/Commonage.Tests/ExportTests.cs +++ b/tests/Commonage.Tests/ExportTests.cs @@ -102,7 +102,7 @@ public async Task Without_personal_data_no_name_or_email_is_in_the_export() /// and nobody would notice until then. Names are as they appear in archive.json. /// [Theory] - [InlineData(typeof(ArchiveItem), "item", "id collectionId title description status createdAt updatedAt publishedAt rejectedOrWithdrawnAt contribution files tags rightsUri rightsHolder credit referenceNumber originalLocation receivedFrom receivedOn internalNotes needsTranscription helpWanted notes", + [InlineData(typeof(ArchiveItem), "item", "id collectionId title description status createdAt updatedAt publishedAt rejectedOrWithdrawnAt contribution files tags rightsUri rightsHolder credit referenceNumber originalLocation receivedFrom receivedOn internalNotes needsTranscription helpWanted mediaLevel notes", "Collection: by collectionId. MediaFiles: as files. DateText, DateFrom, DateTo: as date. TagNames: repeats tags. " + "CanBePublished: follows from status. IsUntitled: follows from the empty title. MayTravel: follows from the contribution. FileText: the text of the PDFs, found again from the files. DeletedAt: the bin is not exported. Version: only for open forms.")] [InlineData(typeof(MediaFile), "file", "id originalFileName contentType sizeBytes sha256 uploadedAt altText caption position rotation pageCount", @@ -203,7 +203,7 @@ public async Task A_published_only_export_leaves_out_drafts_and_contributions() Assert.Contains(published.Id, ids); Assert.DoesNotContain(waiting.Id, ids); Assert.Equal(["Published"], statuses); - Assert.Equal(6, document.GetProperty("version").GetInt32()); + Assert.Equal(7, document.GetProperty("version").GetInt32()); } [Fact] diff --git a/tests/Commonage.Tests/MediaLevelTests.cs b/tests/Commonage.Tests/MediaLevelTests.cs new file mode 100644 index 0000000..4f08148 --- /dev/null +++ b/tests/Commonage.Tests/MediaLevelTests.cs @@ -0,0 +1,114 @@ +using System.IO.Compression; +using System.Text.Json; +using Commonage.Web.Domain; +using Commonage.Web.Identity; +using Microsoft.EntityFrameworkCore; + +namespace Commonage.Tests; + +/// Who may choose what visitors get of an item, what is recorded, and what the copies of the archive hold. +[Collection(nameof(AppCollection))] +public class MediaLevelTests(CommonageAppFactory app) +{ + private async Task<(string Word, int ItemId, int CollectionId, int FileId)> SeedAsync(ItemStatus status = ItemStatus.Published) + { + var word = TestData.UniqueWord("level"); + return await app.WithDbAsync(async db => + { + var now = DateTime.UtcNow; + var collection = new Collection { Title = $"Box {word}", CreatedAt = now }; + var item = new ArchiveItem { Title = $"Title {word}", Collection = collection, CreatedAt = now, UpdatedAt = now }; + var file = new MediaFile + { + ArchiveItem = item, OriginalFileName = "a.pdf", ContentType = "application/pdf", Sha256 = new string('b', 64), + StorageId = Guid.NewGuid(), Status = ProcessingStatus.Ready, Caption = $"Caption {word}", ExtractedText = $"Pages {word}", + }; + item.MediaFiles.Add(file); + item.FileText = new ItemFileText { Text = $"Pages {word}" }; + if (status == ItemStatus.Published) + item.Publish(now); + db.AddRange(collection, item); + await db.SaveChangesAsync(); + return (word, item.Id, collection.Id, file.Id); + }); + } + + private Task LevelOfAsync(int itemId) => app.WithDbAsync(db => db.ArchiveItems.Where(i => i.Id == itemId).Select(i => i.MediaLevel).SingleAsync()); + + [Fact] + public async Task A_curator_changes_what_visitors_get_and_it_is_recorded_while_a_helper_cannot() + { + // A draft, as a helper cannot open a published item at all. + var seeded = await SeedAsync(ItemStatus.Draft); + using var admin = app.CreateClient(); + await Browser.LogInAsCuratorAsync(admin); + var (helper, _, _, _) = await app.CreateAccountAsync(admin, Roles.Helper); + var page = $"/Admin/Items/Edit/{seeded.ItemId}"; + + await Browser.SendFormAsync(helper, $"/Admin/Items/Edit/{seeded.ItemId}", new() + { + ["Input.Title"] = $"Title {seeded.Word}", ["Input.CollectionId"] = seeded.CollectionId.ToString(), ["Input.MediaLevel"] = nameof(MediaLevel.RecordOnly), + }, page); + var afterHelper = await LevelOfAsync(seeded.ItemId); + + await Browser.SendFormAsync(admin, page, new() + { + ["Input.Title"] = $"Title {seeded.Word}", ["Input.CollectionId"] = seeded.CollectionId.ToString(), ["Input.MediaLevel"] = nameof(MediaLevel.RecordOnly), + }); + var afterCurator = await LevelOfAsync(seeded.ItemId); + var recorded = await app.WithDbAsync(db => db.AuditEntries.AnyAsync(e => e.Action == AuditAction.ItemMediaLevelChanged && e.ArchiveItemId == seeded.ItemId)); + + Assert.Equal(MediaLevel.Everything, afterHelper); + Assert.Equal(MediaLevel.RecordOnly, afterCurator); + Assert.True(recorded); + } + + [Fact] + public async Task A_curator_still_finds_an_item_by_what_its_pdf_says_when_visitors_cannot() + { + var seeded = await SeedAsync(); + await app.WithDbAsync(async db => + { + (await db.ArchiveItems.SingleAsync(i => i.Id == seeded.ItemId)).MediaLevel = MediaLevel.RecordOnly; + await db.SaveChangesAsync(); + return true; + }); + using var visitor = app.CreateClient(); + using var curator = app.CreateClient(); + await Browser.LogInAsCuratorAsync(curator); + + Assert.DoesNotContain($"Title {seeded.Word}", await visitor.GetStringAsync($"/search?q=Pages+{seeded.Word}")); + Assert.Contains($"Title {seeded.Word}", await curator.GetStringAsync($"/Admin?q=Pages+{seeded.Word}")); + } + + [Fact] + public async Task The_public_copy_of_the_export_holds_no_file_of_a_record_only_item_but_the_full_export_does() + { + var seeded = await SeedAsync(); + await app.WithDbAsync(async db => + { + (await db.ArchiveItems.SingleAsync(i => i.Id == seeded.ItemId)).MediaLevel = MediaLevel.RecordOnly; + await db.SaveChangesAsync(); + return true; + }); + using var admin = app.CreateClient(); + await Browser.LogInAsCuratorAsync(admin); + + var published = await ItemJsonAsync(admin, seeded.ItemId, publishedOnly: true); + var full = await ItemJsonAsync(admin, seeded.ItemId, publishedOnly: false); + + Assert.Equal("RecordOnly", published.GetProperty("mediaLevel").GetString()); + Assert.Empty(published.GetProperty("files").EnumerateArray()); + Assert.Single(full.GetProperty("files").EnumerateArray()); + } + + private static async Task ItemJsonAsync(HttpClient admin, int itemId, bool publishedOnly) + { + var response = await Browser.PostFormAsync(admin, "/Admin/Export", new() { ["PublishedOnly"] = publishedOnly ? "true" : "false" }); + await using var stream = await response.Content.ReadAsStreamAsync(); + using var zip = new ZipArchive(stream); + using var reader = new StreamReader(zip.GetEntry("archive.json")!.Open()); + var items = JsonDocument.Parse(await reader.ReadToEndAsync()).RootElement.GetProperty("items"); + return items.EnumerateArray().Single(i => i.GetProperty("id").GetInt32() == itemId).Clone(); + } +} diff --git a/tests/Commonage.Tests/VisibilityMatrixTests.cs b/tests/Commonage.Tests/VisibilityMatrixTests.cs index c4c2e82..b4da3ca 100644 --- a/tests/Commonage.Tests/VisibilityMatrixTests.cs +++ b/tests/Commonage.Tests/VisibilityMatrixTests.cs @@ -40,6 +40,7 @@ private async Task SeedAsync(string kind, Action ExtractedText = $"Pages {word}", }; item.MediaFiles.Add(file); + item.FileText = new ItemFileText { Text = $"Pages {word}" }; state(item, now); db.AddRange(collection, item); await db.SaveChangesAsync(); @@ -103,6 +104,31 @@ public async Task A_visitor_cannot_open_the_note_form_of_a_hidden_item() Assert.Equal(HttpStatusCode.NotFound, (await visitor.GetAsync($"/items/{draft.ItemId}/tell")).StatusCode); } + [Fact] + public async Task A_record_only_item_shows_its_record_and_nothing_about_its_media() + { + var record = await SeedAsync("recordonly", (i, now) => { i.Publish(now); i.MediaLevel = MediaLevel.RecordOnly; }); + using var visitor = app.CreateClient(); + + var everything = new StringBuilder(); + foreach (var address in Addresses) + everything.Append(await TextAsync(visitor, string.Format(address, record.Word))); + everything.Append(await TextAsync(visitor, $"/items/{record.ItemId}")); + everything.Append(await TextAsync(visitor, $"/collections/{record.CollectionId}")); + var text = everything.ToString(); + + foreach (var part in new[] { "Title ", "Words ", "Credit ", "P " }) + Assert.Contains(part + record.Word, text); + foreach (var part in new[] { "Alt ", "Caption ", "Pages " }) + Assert.DoesNotContain(part + record.Word, text); + Assert.DoesNotContain($"/media/{record.FileId}/", text); + foreach (var variant in new[] { "preview", "thumbnail", "card", "large" }) + Assert.Equal(HttpStatusCode.NotFound, (await visitor.GetAsync($"/media/{record.FileId}/{variant}")).StatusCode); + + // What the pages of the PDFs say is not found by a visitor, but a curator finds it. + Assert.DoesNotContain($"Title {record.Word}", await TextAsync(visitor, $"/search?q=Pages+{record.Word}")); + } + private static async Task TextAsync(HttpClient client, string address) { var response = await client.GetAsync(address);