From 31a87d020327655df708177c498458da5f0389ce Mon Sep 17 00:00:00 2001 From: "Seb H." <138793908+SebHenn@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:45:15 +0100 Subject: [PATCH] M27, third part: embargo (public from), bulk and list for what visitors get Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Seb H. <138793908+SebHenn@users.noreply.github.com> --- CHANGELOG.md | 5 + docs/operations.md | 2 +- docs/security.md | 2 +- src/Commonage.Web/Audit/AuditText.cs | 3 +- src/Commonage.Web/Data/CommonageDbContext.cs | 9 +- .../20261119172908_ItemPublicFrom.Designer.cs | 1114 +++++++++++++++++ .../20261119172908_ItemPublicFrom.cs | 29 + .../CommonageDbContextModelSnapshot.cs | 3 + src/Commonage.Web/Data/Visibility.cs | 17 +- src/Commonage.Web/Dates.cs | 15 + src/Commonage.Web/Domain/ArchiveItem.cs | 37 + src/Commonage.Web/Domain/AuditEntry.cs | 1 + src/Commonage.Web/Export/ArchiveExporter.cs | 4 +- .../Pages/Admin/Collections/Edit.cshtml | 4 + .../Pages/Admin/Collections/Edit.cshtml.cs | 8 +- src/Commonage.Web/Pages/Admin/Index.cshtml | 8 +- src/Commonage.Web/Pages/Admin/Index.cshtml.cs | 4 +- .../Pages/Admin/Items/Bulk.cshtml | 25 + .../Pages/Admin/Items/Bulk.cshtml.cs | 28 +- .../Pages/Admin/Items/Edit.cshtml | 11 + .../Pages/Admin/Items/Edit.cshtml.cs | 9 + .../Pages/Admin/Items/Preview.cshtml | 4 + .../Pages/Admin/Items/Preview.cshtml.cs | 3 + .../Pages/Collections/Details.cshtml.cs | 4 +- src/Commonage.Web/Pages/Search.cshtml.cs | 2 +- .../Resources/SharedResource.de.resx | 14 + .../Resources/SharedResource.resx | 14 + src/Commonage.Web/Search/AdminItemList.cs | 6 +- src/Commonage.Web/Search/ItemSummary.cs | 16 +- src/Commonage.Web/Search/PublicFeeds.cs | 2 +- .../Commonage.BrowserTests/BehaviourTests.cs | 16 + tests/Commonage.Tests/EmbargoTests.cs | 161 +++ tests/Commonage.Tests/ExportTests.cs | 4 +- .../Commonage.Tests/VisibilityMatrixTests.cs | 24 +- 34 files changed, 1567 insertions(+), 41 deletions(-) create mode 100644 src/Commonage.Web/Data/Migrations/20261119172908_ItemPublicFrom.Designer.cs create mode 100644 src/Commonage.Web/Data/Migrations/20261119172908_ItemPublicFrom.cs create mode 100644 tests/Commonage.Tests/EmbargoTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index c7ae300..f662c5c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,11 @@ version may change things that need attention when updating, and these notes say ### For curators +- A published item can have an **embargo**: set "Public from" on the item, and until the start of that day (in the archive's time + zone) it is as hidden as a draft, everywhere, including its pictures. Lists, feeds and the start page put the item where it + belongs on the day it opens. Exports of published items leave out items still under embargo (export format version 8). +- "What visitors get" and "Public from" can be set for many items at once from the item list, and the list can show only items + shown as a record only or still under embargo. The collection cover choice says which photos visitors do not see. - 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 diff --git a/docs/operations.md b/docs/operations.md index 36e7d5d..dd8b9f5 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": 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` +`archive.json` has `"format": "commonage-export"` and `"version": 8`. Version 8 added `publicFrom` to each item (the day an embargo ends, or empty); an export of published items has no item that is still embargoed. 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 fa51bb6..95b31bc 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. 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. | +| 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 under embargo (`PublicFrom` in the future, in the archive's time zone) is as hidden as a draft: it passes through `VisibleItems`/`VisibleMedia` with the day as a parameter, tested with a clock. Feeds and the sitemap are cached for ten minutes, so an item can show up to ten minutes late or stay that long after it is unpublished. 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 405ff91..67429d9 100644 --- a/src/Commonage.Web/Audit/AuditText.cs +++ b/src/Commonage.Web/Audit/AuditText.cs @@ -25,6 +25,7 @@ public static class AuditText AuditAction.ItemPublished => localizer["Published the item"], AuditAction.ItemUnpublished => localizer["Unpublished the item"], AuditAction.ItemMediaLevelChanged => localizer["Changed what visitors get of the item"], + AuditAction.ItemPublicFromChanged => localizer["Changed the date from which the item is public"], 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"], @@ -83,7 +84,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 or AuditAction.ItemMediaLevelChanged + AuditAction.ItemCreated or AuditAction.ItemChanged or AuditAction.ItemFieldRestored or AuditAction.ItemPublished or AuditAction.ItemUnpublished or AuditAction.ItemMediaLevelChanged or AuditAction.ItemPublicFromChanged or AuditAction.ItemDeleted or AuditAction.ItemMovedToBin or AuditAction.ItemRestored or AuditAction.ItemPurged or AuditAction.ItemMovedToBinAfterKeptTime or AuditAction.ItemsImported => AuditKind.Items, AuditAction.PhotosAdded or AuditAction.PhotosArranged or AuditAction.PhotoDeleted or AuditAction.PhotoMovedToBin diff --git a/src/Commonage.Web/Data/CommonageDbContext.cs b/src/Commonage.Web/Data/CommonageDbContext.cs index 989a85b..b47c575 100644 --- a/src/Commonage.Web/Data/CommonageDbContext.cs +++ b/src/Commonage.Web/Data/CommonageDbContext.cs @@ -7,7 +7,7 @@ namespace Commonage.Web.Data; -public class CommonageDbContext(DbContextOptions options) +public class CommonageDbContext(DbContextOptions options, TimeProvider? clock = null) : IdentityDbContext(options), IDataProtectionKeyContext { public DbSet Collections => Set(); @@ -46,10 +46,13 @@ 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 VisibleItems => ArchiveItems.Where(Visibility.Item); + public IQueryable VisibleItems => ArchiveItems.Where(Visibility.Item(Today)); + + /// Today in the archive's time zone: what an embargo is compared with. + public DateOnly Today => Dates.Today((clock ?? TimeProvider.System).GetUtcNow()); /// Files the public may be given. /media and every cover or first photo start from this. - public IQueryable VisibleMedia => MediaFiles.Where(Visibility.Media); + public IQueryable VisibleMedia => MediaFiles.Where(Visibility.Media(Today)); /// 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/Migrations/20261119172908_ItemPublicFrom.Designer.cs b/src/Commonage.Web/Data/Migrations/20261119172908_ItemPublicFrom.Designer.cs new file mode 100644 index 0000000..9021575 --- /dev/null +++ b/src/Commonage.Web/Data/Migrations/20261119172908_ItemPublicFrom.Designer.cs @@ -0,0 +1,1114 @@ +// +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("20261119172908_ItemPublicFrom")] + partial class ItemPublicFrom + { + /// + 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("PublicFrom") + .HasColumnType("date"); + + 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/20261119172908_ItemPublicFrom.cs b/src/Commonage.Web/Data/Migrations/20261119172908_ItemPublicFrom.cs new file mode 100644 index 0000000..50302df --- /dev/null +++ b/src/Commonage.Web/Data/Migrations/20261119172908_ItemPublicFrom.cs @@ -0,0 +1,29 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Commonage.Web.Data.Migrations +{ + /// + public partial class ItemPublicFrom : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "PublicFrom", + table: "ArchiveItems", + type: "date", + nullable: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "PublicFrom", + table: "ArchiveItems"); + } + } +} diff --git a/src/Commonage.Web/Data/Migrations/CommonageDbContextModelSnapshot.cs b/src/Commonage.Web/Data/Migrations/CommonageDbContextModelSnapshot.cs index 9196bf0..f5d4f35 100644 --- a/src/Commonage.Web/Data/Migrations/CommonageDbContextModelSnapshot.cs +++ b/src/Commonage.Web/Data/Migrations/CommonageDbContextModelSnapshot.cs @@ -90,6 +90,9 @@ protected override void BuildModel(ModelBuilder modelBuilder) .HasMaxLength(300) .HasColumnType("character varying(300)"); + b.Property("PublicFrom") + .HasColumnType("date"); + b.Property("PublishedAt") .HasColumnType("timestamp with time zone"); diff --git a/src/Commonage.Web/Data/Visibility.cs b/src/Commonage.Web/Data/Visibility.cs index 0ec0e74..5809daa 100644 --- a/src/Commonage.Web/Data/Visibility.cs +++ b/src/Commonage.Web/Data/Visibility.cs @@ -10,14 +10,19 @@ namespace Commonage.Web.Data; /// 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; + /// + /// An item visitors may see: published, not in the bin (by the query filter) and not embargoed. is + /// the day in the archive's time zone, ; an embargo ends at the start of its day. + /// + public static Expression> Item(DateOnly today) => + i => i.Status == ItemStatus.Published && (i.PublicFrom == null || i.PublicFrom <= today); /// 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; + public static Expression> ItemWithMedia(DateOnly today) => + i => i.Status == ItemStatus.Published && (i.PublicFrom == null || i.PublicFrom <= today) && 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; + public static Expression> Media(DateOnly today) => + f => f.ArchiveItem.Status == ItemStatus.Published && (f.ArchiveItem.PublicFrom == null || f.ArchiveItem.PublicFrom <= today) + && f.ArchiveItem.MediaLevel == MediaLevel.Everything; } diff --git a/src/Commonage.Web/Dates.cs b/src/Commonage.Web/Dates.cs index 44b847b..f9b220a 100644 --- a/src/Commonage.Web/Dates.cs +++ b/src/Commonage.Web/Dates.cs @@ -12,6 +12,21 @@ public static partial class Dates /// The archive's time zone for this request, or null for the server's clock. public static AsyncLocal Zone { get; } = new(); + /// The day it is now in the archive's time zone. + public static DateOnly Today(DateTimeOffset utcNow) => DateOnly.FromDateTime(Local(utcNow.UtcDateTime)); + + /// The moment a day starts in the archive's time zone. + public static DateTime StartOfDayUtc(DateOnly day) + { + var local = day.ToDateTime(TimeOnly.MinValue); + if (Zone.Value is not { } zone) + return local.ToUniversalTime(); + // A day that starts in the gap of a clock change starts when the gap ends. + if (zone.IsInvalidTime(local)) + local = local.AddHours(1); + return TimeZoneInfo.ConvertTimeToUtc(local, zone); + } + public static string Day(DateTime utc) => Local(utc).ToString(DayPattern(), CultureInfo.CurrentCulture); public static string Moment(DateTime utc) => $"{Day(utc)} {Local(utc).ToString("t", CultureInfo.CurrentCulture)}"; diff --git a/src/Commonage.Web/Domain/ArchiveItem.cs b/src/Commonage.Web/Domain/ArchiveItem.cs index bb30b1e..34fdb2b 100644 --- a/src/Commonage.Web/Domain/ArchiveItem.cs +++ b/src/Commonage.Web/Domain/ArchiveItem.cs @@ -17,6 +17,12 @@ public class ArchiveItem /// What visitors get of the item once it is published, see . public MediaLevel MediaLevel { get; set; } + /// + /// An embargo: a published item is not public until the start of this day in the archive's time zone. Empty means none. + /// Kept when the item is unpublished, so publishing it again honours the date. + /// + public DateOnly? PublicFrom { get; set; } + public int CollectionId { get; set; } public Collection Collection { get; set; } = null!; @@ -121,9 +127,40 @@ public void Publish(DateTime now) MarkReviewed(now); Status = ItemStatus.Published; PublishedAt ??= now; + AlignPublishedAt(now); RejectedOrWithdrawnAt = null; } + /// Sets or removes the embargo. follows, so that lists and feeds order by when an item is public. + public void SetPublicFrom(DateOnly? day, DateTime now) + { + PublicFrom = day; + AlignPublishedAt(now); + } + + /// + /// is when the item is, or will be, public: never earlier than the start of the embargo's day, and + /// not in the future once there is no embargo. That way every list ordered by it surfaces an item on the day it opens. + /// + private void AlignPublishedAt(DateTime now) + { + if (PublishedAt is not { } at) + return; + if (PublicFrom is { } day) + { + var opens = Dates.StartOfDayUtc(day); + // A date that was only a promise (still ahead) follows the embargo both ways; one already past only moves later. + if (at > now) + PublishedAt = opens > now ? opens : now; + else if (opens > at) + PublishedAt = opens; + } + else if (at > now) + { + PublishedAt = now; + } + } + public void Unpublish() { if (Status == ItemStatus.Published) diff --git a/src/Commonage.Web/Domain/AuditEntry.cs b/src/Commonage.Web/Domain/AuditEntry.cs index 89f6488..897aff3 100644 --- a/src/Commonage.Web/Domain/AuditEntry.cs +++ b/src/Commonage.Web/Domain/AuditEntry.cs @@ -8,6 +8,7 @@ public enum AuditAction ItemPublished, ItemUnpublished, ItemMediaLevelChanged, + ItemPublicFromChanged, ItemDeleted, PhotosAdded, PhotoDeleted, diff --git a/src/Commonage.Web/Export/ArchiveExporter.cs b/src/Commonage.Web/Export/ArchiveExporter.cs index 1c4ad3a..1f193be 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 = 7; + public const int Version = 8; private static readonly JsonSerializerOptions JsonOptions = new() { @@ -271,6 +271,7 @@ private static ExportFile Describe(MediaFile file, string? path, string? problem options.PublishedOnly ? null : item.NeedsTranscription, item.HelpWanted, item.MediaLevel, + item.PublicFrom, item.Contribution is not { } contribution ? null : new ExportContribution( options.IncludePersonalData ? contribution.ContributorName : null, options.IncludePersonalData ? contribution.ContributorEmail : null, @@ -424,6 +425,7 @@ internal record ExportItem( bool? NeedsTranscription, bool HelpWanted, MediaLevel MediaLevel, + DateOnly? PublicFrom, ExportContribution? Contribution, IReadOnlyList? Notes, IReadOnlyList Files); diff --git a/src/Commonage.Web/Pages/Admin/Collections/Edit.cshtml b/src/Commonage.Web/Pages/Admin/Collections/Edit.cshtml index 851c08a..0a4845c 100644 --- a/src/Commonage.Web/Pages/Admin/Collections/Edit.cshtml +++ b/src/Commonage.Web/Pages/Admin/Collections/Edit.cshtml @@ -78,6 +78,10 @@ { @T["Not published"] } + else if (!choice.ShownToVisitors) + { + @T["Visitors do not see this photo yet or at all"] + } diff --git a/src/Commonage.Web/Pages/Admin/Collections/Edit.cshtml.cs b/src/Commonage.Web/Pages/Admin/Collections/Edit.cshtml.cs index 8f714f4..4b0e17b 100644 --- a/src/Commonage.Web/Pages/Admin/Collections/Edit.cshtml.cs +++ b/src/Commonage.Web/Pages/Admin/Collections/Edit.cshtml.cs @@ -26,7 +26,7 @@ public class EditModel(CommonageDbContext db, AuditLog audit, IStringLocalizerWhat still uses the collection. Only an unused one can be deleted. public CollectionUse Use { get; private set; } = new(0, 0, 0); - public record CoverChoice(int MediaFileId, string ItemTitle, bool Published); + public record CoverChoice(int MediaFileId, string ItemTitle, bool Published, bool ShownToVisitors); public record CollectionUse(int Items, int InBin, int Links) { @@ -164,13 +164,15 @@ await db.ArchiveItems.IgnoreQueryFilters().CountAsync(i => i.CollectionId == id // The chosen one first, so it is always offered, then published items' photos, newest item first, each item's in order. var current = collection.CoverMediaFileId; + var today = db.Today; CoverChoices = await db.MediaFiles .Where(f => f.ArchiveItem.CollectionId == id && f.Status == ProcessingStatus.Ready && !f.ContentType.StartsWith("audio/")) .OrderByDescending(f => f.Id == current) - .ThenByDescending(f => f.ArchiveItem.Status == ItemStatus.Published) + .ThenByDescending(f => f.ArchiveItem.Status == ItemStatus.Published && (f.ArchiveItem.PublicFrom == null || f.ArchiveItem.PublicFrom <= today) && f.ArchiveItem.MediaLevel == MediaLevel.Everything) .ThenByDescending(f => f.ArchiveItemId).ThenBy(f => f.Position).ThenBy(f => f.Id) .Take(MaxCoverChoices) - .Select(f => new CoverChoice(f.Id, f.ArchiveItem.Title, f.ArchiveItem.Status == ItemStatus.Published)) + .Select(f => new CoverChoice(f.Id, f.ArchiveItem.Title, f.ArchiveItem.Status == ItemStatus.Published, + f.ArchiveItem.Status == ItemStatus.Published && (f.ArchiveItem.PublicFrom == null || f.ArchiveItem.PublicFrom <= today) && f.ArchiveItem.MediaLevel == MediaLevel.Everything)) .ToListAsync(cancellationToken); } } diff --git a/src/Commonage.Web/Pages/Admin/Index.cshtml b/src/Commonage.Web/Pages/Admin/Index.cshtml index 5c3ed0f..f249d48 100644 --- a/src/Commonage.Web/Pages/Admin/Index.cshtml +++ b/src/Commonage.Web/Pages/Admin/Index.cshtml @@ -125,6 +125,10 @@ else + + + +
@@ -163,6 +167,8 @@ else + +
@@ -219,7 +225,7 @@ else } @item.CollectionTitle - @if (item.RecordOnly) { @T["Record only"] } + @if (item.RecordOnly) { @T["Record only"] }@if (item.EmbargoedUntil is { } until) { @T["Public from {0}", until.ToString("d", System.Globalization.CultureInfo.CurrentCulture)] } @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 fc42694..63f3027 100644 --- a/src/Commonage.Web/Pages/Admin/Index.cshtml.cs +++ b/src/Commonage.Web/Pages/Admin/Index.cshtml.cs @@ -105,6 +105,7 @@ public async Task OnGetAsync(CancellationToken cancellationToken) HelpWantedNotPublished = await visible.CountAsync(i => i.HelpWanted && (i.Status == ItemStatus.Draft || i.Status == ItemStatus.Submitted), cancellationToken); var items = await db.QueryAsync(Filter, cancellationToken); + var today = db.Today; Items = await items .Select(i => new AdminItemRow( i.Id, @@ -117,7 +118,8 @@ public async Task OnGetAsync(CancellationToken cancellationToken) 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.MediaLevel == MediaLevel.RecordOnly)) + i.MediaLevel == MediaLevel.RecordOnly, + i.Status == ItemStatus.Published && i.PublicFrom > today ? i.PublicFrom : null)) .ToPagedListAsync(PageNumber, PageSize, cancellationToken); } } diff --git a/src/Commonage.Web/Pages/Admin/Items/Bulk.cshtml b/src/Commonage.Web/Pages/Admin/Items/Bulk.cshtml index af4b6f0..1840874 100644 --- a/src/Commonage.Web/Pages/Admin/Items/Bulk.cshtml +++ b/src/Commonage.Web/Pages/Admin/Items/Bulk.cshtml @@ -8,6 +8,8 @@ BulkAction.AddTags => T["Add tags to many at once"], BulkAction.SetDate => T["Set the date of many at once"], BulkAction.MoveToCollection => T["Move many to a collection"], + BulkAction.SetMediaLevel => T["Set what visitors get of many at once"], + BulkAction.SetPublicFrom => T["Set the public-from date of many at once"], _ => T["Set the rights statement of many at once"], }; } @@ -106,6 +108,29 @@
@T["What others may do with this item. Choose a free licence only if whoever holds the rights really gave it."]
} + @if (Model.Action == BulkAction.SetMediaLevel) + { +
+ @T["What visitors get"] +
+ + +
+
+ + +
+
+ } + @if (Model.Action == BulkAction.SetPublicFrom) + { +
+ + + +
@T["Leave empty to take an embargo away."]
+
+ } @if (Model.WouldBeReplaced > 0) {

@T["Items that already have one, which is then replaced: {0}.", Model.WouldBeReplaced]

diff --git a/src/Commonage.Web/Pages/Admin/Items/Bulk.cshtml.cs b/src/Commonage.Web/Pages/Admin/Items/Bulk.cshtml.cs index e29b70e..94ec7b1 100644 --- a/src/Commonage.Web/Pages/Admin/Items/Bulk.cshtml.cs +++ b/src/Commonage.Web/Pages/Admin/Items/Bulk.cshtml.cs @@ -18,6 +18,8 @@ public enum BulkAction SetDate, MoveToCollection, SetRights, + SetMediaLevel, + SetPublicFrom, } /// An item as the confirmation names it. A row of "Untitled" says nothing, so those also show their file. @@ -64,6 +66,13 @@ public string? Back [BindProperty] public string? RightsUri { get; set; } + [BindProperty] + public MediaLevel MediaLevel { get; set; } + + /// The day an embargo ends. Empty takes an embargo away. + [BindProperty] + public DateOnly? PublicFrom { get; set; } + public int Count { get; private set; } /// The items that will change. Only publishing leaves some out. @@ -164,7 +173,13 @@ public async Task OnPostApplyAsync(CancellationToken cancellation continue; changed++; item.UpdatedAt = now; - audit.Record(Action == BulkAction.Publish ? AuditAction.ItemPublished : AuditAction.ItemChanged, item.Title, item); + audit.Record(Action switch + { + BulkAction.Publish => AuditAction.ItemPublished, + BulkAction.SetMediaLevel => AuditAction.ItemMediaLevelChanged, + BulkAction.SetPublicFrom => AuditAction.ItemPublicFromChanged, + _ => AuditAction.ItemChanged, + }, item.Title, item); } try @@ -218,6 +233,16 @@ private bool Apply(ArchiveItem item, List tags, DateTime now) return false; item.RightsUri = statement; return true; + case BulkAction.SetMediaLevel: + if (item.MediaLevel == MediaLevel) + return false; + item.MediaLevel = MediaLevel; + return true; + case BulkAction.SetPublicFrom: + if (item.PublicFrom == PublicFrom) + return false; + item.SetPublicFrom(PublicFrom, now); + return true; default: return false; } @@ -246,6 +271,7 @@ private async Task ShowAsync(List ids, CancellationToken cancellationToken) { BulkAction.SetDate => await items.CountAsync(i => i.DateText != null, cancellationToken), BulkAction.SetRights => await items.CountAsync(i => i.RightsUri != null, cancellationToken), + BulkAction.SetPublicFrom => await items.CountAsync(i => i.PublicFrom != null, cancellationToken), _ => 0, }; Examples = await items.OrderBy(i => i.Id).Take(ExamplesShown) diff --git a/src/Commonage.Web/Pages/Admin/Items/Edit.cshtml b/src/Commonage.Web/Pages/Admin/Items/Edit.cshtml index 4dd332a..c94054e 100644 --- a/src/Commonage.Web/Pages/Admin/Items/Edit.cshtml +++ b/src/Commonage.Web/Pages/Admin/Items/Edit.cshtml @@ -21,6 +21,10 @@ { @T["Record only"] } + @if (Model.Input.PublicFrom is { } publicFrom) + { + @T["Public from {0}", publicFrom.ToString("d", System.Globalization.CultureInfo.CurrentCulture)] + } } @if (Model.CurrentStatus == ItemStatus.Published) { @@ -275,6 +279,13 @@
@T["Applies once the item is published. A recording's transcript in the description stays visible."]
+ +
+ + +
@T["Optional. Until this day the published item is as hidden as a draft."]
+ +
} diff --git a/src/Commonage.Web/Pages/Admin/Items/Edit.cshtml.cs b/src/Commonage.Web/Pages/Admin/Items/Edit.cshtml.cs index a0226a2..aca9e59 100644 --- a/src/Commonage.Web/Pages/Admin/Items/Edit.cshtml.cs +++ b/src/Commonage.Web/Pages/Admin/Items/Edit.cshtml.cs @@ -177,6 +177,9 @@ public class InputModel [Display(Name = "What visitors get")] public MediaLevel MediaLevel { get; set; } + [Display(Name = "Public from")] + public DateOnly? PublicFrom { get; set; } + /// The item's version when the form was opened, to notice changes made by someone else since. public uint? Version { get; set; } } @@ -214,6 +217,7 @@ public async Task OnGetAsync(int? id, int? collectionId) NeedsTranscription = item.NeedsTranscription, HelpWanted = item.HelpWanted, MediaLevel = item.MediaLevel, + PublicFrom = item.PublicFrom, }; RightsWereProposed = item.RightsUri is null && item.Contribution is not null; await ShowStateAsync(item); @@ -351,6 +355,9 @@ public async Task OnPostAsync(int? id, string? command, string? t var mediaLevelChanged = User.MayManage() && item.MediaLevel != Input.MediaLevel; if (mediaLevelChanged) item.MediaLevel = Input.MediaLevel; + var publicFromChanged = User.MayManage() && item.PublicFrom != Input.PublicFrom; + if (publicFromChanged) + item.SetPublicFrom(Input.PublicFrom, now); 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()) @@ -364,6 +371,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); + if (publicFromChanged) + audit.Record(AuditAction.ItemPublicFromChanged, 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 0a7406c..799143d 100644 --- a/src/Commonage.Web/Pages/Admin/Items/Preview.cshtml +++ b/src/Commonage.Web/Pages/Admin/Items/Preview.cshtml @@ -11,6 +11,10 @@ { @T["Preview. Visitors cannot see this item."] } + else if (Model.Item.PublicFrom is { } publicFrom && publicFrom > Model.Today) + { + @T["Preview. Public from {0}.", publicFrom.ToString("d", System.Globalization.CultureInfo.CurrentCulture)] + } else if (Model.Item.MediaLevel == MediaLevel.RecordOnly) { @T["Preview. Visitors see the record only, without its pictures and recordings."] diff --git a/src/Commonage.Web/Pages/Admin/Items/Preview.cshtml.cs b/src/Commonage.Web/Pages/Admin/Items/Preview.cshtml.cs index 2ae06fa..139c94e 100644 --- a/src/Commonage.Web/Pages/Admin/Items/Preview.cshtml.cs +++ b/src/Commonage.Web/Pages/Admin/Items/Preview.cshtml.cs @@ -12,6 +12,9 @@ public class PreviewModel(CommonageDbContext db) : PageModel { public ArchiveItem Item { get; private set; } = null!; + /// Today in the archive's time zone, to tell whether an embargo is still on. + public DateOnly Today => db.Today; + public async Task OnGetAsync(int id) { var items = db.ArchiveItems.AsQueryable(); diff --git a/src/Commonage.Web/Pages/Collections/Details.cshtml.cs b/src/Commonage.Web/Pages/Collections/Details.cshtml.cs index 20d8bed..e18f21e 100644 --- a/src/Commonage.Web/Pages/Collections/Details.cshtml.cs +++ b/src/Commonage.Web/Pages/Collections/Details.cshtml.cs @@ -25,12 +25,12 @@ public record Invitation(string Title, string Token); public async Task OnGetAsync(int id, CancellationToken cancellationToken) { - var collection = await db.Collections.Where(c => c.Id == id && c.Items.AsQueryable().Any(Visibility.Item)).FirstOrDefaultAsync(cancellationToken); + var collection = await db.Collections.Where(c => c.Id == id && c.Items.AsQueryable().Any(Visibility.Item(db.Today))).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); + Years = await db.Collections.Where(c => c.Id == id).ToCards(db.Today).Select(c => c.Years).FirstAsync(cancellationToken); Items = await db.VisibleItems .Filter(new ItemFilter(CollectionId: id)) .Sort(collection.Sort.ToItemSort(), query: null) diff --git a/src/Commonage.Web/Pages/Search.cshtml.cs b/src/Commonage.Web/Pages/Search.cshtml.cs index 9001290..4a7527d 100644 --- a/src/Commonage.Web/Pages/Search.cshtml.cs +++ b/src/Commonage.Web/Pages/Search.cshtml.cs @@ -101,7 +101,7 @@ public async Task OnGetAsync(CancellationToken cancellationToken) Decades = []; } - var collections = await db.Collections.Where(c => c.Items.AsQueryable().Any(Visibility.Item)).OrderBy(c => c.Title).ToListAsync(cancellationToken); + var collections = await db.Collections.Where(c => c.Items.AsQueryable().Any(Visibility.Item(db.Today))).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; diff --git a/src/Commonage.Web/Resources/SharedResource.de.resx b/src/Commonage.Web/Resources/SharedResource.de.resx index c6a0c21..c5dd7b9 100644 --- a/src/Commonage.Web/Resources/SharedResource.de.resx +++ b/src/Commonage.Web/Resources/SharedResource.de.resx @@ -1015,4 +1015,18 @@ 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 + Öffentlich ab + Optional. Bis zu diesem Tag ist der veröffentlichte Eintrag so verborgen wie ein Entwurf. + Öffentlich ab {0} + Vorschau. Öffentlich ab {0}. + Datum geändert, ab dem der Eintrag öffentlich ist + Festlegen, was Besucher bei mehreren bekommen + Öffentlich-ab-Datum für mehrere festlegen + Leer lassen, um eine Sperrfrist aufzuheben. + Festlegen, was Besucher bekommen + Öffentlich-ab-Datum festlegen + Vor Besuchern zurückgehalten + Nur als Datensatz gezeigt + Unter Sperrfrist + Besucher sehen dieses Foto noch nicht oder gar nicht diff --git a/src/Commonage.Web/Resources/SharedResource.resx b/src/Commonage.Web/Resources/SharedResource.resx index 803c3de..acf75a7 100644 --- a/src/Commonage.Web/Resources/SharedResource.resx +++ b/src/Commonage.Web/Resources/SharedResource.resx @@ -109,6 +109,7 @@ Changed the archive settings Changed the collection Changed the contribution link + Changed the date from which the item is public Changed the item Changed the name of an account Changed the order of the collections @@ -344,6 +345,7 @@ JPEG, PNG, TIFF, WebP, AVIF, GIF or PDF. The original file is kept unchanged and is only visible to curators. Keep rejected and withdrawn contributions Keep the activity log + Kept back from visitors Kind Language Language of the archive @@ -356,6 +358,7 @@ Last login Later Later: {0} + Leave empty to take an embargo away. Leave this field empty Left out, because a recording has no transcript yet: {0}. Left out, because the archive already has them: {0} @@ -488,6 +491,7 @@ Open at full size Open: the link accepts contributions Opened a visitor's note again + Optional. Until this day the published item is as hidden as a draft. Or a folder on the server Or start from one of these: Or type this key into the app: @@ -562,6 +566,7 @@ Poster: {0} Preparing the recording… Preview + Preview. Public from {0}. Preview. This item is public. Preview. Visitors cannot see this item. Preview. Visitors see the record only, without its pictures and recordings. @@ -578,6 +583,8 @@ Privacy Problems Public domain: free to use + Public from + Public from {0} Publish Publish many at once Publish: {0} @@ -652,10 +659,14 @@ Separated by semicolons or commas. Set the date Set the date of many at once + Set the public-from date + Set the public-from date of many at once Set the rights statement Set the rights statement of many at once Set up nightly backups (docs/deployment.md) Set up on a new phone + Set what visitors get + Set what visitors get of many at once Settings Setup link Several files have this name. Write the path with its folder. @@ -666,6 +677,7 @@ Show everything Show my name with what I send in Showing the newest {0}. + Shown as a record only Shown to admins on this page and in the list of accounts. Never to visitors. Six digits. Without your phone, type one of your recovery codes instead. Each one works once. Skip to content @@ -886,6 +898,7 @@ Turned off the account's authenticator app Turning the photo… Type the six digits the app shows now: + Under embargo Understood as: {0} Unknown Unpublish @@ -905,6 +918,7 @@ Visitor Visitors can open a photo at about 3000 pixels, to read a letter or look at a face. Without this they only get a smaller one, about 1600 pixels, and the archive saves the disk space. The original stays private either way, and larger versions have no location data or other embedded details either. Visitors can then send the curators more about an item, a correction, or a request to take it down. Only curators read it, under “Notes from visitors”. Name and email address are optional, and the privacy page should say that the archive keeps them. + Visitors do not see this photo yet or at all Visitors find all places and all people on pages of their own, once an item with the tag is published. That page lists every person's name, so name living people only when they agree. Visitors find the collections in this order. Waiting diff --git a/src/Commonage.Web/Search/AdminItemList.cs b/src/Commonage.Web/Search/AdminItemList.cs index cb90c86..779301c 100644 --- a/src/Commonage.Web/Search/AdminItemList.cs +++ b/src/Commonage.Web/Search/AdminItemList.cs @@ -18,6 +18,8 @@ public enum ItemNeed Title, Transcription, HelpWanted, + RecordOnly, + Embargoed, } public enum AdminItemSort @@ -43,7 +45,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, bool RecordOnly = false); + string? FirstFileName = null, bool HasIdenticalFile = false, bool RecordOnly = false, DateOnly? EmbargoedUntil = null); /// 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 @@ -76,6 +78,8 @@ public static async Task> QueryAsync(this CommonageDbCon ItemNeed.Title => items.Where(i => i.Title == ""), ItemNeed.Transcription => items.Where(i => i.NeedsTranscription), ItemNeed.HelpWanted => items.Where(i => i.HelpWanted), + ItemNeed.RecordOnly => items.Where(i => i.MediaLevel == MediaLevel.RecordOnly), + ItemNeed.Embargoed => items.Where(i => i.Status == ItemStatus.Published && i.PublicFrom > db.Today), // With a default for the whole archive, nothing is left undecided. ItemNeed.Rights when !await db.ArchiveSettings.AnyAsync(s => s.DefaultRightsUri != null, cancellationToken) => items.Where(i => i.RightsUri == null), ItemNeed.Rights => items.Where(i => false), diff --git a/src/Commonage.Web/Search/ItemSummary.cs b/src/Commonage.Web/Search/ItemSummary.cs index 6dfb675..f7d5752 100644 --- a/src/Commonage.Web/Search/ItemSummary.cs +++ b/src/Commonage.Web/Search/ItemSummary.cs @@ -25,33 +25,33 @@ 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.AsQueryable().Any(Visibility.Item)) + .Where(c => c.Items.AsQueryable().Any(Visibility.Item(db.Today))) .OrderBy(c => c.Position).ThenBy(c => c.Title).ThenBy(c => c.Id) - .ToCards() + .ToCards(db.Today) .ToListAsync(cancellationToken); /// /// What visitors see of each collection, from its published items only: drafts, items in the bin and their photos count /// for nothing, and a chosen cover whose item is not published, or has moved to another collection, is passed over. /// - public static IQueryable ToCards(this IQueryable collections) => + public static IQueryable ToCards(this IQueryable collections, DateOnly today) => collections.Select(c => new CollectionCard( c.Id, c.Title, c.Description, - c.Items.AsQueryable().Count(Visibility.Item), - c.Items.AsQueryable().Where(Visibility.ItemWithMedia) + c.Items.AsQueryable().Count(Visibility.Item(today)), + c.Items.AsQueryable().Where(Visibility.ItemWithMedia(today)) .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.ItemWithMedia) + ?? c.Items.AsQueryable().Where(Visibility.ItemWithMedia(today)) .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.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)))); + c.Items.AsQueryable().Where(Visibility.Item(today)).Min(i => (int?)(i.DateFrom ?? i.DateTo)!.Value.Year), + c.Items.AsQueryable().Where(Visibility.Item(today)).Max(i => (int?)(i.DateTo ?? i.DateFrom)!.Value.Year)))); } diff --git a/src/Commonage.Web/Search/PublicFeeds.cs b/src/Commonage.Web/Search/PublicFeeds.cs index d998c47..b9d8d60 100644 --- a/src/Commonage.Web/Search/PublicFeeds.cs +++ b/src/Commonage.Web/Search/PublicFeeds.cs @@ -123,7 +123,7 @@ private static async Task ServeSitemapAsync(HttpContext context, Common var address = context.Request.BaseAddress(); var collections = await db.Collections - .Where(c => c.Items.AsQueryable().Any(Visibility.Item)) + .Where(c => c.Items.AsQueryable().Any(Visibility.Item(db.Today))) .OrderBy(c => c.Id) .Select(c => c.Id) .ToListAsync(cancellationToken); diff --git a/tests/Commonage.BrowserTests/BehaviourTests.cs b/tests/Commonage.BrowserTests/BehaviourTests.cs index 653dcdc..f088a30 100644 --- a/tests/Commonage.BrowserTests/BehaviourTests.cs +++ b/tests/Commonage.BrowserTests/BehaviourTests.cs @@ -36,6 +36,22 @@ private async Task CreateItemAsync(IPage page, string title) return int.Parse(page.Url.Split('/').Last()); } + [Fact] + public async Task What_visitors_get_and_the_public_from_date_are_chosen_on_the_item_and_kept() + { + var page = await app.LogInAsync(); + var id = await CreateItemAsync(page, "Embargo form test"); + + await page.CheckAsync("#media-level-record"); + await page.FillAsync("[name='Input.PublicFrom']", "2099-01-01"); + await page.ClickAsync(Button("Save as draft")); + await page.WaitForURLAsync($"**/Admin/Items/Edit/{id}"); + await page.GotoAsync($"/Admin/Items/Edit/{id}"); + + Assert.True(await page.IsCheckedAsync("#media-level-record")); + Assert.Equal("2099-01-01", await page.InputValueAsync("[name='Input.PublicFrom']")); + } + [Fact] public async Task Answering_no_to_a_confirmation_stops_the_action() { diff --git a/tests/Commonage.Tests/EmbargoTests.cs b/tests/Commonage.Tests/EmbargoTests.cs new file mode 100644 index 0000000..b506fc8 --- /dev/null +++ b/tests/Commonage.Tests/EmbargoTests.cs @@ -0,0 +1,161 @@ +using System.IO.Compression; +using System.Text.Json; +using Commonage.Web; +using Commonage.Web.Data; +using Commonage.Web.Domain; +using Commonage.Web.Identity; +using Microsoft.EntityFrameworkCore; + +namespace Commonage.Tests; + +/// An embargo: a published item that is not public until the start of a day in the archive's time zone. +[Collection(nameof(AppCollection))] +public class EmbargoTests(CommonageAppFactory app) +{ + private sealed class FixedClock(DateTimeOffset now) : TimeProvider + { + public override DateTimeOffset GetUtcNow() => now; + } + + private async Task<(string Word, int ItemId, int CollectionId)> SeedAsync(ItemStatus status, DateOnly? publicFrom = null) + { + var word = TestData.UniqueWord("embargo"); + 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, PublicFrom = publicFrom }; + if (status == ItemStatus.Published) + item.Publish(now); + db.AddRange(collection, item); + await db.SaveChangesAsync(); + return (word, item.Id, collection.Id); + }); + } + + [Fact] + public async Task An_item_opens_at_the_start_of_its_day_in_the_archives_time_zone_and_not_a_second_before() + { + // Auckland is 13 hours ahead of UTC in March, so 1 March starts at 11:00 UTC on 28 February. + Dates.Zone.Value = TimeZoneInfo.FindSystemTimeZoneById("Pacific/Auckland"); + try + { + var seeded = await SeedAsync(ItemStatus.Published, new DateOnly(2030, 3, 1)); + var options = new DbContextOptionsBuilder().UseNpgsql(app.ConnectionString).Options; + async Task VisibleAtAsync(DateTimeOffset utc) + { + await using var db = new CommonageDbContext(options, new FixedClock(utc)); + return await db.VisibleItems.AnyAsync(i => i.Id == seeded.ItemId); + } + + Assert.False(await VisibleAtAsync(new DateTimeOffset(2030, 2, 28, 10, 59, 59, TimeSpan.Zero))); + Assert.True(await VisibleAtAsync(new DateTimeOffset(2030, 2, 28, 11, 0, 0, TimeSpan.Zero))); + } + finally + { + Dates.Zone.Value = null; + } + } + + [Fact] + public void An_embargo_moves_the_date_an_item_is_listed_by_to_the_day_it_opens_and_removing_it_brings_it_back() + { + Dates.Zone.Value = TimeZoneInfo.Utc; + try + { + var now = new DateTime(2030, 1, 10, 12, 0, 0, DateTimeKind.Utc); + var item = new ArchiveItem { Title = "A" }; + item.Publish(now); + + item.SetPublicFrom(new DateOnly(2030, 2, 1), now); + Assert.Equal(new DateTime(2030, 2, 1, 0, 0, 0, DateTimeKind.Utc), item.PublishedAt!.Value.ToUniversalTime()); + + item.SetPublicFrom(new DateOnly(2030, 1, 20), now); + Assert.Equal(new DateTime(2030, 1, 20, 0, 0, 0, DateTimeKind.Utc), item.PublishedAt!.Value.ToUniversalTime()); + + item.SetPublicFrom(new DateOnly(2030, 1, 1), now); + Assert.Equal(now, item.PublishedAt); + + item.SetPublicFrom(new DateOnly(2030, 2, 1), now); + item.SetPublicFrom(null, now); + Assert.Equal(now, item.PublishedAt); + } + finally + { + Dates.Zone.Value = null; + } + } + + [Fact] + public async Task A_curator_sets_the_date_and_it_is_recorded_while_a_helper_cannot() + { + 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}"; + Dictionary Form() => new() + { + ["Input.Title"] = $"Title {seeded.Word}", ["Input.CollectionId"] = seeded.CollectionId.ToString(), ["Input.PublicFrom"] = "2031-05-04", + }; + + await Browser.SendFormAsync(helper, page, Form(), page); + var afterHelper = await app.WithDbAsync(db => db.ArchiveItems.Where(i => i.Id == seeded.ItemId).Select(i => i.PublicFrom).SingleAsync()); + await Browser.SendFormAsync(admin, page, Form(), page); + var afterCurator = await app.WithDbAsync(db => db.ArchiveItems.Where(i => i.Id == seeded.ItemId).Select(i => i.PublicFrom).SingleAsync()); + var recorded = await app.WithDbAsync(db => db.AuditEntries.AnyAsync(e => e.Action == AuditAction.ItemPublicFromChanged && e.ArchiveItemId == seeded.ItemId)); + + Assert.Null(afterHelper); + Assert.Equal(new DateOnly(2031, 5, 4), afterCurator); + Assert.True(recorded); + } + + [Fact] + public async Task The_public_copy_of_the_export_leaves_out_an_embargoed_item_and_the_full_export_keeps_its_date() + { + var embargoed = await SeedAsync(ItemStatus.Published, DateOnly.FromDateTime(DateTime.UtcNow).AddDays(30)); + using var admin = app.CreateClient(); + await Browser.LogInAsCuratorAsync(admin); + + var published = await ItemIdsAsync(admin, publishedOnly: true); + var full = await ItemsAsync(admin, publishedOnly: false); + + Assert.DoesNotContain(embargoed.ItemId, published); + Assert.NotNull(full.Single(i => i.GetProperty("id").GetInt32() == embargoed.ItemId).GetProperty("publicFrom").GetString()); + } + + [Fact] + public async Task Many_items_can_be_embargoed_and_set_to_record_only_together_and_the_list_finds_them() + { + var one = await SeedAsync(ItemStatus.Published); + var two = await SeedAsync(ItemStatus.Published); + using var admin = app.CreateClient(); + await Browser.LogInAsCuratorAsync(admin); + var ids = $"{one.ItemId},{two.ItemId}"; + + var token = Browser.Token(await admin.GetStringAsync("/Admin")); + await admin.PostAsync("/Admin/Items/Bulk?handler=Apply", new FormUrlEncodedContent(new Dictionary + { ["__RequestVerificationToken"] = token, ["Action"] = "SetPublicFrom", ["Ids"] = ids, ["PublicFrom"] = "2099-01-01" })); + await admin.PostAsync("/Admin/Items/Bulk?handler=Apply", new FormUrlEncodedContent(new Dictionary + { ["__RequestVerificationToken"] = token, ["Action"] = "SetMediaLevel", ["Ids"] = ids, ["MediaLevel"] = "RecordOnly" })); + var state = await app.WithDbAsync(db => db.ArchiveItems.Where(i => i.Id == one.ItemId || i.Id == two.ItemId).Select(i => new { i.PublicFrom, i.MediaLevel }).ToListAsync()); + var embargoedList = await admin.GetStringAsync($"/Admin?needs=Embargoed&q=embargo"); + var recordList = await admin.GetStringAsync($"/Admin?needs=RecordOnly&q=embargo"); + + Assert.All(state, s => { Assert.Equal(new DateOnly(2099, 1, 1), s.PublicFrom); Assert.Equal(MediaLevel.RecordOnly, s.MediaLevel); }); + Assert.Contains($"Title {one.Word}", embargoedList); + Assert.Contains($"Title {two.Word}", recordList); + } + + private static async Task> ItemIdsAsync(HttpClient admin, bool publishedOnly) => + (await ItemsAsync(admin, publishedOnly)).Select(i => i.GetProperty("id").GetInt32()).ToList(); + + private static async Task> ItemsAsync(HttpClient admin, 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()); + return JsonDocument.Parse(await reader.ReadToEndAsync()).RootElement.GetProperty("items").EnumerateArray().Select(i => i.Clone()).ToList(); + } +} diff --git a/tests/Commonage.Tests/ExportTests.cs b/tests/Commonage.Tests/ExportTests.cs index 0182a29..a70d5b3 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 mediaLevel 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 publicFrom 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(7, document.GetProperty("version").GetInt32()); + Assert.Equal(8, document.GetProperty("version").GetInt32()); } [Fact] diff --git a/tests/Commonage.Tests/VisibilityMatrixTests.cs b/tests/Commonage.Tests/VisibilityMatrixTests.cs index b4da3ca..aeaf21b 100644 --- a/tests/Commonage.Tests/VisibilityMatrixTests.cs +++ b/tests/Commonage.Tests/VisibilityMatrixTests.cs @@ -54,10 +54,12 @@ 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); }); + var embargoed = await SeedAsync("embargoed", (i, now) => { i.Publish(now); i.SetPublicFrom(DateOnly.FromDateTime(now).AddDays(3), now); }); + var opened = await SeedAsync("opened", (i, now) => { i.Publish(now); i.SetPublicFrom(DateOnly.FromDateTime(now).AddDays(-3), now); }); using var visitor = app.CreateClient(); var everything = new StringBuilder(); - foreach (var marked in new[] { shown, draft, binned }) + foreach (var marked in new[] { shown, opened, draft, binned, embargoed }) { foreach (var address in Addresses) everything.Append(await TextAsync(visitor, string.Format(address, marked.Word))); @@ -67,7 +69,8 @@ public async Task Only_published_items_show_up_anywhere_a_visitor_can_look() var text = everything.ToString(); Assert.Contains($"Title {shown.Word}", text); - foreach (var hidden in new[] { draft, binned }) + Assert.Contains($"Title {opened.Word}", text); + foreach (var hidden in new[] { draft, binned, embargoed }) foreach (var part in new[] { "Title ", "Words ", "Credit ", "Alt ", "Caption ", "Pages ", "Box ", "P " }) Assert.DoesNotContain(part + hidden.Word, text); } @@ -76,11 +79,15 @@ public async Task Only_published_items_show_up_anywhere_a_visitor_can_look() public async Task A_collection_of_hidden_items_has_no_page_card_or_sitemap_entry() { var draft = await SeedAsync("onlydraft", (_, _) => { }); + var embargoed = await SeedAsync("onlyembargoed", (i, now) => { i.Publish(now); i.SetPublicFrom(DateOnly.FromDateTime(now).AddDays(3), now); }); 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")); + foreach (var hidden in new[] { draft, embargoed }) + { + Assert.Equal(HttpStatusCode.NotFound, (await visitor.GetAsync($"/collections/{hidden.CollectionId}")).StatusCode); + Assert.DoesNotContain($"/collections/{hidden.CollectionId}\"", await TextAsync(visitor, "/collections")); + Assert.DoesNotContain($"/collections/{hidden.CollectionId}<", await TextAsync(visitor, "/sitemap.xml")); + } } [Fact] @@ -88,9 +95,10 @@ 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); }); + var embargoed = await SeedAsync("pictureembargoed", (i, now) => { i.Publish(now); i.SetPublicFrom(DateOnly.FromDateTime(now).AddDays(3), now); }); using var visitor = app.CreateClient(); - foreach (var hidden in new[] { draft, binned }) + foreach (var hidden in new[] { draft, binned, embargoed }) foreach (var variant in new[] { "preview", "thumbnail", "card", "large" }) Assert.Equal(HttpStatusCode.NotFound, (await visitor.GetAsync($"/media/{hidden.FileId}/{variant}")).StatusCode); } @@ -99,9 +107,11 @@ public async Task The_pictures_of_hidden_items_are_not_served_to_visitors() public async Task A_visitor_cannot_open_the_note_form_of_a_hidden_item() { var draft = await SeedAsync("notedraft", (_, _) => { }); + var embargoed = await SeedAsync("noteembargoed", (i, now) => { i.Publish(now); i.SetPublicFrom(DateOnly.FromDateTime(now).AddDays(3), now); }); using var visitor = app.CreateClient(); - Assert.Equal(HttpStatusCode.NotFound, (await visitor.GetAsync($"/items/{draft.ItemId}/tell")).StatusCode); + foreach (var hidden in new[] { draft, embargoed }) + Assert.Equal(HttpStatusCode.NotFound, (await visitor.GetAsync($"/items/{hidden.ItemId}/tell")).StatusCode); } [Fact]