diff --git a/CHANGELOG.md b/CHANGELOG.md index fc69394..24179b2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,19 @@ All notable changes to Commonage. Versions follow [Semantic Versioning](https://semver.org/); before 1.0, a minor version may change things that need attention when updating, and these notes say so. +## Unreleased + +### For curators + +- **Stories, first part.** Under "Stories" in the admin area, curators write a story: a title, a few words of summary, and + parts in order, each a text or one of the items of the archive with a caption. A story can be moved up and down in the + list, and its parts within it, with buttons that work without JavaScript and keep the place on the page. The preview shows + it as visitors will see it: a part with an item that is not public is left out. A story with parts that visitors cannot + see says so on the page, only here. Publishing a story changes nothing for visitors yet; the public pages come in a later + part. Helpers do not see stories. +- **Export format 9** has `stories` after `items`. An export of published items has only published stories and the parts + whose item is in it. An import counts the stories in the dry run and does not import them. The demo archive has a story. + ## 0.6.0 (2026-11-23) Updating needs no picture regeneration. Migrations run by themselves at start. **This update moves the database to diff --git a/docs/operations.md b/docs/operations.md index 558d0b0..c5975d2 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -239,7 +239,7 @@ file is kept in `import-staging` on the media volume until the import is done, o the spreadsheet import and runs inside one web request, so the reverse proxy needs the same long timeout. Limits: a ZIP of at most 4 GB; `archive.json` at most 256 MB when unpacked, counted as it is read; at most 20,000 items, 5,000 collections, 50,000 tags and 500 files per item and 100,000 files in all; at most 8 GB of files in all; at most 50 new collections per run; the dry run keeps -at most 10,000 lines and counts the rest. The format versions 4 to 8 are read. Every +at most 10,000 lines and counts the rest. The format versions 4 to 9 are read. Stories in an export are counted in the dry run and not imported. Every item is a draft, and the activity log records the run ("Imported items from a Commonage export", with counts only) and each new collection, never a title of the other archive's contributors or their details. The database is only added to: nothing is changed or removed, so a run that breaks off can be run again. A file that cannot be stored (a full disk, a broken ZIP entry) is @@ -281,7 +281,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": 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` +`archive.json` has `"format": "commonage-export"` and `"version": 9`. Version 9 added `stories`, after `items`: each story has its `title`, `summary`, `status`, `createdAt`, `publishedAt`, `position` and its `blocks` in order, and a block is a `Text` (with `text`) or an `Item` (with the `itemId` of an item under `items`, and a `caption`). An export of published items has only published stories, and in them only the blocks of items that are in that export. A copy of everything leaves out stories in the bin and the blocks of items in the bin. 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/plan-m29-stories.md b/docs/plan-m29-stories.md new file mode 100644 index 0000000..0c39b43 --- /dev/null +++ b/docs/plan-m29-stories.md @@ -0,0 +1,225 @@ +# Plan for M29: stories and exhibitions + +Status: **decided (see "Decisions"); part 1 not started.** Three parts, in this order, each its own pull request, all three in +one release. The plan goes to the `privacy-reviewer` agent before part 1 starts, because part 2 adds public addresses that show +items by reference. The agent runs again after each part. Run `/gate` before each push and `/walkthrough` for the pages. Commit +subjects follow `M29, first part: ...`. + +## What is wanted + +A curator puts together a **story**: a title, a short summary and an ordered list of **blocks**. A block is plain text written by +the curator, or a reference to an item with an optional caption written by the curator. Visitors read it at `/stories/{id}` in +one layout. Roadmap "Later", item 1. + +Kept out on purpose: rich text, Markdown or HTML; more than one layout; drag-and-drop (ordering uses "Move earlier / Move +later" buttons, as photos and collections do); choosing which photo of an item a block shows (it uses the item's card picture); +an embargo date for a story; stories in the feed, in search, in JSON or Dublin Core; reading stories when importing an export; a +"Part of the story" link on the item page. + +## The rule, stated once + +**A story is public when it is published, not in the bin, and has at least one visible block. Its item blocks show only items +that `Visibility.Item(today)` allows, and only what `ItemSummary.FromItem` shows of them (no picture for a record-only item). +A block whose item is hidden is left out without a trace: no placeholder, no caption, no item number, no link, no count.** + +The rule lives in `Data/` only, as it does for M27: + +- `Visibility.Story(DateOnly today)` in `Data/Visibility.cs`: published, and at least one text block or one item block whose item + passes the item rule. The item condition is built from `Visibility.Item`, never a second spelling of `ItemStatus.Published`. + The explicit `DeletedAt == null` is belt and braces on top of the query filter. +- `CommonageDbContext.VisibleStories` and `BinnedStories` (`IgnoreQueryFilters`, `DeletedAt != null`). +- `Data/VisibleStoryBlocks.cs`: `LoadAsync(db, storyId, ct)` returns `StoryBlockView` (`Text` or `Item(ItemSummary, Caption)`). + It reads the block rows, runs **one** query `db.VisibleItems.Where(i => ids.Contains(i.Id)).Select(ItemSummary.FromItem)` and + drops every item block whose id is missing. Public code never follows `StoryBlock.ArchiveItem`. Pictures come only through + `ItemSummary.ThumbnailMediaFileId` (null for record-only), served by the existing `/media/{id}/thumbnail`. +- The curator preview uses the same `LoadAsync`, so the preview shows what a visitor will see. + +## Data model + +Migration `AddStories` (after `ItemPublicFrom`). New `Domain/Story.cs`: + +| Column | Type | Meaning | +|---|---|---| +| Id | int | Key; the address is `/stories/{id}` | +| Title | string, required, max 200 | Plain text | +| Summary | string?, max 1000 | Lead paragraph, list text and link preview description | +| Status | `StoryStatus` (Draft, Published), stored as a string | Not `ItemStatus`: a story has no contribution states | +| CreatedAt, UpdatedAt | DateTime (UTC) | From `TimeProvider` | +| PublishedAt | DateTime? | Set by `Publish(now)`, kept by `Unpublish()` as for items | +| DeletedAt | DateTime?, private set | Bin; query filter `DeletedAt == null` | +| Position | int, indexed | Order on `/stories` and in the admin list | +| Version | uint, `IsRowVersion` (xmin) | Concurrency for the title/summary form | +| Blocks | `List` | Cascade | + +Methods `Publish`, `Unpublish`, `MoveToBin`, `RestoreFromBin`, `Touch`, shaped like `ArchiveItem`. + +`StoryBlock`: Id; StoryId (cascade); Position (renumbered 0..n-1 after every change); Kind (`StoryBlockKind` Text or Item, string); +Text (max 20000, Text only); ArchiveItemId (Item only, FK **cascade**); Caption (max 1000, Item only; hidden whenever the item is). +Check constraint: Text kind has Text and no item, Item kind has an item and no Text. Indexes `(StoryId, Position)` and +`ArchiveItemId`. Query filter `b => b.Story.DeletedAt == null`. Limit of 200 blocks per story, enforced in the page model. + +`AuditEntry` gets `int? StoryId` (FK `SetNull`). `AuditEntry` is not exported. + +## Public surface (part 2) + +| Surface | Change | +|---|---| +| `/stories` | `VisibleStories` ordered by `Position, Id`: title, summary, the first visible item card's picture as cover or a text tile; paged like collections; "No stories yet." with 200 | +| `/stories/{id:int}` | 404 unless in `VisibleStories`; the same `NotFound()` for unknown, draft, binned and all-hidden | +| Start page | A "Stories" section with the first three when any is visible; no header link | +| `/sitemap.xml` | `/stories` and each visible story (follows `AllowSearchEngines`, `public, max-age=600`) | +| `/feed.xml`, `/search`, JSON, Dublin Core | Unchanged: stories are not in them | +| Link preview | The story's title and summary, **no image**, nothing from an item | +| `/media/...` | Unchanged; item thumbnails go through the existing visibility checks | + +Story page: `
`, `

`, summary as lead; a text block is `text-preserve-lines` with `lang` of the material language; an +item block is a `
` with the shared card partial (split from `_ItemCards.cshtml`) and a `
`; breadcrumb; works +without JavaScript; logical CSS properties only. + +## Curator screens (part 1) + +Under `/Admin/Stories`, `Policies.ManageArchive`, a "Stories" link in the admin navigation next to Collections. + +- **Index**: title, status, block count and hidden-block count (`T.Plural`), move earlier/later, a "New story" form (title only). +- **Edit**: title and summary form (`data-warn-unsaved`, `Version`; a conflict keeps the typed text); Publish/Unpublish, Preview, + Move to bin (reversible, no confirm). Blocks in order, each with an anchor: text blocks have a textarea form; item blocks show + the card, a caption form and, when visitors do not see the item, why (localized when shown: draft, public from {date}, in the + bin, withdrawn; "Visitors see this item without its photos." for record-only). Every block has Move earlier, Move later and + Remove (`data-confirm`). "Add text" and "Add an item" (item number or an `/items/{n}` or `/Admin/Items/Edit/{n}` address; binned + or unknown items refused, rejected and withdrawn refused, drafts and embargoed accepted with a note). After a move or add the + page redirects to the block's anchor with `data-focus-on-load`, as the photo order does. +- **Preview**: `_StoryBody` through `VisibleStoryBlocks` with a banner. +- **Item edit page** (part 3): "Used in N stories" with links, and a note when unpublishing or binning an item removes it from + published stories. + +## Privacy rules in detail + +1. Draft, waiting, rejected, withdrawn items: dropped with their caption. +2. Embargoed: dropped until the day, using the injected `TimeProvider`. +3. Record-only: title, date and link, no picture. +4. In the bin: dropped; restoring the item brings the block back. +5. Deleted for good: the block goes with it (cascade). +6. Contributor did not agree to sharing beyond the website: the card shows on the website as items do; nothing reaches a surface + that travels (preview has no image or item text, no feed, no JSON). +7. No leak of existence: a hidden block leaves no figure, id, caption, empty slot or "removed" text; a story with only hidden + blocks answers the same 404; hidden-block counts exist only under `/Admin`. +8. Computed on each request; the sitemap may lag up to ten minutes (already accepted in `security.md`). +9. Curator text and captions are the curator's words and are not checked; the handbook says so. +10. A story draft is never public. + +## Bin, audit, roles + +- Stories go to the bin for 30 days (`Story.MoveToBin`); Bin page "Stories" section (restore, delete for good with confirm); + `ArchiveBin.DeleteStoryAsync` and a purge step with `StoryPurged`. Binned stories are not exported. +- New `AuditAction` values, added at the end: `StoryCreated, StoryChanged, StoryPublished, StoryUnpublished, StoryItemAdded, + StoryItemRemoved, StoryBlocksArranged, StoriesArranged, StoryMovedToBin, StoryRestored, StoryDeleted, StoryPurged`; new + `AuditKind.Stories`; texts in `AuditText.Describe`, kinds in `KindOf`. `AuditLog.Record` takes an optional story; item + add/remove also name the item. `StoryBlocksArranged` is recorded once per 30-minute sitting, like photos. Every handler + records before `SaveChanges`. +- Roles: helpers get nothing (403); curators and admins everything. + +## Export and import + +- `ArchiveExporter.Version` 8 to 9; `archive.json` gets a `"stories"` array (streamed) with `ExportStory` and `ExportStoryBlock`. +- Full export: stories not in the bin and blocks whose item is not in the bin. Published-only export: `VisibleStories` and only + the blocks `VisibleStoryBlocks` keeps, so a hidden item's id and caption never reach a public copy. +- `ExportTests` field list gets both types. **The import does not read stories**: `ExportImportTable` lists both as `Dropped` + with the reason that their items arrive as drafts with new numbers; the dry run shows one plural line counting them (a capped + counter, never deserialising the stories). Version 9 must be accepted. +- `docs/operations.md` format section and the export README text name stories. + +## Languages + +Only curator content is stored (title, summary, text, caption, the audit subject). Status words, "Untitled", the hidden-block +reasons and messages are localized when shown. Every new text is written out in `T[...]` or `T.Plural(...)` (ICU), has a German +entry, and the base file is rewritten. "Earlier/later", never up/down or left/right. + +## Tests + +1. `StoryVisibilityMatrixTests` (copy the seeding from `VisibilityMatrixTests`): a published story with a text block, a visible + item A with a caption and an item B (own title word, caption and photo) in each state: draft, waiting, rejected, withdrawn, + embargoed, in the bin, record-only, contributor not sharing, published. On `/stories`, `/stories/{id}`, `/`, `/sitemap.xml`, + `/feed.xml`, `/search`, `/items/{B}` and B's thumbnail: hidden states show none of B's title, caption, id or file, and the + story page HTML equals the page without block B (after the token and id are normalised); record-only shows title and link + but no picture; not-sharing has nothing of B in any `og:` tag or the feed; story text never appears in search or the feed. +2. A draft, a binned story, an all-hidden story and an unknown id give an identical 404 and appear nowhere. +3. Change over time with the clock moved: embargo opens, publish/unpublish, bin and restore an item, delete an item for good. +4. `VisibilityGuardTests`: forbid `StoryStatus.Published`, `db.Stories`, `StoryBlocks` and `.Blocks` in public code. +5. `EndpointAccessTests` lists `/stories` and `/stories/{id:int}` as meant for visitors. +6. `HelperTests`: 403 on every Stories page and handler. +7. `StoryEditTests`: create, edit, publish, unpublish, add text and items (number and address), refusals, the block limit, move at + both ends, a block of another story gives 404, the `Version` conflict, an audit entry per handler, one arranged entry per sitting. +8. Bin tests (part 3): bin, restore, delete, purge after 30 days. +9. Audit tests: every action has a kind and a text; the Activity filter offers "Stories". +10. Export tests: field lists, published-only and full exports as above, version 9, import dry run counts and creates nothing. +11. Browser tests for each reused behaviour: keyboard move keeps focus; the same move without JavaScript; Remove asks first; + leaving an edited text block warns. +12. `AccessibilityTests`: public pages `/stories` and `/stories/1`; curator pages Index, Edit, Preview; `/stories/1` in the RTL + and long-text runs. +13. Demo: a story at the end of the seeding ("Mill Street over thirty years": three text blocks, three published items with + captions, one block naming the demo draft); a browser test checks the draft's title is absent publicly and present with + its status line under `/Admin`. + +## Parts + +| Part | Content | Behaviour change | +|---|---|---| +| 1. Stories for curators | Model, migration (with `AuditEntry.StoryId`), `Visibility.Story`, `VisibleStories`, `VisibleStoryBlocks`, `/Admin/Stories` Index, Edit, Preview and `_StoryBody`, folder policy, audit, export version 9 and import table, demo story, tests 4, 6, 7, 9, 10, 11 and the curator half of 12, German entries, CHANGELOG | None for visitors | +| 2. Stories for visitors | `/stories`, `/stories/{id}`, start page, sitemap, link preview, card partial; tests 1, 2, 3, 5 and the public half of 12; security.md rows; German entries; CHANGELOG | Published stories become public. The `privacy-reviewer` must pass this part before merging | +| 3. Bin, item page, handbook | Story bin and purge, "Used in N stories", handbook in English and German, roadmap table (the milestone table is duplicated near lines 531 to 730: fix that), test 8, `/walkthrough` | Curators can bin stories | + +## Security rows (docs/security.md) + +Stories (public only when published, not in the bin and with a visible block; item blocks only through `VisibleStoryBlocks`; a +hidden story answers the same 404), stories beyond the website (no image or item text in the preview; not in feed, search, JSON), +stories in an export (published-only holds visible stories and blocks; the import does not read them). Known limit: story text +and captions are not checked and can name a hidden item or person; the sitemap may list a hidden story for up to ten minutes. + +## Risks + +- A later page reads `story.Blocks.Select(b => b.ArchiveItem...)`: stopped by the guard test and the "same page without the + block" matrix check. +- A caption about a hidden item is the likeliest leak: it is dropped with its block, also in the published-only export. +- Removing a text block is immediate (with a confirm); there is no history for story text. Say so in the handbook; a history is + a follow-up if wanted. +- EF query-filter warnings for `StoryBlock` reaching `ArchiveItem`: `VisibleStoryBlocks` never relies on the navigation. +- Two older places use `DateTime.UtcNow` (the feed's updated fallback and the item citation); new code uses `TimeProvider`. + +## Changes after the privacy review + +The `privacy-reviewer` found no design-level leak and asked for these, which are part of the plan: + +1. **No trace in the HTML.** The public `_StoryBody` emits no block id, position, anchor, `data-` attribute or "n of m". Anchors + and ids exist only on the Edit page. The "same page without block B" test normalises only the antiforgery token (not ids) and + has a case with a hidden block between two visible ones. +2. **Block changes never touch the story row.** Block handlers save only `StoryBlock` rows: no `Touch`, no `Version` bump (an + open title form must not report a conflict), and moving a block leaves `Story.UpdatedAt` alone. The sitemap has no `lastmod` + for stories, the page shows no "updated" date, and no ETag or `Last-Modified` derives from block or item data. Test: a block + move leaves `Version` unchanged. +3. **The rule's shape.** `Visibility.Item` is an expression over `ArchiveItem` and cannot be applied to a navigation. The story + rule is a method on the context: `db.VisibleItems.Any(i => i.Id == b.ArchiveItemId)` inside the story query, so embargo and + withdrawn come with it. The guard test also forbids `.ArchiveItem` and `b.ArchiveItem` under `Pages/Stories` and + `Pages/Index`. Test: a story whose only item is embargoed answers 404 until the day. +4. **`StoryBlock.ArchiveItemId` is a nullable optional FK with cascade.** Admin code that labels blocks looks items up with + `IgnoreQueryFilters`; public code loads by id through `VisibleItems`. Test: deleting an item for good leaves the story with + its other blocks in order. +5. **`/stories` is computed from visible rows only**: total, paging and covers. Covers come from one query, not one per story, + and the page size is capped. Test: `/stories` is byte-identical with and without a hidden story. +6. **Link preview and sitemap.** The preview holds no item text, id or picture; when the summary is empty the description is empty + (never the first text block). A story cover must never go into `og:image` without a `MayTravel` check (comment in the code). + Story ids are sequential, so a gap is visible, as for items: listed under known limits. +7. **A published-only export is a public copy**, so captions of visible items travel with it; this is intended (the items do too). + `Today` is captured once and used for both the items and the stories, and a test checks that no block in a published-only + export names an item missing from `items`. +8. **404 comparison includes headers** (`Cache-Control`, `Vary`), not only status and body. + +## Decisions + +All recommended answers accepted by the maintainer (Seb H.) on 2026-11-23: + +1. Helpers do not draft stories; only curators and admins. +2. Stories are not in `/feed.xml`. +3. Stories are not searched in M29. +4. The import does not read stories (counted and reported in the dry run). +5. A block goes when its item is deleted for good. +6. A published story whose blocks are all hidden answers 404, like a draft. diff --git a/docs/security.md b/docs/security.md index 59f64b4..7398f9f 100644 --- a/docs/security.md +++ b/docs/security.md @@ -29,6 +29,7 @@ vulnerability, see [SECURITY.md](../SECURITY.md). | Import | Only curators (the `/Admin` policy). The sheet and ZIP are kept in `import-staging` on the media volume, which is never served by path, for a day at most. A sheet is read as strict UTF-8, at most 20 MB and 100,000 rows; a ZIP at most 4 GB and 200,000 entries; every entry is counted as it is unpacked into a temporary file, and a name inside it is never used in a path. A folder to import from is chosen from a listing of `import/`, links and hidden files are skipped. Files go through the same checks as an upload. One import at a time. Everything imported is a draft; the activity log records each item and the import, never the spreadsheet or the contributors' details. `ImportTests`. | | Reading an export | Admins only (`Administer`), the dry run is `private, no-store`. Same staging folder, one-at-a-time lock and file checks as the spreadsheet import; the ZIP is at most 4 GB and 200,000 entries, `archive.json` at most 256 MB counted as it is unpacked (a ZIP entry's declared size is not trusted), parsed with a depth limit and capped lists (20,000 items, 5,000 collections, 50,000 tags, 500 files per item, 100,000 files in all), at most 8 GB of files in all, 50 new collections per run and 10,000 recorded lines in the dry run (the rest is counted). A file is taken only under the exact path `files//-`, unique, never by name and never as a path on disk; its type and size are found from the bytes and its sha256 must match. Unknown values are lines in the dry run, not exceptions. **Decision on consent:** a contributor's name, email address, consent text, rights statement and reference code, visitor notes, internal notes and received-from are never deserialised or stored (`ExportImportTable` decides every property of the export, and `ExportImportTests` fails when the exporter gains one without a decision); only whether the contributor agreed to sharing is read, and an item with a contribution that does not say yes (no, null or no answer at all), or one rejected or withdrawn, is left out. The ZIP is staged in a folder and file only the app's account can read (Linux and macOS), and a file that cannot be stored costs only that file, counted without the error text; the run is not cancelled by closing the tab. Everything arrives as a draft, whatever its status, and the code only inserts (a test reads the source for publishing, removing and unfiltered queries). `ExportImportTests`. | | Earlier texts | `ItemRevisions` keeps what a title, description, date, credit, original location or reference number said before a change, with the account that changed it (its name at the time) and when. The fields are a fixed list (`RevisionField`): never a contributor's name or email, the internal notes or where an item was received from, so removing a contributor's details never has to touch it. Who changed it is forgotten on the activity log's schedule (`ActivityLogKeptYears`); the text itself stays with the item. Shown on the item's admin page only; a curator may restore, a helper only reads. The rows go with their item (cascade, hidden while it is in the bin) and are not exported. `RevisionTests`, `ExportTests`. | +| Stories | Curators and admins only (`ManageArchive`; a helper gets 403 on every page and handler). A story is text and item parts in a chosen order; part 1 has no public page. What visitors will be able to see is decided in one place: `Visibility.Story` and `VisibleStoryBlocks` (a published story, and only the parts whose item passes `Visibility.Item` with the day; a story with no visible part is as hidden as a draft). The curator pages show hidden items to curators only and say why visitors do not see them. Input is limited on the server (title 200, summary 1,000, text 20,000, caption 1,000 characters, 200 parts per story); an item is added by number or by a page address on this site, never by path. Block handlers are scoped to their story and never save the story row. Accepted: a removed part is deleted at once (the bin covers whole stories, from part 3; the confirmation says so). The export lists stories (`stories`, format 9): a copy of what is public holds published stories with only parts whose item is in the copy, a full copy holds drafts, and the bin is never exported. The import only counts stories (`StoryCountConverter` skips them) and creates nothing. `StoryEditTests`, `VisibilityGuardTests`, `ExportTests`, `ExportImportTests`. | | Recordings | Only curators can add a recording (MP3, M4A, WAV, FLAC, recognised by their first bytes); contribution links refuse them. Visitors hear only a copy made by the app itself (`AudioTools`, no outside program): the sound is copied byte for byte, and ID3v2/ID3v1/APE tags (MP3), `udta`, `meta`, `uuid` and padding boxes and the dates in the headers (M4A), every chunk except `fmt `, `fact` and `data` (WAV), and every block except stream info and the seek table (FLAC) are left out. A file that is not built as its type says (impossible sizes, missing parts, fragmented M4A) fails and has no copy, so nothing is ever served untouched. The parser is managed code reading sizes against the file's length, with the header of an M4A limited to 64 MB; it runs on the single preview queue and a failure marks only that file. Served for published items only, from `/media/{id}/audio` with range requests, with its own copy (`audio/…` key); the original is only at `/admin/media/{id}/original` for curators. Accepted: the sound itself may contain a voice that identifies someone, which is what an oral history is; curators decide what to publish. `AudioTests`. | | PDF files | Only curators can add a PDF; contribution links refuse it. A PDF is recognised by `%PDF-` and read by poppler (`pdfinfo`, `pdftoppm`), a large C++ parser, so it runs as separate processes, never inside the app: each call has a time limit (`Uploads:PdfTimeoutSeconds`, 60) and is killed with its children when it takes longer, the size of the drawn picture is set by us with `-scale-to` whatever size the page claims, at most 300 pages are drawn, and no part of the file or its name reaches a command line (arguments are passed as a list, the file is copied to a random name in an owner-only temporary folder that is removed afterwards). Pages are served only for published items; the PDF stays private. Accepted: a hostile PDF made by a curator could still exploit poppler, which runs with the app's rights in the container; build with `WITH_PDF=false` to remove it. `poppler-utils` comes from the distribution at build time and is not pinned to a version, so a rebuild of the same commit can ship another poppler (accepted; the base image digest is pinned). The text of a PDF (`pdftotext`, same limits, control characters removed, at most 200,000 characters) is only matched by search, never shown, and it is in the index only while the item is not in the bin and the PDF is not in the bin; a draft is found only by curators, as before. The preview queue is single, so a very long PDF delays other previews (at most 60 s per page); copies of a PDF left by a stopped app are removed at the next start. | | Uploads | Files are recognised by their content (magic bytes), never by name or browser type, and stored under random names outside the web root. Originals are never changed or served to visitors. Previews are made by libvips, rotated upright and stripped of all metadata. Images over 250 megapixels get no preview (decompression bombs), also for GIF and AVIF (`Images_with_more_pixels_than_the_limit_get_no_preview`). GIF and AVIF (libheif with an AV1 decoder, from M23) are further decoders reachable from a contribution link; a GIF is read as its first frame only. There is no time limit on a decode, so a very large AVIF costs memory and time on a small server; the pixel limit and the three-attempt guard are the protection. Size limits per file and per request. A file that the preview maker fails on, in whatever way, costs only its own preview, and one that takes the app down is given up after three attempts instead of at every start (`PreviewFailureTests`). | diff --git a/src/Commonage.Web/Audit/AuditLog.cs b/src/Commonage.Web/Audit/AuditLog.cs index 21d85fe..40b4f90 100644 --- a/src/Commonage.Web/Audit/AuditLog.cs +++ b/src/Commonage.Web/Audit/AuditLog.cs @@ -19,6 +19,15 @@ public Task RecordPhotosAddedAsync(ArchiveItem item, CancellationToken cancellat public Task RecordPhotosArrangedAsync(ArchiveItem item, CancellationToken cancellationToken) => RecordOncePerSittingAsync(AuditAction.PhotosArranged, item, cancellationToken); + /// Putting the blocks of a story in order takes many moves; one sitting of them is one entry. + public async Task RecordStoryBlocksArrangedAsync(Story story, CancellationToken cancellationToken) + { + var userId = httpContextAccessor.HttpContext?.User.FindFirstValue(ClaimTypes.NameIdentifier); + var since = clock.GetUtcNow().UtcDateTime.AddMinutes(-30); + if (!await db.AuditEntries.AnyAsync(e => e.StoryId == story.Id && e.Action == AuditAction.StoryBlocksArranged && e.UserId == userId && e.At > since, cancellationToken)) + Record(AuditAction.StoryBlocksArranged, story.Title, story: story); + } + private async Task RecordOncePerSittingAsync(AuditAction action, ArchiveItem item, CancellationToken cancellationToken) { var userId = httpContextAccessor.HttpContext?.User.FindFirstValue(ClaimTypes.NameIdentifier); @@ -43,18 +52,18 @@ public void RecordRevision(ArchiveItem item, RevisionField field, string? oldVal }); } - public AuditEntry Record(AuditAction action, string? subject, ArchiveItem? item = null) + public AuditEntry Record(AuditAction action, string? subject, ArchiveItem? item = null, Story? story = null) { var user = httpContextAccessor.HttpContext?.User; var signedIn = user?.Identity?.IsAuthenticated == true; - return Add(action, subject, item, signedIn ? user!.FindFirstValue(ClaimTypes.NameIdentifier) : null, signedIn ? user!.Identity!.Name : null); + return Add(action, subject, item, signedIn ? user!.FindFirstValue(ClaimTypes.NameIdentifier) : null, signedIn ? user!.Identity!.Name : null, story); } /// For what an account does while it logs in, before the request knows who it is. public void RecordFor(Microsoft.AspNetCore.Identity.IdentityUser account, AuditAction action, string? subject) => - Add(action, subject, null, account.Id, account.UserName); + Add(action, subject, null, account.Id, account.UserName, null); - private AuditEntry Add(AuditAction action, string? subject, ArchiveItem? item, string? userId, string? userName) + private AuditEntry Add(AuditAction action, string? subject, ArchiveItem? item, string? userId, string? userName, Story? story) { var entry = new AuditEntry { @@ -63,6 +72,7 @@ private AuditEntry Add(AuditAction action, string? subject, ArchiveItem? item, s UserName = userName, Action = action, ArchiveItem = item, + Story = story, Subject = subject is { Length: > AuditEntry.SubjectMaxLength } ? subject[..AuditEntry.SubjectMaxLength] : subject, }; db.AuditEntries.Add(entry); diff --git a/src/Commonage.Web/Audit/AuditText.cs b/src/Commonage.Web/Audit/AuditText.cs index 4c9bd5f..65a225e 100644 --- a/src/Commonage.Web/Audit/AuditText.cs +++ b/src/Commonage.Web/Audit/AuditText.cs @@ -10,6 +10,7 @@ public enum AuditKind Photos, Contributions, Collections, + Stories, Tags, Accounts, Archive, @@ -46,6 +47,18 @@ public static class AuditText AuditAction.CollectionChanged => localizer["Changed the collection"], AuditAction.CollectionMoved => localizer["Changed the order of the collections"], AuditAction.CollectionDeleted => localizer["Deleted the empty collection"], + AuditAction.StoryCreated => localizer["Created the story"], + AuditAction.StoryChanged => localizer["Changed the story"], + AuditAction.StoryPublished => localizer["Published the story"], + AuditAction.StoryUnpublished => localizer["Unpublished the story"], + AuditAction.StoryItemAdded => localizer["Added an item to the story"], + AuditAction.StoryItemRemoved => localizer["Removed an item from the story"], + AuditAction.StoryBlocksArranged => localizer["Changed the order of the parts of the story"], + AuditAction.StoriesArranged => localizer["Changed the order of the stories"], + AuditAction.StoryMovedToBin => localizer["Moved the story to the bin"], + AuditAction.StoryRestored => localizer["Took the story out of the bin"], + AuditAction.StoryDeleted => localizer["Deleted the story for good"], + AuditAction.StoryPurged => localizer["Deleted the story after its time in the bin"], AuditAction.VisitorNoteReceived => localizer["A visitor sent a note about the item"], AuditAction.VisitorNoteHandled => localizer["Marked a visitor's note as dealt with"], AuditAction.VisitorNoteReopened => localizer["Opened a visitor's note again"], @@ -99,6 +112,9 @@ or AuditAction.VisitorNoteReceived or AuditAction.VisitorNoteHandled or AuditAct or AuditAction.VisitorNoteDetailsRemoved or AuditAction.VisitorNoteDeleted => AuditKind.Contributions, AuditAction.CollectionCreated or AuditAction.CollectionChanged or AuditAction.CollectionMoved or AuditAction.CollectionDeleted or AuditAction.CollectionCreatedByImport => AuditKind.Collections, + AuditAction.StoryCreated or AuditAction.StoryChanged or AuditAction.StoryPublished or AuditAction.StoryUnpublished + or AuditAction.StoryItemAdded or AuditAction.StoryItemRemoved or AuditAction.StoryBlocksArranged or AuditAction.StoriesArranged + or AuditAction.StoryMovedToBin or AuditAction.StoryRestored or AuditAction.StoryDeleted or AuditAction.StoryPurged => AuditKind.Stories, AuditAction.TagChanged or AuditAction.TagsMerged or AuditAction.TagDeleted or AuditAction.UnusedTagsDeleted => AuditKind.Tags, AuditAction.AccountCreated or AuditAction.AccountRoleChanged or AuditAction.AccountNameChanged or AuditAction.AccountDisabled or AuditAction.AccountEnabled or AuditAction.AccountDeleted or AuditAction.SetupLinkCreated or AuditAction.PasswordChanged @@ -115,6 +131,7 @@ AuditAction.ArchiveExported or AuditAction.ArchiveExportedWithPersonalData or Au AuditKind.Photos => localizer["Photos"], AuditKind.Contributions => localizer["Contributions, links and notes from visitors"], AuditKind.Collections => localizer["Collections"], + AuditKind.Stories => localizer["Stories"], AuditKind.Tags => localizer["Tags"], AuditKind.Accounts => localizer["Accounts and logins"], AuditKind.Archive => localizer["Export, settings and the log itself"], diff --git a/src/Commonage.Web/Data/CommonageDbContext.cs b/src/Commonage.Web/Data/CommonageDbContext.cs index b47c575..67760d6 100644 --- a/src/Commonage.Web/Data/CommonageDbContext.cs +++ b/src/Commonage.Web/Data/CommonageDbContext.cs @@ -12,6 +12,8 @@ public class CommonageDbContext(DbContextOptions options, Ti { public DbSet Collections => Set(); public DbSet ArchiveItems => Set(); + public DbSet Stories => Set(); + public DbSet StoryBlocks => Set(); public DbSet MediaFiles => Set(); public DbSet ItemFileTexts => Set(); public DbSet StaffProfiles => Set(); @@ -57,6 +59,15 @@ public class CommonageDbContext(DbContextOptions options, Ti /// Items in the bin. Query filters hide them from every other query, see . public IQueryable BinnedItems => ArchiveItems.IgnoreQueryFilters().Where(i => i.DeletedAt != null); + /// + /// Stories the public may read: published, not in the bin and with at least one block visitors may see. Every public story + /// page must start from this query, and show blocks only through . + /// + public IQueryable VisibleStories => Visibility.Story(this, Today); + + /// Stories in the bin. Query filters hide them from every other query. + public IQueryable BinnedStories => Stories.IgnoreQueryFilters().Where(s => s.DeletedAt != null); + /// Photos in the bin on their own. The photos of an item in the bin go and come back with the item. public IQueryable BinnedPhotos => MediaFiles.IgnoreQueryFilters().Where(f => f.DeletedAt != null && f.ArchiveItem.DeletedAt == null); @@ -77,6 +88,39 @@ protected override void OnModelCreating(ModelBuilder builder) .OnDelete(DeleteBehavior.SetNull); }); + builder.Entity(story => + { + story.HasQueryFilter(s => s.DeletedAt == null); + story.Property(s => s.Version).IsRowVersion(); + story.Property(s => s.Title).HasMaxLength(Story.TitleMaxLength); + story.Property(s => s.Summary).HasMaxLength(Story.SummaryMaxLength); + story.Property(s => s.Status).HasConversion().HasMaxLength(20); + story.HasIndex(s => s.Position); + story.HasMany(s => s.Blocks) + .WithOne(b => b.Story) + .HasForeignKey(b => b.StoryId) + .OnDelete(DeleteBehavior.Cascade); + }); + + builder.Entity(block => + { + // A story in the bin takes its blocks with it, and brings them back. + block.HasQueryFilter(b => b.Story.DeletedAt == null); + block.Property(b => b.Kind).HasConversion().HasMaxLength(20); + block.Property(b => b.Text).HasMaxLength(StoryBlock.TextMaxLength); + block.Property(b => b.Caption).HasMaxLength(StoryBlock.CaptionMaxLength); + block.HasIndex(b => new { b.StoryId, b.Position }); + block.HasIndex(b => b.ArchiveItemId); + // An item deleted for good takes its blocks with it. Optional, so that the item's own query filter does not hide the block. + block.HasOne(b => b.ArchiveItem) + .WithMany() + .HasForeignKey(b => b.ArchiveItemId) + .OnDelete(DeleteBehavior.Cascade); + block.ToTable(t => t.HasCheckConstraint("CK_StoryBlocks_Kind", + "(\"Kind\" = 'Text' AND \"ArchiveItemId\" IS NULL AND \"Text\" IS NOT NULL AND \"Caption\" IS NULL) OR " + + "(\"Kind\" = 'Item' AND \"ArchiveItemId\" IS NOT NULL AND \"Text\" IS NULL)")); + }); + builder.Entity(item => { item.HasQueryFilter(i => i.DeletedAt == null); @@ -225,6 +269,9 @@ protected override void OnModelCreating(ModelBuilder builder) entry.HasOne(e => e.ArchiveItem) .WithMany() .OnDelete(DeleteBehavior.SetNull); + entry.HasOne(e => e.Story) + .WithMany() + .OnDelete(DeleteBehavior.SetNull); }); builder.Entity(file => diff --git a/src/Commonage.Web/Data/Migrations/20261123194836_AddStories.Designer.cs b/src/Commonage.Web/Data/Migrations/20261123194836_AddStories.Designer.cs new file mode 100644 index 0000000..e201d50 --- /dev/null +++ b/src/Commonage.Web/Data/Migrations/20261123194836_AddStories.Designer.cs @@ -0,0 +1,1241 @@ +// +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("20261123194836_AddStories")] + partial class AddStories + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.15") + .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("StoryId") + .HasColumnType("integer"); + + 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.HasIndex("StoryId"); + + 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.Story", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DeletedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Position") + .HasColumnType("integer"); + + b.Property("PublishedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("Summary") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Version") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("xid") + .HasColumnName("xmin"); + + b.HasKey("Id"); + + b.HasIndex("Position"); + + b.ToTable("Stories"); + }); + + modelBuilder.Entity("Commonage.Web.Domain.StoryBlock", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ArchiveItemId") + .HasColumnType("integer"); + + b.Property("Caption") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("Position") + .HasColumnType("integer"); + + b.Property("StoryId") + .HasColumnType("integer"); + + b.Property("Text") + .HasMaxLength(20000) + .HasColumnType("character varying(20000)"); + + b.HasKey("Id"); + + b.HasIndex("ArchiveItemId"); + + b.HasIndex("StoryId", "Position"); + + b.ToTable("StoryBlocks", t => + { + t.HasCheckConstraint("CK_StoryBlocks_Kind", "(\"Kind\" = 'Text' AND \"ArchiveItemId\" IS NULL AND \"Text\" IS NOT NULL AND \"Caption\" IS NULL) OR (\"Kind\" = 'Item' AND \"ArchiveItemId\" IS NOT NULL AND \"Text\" IS NULL)"); + }); + }); + + 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.HasOne("Commonage.Web.Domain.Story", "Story") + .WithMany() + .HasForeignKey("StoryId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("ArchiveItem"); + + b.Navigation("Story"); + }); + + 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.StoryBlock", b => + { + b.HasOne("Commonage.Web.Domain.ArchiveItem", "ArchiveItem") + .WithMany() + .HasForeignKey("ArchiveItemId") + .OnDelete(DeleteBehavior.Cascade); + + b.HasOne("Commonage.Web.Domain.Story", "Story") + .WithMany("Blocks") + .HasForeignKey("StoryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ArchiveItem"); + + b.Navigation("Story"); + }); + + 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"); + }); + + modelBuilder.Entity("Commonage.Web.Domain.Story", b => + { + b.Navigation("Blocks"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Commonage.Web/Data/Migrations/20261123194836_AddStories.cs b/src/Commonage.Web/Data/Migrations/20261123194836_AddStories.cs new file mode 100644 index 0000000..f07df7e --- /dev/null +++ b/src/Commonage.Web/Data/Migrations/20261123194836_AddStories.cs @@ -0,0 +1,124 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace Commonage.Web.Data.Migrations +{ + /// + public partial class AddStories : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "StoryId", + table: "AuditEntries", + type: "integer", + nullable: true); + + migrationBuilder.CreateTable( + name: "Stories", + columns: table => new + { + Id = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + Title = table.Column(type: "character varying(200)", maxLength: 200, nullable: false), + Summary = table.Column(type: "character varying(1000)", maxLength: 1000, nullable: true), + Status = table.Column(type: "character varying(20)", maxLength: 20, nullable: false), + CreatedAt = table.Column(type: "timestamp with time zone", nullable: false), + UpdatedAt = table.Column(type: "timestamp with time zone", nullable: false), + PublishedAt = table.Column(type: "timestamp with time zone", nullable: true), + DeletedAt = table.Column(type: "timestamp with time zone", nullable: true), + Position = table.Column(type: "integer", nullable: false), + xmin = table.Column(type: "xid", rowVersion: true, nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Stories", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "StoryBlocks", + columns: table => new + { + Id = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + StoryId = table.Column(type: "integer", nullable: false), + Position = table.Column(type: "integer", nullable: false), + Kind = table.Column(type: "character varying(20)", maxLength: 20, nullable: false), + Text = table.Column(type: "character varying(20000)", maxLength: 20000, nullable: true), + ArchiveItemId = table.Column(type: "integer", nullable: true), + Caption = table.Column(type: "character varying(1000)", maxLength: 1000, nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_StoryBlocks", x => x.Id); + table.CheckConstraint("CK_StoryBlocks_Kind", "(\"Kind\" = 'Text' AND \"ArchiveItemId\" IS NULL AND \"Text\" IS NOT NULL AND \"Caption\" IS NULL) OR (\"Kind\" = 'Item' AND \"ArchiveItemId\" IS NOT NULL AND \"Text\" IS NULL)"); + table.ForeignKey( + name: "FK_StoryBlocks_ArchiveItems_ArchiveItemId", + column: x => x.ArchiveItemId, + principalTable: "ArchiveItems", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_StoryBlocks_Stories_StoryId", + column: x => x.StoryId, + principalTable: "Stories", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_AuditEntries_StoryId", + table: "AuditEntries", + column: "StoryId"); + + migrationBuilder.CreateIndex( + name: "IX_Stories_Position", + table: "Stories", + column: "Position"); + + migrationBuilder.CreateIndex( + name: "IX_StoryBlocks_ArchiveItemId", + table: "StoryBlocks", + column: "ArchiveItemId"); + + migrationBuilder.CreateIndex( + name: "IX_StoryBlocks_StoryId_Position", + table: "StoryBlocks", + columns: new[] { "StoryId", "Position" }); + + migrationBuilder.AddForeignKey( + name: "FK_AuditEntries_Stories_StoryId", + table: "AuditEntries", + column: "StoryId", + principalTable: "Stories", + principalColumn: "Id", + onDelete: ReferentialAction.SetNull); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropForeignKey( + name: "FK_AuditEntries_Stories_StoryId", + table: "AuditEntries"); + + migrationBuilder.DropTable( + name: "StoryBlocks"); + + migrationBuilder.DropTable( + name: "Stories"); + + migrationBuilder.DropIndex( + name: "IX_AuditEntries_StoryId", + table: "AuditEntries"); + + migrationBuilder.DropColumn( + name: "StoryId", + table: "AuditEntries"); + } + } +} diff --git a/src/Commonage.Web/Data/Migrations/CommonageDbContextModelSnapshot.cs b/src/Commonage.Web/Data/Migrations/CommonageDbContextModelSnapshot.cs index f5d4f35..f0a0c54 100644 --- a/src/Commonage.Web/Data/Migrations/CommonageDbContextModelSnapshot.cs +++ b/src/Commonage.Web/Data/Migrations/CommonageDbContextModelSnapshot.cs @@ -18,7 +18,7 @@ protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder - .HasAnnotation("ProductVersion", "10.0.14") + .HasAnnotation("ProductVersion", "10.0.15") .HasAnnotation("Relational:MaxIdentifierLength", 63); NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); @@ -268,6 +268,9 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.Property("At") .HasColumnType("timestamp with time zone"); + b.Property("StoryId") + .HasColumnType("integer"); + b.Property("Subject") .HasMaxLength(300) .HasColumnType("character varying(300)"); @@ -286,6 +289,8 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.HasIndex("At"); + b.HasIndex("StoryId"); + b.ToTable("AuditEntries"); }); @@ -621,6 +626,98 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.ToTable("StaffProfiles"); }); + modelBuilder.Entity("Commonage.Web.Domain.Story", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DeletedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Position") + .HasColumnType("integer"); + + b.Property("PublishedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("Summary") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Version") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("xid") + .HasColumnName("xmin"); + + b.HasKey("Id"); + + b.HasIndex("Position"); + + b.ToTable("Stories"); + }); + + modelBuilder.Entity("Commonage.Web.Domain.StoryBlock", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ArchiveItemId") + .HasColumnType("integer"); + + b.Property("Caption") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("Position") + .HasColumnType("integer"); + + b.Property("StoryId") + .HasColumnType("integer"); + + b.Property("Text") + .HasMaxLength(20000) + .HasColumnType("character varying(20000)"); + + b.HasKey("Id"); + + b.HasIndex("ArchiveItemId"); + + b.HasIndex("StoryId", "Position"); + + b.ToTable("StoryBlocks", t => + { + t.HasCheckConstraint("CK_StoryBlocks_Kind", "(\"Kind\" = 'Text' AND \"ArchiveItemId\" IS NULL AND \"Text\" IS NOT NULL AND \"Caption\" IS NULL) OR (\"Kind\" = 'Item' AND \"ArchiveItemId\" IS NOT NULL AND \"Text\" IS NULL)"); + }); + }); + modelBuilder.Entity("Commonage.Web.Domain.Tag", b => { b.Property("Id") @@ -943,7 +1040,14 @@ protected override void BuildModel(ModelBuilder modelBuilder) .HasForeignKey("ArchiveItemId") .OnDelete(DeleteBehavior.SetNull); + b.HasOne("Commonage.Web.Domain.Story", "Story") + .WithMany() + .HasForeignKey("StoryId") + .OnDelete(DeleteBehavior.SetNull); + b.Navigation("ArchiveItem"); + + b.Navigation("Story"); }); modelBuilder.Entity("Commonage.Web.Domain.Collection", b => @@ -1025,6 +1129,24 @@ protected override void BuildModel(ModelBuilder modelBuilder) .IsRequired(); }); + modelBuilder.Entity("Commonage.Web.Domain.StoryBlock", b => + { + b.HasOne("Commonage.Web.Domain.ArchiveItem", "ArchiveItem") + .WithMany() + .HasForeignKey("ArchiveItemId") + .OnDelete(DeleteBehavior.Cascade); + + b.HasOne("Commonage.Web.Domain.Story", "Story") + .WithMany("Blocks") + .HasForeignKey("StoryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ArchiveItem"); + + b.Navigation("Story"); + }); + modelBuilder.Entity("Commonage.Web.Domain.VisitorNote", b => { b.HasOne("Commonage.Web.Domain.ArchiveItem", "ArchiveItem") @@ -1105,6 +1227,11 @@ protected override void BuildModel(ModelBuilder modelBuilder) { b.Navigation("Contributions"); }); + + modelBuilder.Entity("Commonage.Web.Domain.Story", b => + { + b.Navigation("Blocks"); + }); #pragma warning restore 612, 618 } } diff --git a/src/Commonage.Web/Data/Visibility.cs b/src/Commonage.Web/Data/Visibility.cs index 5809daa..f22fbec 100644 --- a/src/Commonage.Web/Data/Visibility.cs +++ b/src/Commonage.Web/Data/Visibility.cs @@ -25,4 +25,15 @@ public static Expression> ItemWithMedia(DateOnly today) 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; + + /// + /// The stories visitors may read: published, not in the bin, and with at least one text block or one item block whose item + /// allows (so embargo and withdrawal come with it). This is the only place that writes + /// in a query. The explicit DeletedAt test is belt and braces on the query filter. + /// A method on the context rather than an expression: it cannot be applied to a navigation from a block to its item. + /// + public static IQueryable Story(CommonageDbContext db, DateOnly today) => + db.Stories.Where(s => s.Status == StoryStatus.Published && s.DeletedAt == null + && s.Blocks.Any(b => b.Kind == StoryBlockKind.Text + || db.ArchiveItems.Where(Item(today)).Any(i => i.Id == b.ArchiveItemId))); } diff --git a/src/Commonage.Web/Data/VisibleStoryBlocks.cs b/src/Commonage.Web/Data/VisibleStoryBlocks.cs new file mode 100644 index 0000000..0c07e96 --- /dev/null +++ b/src/Commonage.Web/Data/VisibleStoryBlocks.cs @@ -0,0 +1,59 @@ +using Commonage.Web.Domain; +using Commonage.Web.Search; +using Microsoft.EntityFrameworkCore; + +namespace Commonage.Web.Data; + +/// One block of a story as a visitor sees it: words, or a visible item with the curator's caption. +public abstract record StoryBlockView +{ + /// A block of text. + public sealed record Text(string Value) : StoryBlockView; + + /// An item visitors may see, as shows it, and a caption about it. + public sealed record Item(ItemSummary Summary, string? Caption) : StoryBlockView; +} + +/// +/// The blocks of a story that visitors may see, in order. An item block whose item is not visible (draft, embargoed, withdrawn, +/// in the bin, unknown) is left out together with its caption and leaves no trace. Public code and the curator preview +/// load blocks only through here, and never follow . +/// +public static class VisibleStoryBlocks +{ + public static Task> LoadAsync(CommonageDbContext db, int storyId, CancellationToken ct = default) => + LoadAsync(db, storyId, db.Today, ct); + + /// For code that has fixed one for several decisions, such as an export. + public static async Task> LoadAsync(CommonageDbContext db, int storyId, DateOnly today, CancellationToken ct = default) + { + var blocks = await db.StoryBlocks.AsNoTracking() + .Where(b => b.StoryId == storyId) + .OrderBy(b => b.Position).ThenBy(b => b.Id) + .Select(b => new { b.Kind, b.Text, b.ArchiveItemId, b.Caption }) + .ToListAsync(ct); + + var ids = blocks.Where(b => b.Kind == StoryBlockKind.Item && b.ArchiveItemId != null) + .Select(b => b.ArchiveItemId!.Value).Distinct().ToList(); + var items = ids.Count == 0 + ? [] + : await db.ArchiveItems.Where(Visibility.Item(today)) + .Where(i => ids.Contains(i.Id)) + .Select(ItemSummary.FromItem) + .ToDictionaryAsync(i => i.Id, ct); + + var result = new List(); + foreach (var block in blocks) + { + if (block.Kind == StoryBlockKind.Text) + result.Add(new StoryBlockView.Text(block.Text ?? "")); + else if (block.ArchiveItemId is { } id && items.TryGetValue(id, out var summary)) + result.Add(new StoryBlockView.Item(summary, block.Caption)); + } + + return result; + } +} + +/// What the shared story partial shows: the words of a story and the blocks visitors may see. +public record StoryBody(string Title, string? Summary, IReadOnlyList Blocks); diff --git a/src/Commonage.Web/Demo/DemoContent.cs b/src/Commonage.Web/Demo/DemoContent.cs index 8412c66..8b8aa67 100644 --- a/src/Commonage.Web/Demo/DemoContent.cs +++ b/src/Commonage.Web/Demo/DemoContent.cs @@ -170,6 +170,31 @@ await AddPhotoAsync(letter, "letter-page-2", DemoLetter.Render(letterPages[1], s } db.ArchiveItems.AddRange(items); + // A story that curators can open under Stories: words between three published items, and one part that names the draft, + // which visitors will not see. + var story = new Story + { + Title = T("Mill Street over thirty years", "Die Mühlenstraße in dreißig Jahren"), + Summary = T("From the winter of 1952 to the street party of 1971, told with a few of the photos.", + "Vom Winter 1952 bis zum Straßenfest 1971, erzählt mit einigen der Fotos."), + Status = StoryStatus.Draft, + CreatedAt = now, + UpdatedAt = now, + Position = 0, + }; + void Part(StoryBlockKind kind, string? text = null, ArchiveItem? item = null, string? caption = null) => + story.Blocks.Add(new StoryBlock { Position = story.Blocks.Count, Kind = kind, Text = text, ArchiveItem = item, Caption = caption }); + Part(StoryBlockKind.Text, T("The mill stood at the top of the street, and for many years everything in Mill Street was named after it.", + "Die Mühle stand am oberen Ende der Straße, und viele Jahre hieß in der Mühlenstraße alles nach ihr.")); + Part(StoryBlockKind.Item, item: items[0], caption: T("The mill in the first winter we have a photo of.", "Die Mühle im ersten Winter, aus dem wir ein Foto haben.")); + Part(StoryBlockKind.Text, T("In 1962 the water came into the street. People remember how neighbours carried the bakery's flour upstairs.", + "1962 kam das Wasser in die Straße. Man erinnert sich, wie die Nachbarn das Mehl der Bäckerei die Treppe hinauftrugen.")); + Part(StoryBlockKind.Item, item: items[1], caption: T("The street in March 1962.", "Die Straße im März 1962.")); + Part(StoryBlockKind.Item, item: draft, caption: T("Still to be sorted before visitors can see it.", "Muss noch sortiert werden, bevor Besucher es sehen.")); + Part(StoryBlockKind.Text, T("Nine years later a new bridge was opened, and the whole street celebrated.", + "Neun Jahre später wurde eine neue Brücke eröffnet, und die ganze Straße feierte.")); + Part(StoryBlockKind.Item, item: items[3], caption: T("The street party for the new bridge.", "Das Straßenfest zur neuen Brücke.")); + db.Stories.Add(story); // A made-up group, so the demo shows an archive as a group would set it up. db.ArchiveSettings.Add(new ArchiveSettings { DefaultLanguage = language, ContentLanguage = language, PrivacyReviewed = true, ImprintNotNeeded = true, DefaultRightsUri = RightsOptions.NotEvaluated }); void Text(ArchiveTextKind kind, string text) => db.ArchiveTexts.Add(new ArchiveText { Language = language, Kind = kind, Text = text }); diff --git a/src/Commonage.Web/Domain/AuditEntry.cs b/src/Commonage.Web/Domain/AuditEntry.cs index bfe01ed..422c21c 100644 --- a/src/Commonage.Web/Domain/AuditEntry.cs +++ b/src/Commonage.Web/Domain/AuditEntry.cs @@ -65,6 +65,18 @@ public enum AuditAction ArchiveImported, CollectionCreatedByImport, ImportPhotosMissing, + StoryCreated, + StoryChanged, + StoryPublished, + StoryUnpublished, + StoryItemAdded, + StoryItemRemoved, + StoryBlocksArranged, + StoriesArranged, + StoryMovedToBin, + StoryRestored, + StoryDeleted, + StoryPurged, } /// @@ -91,6 +103,10 @@ public class AuditEntry public int? ArchiveItemId { get; set; } public ArchiveItem? ArchiveItem { get; set; } + /// The story concerned, if any. Set to null when the story is deleted; keeps its title. + public int? StoryId { get; set; } + public Story? Story { get; set; } + /// What the action was about, as it was called at the time: an item's or collection's title, an account name. public string? Subject { get; set; } } diff --git a/src/Commonage.Web/Domain/Story.cs b/src/Commonage.Web/Domain/Story.cs new file mode 100644 index 0000000..c626efe --- /dev/null +++ b/src/Commonage.Web/Domain/Story.cs @@ -0,0 +1,104 @@ +namespace Commonage.Web.Domain; + +/// Whether visitors may read a story. Not : a story has no contribution states. +public enum StoryStatus +{ + Draft, + Published, +} + +/// What a block of a story is: words a curator wrote, or a reference to an item. +public enum StoryBlockKind +{ + Text, + Item, +} + +/// +/// A curator's telling put together from text and items: a title, a short summary and blocks in order. Only a published story +/// that is not in the bin and has at least one block visitors may see is public, see CommonageDbContext.VisibleStories. +/// +public class Story +{ + public const int TitleMaxLength = 200; + public const int SummaryMaxLength = 1000; + + /// The most blocks one story holds, so that one page stays a page. + public const int MaxBlocks = 200; + + public int Id { get; set; } + public string Title { get; set; } = ""; + public string? Summary { get; set; } + public StoryStatus Status { get; set; } + public DateTime CreatedAt { get; set; } + public DateTime UpdatedAt { get; set; } + public DateTime? PublishedAt { get; set; } + + /// When the story went to the bin, or null. Query filters hide a story in the bin. + public DateTime? DeletedAt { get; private set; } + + /// Where the story stands among the others, lowest first. + public int Position { get; set; } + + /// Concurrency token (PostgreSQL xmin) for the title and summary form. Block changes never change it. + public uint Version { get; set; } + + public List Blocks { get; set; } = []; + + public bool IsUntitled => string.IsNullOrWhiteSpace(Title); + + public bool CanBePublished => !IsUntitled; + + public void Publish(DateTime now) + { + if (!CanBePublished) + throw new InvalidOperationException("A story without a title cannot be published."); + + Status = StoryStatus.Published; + PublishedAt ??= now; + } + + /// Takes the story back to a draft. stays, as it does for items. + public void Unpublish() => Status = StoryStatus.Draft; + + public void MoveToBin(DateTime now) => DeletedAt = now; + + public void RestoreFromBin(DateTime now) + { + DeletedAt = null; + UpdatedAt = now; + } + + public void Touch(DateTime now) => UpdatedAt = now; +} + +/// One block of a story, in order: text, or an item with a caption. +public class StoryBlock +{ + public const int TextMaxLength = 20000; + public const int CaptionMaxLength = 1000; + + public int Id { get; set; } + public int StoryId { get; set; } + public Story Story { get; set; } = null!; + + /// 0 to n-1, renumbered after every change. + public int Position { get; set; } + + public StoryBlockKind Kind { get; set; } + + /// The words of a text block; null for an item block. + public string? Text { get; set; } + + /// The item of an item block; null for a text block. Deleting the item for good deletes the block. + public int? ArchiveItemId { get; set; } + + /// + /// Admin pages only. Public code never follows this: it loads items through VisibleItems (see + /// VisibleStoryBlocks), so that a hidden item leaves no trace. + /// + public ArchiveItem? ArchiveItem { get; set; } + + /// A curator's words about the item in this story; hidden whenever the item is. + public string? Caption { get; set; } +} diff --git a/src/Commonage.Web/Export/ArchiveExporter.cs b/src/Commonage.Web/Export/ArchiveExporter.cs index 1f193be..f7614bb 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 = 8; + public const int Version = 9; private static readonly JsonSerializerOptions JsonOptions = new() { @@ -51,7 +51,9 @@ 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.VisibleItems : db.ArchiveItems).AsNoTracking(); + // One day for every decision of the export: items, stories and their blocks agree on what is embargoed. + var today = db.Today; + var source = (options.PublishedOnly ? db.ArchiveItems.Where(Visibility.Item(today)) : db.ArchiveItems).AsNoTracking(); if (options.PublishedOnly) { var used = await source.Select(i => i.CollectionId).Distinct().ToListAsync(cancellationToken); @@ -128,6 +130,16 @@ await WriteEntryAsync(zip, "archive.json", CompressionLevel.Optimal, async strea await json.FlushAsync(cancellationToken); } + json.WriteEndArray(); + json.WritePropertyName("stories"); + json.WriteStartArray(); + await foreach (var story in DescribeStoriesAsync(source, options, today, cancellationToken)) + { + JsonSerializer.Serialize(json, story, JsonOptions); + if (json.BytesPending > 64 * 1024) + await json.FlushAsync(cancellationToken); + } + json.WriteEndArray(); Property(json, "settings", new ExportSettings( settings.DefaultLanguage, settings.ContentLanguage, settings.OtherContentLanguages, settings.AccentColor, settings.TimeZone, settings.DefaultRightsUri, settings.AllowSearchEngines, settings.RequireTwoFactor, settings.LargePhotos, settings.PrivacyReviewed, @@ -169,6 +181,39 @@ private async IAsyncEnumerable> ItemBatchesAsync( } } + /// + /// The stories in order, a batch at a time. A copy of what is public holds only published stories, and in them only the blocks + /// whose item is in this export; a copy of everything leaves out stories in the bin and the blocks of items in the bin. No + /// block names an item that is not under "items". + /// + private async IAsyncEnumerable DescribeStoriesAsync( + IQueryable items, ExportOptions options, DateOnly today, + [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken) + { + var stories = (options.PublishedOnly ? Visibility.Story(db, today) : db.Stories).AsNoTracking(); + var last = 0; + while (true) + { + var after = last; + var batch = await stories.Where(s => s.Id > after).OrderBy(s => s.Id).Take(50) + .Select(s => new + { + s.Id, s.Title, s.Summary, s.Status, s.CreatedAt, s.PublishedAt, s.Position, + Blocks = s.Blocks + .Where(b => b.Kind == StoryBlockKind.Text || items.Any(i => i.Id == b.ArchiveItemId)) + .OrderBy(b => b.Position).ThenBy(b => b.Id) + .Select(b => new ExportStoryBlock(b.Kind, b.Text, b.ArchiveItemId, b.Caption)) + .ToList(), + }) + .ToListAsync(cancellationToken); + if (batch.Count == 0) + yield break; + last = batch[^1].Id; + foreach (var s in batch) + yield return new ExportStory(s.Id, s.Title, s.Summary, s.Status, s.CreatedAt, s.PublishedAt, s.Position, s.Blocks); + } + } + /// The items in the order of their ids, read a batch at a time. private async IAsyncEnumerable DescribeItemsAsync( IQueryable source, ExportOptions options, Dictionary problems, @@ -353,6 +398,7 @@ void Entry(string name, string description) text.Append(" files//-\n\n"); Paragraph(localizer["Curators may have turned a photo: archive.json gives its \"rotation\" in degrees clockwise, and its \"position\" among the photos of the item."], " "); Entry("branding/", localizer["The archive's logo, if it has one. Its name and pages are under \"settings\" in archive.json."]); + Paragraph(localizer["\"stories\" in archive.json lists the stories: each has its parts in order, and a part is either a text or the number of an item under \"items\" with a caption."]); Paragraph(localizer["\"includesPersonalData\" in archive.json says whether the names of contributors, photographers and authors and contributors' email addresses are included. If they are, keep this file as carefully as the archive itself."]); Paragraph(localizer["\"contentLanguage\" under \"settings\" says which language most of the material is written in, as a code such as \"de\" or \"pl\". \"mul\" means several languages, none of them most."]); Paragraph(localizer["A file with \"problem\": \"missing\" was not found on the server; \"checksumMismatch\" means it no longer matches the checksum taken when it was uploaded. Both should be looked into."]); @@ -399,6 +445,11 @@ internal record ExportText(string Language, ArchiveTextKind Kind, string Text); internal record ExportCollection(int Id, string Title, string? Description, DateTime CreatedAt, int Position, CollectionSort Sort, int? CoverFileId); +/// A story: its words and its parts in order. A part is a text or names an item that is under "items". +internal record ExportStory(int Id, string Title, string? Summary, StoryStatus Status, DateTime CreatedAt, DateTime? PublishedAt, int Position, IReadOnlyList Blocks); + +internal record ExportStoryBlock(StoryBlockKind Kind, string? Text, int? ItemId, string? Caption); + /// A tag and what it names. Items list their tags by name. internal record ExportTag(string Name, TagKind Kind); diff --git a/src/Commonage.Web/Import/ExportImport.cs b/src/Commonage.Web/Import/ExportImport.cs index cc12327..a6a7bd6 100644 --- a/src/Commonage.Web/Import/ExportImport.cs +++ b/src/Commonage.Web/Import/ExportImport.cs @@ -151,6 +151,9 @@ public class ExportPlan public ExportRefusal Refusal { get; init; } public int? FoundVersion { get; init; } public int Version { get; init; } + + /// How many stories the export holds. They are not imported. + public int StoriesNotImported { get; init; } public IReadOnlyList Items { get; init; } = []; public IReadOnlyList NewCollections { get; init; } = []; @@ -383,7 +386,7 @@ public async Task PlanAsync(IImportSource source, CancellationToken } } - return new ExportPlan { Version = ArchiveExporter.Version, Items = items, NewCollections = newCollections.Values.ToList(), IssuesNotListed = budget.Omitted }; + return new ExportPlan { Version = ArchiveExporter.Version, Items = items, NewCollections = newCollections.Values.ToList(), IssuesNotListed = budget.Omitted, StoriesNotImported = archive.Stories?.Count ?? 0 }; } private static bool HasProblem(PlannedExportItem planned) => planned.Issues.Any(i => i.Severity == ExportIssueSeverity.Problem); diff --git a/src/Commonage.Web/Import/ExportReading.cs b/src/Commonage.Web/Import/ExportReading.cs index f76a03c..e3c7578 100644 --- a/src/Commonage.Web/Import/ExportReading.cs +++ b/src/Commonage.Web/Import/ExportReading.cs @@ -76,6 +76,10 @@ void Add(string type, ExportFieldDecision decision, string why, params string[] Add("ExportNote", ExportFieldDecision.Dropped, "Notes from visitors are for the curators of the archive they were sent to.", "Kind", "Message", "Name", "Email", "ReceivedAt", "HandledAt", "PersonalDetailsRemovedAt"); + const string StoryNotImported = "Stories are not imported: they are made of the items of the other archive, and an import makes new items with new numbers. The dry run only counts them."; + Add("ExportStory", ExportFieldDecision.Dropped, StoryNotImported, "Id", "Title", "Summary", "Status", "CreatedAt", "PublishedAt", "Position", "Blocks"); + Add("ExportStoryBlock", ExportFieldDecision.Dropped, StoryNotImported, "Kind", "Text", "ItemId", "Caption"); + Add("ExportFile", ExportFieldDecision.ReadForDecision, "Only the key that the path of the file is checked against.", "Id"); Add("ExportFile", ExportFieldDecision.Read, "Comes with the photo; the path is only a key into the ZIP file and never a path on disk.", "Path", "OriginalFileName", "Sha256", "AltText", "Caption", "Position", "Rotation"); @@ -97,6 +101,38 @@ public sealed class ImportedArchive public List? Collections { get; set; } public List? Tags { get; set; } public List? Items { get; set; } + + /// Only how many stories there are: they are never read, see . + public StoryCount? Stories { get; set; } +} + +/// The number of stories of an export. Reading skips every story without making an object of it. +[JsonConverter(typeof(StoryCountConverter))] +public sealed record StoryCount(int Count); + +internal sealed class StoryCountConverter : JsonConverter +{ + /// The count stops here; the stories beyond it are skipped all the same. + public const int Cap = 1_000_000; + + public override StoryCount? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + if (reader.TokenType == JsonTokenType.Null) + return null; + if (reader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + var count = 0; + while (reader.Read() && reader.TokenType != JsonTokenType.EndArray) + { + reader.Skip(); + if (count < Cap) + count++; + } + + return new StoryCount(count); + } + + public override void Write(Utf8JsonWriter writer, StoryCount value, JsonSerializerOptions options) => throw new NotSupportedException(); } public sealed class ImportedCollection diff --git a/src/Commonage.Web/Pages/Admin/Activity.cshtml b/src/Commonage.Web/Pages/Admin/Activity.cshtml index 844c6fe..ff5167c 100644 --- a/src/Commonage.Web/Pages/Admin/Activity.cshtml +++ b/src/Commonage.Web/Pages/Admin/Activity.cshtml @@ -69,7 +69,11 @@ else @AuditText.Describe(T, entry.Action)@if (entry.Subject is not null) { : - @if (entry.ArchiveItemId is { } itemId) + @if (entry.StoryId is { } storyId) + { + @ArchiveItem.ShownTitle(T, entry.Subject) + } + else if (entry.ArchiveItemId is { } itemId) { @ArchiveItem.ShownTitle(T, entry.Subject) } diff --git a/src/Commonage.Web/Pages/Admin/ImportArchive.cshtml b/src/Commonage.Web/Pages/Admin/ImportArchive.cshtml index 9620594..319cd58 100644 --- a/src/Commonage.Web/Pages/Admin/ImportArchive.cshtml +++ b/src/Commonage.Web/Pages/Admin/ImportArchive.cshtml @@ -32,6 +32,10 @@
  • @T["Collections that would be created: {0}", plan.NewCollections.Count]
  • @T["Items with problems, which are left out: {0}", plan.Items.Count(i => i.HasProblem)]
  • @T["Items left out on purpose: {0}", plan.Items.Count(i => i.IsLeftOut)]
  • + @if (plan.StoriesNotImported > 0) + { +
  • @T.Plural("The export holds {0, plural, one {# story} other {# stories}}. Stories are not imported.", plan.StoriesNotImported)
  • + } @if (plan.Ready.Any(i => i.MediaLevel != Commonage.Web.Domain.MediaLevel.Everything || i.PublicFrom is not null)) diff --git a/src/Commonage.Web/Pages/Admin/Stories/Edit.cshtml b/src/Commonage.Web/Pages/Admin/Stories/Edit.cshtml new file mode 100644 index 0000000..e6b83fa --- /dev/null +++ b/src/Commonage.Web/Pages/Admin/Stories/Edit.cshtml @@ -0,0 +1,185 @@ +@page "{id:int}" +@model Commonage.Web.Pages.Admin.Stories.EditModel +@using Commonage.Web.Pages.Admin.Stories +@using Commonage.Web.Domain +@inject Commonage.Web.Operations.ArchiveProfile Profile +@{ + ViewData["Title"] = T["Edit story"]; + var material = (await Profile.GetAsync()).MaterialLanguage; + var story = Model.Story; + var total = Model.Blocks.Count; +} + + + +
    +

    @ViewData["Title"]

    + @(story.Status == StoryStatus.Published ? T["Published"] : T["Draft"]) + @T["Preview"] +
    + @if (story.Status == StoryStatus.Published) + { + + } + else + { + + } +
    +
    +

    @T["Visitors cannot read stories yet. A published story is the first thing they will see once they can."]

    + +@if (Model.SavedByOthers is { } saved) +{ + +} + +
    + @if (!ViewData.ModelState.ContainsKey("newText") && !ViewData.ModelState.ContainsKey("item") && !ViewData.ModelState.ContainsKey("caption")) + { + + } + +
    + + + +
    +
    + + + +
    @T["A few words that open the story and describe it in a list."]
    +
    + + + +

    @T["Parts of the story"]

    +@if (ViewData.ModelState.ContainsKey("newText") || ViewData.ModelState.ContainsKey("item") || ViewData.ModelState.ContainsKey("caption") || Model.TypedText.Count > 0) +{ + +} +@if (total == 0) +{ +

    @T["This story has no parts yet. Add text or an item below."]

    +} +else +{ +
      + @for (var index = 0; index < total; index++) + { + var block = Model.Blocks[index]; + var typed = Model.TypedText.GetValueOrDefault(block.Id); + var label = block.Kind == StoryBlockKind.Text ? T["Text {0} of {1}", index + 1, total] : T["Item {0} of {1}", index + 1, total]; +
    1. +
      +

      @label

      + @if (block.Kind == StoryBlockKind.Text) + { + var textId = $"text-{block.Id}"; +
      + + + @Html.ValidationMessage(textId) + +
      + } + else if (block.State == EditModel.ItemState.Missing) + { +

      @T["This item no longer exists."]

      + } + else + { + var captionId = $"caption-{block.Id}"; +
      + @if (block.ThumbnailMediaFileId is { } mediaFileId) + { + + } +
      + @ArchiveItem.ShownTitle(T, block.ItemTitle ?? "") + @T["Item number {0}", block.ItemId!.Value]@(block.DateText is null ? "" : " · ")@block.DateText + @switch (block.State) + { + case EditModel.ItemState.Draft: + @T["Visitors do not see this item: it is not published."] + break; + case EditModel.ItemState.PublicFrom: + @T["Visitors do not see this item until {0}.", block.PublicFrom!.Value.ToString("d", System.Globalization.CultureInfo.CurrentCulture)] + break; + case EditModel.ItemState.InBin: + @T["Visitors do not see this item: it is in the bin."] + break; + case EditModel.ItemState.Withdrawn: + @T["Visitors do not see this item: it was turned down or withdrawn."] + break; + case EditModel.ItemState.ShownWithoutPhotos: + @T["Visitors see this item without its photos."] + break; + } +
      +
      +
      + + + @Html.ValidationMessage(captionId) + +
      + } +
      +
      + + +
      +
      + +
      +
      +
      +
    2. + } +
    +} + +@if (total < Story.MaxBlocks) +{ +
    +
    +

    @T["Add text"]

    + + + @Html.ValidationMessage("newText") + +
    +
    +

    @T["Add an item"]

    + + +
    @T["The number of the item, or the address of its page, for example /items/12."]
    + @Html.ValidationMessage("item") + + + @Html.ValidationMessage("caption") + +
    +
    +} +else +{ +

    @T.Plural("A story can have at most {0, plural, one {# part} other {# parts}}.", Story.MaxBlocks)

    +} diff --git a/src/Commonage.Web/Pages/Admin/Stories/Edit.cshtml.cs b/src/Commonage.Web/Pages/Admin/Stories/Edit.cshtml.cs new file mode 100644 index 0000000..8989473 --- /dev/null +++ b/src/Commonage.Web/Pages/Admin/Stories/Edit.cshtml.cs @@ -0,0 +1,426 @@ +using System.ComponentModel.DataAnnotations; +using System.Text.RegularExpressions; +using Commonage.Web.Audit; +using Commonage.Web.Data; +using Commonage.Web.Domain; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.RazorPages; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Localization; + +namespace Commonage.Web.Pages.Admin.Stories; + +/// +/// A story's title and summary, and its blocks: text and items, in the order a curator gives them. Changing the blocks +/// never touches the story's own row, so a title form that is open stays savable and nothing about the story's +/// version or date moves. +/// +public partial class EditModel(CommonageDbContext db, AuditLog audit, IStringLocalizer localizer, TimeProvider clock) : PageModel +{ + public Story Story { get; private set; } = null!; + + public InputModel Input { get; private set; } = new(); + + /// The story as another curator saved it, when the title form was sent from an older version. + public Story? SavedByOthers { get; private set; } + + public IReadOnlyList Blocks { get; private set; } = []; + + /// The block that was just added or moved. The page puts the keyboard focus on it. + public int? FocusBlockId { get; private set; } + + /// Text typed into a block's form that did not go through, so that it is not lost. + public Dictionary TypedText { get; } = []; + + public string? TypedNewText { get; private set; } + public string? TypedItemReference { get; private set; } + public string? TypedItemCaption { get; private set; } + + /// Whether visitors would see an item block, and if not, why. Curators see this under /Admin only. + public enum ItemState + { + Shown, + ShownWithoutPhotos, + Draft, + PublicFrom, + InBin, + Withdrawn, + Missing, + } + + public record BlockRow(int Id, StoryBlockKind Kind, string? Text, string? Caption, int? ItemId, string? ItemTitle, string? DateText, + int? ThumbnailMediaFileId, ItemState State, DateOnly? PublicFrom); + + public class InputModel + { + [Required(ErrorMessage = "Please enter a title.")] + [StringLength(Story.TitleMaxLength, ErrorMessage = "The title can be at most {1} characters long.")] + [Display(Name = "Title")] + public string Title { get; set; } = ""; + + [StringLength(Story.SummaryMaxLength, ErrorMessage = "The summary can be at most {1} characters long.")] + [Display(Name = "Summary")] + public string? Summary { get; set; } + + public uint? Version { get; set; } + } + + public async Task OnGetAsync(int id, int? block, CancellationToken cancellationToken) + { + var story = await db.Stories.FindAsync([id], cancellationToken); + if (story is null) + return NotFound(); + + Input = new InputModel { Title = story.Title, Summary = story.Summary, Version = story.Version }; + FocusBlockId = block; + await LoadAsync(story, cancellationToken); + return Page(); + } + + /// Saves the title and summary. If someone else saved them since the form was opened, nothing is overwritten. + public async Task OnPostAsync(int id, [Bind(Prefix = "Input")] InputModel input, CancellationToken cancellationToken) + { + var story = await db.Stories.FindAsync([id], cancellationToken); + if (story is null) + return NotFound(); + + Input = input; + if (!ModelState.IsValid) + { + await LoadAsync(story, cancellationToken); + return Page(); + } + + if (input.Version is { } version) + db.Entry(story).Property(s => s.Version).OriginalValue = version; + + var title = input.Title.Trim(); + var summary = string.IsNullOrWhiteSpace(input.Summary) ? null : input.Summary.Trim(); + if (title != story.Title || summary != story.Summary) + { + story.Title = title; + story.Summary = summary; + story.Touch(clock.GetUtcNow().UtcDateTime); + audit.Record(AuditAction.StoryChanged, story.Title, story: story); + } + + try + { + await db.SaveChangesAsync(cancellationToken); + } + catch (DbUpdateConcurrencyException) + { + db.ChangeTracker.Clear(); + var current = await db.Stories.FindAsync([id], cancellationToken); + if (current is null) + return NotFound(); + + SavedByOthers = new Story { Title = current.Title, Summary = current.Summary }; + // The next save is a deliberate decision to replace the other version, so it may go through. + ModelState.Remove("Input.Version"); + Input = new InputModel { Title = input.Title, Summary = input.Summary, Version = current.Version }; + await LoadAsync(current, cancellationToken); + return Page(); + } + + TempData["Message"] = localizer["Your changes are saved."].Value; + return RedirectToPage(new { id }); + } + + public async Task OnPostPublishAsync(int id, CancellationToken cancellationToken) + { + var story = await db.Stories.FindAsync([id], cancellationToken); + if (story is null) + return NotFound(); + if (!story.CanBePublished) + return BadRequest(); + + if (story.Status != StoryStatus.Published) + { + var now = clock.GetUtcNow().UtcDateTime; + story.Publish(now); + story.Touch(now); + audit.Record(AuditAction.StoryPublished, story.Title, story: story); + await db.SaveChangesAsync(cancellationToken); + } + + TempData["Message"] = localizer["The story is published."].Value; + return RedirectToPage(new { id }); + } + + public async Task OnPostUnpublishAsync(int id, CancellationToken cancellationToken) + { + var story = await db.Stories.FindAsync([id], cancellationToken); + if (story is null) + return NotFound(); + + if (story.Status == StoryStatus.Published) + { + story.Unpublish(); + story.Touch(clock.GetUtcNow().UtcDateTime); + audit.Record(AuditAction.StoryUnpublished, story.Title, story: story); + await db.SaveChangesAsync(cancellationToken); + } + + TempData["Message"] = localizer["The story is a draft again."].Value; + return RedirectToPage(new { id }); + } + + public async Task OnPostAddTextAsync(int id, string? text, CancellationToken cancellationToken) + { + var story = await db.Stories.FindAsync([id], cancellationToken); + if (story is null) + return NotFound(); + + var words = Clean(text); + if (words is null) + ModelState.AddModelError("newText", localizer["Please write some text."]); + else if (words.Length > StoryBlock.TextMaxLength) + ModelState.AddModelError("newText", localizer["The text can be at most {0} characters long.", StoryBlock.TextMaxLength]); + else if (await IsFullAsync(id, cancellationToken)) + ModelState.AddModelError("newText", FullMessage()); + if (!ModelState.IsValid) + { + TypedNewText = text; + return await ShowAsync(story, cancellationToken); + } + + var block = new StoryBlock { StoryId = id, Kind = StoryBlockKind.Text, Text = words, Position = await db.StoryBlocks.CountAsync(b => b.StoryId == id, cancellationToken) }; + db.StoryBlocks.Add(block); + audit.Record(AuditAction.StoryChanged, story.Title, story: story); + await db.SaveChangesAsync(cancellationToken); + return BackToBlock(id, block.Id); + } + + /// Adds an item by its number or by the address of its page, on the website or under /Admin. + public async Task OnPostAddItemAsync(int id, string? item, string? caption, CancellationToken cancellationToken) + { + var story = await db.Stories.FindAsync([id], cancellationToken); + if (story is null) + return NotFound(); + + var number = ItemNumber(item); + // A curator may add an item visitors do not see yet; items in the bin or turned down are not offered. + var found = number is { } n + ? await db.ArchiveItems.IgnoreQueryFilters().Where(i => i.Id == n) + .Select(i => new { i.Id, i.Status, i.DeletedAt }).FirstOrDefaultAsync(cancellationToken) + : null; + var cleanCaption = Clean(caption); + if (number is null) + ModelState.AddModelError("item", localizer["Please enter the number of an item, or the address of its page."]); + else if (found is null) + ModelState.AddModelError("item", localizer["There is no item with this number."]); + else if (found.DeletedAt is not null) + ModelState.AddModelError("item", localizer["This item is in the bin. Take it out of the bin first."]); + else if (found.Status is ItemStatus.Rejected or ItemStatus.Withdrawn) + ModelState.AddModelError("item", localizer["This item was turned down or withdrawn, and cannot be part of a story."]); + else if (cleanCaption is { Length: > StoryBlock.CaptionMaxLength }) + ModelState.AddModelError("caption", localizer["The caption can be at most {0} characters long.", StoryBlock.CaptionMaxLength]); + else if (await IsFullAsync(id, cancellationToken)) + ModelState.AddModelError("item", FullMessage()); + if (!ModelState.IsValid || found is null) + { + TypedItemReference = item; + TypedItemCaption = caption; + return await ShowAsync(story, cancellationToken); + } + + var block = new StoryBlock + { + StoryId = id, + Kind = StoryBlockKind.Item, + ArchiveItemId = found.Id, + Caption = cleanCaption, + Position = await db.StoryBlocks.CountAsync(b => b.StoryId == id, cancellationToken), + }; + db.StoryBlocks.Add(block); + audit.Record(AuditAction.StoryItemAdded, story.Title, await db.ArchiveItems.FindAsync([found.Id], cancellationToken), story); + await db.SaveChangesAsync(cancellationToken); + + if (!await db.VisibleItems.AnyAsync(i => i.Id == found.Id, cancellationToken)) + TempData["Message"] = localizer["The item is added. Visitors will not see it until it is public."].Value; + return BackToBlock(id, block.Id); + } + + public async Task OnPostSaveTextAsync(int id, int blockId, string? text, CancellationToken cancellationToken) + { + var block = await FindBlockAsync(id, blockId, StoryBlockKind.Text, cancellationToken); + if (block is null) + return NotFound(); + + var words = Clean(text); + if (words is null) + ModelState.AddModelError($"text-{blockId}", localizer["Please write some text."]); + else if (words.Length > StoryBlock.TextMaxLength) + ModelState.AddModelError($"text-{blockId}", localizer["The text can be at most {0} characters long.", StoryBlock.TextMaxLength]); + if (!ModelState.IsValid) + { + TypedText[blockId] = text ?? ""; + return await ShowAsync(await db.Stories.FindAsync([id], cancellationToken), cancellationToken); + } + + if (words != block.Text) + { + block.Text = words; + var story = (await db.Stories.FindAsync([id], cancellationToken))!; + audit.Record(AuditAction.StoryChanged, story.Title, story: story); + await db.SaveChangesAsync(cancellationToken); + } + + return BackToBlock(id, blockId); + } + + public async Task OnPostSaveCaptionAsync(int id, int blockId, string? caption, CancellationToken cancellationToken) + { + var block = await FindBlockAsync(id, blockId, StoryBlockKind.Item, cancellationToken); + if (block is null) + return NotFound(); + + var words = Clean(caption); + if (words is { Length: > StoryBlock.CaptionMaxLength }) + { + ModelState.AddModelError($"caption-{blockId}", localizer["The caption can be at most {0} characters long.", StoryBlock.CaptionMaxLength]); + TypedText[blockId] = caption ?? ""; + return await ShowAsync(await db.Stories.FindAsync([id], cancellationToken), cancellationToken); + } + + if (words != block.Caption) + { + block.Caption = words; + var story = (await db.Stories.FindAsync([id], cancellationToken))!; + audit.Record(AuditAction.StoryChanged, story.Title, story: story); + await db.SaveChangesAsync(cancellationToken); + } + + return BackToBlock(id, blockId); + } + + /// Puts a block earlier or later. Only block rows change: the story's own row, version and date stay as they are. + /// "earlier" or "later". + public async Task OnPostMoveBlockAsync(int id, int blockId, string? direction, CancellationToken cancellationToken) + { + var story = await db.Stories.FindAsync([id], cancellationToken); + if (story is null) + return NotFound(); + + var blocks = await db.StoryBlocks.Where(b => b.StoryId == id).OrderBy(b => b.Position).ThenBy(b => b.Id).ToListAsync(cancellationToken); + var from = blocks.FindIndex(b => b.Id == blockId); + if (from < 0) + return NotFound(); + + var to = direction switch + { + "earlier" => Math.Max(from - 1, 0), + "later" => Math.Min(from + 1, blocks.Count - 1), + _ => from, + }; + if (to == from) + return BackToBlock(id, blockId); + var block = blocks[from]; + blocks.RemoveAt(from); + blocks.Insert(to, block); + for (var position = 0; position < blocks.Count; position++) + blocks[position].Position = position; + + await audit.RecordStoryBlocksArrangedAsync(story, cancellationToken); + await db.SaveChangesAsync(cancellationToken); + return BackToBlock(id, blockId); + } + + public async Task OnPostRemoveBlockAsync(int id, int blockId, CancellationToken cancellationToken) + { + var story = await db.Stories.FindAsync([id], cancellationToken); + if (story is null) + return NotFound(); + + var blocks = await db.StoryBlocks.Where(b => b.StoryId == id).OrderBy(b => b.Position).ThenBy(b => b.Id).ToListAsync(cancellationToken); + var block = blocks.Find(b => b.Id == blockId); + if (block is null) + return NotFound(); + + var item = block.ArchiveItemId is { } itemId ? await db.ArchiveItems.IgnoreQueryFilters().FirstOrDefaultAsync(i => i.Id == itemId, cancellationToken) : null; + blocks.Remove(block); + db.StoryBlocks.Remove(block); + for (var position = 0; position < blocks.Count; position++) + blocks[position].Position = position; + + audit.Record(block.Kind == StoryBlockKind.Item ? AuditAction.StoryItemRemoved : AuditAction.StoryChanged, story.Title, item, story); + await db.SaveChangesAsync(cancellationToken); + return RedirectToPage(new { id }); + } + + private async Task FindBlockAsync(int storyId, int blockId, StoryBlockKind kind, CancellationToken cancellationToken) => + await db.StoryBlocks.FirstOrDefaultAsync(b => b.Id == blockId && b.StoryId == storyId && b.Kind == kind, cancellationToken); + + private async Task IsFullAsync(int id, CancellationToken cancellationToken) => + await db.StoryBlocks.CountAsync(b => b.StoryId == id, cancellationToken) >= Story.MaxBlocks; + + private string FullMessage() => localizer.Plural("A story can have at most {0, plural, one {# part} other {# parts}}.", Story.MaxBlocks); + + /// Back to the page at the block, with the keyboard focus on it and also without JavaScript. + private IActionResult BackToBlock(int id, int blockId) => + RedirectToPage("Edit", null, new { id, block = blockId }, $"block-{blockId}"); + + private async Task ShowAsync(Story? story, CancellationToken cancellationToken) + { + if (story is null) + return NotFound(); + + Input = new InputModel { Title = story.Title, Summary = story.Summary, Version = story.Version }; + await LoadAsync(story, cancellationToken); + return Page(); + } + + private async Task LoadAsync(Story story, CancellationToken cancellationToken) + { + Story = story; + var blocks = await db.StoryBlocks.AsNoTracking().Where(b => b.StoryId == story.Id) + .OrderBy(b => b.Position).ThenBy(b => b.Id).ToListAsync(cancellationToken); + var ids = blocks.Where(b => b.ArchiveItemId is not null).Select(b => b.ArchiveItemId!.Value).Distinct().ToList(); + + // Curators see every item and why visitors may not, so the items come with the bin and the drafts. + var items = ids.Count == 0 ? [] : await db.ArchiveItems.IgnoreQueryFilters().Where(i => ids.Contains(i.Id)) + .Select(i => new + { + i.Id, + i.Title, + i.DateText, + i.Status, + i.PublicFrom, + i.DeletedAt, + Thumbnail = i.MediaFiles.Where(f => f.DeletedAt == null && f.Status == ProcessingStatus.Ready && !f.ContentType.StartsWith("audio/")) + .OrderBy(f => f.Position).ThenBy(f => f.Id).Select(f => (int?)f.Id).FirstOrDefault(), + }).ToDictionaryAsync(i => i.Id, cancellationToken); + // The one definition of "visitors see it", with and without its photos. + var shown = ids.Count == 0 ? [] : (await db.VisibleItems.Where(i => ids.Contains(i.Id)).Select(i => i.Id).ToListAsync(cancellationToken)).ToHashSet(); + var shownWithPhotos = ids.Count == 0 ? [] : (await db.VisibleItems.Where(i => ids.Contains(i.Id) && i.MediaLevel == MediaLevel.Everything).Select(i => i.Id).ToListAsync(cancellationToken)).ToHashSet(); + + Blocks = blocks.Select(b => + { + if (b.Kind == StoryBlockKind.Text || b.ArchiveItemId is not { } itemId || !items.TryGetValue(itemId, out var item)) + return new BlockRow(b.Id, b.Kind, b.Text, b.Caption, b.ArchiveItemId, null, null, null, b.Kind == StoryBlockKind.Text ? ItemState.Shown : ItemState.Missing, null); + + var state = shown.Contains(itemId) + ? shownWithPhotos.Contains(itemId) ? ItemState.Shown : ItemState.ShownWithoutPhotos + : item.DeletedAt is not null ? ItemState.InBin + : item.Status is ItemStatus.Rejected or ItemStatus.Withdrawn ? ItemState.Withdrawn + : item.PublicFrom is not null && item.Status == ItemStatus.Published ? ItemState.PublicFrom + : ItemState.Draft; + return new BlockRow(b.Id, b.Kind, b.Text, b.Caption, itemId, item.Title, item.DateText, item.Thumbnail, state, item.PublicFrom); + }).ToList(); + } + + /// The text with the line breaks of every system made one kind and the edges trimmed; null when nothing is left. + private static string? Clean(string? text) => + string.IsNullOrWhiteSpace(text) ? null : text.Replace("\r\n", "\n").Replace('\r', '\n').Trim(); + + /// The number in "12", "/items/12", "/Admin/Items/Edit/12" or the same with the address of the site in front. + public static int? ItemNumber(string? reference) + { + var match = ItemReference().Match(reference ?? ""); + return match.Success && int.TryParse(match.Groups["number"].Value, out var number) && number > 0 ? number : null; + } + + [GeneratedRegex(@"^\s*(?:https?://[^/\s]+)?(?:/(?:items|admin/items/edit)/)?(?\d{1,9})(?:[/?#]\S*)?\s*$", RegexOptions.IgnoreCase)] + private static partial Regex ItemReference(); +} diff --git a/src/Commonage.Web/Pages/Admin/Stories/Index.cshtml b/src/Commonage.Web/Pages/Admin/Stories/Index.cshtml new file mode 100644 index 0000000..8a666e0 --- /dev/null +++ b/src/Commonage.Web/Pages/Admin/Stories/Index.cshtml @@ -0,0 +1,51 @@ +@page +@model Commonage.Web.Pages.Admin.Stories.IndexModel +@using Commonage.Web.Domain +@{ + ViewData["Title"] = T["Stories"]; +} + +

    @ViewData["Title"]

    +

    @T["A story puts text and items in an order of your choice. Visitors cannot read stories yet."]

    + +
    + +
    + + +
    +
    + +
    + + +@if (Model.Stories.Count == 0) +{ +

    @T["There are no stories yet."]

    +} +else +{ +
      + @for (var index = 0; index < Model.Stories.Count; index++) + { + var story = Model.Stories[index]; +
    1. + + @ArchiveItem.ShownTitle(T, story.Title) + @(story.Status == StoryStatus.Published ? T["Published"] : T["Draft"]) + @T.Plural("{0, plural, one {# part} other {# parts}}", story.BlockCount) + @if (story.HiddenCount > 0) + { + @T.Plural("{0, plural, one {# item not shown to visitors} other {# items not shown to visitors}}", story.HiddenCount) + } + +
      + + +
      +
    2. + } +
    +} diff --git a/src/Commonage.Web/Pages/Admin/Stories/Index.cshtml.cs b/src/Commonage.Web/Pages/Admin/Stories/Index.cshtml.cs new file mode 100644 index 0000000..f6c6149 --- /dev/null +++ b/src/Commonage.Web/Pages/Admin/Stories/Index.cshtml.cs @@ -0,0 +1,85 @@ +using System.ComponentModel.DataAnnotations; +using Commonage.Web.Audit; +using Commonage.Web.Data; +using Commonage.Web.Domain; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.RazorPages; +using Microsoft.EntityFrameworkCore; + +namespace Commonage.Web.Pages.Admin.Stories; + +/// Every story, in the order visitors will find them, which curators change here one step at a time. +public class IndexModel(CommonageDbContext db, AuditLog audit, TimeProvider clock) : PageModel +{ + public record StoryRow(int Id, string Title, StoryStatus Status, int BlockCount, int HiddenCount); + + public IReadOnlyList Stories { get; private set; } = []; + + [BindProperty] + [Required(ErrorMessage = "Please enter a title.")] + [StringLength(Story.TitleMaxLength, ErrorMessage = "The title can be at most {1} characters long.")] + [Display(Name = "Title of the new story")] + public string? NewTitle { get; set; } + + public async Task OnGetAsync(CancellationToken cancellationToken) => await LoadAsync(cancellationToken); + + public async Task OnPostCreateAsync(CancellationToken cancellationToken) + { + var title = NewTitle?.Trim(); + if (!ModelState.IsValid || string.IsNullOrEmpty(title)) + { + await LoadAsync(cancellationToken); + return Page(); + } + + var now = clock.GetUtcNow().UtcDateTime; + // Last in the list: one more than the highest number, which stays right while the others are renumbered on a move. + var position = await db.Stories.AnyAsync(cancellationToken) ? await db.Stories.MaxAsync(s => s.Position, cancellationToken) + 1 : 0; + var story = new Story { Title = title, Status = StoryStatus.Draft, CreatedAt = now, UpdatedAt = now, Position = position }; + db.Stories.Add(story); + audit.Record(AuditAction.StoryCreated, story.Title, story: story); + await db.SaveChangesAsync(cancellationToken); + return RedirectToPage("Edit", new { id = story.Id }); + } + + public Task OnPostMoveEarlierAsync(int id, CancellationToken cancellationToken) => MoveAsync(id, -1, cancellationToken); + + public Task OnPostMoveLaterAsync(int id, CancellationToken cancellationToken) => MoveAsync(id, 1, cancellationToken); + + /// Swaps the story with its neighbour and numbers them all again from 0. A move does not touch the story's own text or version. + private async Task MoveAsync(int id, int step, CancellationToken cancellationToken) + { + var all = await db.Stories.OrderBy(s => s.Position).ThenBy(s => s.Id).ToListAsync(cancellationToken); + var at = all.FindIndex(s => s.Id == id); + if (at < 0) + return NotFound(); + + var to = at + step; + if (to >= 0 && to < all.Count) + { + (all[at], all[to]) = (all[to], all[at]); + for (var position = 0; position < all.Count; position++) + all[position].Position = position; + audit.Record(AuditAction.StoriesArranged, all[to].Title, story: all[to]); + await db.SaveChangesAsync(cancellationToken); + } + + return Redirect($"{Url.Page("/Admin/Stories/Index")}#story-{id}"); + } + + private async Task LoadAsync(CancellationToken cancellationToken) + { + var rows = await db.Stories.OrderBy(s => s.Position).ThenBy(s => s.Id) + .Select(s => new + { + s.Id, + s.Title, + s.Status, + Blocks = s.Blocks.Count, + // An item block that visitors do not see: counted here, under /Admin, and nowhere else. + Hidden = s.Blocks.Count(b => b.Kind == StoryBlockKind.Item && !db.VisibleItems.Any(i => i.Id == b.ArchiveItemId)), + }) + .ToListAsync(cancellationToken); + Stories = rows.Select(r => new StoryRow(r.Id, r.Title, r.Status, r.Blocks, r.Hidden)).ToList(); + } +} diff --git a/src/Commonage.Web/Pages/Admin/Stories/Preview.cshtml b/src/Commonage.Web/Pages/Admin/Stories/Preview.cshtml new file mode 100644 index 0000000..297e1f3 --- /dev/null +++ b/src/Commonage.Web/Pages/Admin/Stories/Preview.cshtml @@ -0,0 +1,26 @@ +@page "{id:int}" +@model Commonage.Web.Pages.Admin.Stories.PreviewModel +@using Commonage.Web.Domain +@{ + ViewData["Title"] = T["Preview: {0}", ArchiveItem.ShownTitle(T, Model.Body.Title)]; +} + +
    + + @if (Model.Status != StoryStatus.Published) + { + @T["Preview. This story is a draft: visitors cannot see it."] + } + else if (Model.Body.Blocks.Count == 0) + { + @T["Preview. Visitors see no part of this story, so they cannot find it."] + } + else + { + @T["Preview. This is what visitors will see, without the items they may not see."] + } + + @T["Back to editing"] +
    + + diff --git a/src/Commonage.Web/Pages/Admin/Stories/Preview.cshtml.cs b/src/Commonage.Web/Pages/Admin/Stories/Preview.cshtml.cs new file mode 100644 index 0000000..0233085 --- /dev/null +++ b/src/Commonage.Web/Pages/Admin/Stories/Preview.cshtml.cs @@ -0,0 +1,27 @@ +using Commonage.Web.Data; +using Commonage.Web.Domain; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.RazorPages; +using Microsoft.EntityFrameworkCore; + +namespace Commonage.Web.Pages.Admin.Stories; + +/// Shows curators a story as visitors would see it, whatever its status. The blocks come the way public ones will: only what visitors may see. +public class PreviewModel(CommonageDbContext db) : PageModel +{ + public int StoryId { get; private set; } + public StoryStatus Status { get; private set; } + public StoryBody Body { get; private set; } = null!; + + public async Task OnGetAsync(int id, CancellationToken cancellationToken) + { + var story = await db.Stories.AsNoTracking().FirstOrDefaultAsync(s => s.Id == id, cancellationToken); + if (story is null) + return NotFound(); + + StoryId = story.Id; + Status = story.Status; + Body = new StoryBody(story.Title, story.Summary, await VisibleStoryBlocks.LoadAsync(db, id, cancellationToken)); + return Page(); + } +} diff --git a/src/Commonage.Web/Pages/Admin/_AdminLayout.cshtml b/src/Commonage.Web/Pages/Admin/_AdminLayout.cshtml index c5b964e..13d2f22 100644 --- a/src/Commonage.Web/Pages/Admin/_AdminLayout.cshtml +++ b/src/Commonage.Web/Pages/Admin/_AdminLayout.cshtml @@ -14,6 +14,7 @@ @if (Commonage.Web.Identity.Roles.MayManage(User)) { @T["Collections"] + @T["Stories"] @T["Tags"] @T["Contribution links"] @T["Notes from visitors"] diff --git a/src/Commonage.Web/Pages/Shared/_StoryBody.cshtml b/src/Commonage.Web/Pages/Shared/_StoryBody.cshtml new file mode 100644 index 0000000..872ce86 --- /dev/null +++ b/src/Commonage.Web/Pages/Shared/_StoryBody.cshtml @@ -0,0 +1,33 @@ +@model Commonage.Web.Data.StoryBody +@inject Commonage.Web.Operations.ArchiveProfile Profile +@{ + var material = (await Profile.GetAsync()).MaterialLanguage; +} + +@* Public: nothing here may say more than the page shows. No ids, positions, anchors or data attributes, so that a block + left out because its item is hidden leaves nothing to tell it was there. *@ +
    +

    @Model.Title

    + @if (!string.IsNullOrWhiteSpace(Model.Summary)) + { +

    @Model.Summary

    + } + @foreach (var block in Model.Blocks) + { + switch (block) + { + case Commonage.Web.Data.StoryBlockView.Text text: +

    @text.Value

    + break; + case Commonage.Web.Data.StoryBlockView.Item item: +
    + + @if (!string.IsNullOrWhiteSpace(item.Caption)) + { +
    @item.Caption
    + } +
    + break; + } + } +
    diff --git a/src/Commonage.Web/Program.cs b/src/Commonage.Web/Program.cs index ee52a50..6ed1f23 100644 --- a/src/Commonage.Web/Program.cs +++ b/src/Commonage.Web/Program.cs @@ -124,7 +124,7 @@ // A helper reaches the item list, the item form, adding many photos and the preview, and nothing else: EndpointAccessTests // lists what a helper may reach, so a new page under /Admin stays closed to them until that list says otherwise. options.Conventions.AuthorizeFolder("/Admin", Policies.Describe); - foreach (var folder in new[] { "/Admin/Collections", "/Admin/Tags", "/Admin/Contributions", "/Admin/Notes" }) + foreach (var folder in new[] { "/Admin/Collections", "/Admin/Stories", "/Admin/Tags", "/Admin/Contributions", "/Admin/Notes" }) options.Conventions.AuthorizeFolder(folder, Policies.ManageArchive); foreach (var page in new[] { "/Admin/Contributors", "/Admin/Bin", "/Admin/Items/Bulk", "/Admin/Items/Import" }) options.Conventions.AuthorizePage(page, Policies.ManageArchive); diff --git a/src/Commonage.Web/Resources/SharedResource.de.resx b/src/Commonage.Web/Resources/SharedResource.de.resx index 5079d50..8c3e86a 100644 --- a/src/Commonage.Web/Resources/SharedResource.de.resx +++ b/src/Commonage.Web/Resources/SharedResource.de.resx @@ -1083,4 +1083,66 @@ {0, plural, one {Und # weiterer Fund, der nicht aufgelistet ist.} other {Und # weitere Funde, die nicht aufgelistet sind.}} Ein Objekt mit diesem Titel und Datum ist in dieser Sammlung schon vorhanden. Fotos, die nicht hinzugefügt werden konnten, weil sich die Dateien geändert hatten: {0} + „stories“ in archive.json listet die Geschichten auf: Jede hat ihre Teile in der Reihenfolge, und ein Teil ist entweder ein Text oder die Nummer eines Objekts unter „items“ mit einer Bildunterschrift. + Ein paar Worte, die die Geschichte eröffnen und sie in einer Liste beschreiben. + Eine Geschichte kann höchstens {0, plural, one {# Teil} other {# Teile}} haben. + Eine Geschichte bringt Texte und Objekte in eine Reihenfolge Ihrer Wahl. Besucher können Geschichten noch nicht lesen. + Objekt hinzufügen + Text hinzufügen + Hat der Geschichte ein Objekt hinzugefügt + Bildunterschrift (optional) + Hat die Reihenfolge der Teile der Geschichte geändert + Hat die Reihenfolge der Geschichten geändert + Hat die Geschichte geändert + Hat die Geschichte angelegt + Hat die Geschichte nach ihrer Zeit im Papierkorb gelöscht + Hat die Geschichte endgültig gelöscht + Geschichte bearbeiten + Objekt Nummer {0} + Objekt {0} von {1} + Hat die Geschichte in den Papierkorb gelegt + Neue Geschichte + Nummer oder Adresse des Objekts + Teile der Geschichte + Bitte geben Sie die Nummer eines Objekts oder die Adresse seiner Seite ein. + Bitte schreiben Sie etwas Text. + Vorschau. So sehen Besucher die Geschichte, ohne die Objekte, die sie nicht sehen dürfen. + Vorschau. Diese Geschichte ist ein Entwurf: Besucher können sie nicht sehen. + Vorschau. Besucher sehen keinen Teil dieser Geschichte und können sie deshalb nicht finden. + Hat die Geschichte veröffentlicht + Dieses Objekt aus der Geschichte entfernen? Das Objekt selbst bleibt im Archiv. + Diesen Text aus der Geschichte entfernen? Er lässt sich nicht zurückholen. + Entfernen: {0} + Hat ein Objekt aus der Geschichte entfernt + Bildunterschrift speichern + Text speichern + Jemand anderes hat diese Geschichte geändert, während Sie daran gearbeitet haben + Geschichten + Zusammenfassung + Text {0} von {1} + Die Bildunterschrift kann höchstens {0} Zeichen lang sein. + Der Export enthält {0, plural, one {# Geschichte} other {# Geschichten}}. Geschichten werden nicht importiert. + Das Objekt ist hinzugefügt. Besucher sehen es erst, wenn es öffentlich ist. + Die Nummer des Objekts oder die Adresse seiner Seite, zum Beispiel /items/12. + Die Geschichte ist wieder ein Entwurf. + Die Geschichte ist veröffentlicht. + Die Zusammenfassung kann höchstens {1} Zeichen lang sein. + Der Text kann höchstens {0} Zeichen lang sein. + Es gibt noch keine Geschichten. + Es gibt kein Objekt mit dieser Nummer. + Dieses Objekt ist im Papierkorb. Holen Sie es zuerst aus dem Papierkorb. + Dieses Objekt gibt es nicht mehr. + Dieses Objekt wurde abgelehnt oder zurückgezogen und kann nicht Teil einer Geschichte sein. + Diese Geschichte hat noch keine Teile. Fügen Sie unten Text oder ein Objekt hinzu. + Titel der neuen Geschichte + Hat die Geschichte aus dem Papierkorb geholt + Hat die Veröffentlichung der Geschichte zurückgenommen + Besucher können Geschichten noch nicht lesen. Eine veröffentlichte Geschichte sehen sie als Erstes, sobald sie es können. + Besucher sehen dieses Objekt erst ab {0}. + Besucher sehen dieses Objekt nicht: Es ist im Papierkorb. + Besucher sehen dieses Objekt nicht: Es ist nicht veröffentlicht. + Besucher sehen dieses Objekt nicht: Es wurde abgelehnt oder zurückgezogen. + Besucher sehen dieses Objekt ohne seine Fotos. + {0, plural, one {# Objekt, das Besuchern nicht gezeigt wird} other {# Objekte, die Besuchern nicht gezeigt werden}} + {0, plural, one {# Teil} other {# Teile}} diff --git a/src/Commonage.Web/Resources/SharedResource.resx b/src/Commonage.Web/Resources/SharedResource.resx index 80c2f34..aa54c30 100644 --- a/src/Commonage.Web/Resources/SharedResource.resx +++ b/src/Commonage.Web/Resources/SharedResource.resx @@ -8,6 +8,7 @@ "Needs attention" still answers with HTTP status 200, so an uptime monitor only notices it if it looks for the word Healthy. docs/operations.md says how. "contentLanguage" under "settings" says which language most of the material is written in, as a code such as "de" or "pl". "mul" means several languages, none of them most. "includesPersonalData" in archive.json says whether the names of contributors, photographers and authors and contributors' email addresses are included. If they are, keep this file as carefully as the archive itself. + "stories" in archive.json lists the stories: each has its parts in order, and a part is either a text or the number of an item under "items" with a caption. /health answers: A built-in folding that covers most, but not all, letters. With the PostgreSQL extension unaccent on the database server, the archive uses it from the next start. A caption can be at most {0, plural, one {# character} other {# characters}} long.Has a count. Write a form for each one your language needs, in ICU MessageFormat. @@ -15,6 +16,7 @@ A date A description A few words about what this archive is, for example: Photos and memories from Lindenau. + A few words that open the story and describe it in a list. A few words, for example: Flood in Mill Street A file with "problem": "missing" was not found on the server; "checksumMismatch" means it no longer matches the checksum taken when it was uploaded. Both should be looked into. A large archive can take a while. Keep this page open until the download has finished. @@ -24,6 +26,8 @@ A photo description can be at most {0, plural, one {# character} other {# characters}} long.Has a count. Write a form for each one your language needs, in ICU MessageFormat. A recording needs its transcript in the description before it is published, or tick that a transcript will follow. A rights statement + A story can have at most {0, plural, one {# part} other {# parts}}.Has a count. Write a form for each one your language needs, in ICU MessageFormat. + A story puts text and items in an order of your choice. Visitors cannot read stories yet. A tag can be at most {0, plural, one {# character} other {# characters}} long.Has a count. Write a form for each one your language needs, in ICU MessageFormat. A tag can be at most {1} characters long. A tag name cannot contain commas or semicolons. @@ -42,14 +46,17 @@ Accounts and logins Active Activity log + Add an item Add anyway Add item Add many photos Add more photos Add tags Add tags to many at once + Add text Add these photos Added + Added an item to the story Added in the last 30 days Added photos Address of the link @@ -102,6 +109,7 @@ Can you help? Cancel Caption + Caption (optional) Catalogue details Change many at once Change password @@ -115,7 +123,10 @@ Changed the item Changed the name of an account Changed the order of the collections + Changed the order of the parts of the story + Changed the order of the stories Changed the order or direction of photos + Changed the story Changed the tag Changed their password Changed what visitors get of the item @@ -184,6 +195,7 @@ Created the collection while importing Created the contribution link Created the item + Created the story Creating preview… Credit Curator @@ -219,6 +231,8 @@ Deleted the empty collection Deleted the item for good Deleted the item for good after its time in the bin + Deleted the story after its time in the bin + Deleted the story for good Deleted the unused tag Describes items and adds photos. Cannot publish, delete, review contributions or see contributors' details. Description @@ -247,6 +261,7 @@ Earlier: {0} Edit collection Edit contribution link + Edit story Edit: {0} Email Email address @@ -346,6 +361,8 @@ Invite visitors on the collection's page It should be taken down, for example because it shows me Item + Item number {0} + Item {0} of {1} Items Items belong to a collection. Items changed: {0}. Left as they were: {1}. @@ -431,6 +448,7 @@ Moved a photo to the bin Moved the item to the bin Moved the rejected or withdrawn contribution to the bin, at the end of the time the archive keeps them + Moved the story to the bin Moved to the bin on {0} Name Name and email address removed on {0} @@ -451,6 +469,7 @@ New password New password again New recovery codes replace the old ones. + New story Newest first Next Next item @@ -493,6 +512,7 @@ Nothing is waiting for help right now. Thank you for looking. Nothing matches your search. Try fewer words or remove a filter. Now + Number or address of the item Of which originals: {0} in {1, plural, one {# file} other {# files}}. The rest are the picture sizes made from them.Has a count. Write a form for each one your language needs, in ICU MessageFormat. Oldest first On each contribution you can remove their name and email address, mark it as withdrawn, or move the item to the bin and delete it there for good. Backups keep older copies until they are replaced. @@ -527,6 +547,7 @@ Page {0} of {1} Pages Pages about your archive + Parts of the story Password People Period @@ -576,6 +597,7 @@ Please enter an email address. Please enter at least one tag. Please enter the code from your app. + Please enter the number of an item, or the address of its page. Please enter the password again. Please enter the tag to merge this one into. Please enter your current password. @@ -586,14 +608,18 @@ Please keep this page open until it is done. Please tell us who made it. Please tick at least one item. + Please write some text. Please write your message. Poster to print Poster: {0} Preparing the recording… Preview Preview. Public from {0}. + Preview. This is what visitors will see, without the items they may not see. Preview. This item is public. + Preview. This story is a draft: visitors cannot see it. Preview. Visitors cannot see this item. + Preview. Visitors see no part of this story, so they cannot find it. Preview. Visitors see the record only, without its pictures and recordings. Preview: {0} Previews @@ -615,6 +641,7 @@ Publish: {0} Published Published the item + Published the story Read an export into this archive Read the privacy text and adapt it Reads the ZIP file that the export of a Commonage archive makes, to merge two archives or to start a new one from another. Every item becomes a draft, and nothing is imported before you have seen a dry run. @@ -636,7 +663,11 @@ Remove the logo Remove the name and email address from this note? The message stays. This cannot be undone. Remove this filter + Remove this item from the story? The item itself stays in the archive. + Remove this text from the story? It cannot be brought back. Remove {0} + Remove: {0} + Removed an item from the story Removed the contributor's name and email address Removed the name and email address from a visitor's note Request to take it down @@ -660,9 +691,11 @@ Save and next Save and publish Save as draft + Save caption Save name Save password Save role + Save text Save these details Say how people can reach you Scan the code with your phone's camera, or type this address: @@ -713,6 +746,7 @@ Some items wait for someone who knows more about them. Someone else changed one of these items just now, so nothing was changed. Please try again. Someone else changed this item while you were working on it + Someone else changed this story while you were working on it Someone else made it, and I have their permission or inherited the rights. Someone else; the contributor has permission or inherited the rights Someone who opens a closed link is told that it is closed, and that nothing can be sent through it. You can open it again at any time. @@ -728,9 +762,11 @@ Still needs a transcription Stop sending Stopped logging in with an authenticator app + Stories Submitted Suggested because the contributor offered this themselves. Check that it is theirs to give before you publish: a free licence cannot be taken back from those who have already reused it. Suggested from what the contributor answered. They agreed to publication on this website, not to reuse by others, so only a free licence they gave you themselves should go further. + Summary System Tag Tag “{0}” @@ -742,6 +778,7 @@ Tell us Test restoring a backup, on another machine (docs/deployment.md) Text + Text {0} of {1} Text. Thank you That took too long. Please log in again. @@ -763,6 +800,7 @@ The archive's storage is full The authenticator app is turned off for this account. The person logs in with their password now. The bin is empty. + The caption can be at most {0} characters long. The collection is empty, so it can be deleted. The collection of this item is not in the export. The collection “{0}” is deleted. @@ -796,6 +834,7 @@ The earlier text is back. The email address can be at most {1} characters long. The email address or password is incorrect. + The export holds {0, plural, one {# story} other {# stories}}. Stories are not imported.Has a count. Write a form for each one your language needs, in ICU MessageFormat. The file archive.json in this export could not be read. The file archive.json in this export is too large to read. The files for this import are no longer there. Please choose them again. @@ -805,6 +844,7 @@ The heading contributors see, for example: Share your photos of the Mill Street flood The import stopped early, because the disk or the database kept failing, or the server was shutting down. {0, plural, one {# item was} other {# items were}} not tried. What came in stays as drafts. Choose the same file again for the rest.Has a count. Write a form for each one your language needs, in ICU MessageFormat. The introduction can be at most {1} characters long. + The item is added. Visitors will not see it until it is public. The item is deleted for good. The item is in the bin. You can restore it there for {0, plural, one {# day} other {# days}}.Has a count. Write a form for each one your language needs, in ICU MessageFormat. The item is no longer public. @@ -825,6 +865,7 @@ The note is deleted. The note is marked as dealt with. The note is open again. + The number of the item, or the address of its page, for example /items/12. The old app no longer works. Set up the new one now: this archive requires it. The original files exactly as they were uploaded, in one folder per item: The other archive could not export this file, so it is left out. @@ -856,7 +897,11 @@ The spreadsheet is not saved as UTF-8, so letters such as ä or ł would be wrong. In the spreadsheet program, save it again as "CSV UTF-8". The spreadsheet is too large. The spreadsheet names files, but no ZIP file or folder was given to find them in. + The story is a draft again. + The story is published. + The summary can be at most {1} characters long. The tag “{0}” is deleted. + The text can be at most {0} characters long. The title can be at most {1} characters long. The title, date and description are kept on this device for three days, in case you have to stop. Your name and email address are not. The two passwords are not the same. @@ -864,11 +909,13 @@ There are no collections yet. There are no contribution links yet. There are no items yet. + There are no stories yet. There are no tags yet. Tags are added on each item. There has been no backup for too long, or none yet. There is already a tag “{0}”. To make one tag of the two, merge them below. There is already an account with this email address. There is no collection with this name. Create it first, or correct the name. + There is no item with this number. There is no tag “{0}”. To give this tag a new name, change its name above. There is nothing left to import. These become public at once: {0}. @@ -902,6 +949,9 @@ This is not one of the archive's rights statements. Write its web address as an export does, or leave the cell empty. This is your own account. Another admin can change its role, disable or delete it. This item is in the bin. + This item is in the bin. Take it out of the bin first. + This item no longer exists. + This item was turned down or withdrawn, and cannot be part of a story. This link is closed This link is closed. The poster would send people to a page that says so. Open the link first. This link is no longer valid. Please ask an admin for a new one. @@ -912,6 +962,7 @@ This reference number is already used by another item. This reference number is already used by: {0} This site only sets the cookies it needs: one for the chosen language, one to protect forms, and one to keep curators logged in. There are no analytics and no third-party services. Visitors' addresses are held in memory for a short time, to limit abuse of forms and logins.Part of the privacy text an archive starts with. Please have a second translator review it. + This story has no parts yet. Add text or an item below. This text can be at most {0, plural, one {# character} other {# characters}} long.Has a count. Write a form for each one your language needs, in ICU MessageFormat. This text can be at most {1} characters long. This text cannot be put back: the field would be empty or no longer reads as valid. @@ -922,6 +973,7 @@ Tick all on this page Time zone Title + Title of the new story Title or name To do: To the archive @@ -932,6 +984,7 @@ Too many attempts Too many attempts came from your network in the last hour. Please try again later. Too many failed attempts. Please try again in a few minutes. + Took the story out of the bin Topic Topics Try again @@ -950,6 +1003,7 @@ Unknown Unpublish Unpublished the item + Unpublished the story Until a curator deletes them Untitled Unused only @@ -965,9 +1019,15 @@ 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 cannot read stories yet. A published story is the first thing they will see once they can. + Visitors do not see this item until {0}. + Visitors do not see this item: it is in the bin. + Visitors do not see this item: it is not published. + Visitors do not see this item: it was turned down or withdrawn. 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. + Visitors see this item without its photos. Waiting Waiting for review: {0} Waiting for setup @@ -1047,11 +1107,13 @@ {0, plural, =0 {You have no recovery codes left. Create new ones, in case you lose your phone.} one {You have one recovery code left.} other {You have # recovery codes left.}}Has a count. Write a form for each one your language needs, in ICU MessageFormat. {0, plural, one {# asks for removal} other {# ask for removal}}Has a count. Write a form for each one your language needs, in ICU MessageFormat. {0, plural, one {# item asks visitors for help} other {# items ask visitors for help}}Has a count. Write a form for each one your language needs, in ICU MessageFormat. + {0, plural, one {# item not shown to visitors} other {# items not shown to visitors}}Has a count. Write a form for each one your language needs, in ICU MessageFormat. {0, plural, one {# item waits for a transcription} other {# items wait for a transcription}}Has a count. Write a form for each one your language needs, in ICU MessageFormat. {0, plural, one {# item} other {# items}}Has a count. Write a form for each one your language needs, in ICU MessageFormat. {0, plural, one {# item} other {# items}} could not be created.Has a count. Write a form for each one your language needs, in ICU MessageFormat. {0, plural, one {# note from visitors to deal with} other {# notes from visitors to deal with}}Has a count. Write a form for each one your language needs, in ICU MessageFormat. {0, plural, one {# of them is not published yet} other {# of them are not published yet}}Has a count. Write a form for each one your language needs, in ICU MessageFormat. + {0, plural, one {# part} other {# parts}}Has a count. Write a form for each one your language needs, in ICU MessageFormat. {0, plural, one {A visitor sent a note about this item.} other {Visitors sent # notes about this item.}}Has a count. Write a form for each one your language needs, in ICU MessageFormat. {0, plural, one {And # more thing found, which is not listed.} other {And # more things found, which are not listed.}}Has a count. Write a form for each one your language needs, in ICU MessageFormat. {0, plural, one {Delete the unused tag} other {Delete the # unused tags}}Has a count. Write a form for each one your language needs, in ICU MessageFormat. diff --git a/src/Commonage.Web/wwwroot/css/site.css b/src/Commonage.Web/wwwroot/css/site.css index 96da1b4..de1144b 100644 --- a/src/Commonage.Web/wwwroot/css/site.css +++ b/src/Commonage.Web/wwwroot/css/site.css @@ -793,3 +793,30 @@ main:focus { outline: 3px solid var(--bs-primary); outline-offset: 2px; } + +/* A story: its text and its items in one column. An item is one card with the curator's words under it. */ +.story { + max-inline-size: 42rem; +} + +.story-figure { + margin-inline: 0; + margin-block: 1.5rem; + max-inline-size: 16rem; +} + +.story-figure .row { + margin: 0; +} + +.story-figure .row > * { + inline-size: 100%; + padding: 0; +} + +.story-block-thumbnail { + inline-size: 6rem; + block-size: 6rem; + object-fit: cover; + flex-shrink: 0; +} diff --git a/tests/Commonage.BrowserTests/AccessibilityTests.cs b/tests/Commonage.BrowserTests/AccessibilityTests.cs index 0fe67bf..6cd3390 100644 --- a/tests/Commonage.BrowserTests/AccessibilityTests.cs +++ b/tests/Commonage.BrowserTests/AccessibilityTests.cs @@ -14,7 +14,7 @@ public static TheoryData PublicPages() => Widths( public static TheoryData CuratorPages() => Widths( "/Admin", "/Admin?status=Submitted", "/Admin/Items/Edit/11", "/Admin/Items/Edit", "/Admin/Items/AddMany", "/Admin/Items/Import", "/Admin/Items/Edit/1", "/Admin/Items/Preview/1", "/Admin/Collections", "/Admin/Collections/Edit/1", "/Admin/Collections/Edit", "/Admin/Tags", "/Admin/Tags/Edit/1", "/Admin/Notes", "/Admin/Notes?show=All", "/Admin/Contributions", "/Admin/Contributions/Poster/1", - "/Admin/Contributors?q=a", "/Admin/Bin", "/Admin/Settings", "/Admin/Users", "/Admin/Activity", "/Admin/Activity?what=Items", "/Admin/Export", "/Admin/ImportArchive", "/Admin/System", "/Account/Password", "/Account/TwoFactor"); + "/Admin/Contributors?q=a", "/Admin/Bin", "/Admin/Settings", "/Admin/Users", "/Admin/Activity", "/Admin/Activity?what=Items", "/Admin/Stories", "/Admin/Stories/Edit/1", "/Admin/Stories/Preview/1", "/Admin/Export", "/Admin/ImportArchive", "/Admin/System", "/Account/Password", "/Account/TwoFactor"); private static TheoryData Widths(params string[] paths) { diff --git a/tests/Commonage.BrowserTests/StoryBrowserTests.cs b/tests/Commonage.BrowserTests/StoryBrowserTests.cs new file mode 100644 index 0000000..fea0d13 --- /dev/null +++ b/tests/Commonage.BrowserTests/StoryBrowserTests.cs @@ -0,0 +1,94 @@ +using Microsoft.Playwright; + +namespace Commonage.BrowserTests; + +/// The story editor for curators: moving parts by keyboard and without JavaScript, asking before a part goes, and warning about unsaved text. +[Collection(nameof(BrowserCollection))] +public class StoryBrowserTests(BrowserFixture app) +{ + private static async Task StoryWithTwoTextsAsync(IPage page, string title) + { + await page.GotoAsync("/Admin/Stories"); + await page.FillAsync("[name='NewTitle']", title); + await page.ClickAsync("main form button:text-is('New story')"); + await page.WaitForURLAsync("**/Admin/Stories/Edit/*"); + foreach (var text in new[] { "First part", "Second part" }) + { + await page.FillAsync("#newText", text); + await page.ClickAsync("main form button:text-is('Add text')"); + await page.WaitForLoadStateAsync(); + } + + return page; + } + + private static Task TextsAsync(IPage page) => + page.EvaluateAsync("[...document.querySelectorAll('ol.list-unstyled textarea[id^=text-]')].map(t => t.value)"); + + [Fact] + public async Task Moving_a_part_with_the_keyboard_keeps_the_place_in_the_list() + { + var page = await app.LogInAsync(); + await StoryWithTwoTextsAsync(page, "Keyboard story"); + + await page.FocusAsync("button[aria-label='Later: Text 1 of 2']"); + await page.Keyboard.PressAsync("Enter"); + await page.WaitForFunctionAsync("document.activeElement.id.startsWith('block-')"); + + Assert.Equal(["Second part", "First part"], await TextsAsync(page)); + var focused = await page.EvaluateAsync("document.activeElement.id"); + Assert.StartsWith("block-", focused); + Assert.Equal("First part", await page.InputValueAsync($"#{focused} textarea")); + } + + [Fact] + public async Task Without_javascript_a_part_can_be_moved_and_removed() + { + var page = await app.LogInAsync(javaScript: false); + await StoryWithTwoTextsAsync(page, "Plain story"); + + await page.ClickAsync("button[aria-label='Earlier: Text 2 of 2']"); + Assert.Equal(["Second part", "First part"], await TextsAsync(page)); + + await page.ClickAsync("button[aria-label='Remove: Text 1 of 2']"); + Assert.Equal(["First part"], await TextsAsync(page)); + } + + [Fact] + public async Task Removing_a_part_asks_first_and_no_keeps_it() + { + var page = await app.LogInAsync(); + await StoryWithTwoTextsAsync(page, "Remove story"); + var dialogs = new List(); + page.Dialog += async (_, dialog) => { dialogs.Add(dialog.Type); await dialog.DismissAsync(); }; + + await page.ClickAsync("button[aria-label='Remove: Text 1 of 2']"); + await page.WaitForTimeoutAsync(300); + + Assert.Equal(["confirm"], dialogs); + Assert.Equal(["First part", "Second part"], await TextsAsync(page)); + } + + [Fact] + public async Task Leaving_with_an_edited_text_part_asks_first() + { + var page = await app.LogInAsync(); + await StoryWithTwoTextsAsync(page, "Warning story"); + var dialogs = new List(); + page.Dialog += async (_, dialog) => { dialogs.Add(dialog.Type); await dialog.DismissAsync(); }; + + var editUrl = page.Url; + await page.ClickAsync(".breadcrumb a >> nth=1"); + await page.WaitForURLAsync("**/Admin/Stories"); + Assert.Empty(dialogs); + + await page.GotoAsync(editUrl); + await page.FillAsync("textarea[id^=text-] >> nth=0", "Changed but not saved"); + await page.ClickAsync(".breadcrumb a >> nth=1"); + for (var i = 0; i < 100 && dialogs.Count == 0; i++) + await Task.Delay(50); + + Assert.Equal(["beforeunload"], dialogs); + Assert.Equal("Changed but not saved", await page.InputValueAsync("textarea[id^=text-] >> nth=0")); + } +} diff --git a/tests/Commonage.Tests/ExportImportTests.cs b/tests/Commonage.Tests/ExportImportTests.cs index 946d312..90cf078 100644 --- a/tests/Commonage.Tests/ExportImportTests.cs +++ b/tests/Commonage.Tests/ExportImportTests.cs @@ -208,9 +208,36 @@ await from.WithDbAsync(async db => Assert.Single(await into.WithDbAsync(db => db.ArchiveItems.IgnoreQueryFilters().ToListAsync())); } + /// Stories are only counted: the dry run says how many there are, nothing of them is read, and nothing is created for them. + [Fact] + public async Task Stories_in_an_export_are_counted_by_the_dry_run_and_not_imported() + { + using var curator = await CuratorAsync(app); + var word = Word(); + var json = JsonSerializer.SerializeToUtf8Bytes(new + { + format = "commonage-export", version = 9, collections = new[] { Collection(1, $"{word} Collection") }, tags = Array.Empty(), + items = new[] { Item(1, $"{word} Barn") }, + stories = new object[] + { + new { id = 1, title = "First", blocks = new object[] { new { kind = "Text", text = "words" }, new { kind = "Item", itemId = 1, caption = "c" } } }, + new { id = 2, title = (string?)null, blocks = (object?)null, extra = new { deeply = new[] { 1, 2, 3 } } }, + }, + }, Json); + var storiesBefore = await app.WithDbAsync(db => db.Stories.IgnoreQueryFilters().CountAsync()); + + var html = await DryRunAsync(curator, Zip(("archive.json", json))); + await ImportAsync(curator, html); + + Assert.Contains("The export holds 2 stories. Stories are not imported.", html); + Assert.Single(await ItemsAsync(word)); + Assert.Equal(storiesBefore, await app.WithDbAsync(db => db.Stories.IgnoreQueryFilters().CountAsync())); + } + [Theory] [InlineData(4)] [InlineData(8)] + [InlineData(9)] public async Task Versions_four_to_the_current_one_are_read(int version) { using var curator = await CuratorAsync(app); @@ -225,7 +252,7 @@ public async Task Versions_four_to_the_current_one_are_read(int version) [Theory] [InlineData(3, "format version 3")] - [InlineData(9, "format version 9")] + [InlineData(10, "format version 10")] public async Task Other_versions_and_other_files_are_refused_with_a_sentence(int version, string expected) { using var curator = await CuratorAsync(app); @@ -798,7 +825,7 @@ public async Task Only_an_admin_may_use_the_page() public void Every_property_of_the_export_has_a_decision_and_the_reader_holds_exactly_what_is_not_dropped() { var assembly = typeof(ArchiveExporter).Assembly; - string[] types = ["ExportSettings", "ExportText", "ExportCollection", "ExportTag", "ExportItem", "ExportDate", "ExportContribution", "ExportNote", "ExportFile"]; + string[] types = ["ExportSettings", "ExportText", "ExportCollection", "ExportTag", "ExportItem", "ExportDate", "ExportContribution", "ExportNote", "ExportFile", "ExportStory", "ExportStoryBlock"]; var missing = new List(); var found = new HashSet(); foreach (var name in types) diff --git a/tests/Commonage.Tests/ExportTests.cs b/tests/Commonage.Tests/ExportTests.cs index a70d5b3..8f5d8b1 100644 --- a/tests/Commonage.Tests/ExportTests.cs +++ b/tests/Commonage.Tests/ExportTests.cs @@ -115,9 +115,14 @@ public async Task Without_personal_data_no_name_or_email_is_in_the_export() [InlineData(typeof(Collection), "collection", "id title description createdAt position sort coverFileId", "Items: each item names its collection. CoverMediaFileId: as coverFileId.")] [InlineData(typeof(Tag), "tag", "name kind", "Id: items name their tags. NormalizedName: follows from the name. Items: each item lists its tags.")] [InlineData(typeof(VisitorNote), "note", "kind message name email receivedAt handledAt personalDetailsRemovedAt", "Id, ArchiveItemId, ArchiveItem: listed under its item. RemovePersonalDetails: a method.")] + [InlineData(typeof(Story), "story", "id title summary status createdAt publishedAt position blocks", + "UpdatedAt: made again where the story arrives. DeletedAt: the bin is not exported. Version: only for open forms. IsUntitled: follows from the empty title. CanBePublished: follows from the blocks and the title.")] + [InlineData(typeof(StoryBlock), "block", "kind text itemId caption", + "Id, StoryId, Story: the block is listed under its story. ArchiveItemId: as itemId. Position: follows from the order they are listed in. ArchiveItem: as itemId, and only when that item is in the export.")] public async Task Every_field_is_exported_or_left_out_on_purpose(Type type, string part, string exported, string leftOut) { var item = await app.CreateContributionAsync(ItemStatus.Published); + var storyTitle = TestData.Unique("Fields story"); using var admin = app.CreateClient(); await Browser.LogInAsCuratorAsync(admin); await Browser.UploadAsync(admin, $"/Admin/Items/Edit/{item.Id}", "Upload", "photo.jpg", TestData.Photo); @@ -127,10 +132,15 @@ await app.WithDbAsync(async db => var name = TestData.Unique("place"); tagged.SetTags([new Tag { Name = name, NormalizedName = Tag.Normalize(name), Kind = TagKind.Place }]); db.VisitorNotes.Add(new VisitorNote { ArchiveItemId = item.Id, Kind = VisitorNoteKind.Information, Message = "A note", ReceivedAt = DateTime.UtcNow }); + var story = new Story { Title = storyTitle, Status = StoryStatus.Draft, CreatedAt = DateTime.UtcNow, UpdatedAt = DateTime.UtcNow }; + story.Blocks.Add(new StoryBlock { Position = 0, Kind = StoryBlockKind.Item, ArchiveItemId = item.Id, Caption = "A caption" }); + db.Stories.Add(story); return await db.SaveChangesAsync(); }); using var zip = await ExportAsync(admin, publishedOnly: false, includePersonalData: true); var exportedItem = FindItem(zip, item.Id); + var exportedStory = JsonDocument.Parse(Read(zip, "archive.json")).RootElement.GetProperty("stories").EnumerateArray() + .Single(s => s.GetProperty("title").GetString() == storyTitle); var json = part switch { "item" => exportedItem, @@ -138,6 +148,8 @@ await app.WithDbAsync(async db => "contribution" => exportedItem.GetProperty("contribution"), "settings" => JsonDocument.Parse(Read(zip, "archive.json")).RootElement.GetProperty("settings"), "note" => exportedItem.GetProperty("notes")[0], + "story" => exportedStory, + "block" => exportedStory.GetProperty("blocks")[0], "tag" => JsonDocument.Parse(Read(zip, "archive.json")).RootElement.GetProperty("tags")[0], _ => JsonDocument.Parse(Read(zip, "archive.json")).RootElement.GetProperty("collections")[0], }; @@ -203,7 +215,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(8, document.GetProperty("version").GetInt32()); + Assert.Equal(9, document.GetProperty("version").GetInt32()); } [Fact] @@ -316,6 +328,88 @@ public async Task The_README_is_in_the_language_of_whoever_exports_with_an_Engli Assert.Equal(readme, Encoding.UTF8.GetString(Read(german, "README.en.txt"))); } + /// + /// What a copy holds of stories: a copy of what is public holds the published stories that visitors could find, with only the + /// parts whose item is in the copy; a copy of everything holds drafts too, but nothing from the bin. No part names an item + /// that is not in the same file. + /// + [Fact] + public async Task Stories_travel_with_the_rules_of_what_is_public_and_name_only_items_that_are_exported() + { + await using var archive = await app.NewArchiveAsync(); + using var admin = archive.CreateClient(); + await Browser.LogInAsCuratorAsync(admin); + var shownId = await archive.WithDbAsync(async db => + { + var now = DateTime.UtcNow; + var collection = new Collection { Title = "Streets", CreatedAt = now }; + ArchiveItem Item(string title, bool published, DateOnly? from = null) + { + var item = new ArchiveItem { Title = title, Collection = collection, CreatedAt = now, UpdatedAt = now, Status = ItemStatus.Draft, PublicFrom = from }; + if (published) + item.Publish(now); + return item; + } + + var shown = Item("Shown flood", true); + var draft = Item("Draft flood", false); + var embargoed = Item("Embargoed flood", true, DateOnly.FromDateTime(DateTime.UtcNow).AddDays(30)); + var binned = Item("Binned flood", true); + binned.MoveToBin(now); + db.ArchiveItems.AddRange(shown, draft, embargoed, binned); + Story Make(string title, StoryStatus status, params (StoryBlockKind Kind, string? Text, ArchiveItem? Item, string? Caption)[] blocks) + { + var story = new Story { Title = title, Status = StoryStatus.Draft, CreatedAt = now, UpdatedAt = now }; + if (status == StoryStatus.Published) + story.Publish(now); + foreach (var (kind, text, item, caption) in blocks) + story.Blocks.Add(new StoryBlock { Position = story.Blocks.Count, Kind = kind, Text = text, ArchiveItem = item, Caption = caption }); + db.Stories.Add(story); + return story; + } + + const StoryBlockKind T = StoryBlockKind.Text, I = StoryBlockKind.Item; + Make("Public story", StoryStatus.Published, (T, "Opening words", null, null), (I, null, shown, "Shown caption"), (I, null, draft, "Draft caption"), + (I, null, embargoed, "Embargoed caption"), (I, null, binned, "Binned caption")); + Make("Only hidden items", StoryStatus.Published, (I, null, draft, "Hidden one"), (I, null, embargoed, "Hidden two")); + Make("A draft story", StoryStatus.Draft, (T, "Draft words", null, null), (I, null, draft, "Draft story caption")); + var gone = Make("A story in the bin", StoryStatus.Published, (T, "Bin words", null, null)); + gone.MoveToBin(now); + await db.SaveChangesAsync(); + return shown.Id; + }); + + using var publicZip = await ExportAsync(admin, publishedOnly: true, includePersonalData: false); + using var fullZip = await ExportAsync(admin, publishedOnly: false, includePersonalData: true); + + var publicJson = JsonDocument.Parse(Read(publicZip, "archive.json")).RootElement; + var publicStories = publicJson.GetProperty("stories").EnumerateArray().ToList(); + Assert.Equal(["Public story"], publicStories.Select(s => s.GetProperty("title").GetString())); + var parts = publicStories[0].GetProperty("blocks").EnumerateArray().ToList(); + Assert.Equal(["Text", "Item"], parts.Select(p => p.GetProperty("kind").GetString())); + Assert.Equal(shownId, parts[1].GetProperty("itemId").GetInt32()); + Assert.Equal("Shown caption", parts[1].GetProperty("caption").GetString()); + var publicText = Encoding.UTF8.GetString(Read(publicZip, "archive.json")); + foreach (var hidden in new[] { "Draft caption", "Embargoed caption", "Binned caption", "Hidden one", "Hidden two", "Draft words", "Draft story caption", "Bin words", "Only hidden items", "A draft story" }) + Assert.DoesNotContain(hidden, publicText); + + var fullJson = JsonDocument.Parse(Read(fullZip, "archive.json")).RootElement; + var fullStories = fullJson.GetProperty("stories").EnumerateArray().ToList(); + Assert.Equal(["Public story", "Only hidden items", "A draft story"], fullStories.Select(s => s.GetProperty("title").GetString())); + var fullParts = fullStories[0].GetProperty("blocks").EnumerateArray().Select(p => p.GetProperty("caption").GetString() ?? p.GetProperty("text").GetString()).ToList(); + Assert.Equal(["Opening words", "Shown caption", "Draft caption", "Embargoed caption"], fullParts); + Assert.DoesNotContain("Bin words", Encoding.UTF8.GetString(Read(fullZip, "archive.json"))); + Assert.DoesNotContain("Binned caption", Encoding.UTF8.GetString(Read(fullZip, "archive.json"))); + + foreach (var document in new[] { publicJson, fullJson }) + { + var exported = document.GetProperty("items").EnumerateArray().Select(i => i.GetProperty("id").GetInt32()).ToHashSet(); + foreach (var story in document.GetProperty("stories").EnumerateArray()) + foreach (var part in story.GetProperty("blocks").EnumerateArray().Where(p => p.GetProperty("kind").GetString() == "Item")) + Assert.Contains(part.GetProperty("itemId").GetInt32(), exported); + } + } + private static async Task ExportAsync(HttpClient admin, bool publishedOnly, bool includePersonalData) { var fields = new Dictionary(); diff --git a/tests/Commonage.Tests/SecurityHeaderTests.cs b/tests/Commonage.Tests/SecurityHeaderTests.cs index 170c466..556444a 100644 --- a/tests/Commonage.Tests/SecurityHeaderTests.cs +++ b/tests/Commonage.Tests/SecurityHeaderTests.cs @@ -54,12 +54,20 @@ public async Task Pages_contain_no_inline_script_or_style() return tag.Id; }); + var storyId = await app.WithDbAsync(async db => + { + var story = new Story { Title = TestData.Unique("A story"), CreatedAt = DateTime.UtcNow, UpdatedAt = DateTime.UtcNow }; + db.Stories.Add(story); + await db.SaveChangesAsync(); + return story.Id; + }); + // "Do you know more about this?" is off by default and its page is not there then; the shared database is put back afterwards. await SetVisitorNotesAsync(true); var results = new List(); foreach (var route in routes) { - var url = FillIn(route, item, token, tagId, linkId); + var url = FillIn(route, item, token, tagId, linkId, storyId); using var response = await curator.GetAsync(url); var html = await response.Content.ReadAsStringAsync(); if (InlineScript().IsMatch(html) || EventHandlerAttribute().IsMatch(html) || StyleAttributeOrElement().IsMatch(html)) @@ -86,11 +94,12 @@ private Task SetVisitorNotesAsync(bool on) => app.WithDbAsync(async db => return saved; }); - private static string FillIn(string route, ArchiveItem item, string token, int tagId, int linkId) + private static string FillIn(string route, ArchiveItem item, string token, int tagId, int linkId, int storyId) { var id = route.StartsWith("/Collections", StringComparison.OrdinalIgnoreCase) || route.Contains("Admin/Collections", StringComparison.OrdinalIgnoreCase) ? item.CollectionId.ToString() : route.Contains("Admin/Tags", StringComparison.OrdinalIgnoreCase) ? tagId.ToString() + : route.Contains("Admin/Stories", StringComparison.OrdinalIgnoreCase) ? storyId.ToString() : route.Contains("Admin/Contributions", StringComparison.OrdinalIgnoreCase) ? linkId.ToString() : item.Id.ToString(); var url = route .Replace("{token}", token) diff --git a/tests/Commonage.Tests/StoryEditTests.cs b/tests/Commonage.Tests/StoryEditTests.cs new file mode 100644 index 0000000..a961a35 --- /dev/null +++ b/tests/Commonage.Tests/StoryEditTests.cs @@ -0,0 +1,418 @@ +using System.Net; +using System.Text.RegularExpressions; +using Commonage.Web.Domain; +using Commonage.Web.Identity; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.EntityFrameworkCore; + +namespace Commonage.Tests; + +/// Stories as curators write them: parts in order, refusals, versions and the activity log. Each test has an archive of its own. +[Collection(nameof(AppCollection))] +public class StoryEditTests(CommonageAppFactory app) +{ + private sealed record Seed(int Published, int Draft, int Binned, int Withdrawn); + + private static async Task<(WebApplicationFactory Archive, HttpClient Curator, Seed Items)> StartAsync(CommonageAppFactory app) + { + var archive = await app.NewArchiveAsync(); + var curator = archive.CreateClient(); + await Browser.LogInAsCuratorAsync(curator); + var items = await archive.WithDbAsync(async db => + { + var now = DateTime.UtcNow; + var collection = new Collection { Title = "Streets", CreatedAt = now }; + ArchiveItem Item(string title, ItemStatus status) + { + var item = new ArchiveItem { Title = title, Collection = collection, CreatedAt = now, UpdatedAt = now, Status = ItemStatus.Draft }; + if (status == ItemStatus.Published) + item.Publish(now); + return item; + } + + var published = Item("Published flood", ItemStatus.Published); + var draft = Item("Draft flood", ItemStatus.Draft); + var binned = Item("Binned flood", ItemStatus.Published); + binned.MoveToBin(now); + var withdrawn = Item("Withdrawn flood", ItemStatus.Published); + withdrawn.Status = ItemStatus.Rejected; + db.ArchiveItems.AddRange(published, draft, binned, withdrawn); + await db.SaveChangesAsync(); + return new Seed(published.Id, draft.Id, binned.Id, withdrawn.Id); + }); + return (archive, curator, items); + } + + private static async Task CreateAsync(HttpClient curator, string title = "Mill Street") + { + var response = await Browser.PostFormAsync(curator, "/Admin/Stories?handler=Create", new() { ["NewTitle"] = title }, "/Admin/Stories"); + return int.Parse(Regex.Match(response.RequestMessage!.RequestUri!.AbsolutePath, @"/Admin/Stories/Edit/(\d+)").Groups[1].Value); + } + + private static string Page(int id) => $"/Admin/Stories/Edit/{id}"; + + private static Task PostAsync(HttpClient curator, int id, string handler, Dictionary fields, int? blockId = null) => + Browser.SendFormAsync(curator, $"{Page(id)}?handler={handler}" + (blockId is { } b ? $"&blockId={b}" : ""), fields, Page(id)); + + private static Task AddTextAsync(HttpClient curator, int id, string text) => PostAsync(curator, id, "AddText", new() { ["text"] = text }); + + private static Task AddItemAsync(HttpClient curator, int id, string reference, string caption = "") => + PostAsync(curator, id, "AddItem", new() { ["item"] = reference, ["caption"] = caption }); + + private static Task> BlocksAsync(WebApplicationFactory archive, int id) => + archive.WithDbAsync(db => db.StoryBlocks.Where(b => b.StoryId == id).OrderBy(b => b.Position).ThenBy(b => b.Id).ToListAsync()); + + private static Task> ActionsAsync(WebApplicationFactory archive, int id) => + archive.WithDbAsync(db => db.AuditEntries.Where(e => e.StoryId == id).OrderBy(e => e.Id).Select(e => e.Action).ToListAsync()); + + [Fact] + public async Task A_curator_creates_edits_publishes_and_unpublishes_a_story() + { + var (archive, curator, _) = await StartAsync(app); + await using (archive) + using (curator) + { + var id = await CreateAsync(curator); + var created = await archive.WithDbAsync(db => db.Stories.SingleAsync(s => s.Id == id)); + Assert.Equal(("Mill Street", StoryStatus.Draft), (created.Title, created.Status)); + + var form = await curator.GetStringAsync(Page(id)); + var version = System.Net.WebUtility.HtmlDecode(Regex.Match(form, @"name=""Input.Version""[^>]*value=""(\d+)""").Groups[1].Value); + var saved = await Browser.PostFormAsync(curator, Page(id), new() { ["Input.Title"] = "Mill Street, 1962", ["Input.Summary"] = "A flood.", ["Input.Version"] = version }); + Assert.Contains("Mill Street, 1962", await saved.Content.ReadAsStringAsync()); + + await PostAsync(curator, id, "Publish", []); + var published = await archive.WithDbAsync(db => db.Stories.SingleAsync(s => s.Id == id)); + Assert.Equal((StoryStatus.Published, "Mill Street, 1962", "A flood."), (published.Status, published.Title, published.Summary)); + Assert.NotNull(published.PublishedAt); + + await PostAsync(curator, id, "Unpublish", []); + Assert.Equal(StoryStatus.Draft, (await archive.WithDbAsync(db => db.Stories.SingleAsync(s => s.Id == id))).Status); + Assert.Equal([AuditAction.StoryCreated, AuditAction.StoryChanged, AuditAction.StoryPublished, AuditAction.StoryUnpublished], await ActionsAsync(archive, id)); + } + } + + [Fact] + public async Task A_title_is_needed_and_a_missing_story_answers_404() + { + var (archive, curator, _) = await StartAsync(app); + await using (archive) + using (curator) + { + var empty = await Browser.SendFormAsync(curator, "/Admin/Stories?handler=Create", new() { ["NewTitle"] = " " }, "/Admin/Stories"); + Assert.Contains("Please enter a title.", await empty.Content.ReadAsStringAsync()); + Assert.Empty(await archive.WithDbAsync(db => db.Stories.ToListAsync())); + Assert.Equal(HttpStatusCode.NotFound, (await curator.GetAsync(Page(999))).StatusCode); + var id = await CreateAsync(curator); + var missing = await Browser.SendFormAsync(curator, $"{Page(999)}?handler=AddText", new() { ["text"] = "x" }, Page(id)); + Assert.Equal(HttpStatusCode.NotFound, missing.StatusCode); + Assert.Equal(HttpStatusCode.NotFound, (await PostAsync(curator, id, "RemoveBlock", [], 12345)).StatusCode); + } + } + + [Fact] + public async Task Text_and_items_are_added_by_number_and_by_address_and_keep_their_order() + { + var (archive, curator, items) = await StartAsync(app); + await using (archive) + using (curator) + { + var id = await CreateAsync(curator); + await AddTextAsync(curator, id, " First words "); + await AddItemAsync(curator, id, items.Published.ToString(), "The flood"); + await AddItemAsync(curator, id, $"/items/{items.Published}"); + await AddItemAsync(curator, id, $"https://archive.example/Admin/Items/Edit/{items.Draft}"); + var blocks = await BlocksAsync(archive, id); + + Assert.Equal([0, 1, 2, 3], blocks.Select(b => b.Position)); + Assert.Equal(("First words", null), (blocks[0].Text, blocks[0].ArchiveItemId)); + Assert.Equal((items.Published, "The flood"), (blocks[1].ArchiveItemId, blocks[1].Caption)); + Assert.Equal(items.Published, blocks[2].ArchiveItemId); + Assert.Null(blocks[2].Caption); + Assert.Equal(items.Draft, blocks[3].ArchiveItemId); + var page = await curator.GetStringAsync(Page(id)); + Assert.Contains("Visitors do not see this item: it is not published.", page); + } + } + + [Fact] + public async Task Unknown_binned_and_withdrawn_items_and_empty_or_long_text_are_refused() + { + var (archive, curator, items) = await StartAsync(app); + await using (archive) + using (curator) + { + var id = await CreateAsync(curator); + var unknown = await (await AddItemAsync(curator, id, "987654")).Content.ReadAsStringAsync(); + var binned = await (await AddItemAsync(curator, id, items.Binned.ToString())).Content.ReadAsStringAsync(); + var withdrawn = await (await AddItemAsync(curator, id, items.Withdrawn.ToString())).Content.ReadAsStringAsync(); + var nonsense = await (await AddItemAsync(curator, id, "the flood")).Content.ReadAsStringAsync(); + var longCaption = await (await AddItemAsync(curator, id, items.Published.ToString(), new string('c', StoryBlock.CaptionMaxLength + 1))).Content.ReadAsStringAsync(); + var empty = await (await AddTextAsync(curator, id, " ")).Content.ReadAsStringAsync(); + var longText = await (await AddTextAsync(curator, id, new string('t', StoryBlock.TextMaxLength + 1))).Content.ReadAsStringAsync(); + + Assert.Contains("There is no item with this number.", unknown); + Assert.Contains("This item is in the bin.", binned); + Assert.Contains("turned down or withdrawn", withdrawn); + Assert.Contains("Please enter the number of an item", nonsense); + Assert.Contains("The caption can be at most", longCaption); + Assert.Contains("Please write some text.", empty); + Assert.Contains("The text can be at most", longText); + Assert.Empty(await BlocksAsync(archive, id)); + Assert.Equal([AuditAction.StoryCreated], await ActionsAsync(archive, id)); + } + } + + [Fact] + public async Task A_story_holds_at_most_the_limit_of_parts() + { + var (archive, curator, items) = await StartAsync(app); + await using (archive) + using (curator) + { + var id = await CreateAsync(curator); + await archive.WithDbAsync(async db => + { + for (var i = 0; i < Story.MaxBlocks; i++) + db.StoryBlocks.Add(new StoryBlock { StoryId = id, Position = i, Kind = StoryBlockKind.Text, Text = $"Part {i}" }); + return await db.SaveChangesAsync(); + }); + + var text = await (await AddTextAsync(curator, id, "one too many")).Content.ReadAsStringAsync(); + var item = await (await AddItemAsync(curator, id, items.Published.ToString())).Content.ReadAsStringAsync(); + + Assert.Contains("A story can have at most 200 parts.", text); + Assert.Contains("A story can have at most 200 parts.", item); + Assert.Equal(Story.MaxBlocks, (await BlocksAsync(archive, id)).Count); + } + } + + [Fact] + public async Task A_part_moves_earlier_and_later_and_stays_put_at_the_ends() + { + var (archive, curator, _) = await StartAsync(app); + await using (archive) + using (curator) + { + var id = await CreateAsync(curator); + foreach (var word in new[] { "a", "b", "c" }) + await AddTextAsync(curator, id, word); + async Task OrderAsync() => string.Concat((await BlocksAsync(archive, id)).Select(b => b.Text)); + var blocks = await BlocksAsync(archive, id); + + await PostAsync(curator, id, "MoveBlock", new() { ["direction"] = "earlier" }, blocks[2].Id); + Assert.Equal("acb", await OrderAsync()); + await PostAsync(curator, id, "MoveBlock", new() { ["direction"] = "later" }, blocks[0].Id); + Assert.Equal("cab", await OrderAsync()); + await PostAsync(curator, id, "MoveBlock", new() { ["direction"] = "earlier" }, blocks[1].Id); + Assert.Equal("cba", await OrderAsync()); + var first = (await BlocksAsync(archive, id))[0]; + await PostAsync(curator, id, "MoveBlock", new() { ["direction"] = "earlier" }, first.Id); + await PostAsync(curator, id, "MoveBlock", new() { ["direction"] = "later" }, (await BlocksAsync(archive, id))[2].Id); + Assert.Equal("cba", await OrderAsync()); + Assert.Equal([0, 1, 2], (await BlocksAsync(archive, id)).Select(b => b.Position)); + } + } + + [Fact] + public async Task A_part_of_another_story_answers_404_and_changes_nothing() + { + var (archive, curator, _) = await StartAsync(app); + await using (archive) + using (curator) + { + var mine = await CreateAsync(curator, "Mine"); + var other = await CreateAsync(curator, "Other"); + await AddTextAsync(curator, other, "theirs"); + var theirs = (await BlocksAsync(archive, other)).Single(); + + var move = await PostAsync(curator, mine, "MoveBlock", new() { ["direction"] = "later" }, theirs.Id); + var remove = await PostAsync(curator, mine, "RemoveBlock", [], theirs.Id); + var save = await PostAsync(curator, mine, "SaveText", new() { ["text"] = "changed" }, theirs.Id); + var caption = await PostAsync(curator, mine, "SaveCaption", new() { ["caption"] = "changed" }, theirs.Id); + + Assert.All(new[] { move, remove, save, caption }, r => Assert.Equal(HttpStatusCode.NotFound, r.StatusCode)); + Assert.Equal("theirs", (await BlocksAsync(archive, other)).Single().Text); + } + } + + [Fact] + public async Task Texts_and_captions_are_saved_and_a_part_is_removed_with_the_rest_renumbered() + { + var (archive, curator, items) = await StartAsync(app); + await using (archive) + using (curator) + { + var id = await CreateAsync(curator); + await AddTextAsync(curator, id, "a"); + await AddItemAsync(curator, id, items.Published.ToString(), "old"); + await AddTextAsync(curator, id, "c"); + var blocks = await BlocksAsync(archive, id); + + await PostAsync(curator, id, "SaveText", new() { ["text"] = "A changed" }, blocks[0].Id); + await PostAsync(curator, id, "SaveCaption", new() { ["caption"] = "new" }, blocks[1].Id); + await PostAsync(curator, id, "RemoveBlock", [], blocks[1].Id); + var after = await BlocksAsync(archive, id); + + Assert.Equal(["A changed", "c"], after.Select(b => b.Text)); + Assert.Equal([0, 1], after.Select(b => b.Position)); + Assert.True(await archive.WithDbAsync(db => db.ArchiveItems.AnyAsync(i => i.Id == items.Published))); + } + } + + [Fact] + public async Task Moving_and_changing_parts_never_touch_the_story_itself() + { + var (archive, curator, items) = await StartAsync(app); + await using (archive) + using (curator) + { + var id = await CreateAsync(curator); + await AddTextAsync(curator, id, "a"); + await AddItemAsync(curator, id, items.Published.ToString()); + var before = await archive.WithDbAsync(db => db.Stories.AsNoTracking().SingleAsync(s => s.Id == id)); + var blocks = await BlocksAsync(archive, id); + + await PostAsync(curator, id, "MoveBlock", new() { ["direction"] = "later" }, blocks[0].Id); + await PostAsync(curator, id, "SaveText", new() { ["text"] = "b" }, blocks[0].Id); + await AddTextAsync(curator, id, "c"); + await PostAsync(curator, id, "RemoveBlock", [], blocks[1].Id); + var after = await archive.WithDbAsync(db => db.Stories.AsNoTracking().SingleAsync(s => s.Id == id)); + + Assert.Equal((before.Version, before.UpdatedAt), (after.Version, after.UpdatedAt)); + } + } + + [Fact] + public async Task Someone_who_saves_over_a_newer_version_is_shown_the_other_version_first() + { + var (archive, curator, _) = await StartAsync(app); + await using (archive) + using (curator) + { + var id = await CreateAsync(curator); + var form = await curator.GetStringAsync(Page(id)); + var version = Regex.Match(form, @"name=""Input.Version""[^>]*value=""(\d+)""").Groups[1].Value; + await Browser.PostFormAsync(curator, Page(id), new() { ["Input.Title"] = "First save", ["Input.Version"] = version }); + + var stale = await Browser.PostFormAsync(curator, Page(id), new() { ["Input.Title"] = "Second, from the old form", ["Input.Version"] = version }, Page(id)); + var html = await stale.Content.ReadAsStringAsync(); + + Assert.Contains("Someone else changed this story", html); + Assert.Contains("First save", html); + Assert.Equal("First save", (await archive.WithDbAsync(db => db.Stories.SingleAsync(s => s.Id == id))).Title); + } + } + + [Fact] + public async Task Every_change_is_in_the_activity_log_and_one_sitting_of_moves_is_one_entry() + { + var (archive, curator, items) = await StartAsync(app); + await using (archive) + using (curator) + { + var id = await CreateAsync(curator); + await AddTextAsync(curator, id, "a"); + await AddItemAsync(curator, id, items.Published.ToString()); + var blocks = await BlocksAsync(archive, id); + await PostAsync(curator, id, "SaveText", new() { ["text"] = "a2" }, blocks[0].Id); + await PostAsync(curator, id, "MoveBlock", new() { ["direction"] = "later" }, blocks[0].Id); + await PostAsync(curator, id, "MoveBlock", new() { ["direction"] = "earlier" }, blocks[0].Id); + await PostAsync(curator, id, "MoveBlock", new() { ["direction"] = "later" }, blocks[0].Id); + await PostAsync(curator, id, "RemoveBlock", [], blocks[1].Id); + + var actions = await ActionsAsync(archive, id); + Assert.Equal([AuditAction.StoryCreated, AuditAction.StoryChanged, AuditAction.StoryItemAdded, AuditAction.StoryChanged, + AuditAction.StoryBlocksArranged, AuditAction.StoryItemRemoved], actions); + var activity = await curator.GetStringAsync("/Admin/Activity?what=Stories"); + Assert.Contains("Changed the order of the parts of the story", activity); + Assert.Contains($"/Admin/Stories/Edit/{id}", activity); + Assert.Contains("Stories", await curator.GetStringAsync("/Admin/Activity")); + } + } + + [Fact] + public async Task Stories_move_in_the_list_and_the_list_counts_what_visitors_would_not_see() + { + var (archive, curator, items) = await StartAsync(app); + await using (archive) + using (curator) + { + var first = await CreateAsync(curator, "First"); + var second = await CreateAsync(curator, "Second"); + await AddItemAsync(curator, first, items.Draft.ToString()); + await AddItemAsync(curator, first, items.Published.ToString()); + await AddTextAsync(curator, first, "words"); + + var list = await curator.GetStringAsync("/Admin/Stories"); + Assert.Contains("1 item not shown to visitors", list); + Assert.True(list.IndexOf("First", StringComparison.Ordinal) < list.IndexOf("Second", StringComparison.Ordinal)); + + await Browser.PostFormAsync(curator, $"/Admin/Stories?handler=MoveEarlier&id={second}", [], "/Admin/Stories"); + Assert.Equal(["Second", "First"], await archive.WithDbAsync(db => db.Stories.OrderBy(s => s.Position).Select(s => s.Title).ToListAsync())); + await Browser.PostFormAsync(curator, $"/Admin/Stories?handler=MoveEarlier&id={second}", [], "/Admin/Stories"); + Assert.Equal(["Second", "First"], await archive.WithDbAsync(db => db.Stories.OrderBy(s => s.Position).Select(s => s.Title).ToListAsync())); + Assert.Contains(AuditAction.StoriesArranged, await ActionsAsync(archive, second)); + } + } + + [Fact] + public async Task The_preview_leaves_out_what_visitors_would_not_see() + { + var (archive, curator, items) = await StartAsync(app); + await using (archive) + using (curator) + { + var id = await CreateAsync(curator, "Preview me"); + await AddTextAsync(curator, id, "Opening words"); + await AddItemAsync(curator, id, items.Draft.ToString(), "Secret caption"); + await AddItemAsync(curator, id, items.Published.ToString(), "Shown caption"); + + var preview = await curator.GetStringAsync($"/Admin/Stories/Preview/{id}"); + Assert.Contains("Opening words", preview); + Assert.Contains("Shown caption", preview); + Assert.DoesNotContain("Secret caption", preview); + Assert.DoesNotContain("Draft flood", preview); + + } + } + + [Fact] + public async Task A_helper_is_shut_out_of_every_story_page_and_handler() + { + using var admin = app.CreateClient(); + await Browser.LogInAsCuratorAsync(admin); + var (helper, _, _, _) = await app.CreateAccountAsync(admin, Roles.Helper); + var id = await CreateAsync(admin, Unique("Helper story")); + var block = await app.WithDbAsync(async db => + { + var added = new StoryBlock { StoryId = id, Position = 0, Kind = StoryBlockKind.Text, Text = "words" }; + db.StoryBlocks.Add(added); + await db.SaveChangesAsync(); + return added.Id; + }); + + foreach (var url in new[] { "/Admin/Stories", Page(id), $"/Admin/Stories/Preview/{id}" }) + Assert.Equal(HttpStatusCode.Forbidden, (await helper.GetAsync(url)).StatusCode); + var posts = new List + { + await Browser.SendFormAsync(helper, "/Admin/Stories?handler=Create", new() { ["NewTitle"] = "x" }, "/Admin"), + await Browser.SendFormAsync(helper, $"/Admin/Stories?handler=MoveEarlier&id={id}", [], "/Admin"), + await Browser.SendFormAsync(helper, $"/Admin/Stories?handler=MoveLater&id={id}", [], "/Admin"), + await Browser.SendFormAsync(helper, Page(id), new() { ["Input.Title"] = "x" }, "/Admin"), + }; + foreach (var (handler, fields) in new (string, Dictionary)[] + { + ("Publish", []), ("Unpublish", []), ("AddText", new() { ["text"] = "x" }), ("AddItem", new() { ["item"] = "1" }), + ("SaveText", new() { ["text"] = "x" }), ("SaveCaption", new() { ["caption"] = "x" }), + ("MoveBlock", new() { ["direction"] = "later" }), ("RemoveBlock", []), + }) + posts.Add(await Browser.SendFormAsync(helper, $"{Page(id)}?handler={handler}&blockId={block}", fields, "/Admin")); + + Assert.All(posts, r => Assert.Equal(HttpStatusCode.Forbidden, r.StatusCode)); + var stored = await app.WithDbAsync(db => db.Stories.Include(s => s.Blocks).SingleAsync(s => s.Id == id)); + Assert.Equal((StoryStatus.Draft, "words"), (stored.Status, Assert.Single(stored.Blocks).Text)); + } + + private static string Unique(string text) => TestData.Unique(text); +} diff --git a/tests/Commonage.Tests/VisibilityGuardTests.cs b/tests/Commonage.Tests/VisibilityGuardTests.cs index f4efac7..8075e34 100644 --- a/tests/Commonage.Tests/VisibilityGuardTests.cs +++ b/tests/Commonage.Tests/VisibilityGuardTests.cs @@ -45,9 +45,40 @@ public void Public_code_reads_items_only_through_the_visible_queries() + string.Join('\n', offenders)); } - [GeneratedRegex(@"ItemStatus\.Published|\bArchiveItems\b|IgnoreQueryFilters|\bdb\.MediaFiles\b")] + [GeneratedRegex(@"ItemStatus\.Published|\bArchiveItems\b|IgnoreQueryFilters|\bdb\.MediaFiles\b|StoryStatus\.Published|\bdb\.Stories\b|\bdb\.StoryBlocks\b|\bstory\.Blocks\b")] private static partial Regex Forbidden(); + /// + /// A story page must not follow a block to its item: that would show an item the rule hides. The blocks come from + /// VisibleStoryBlocks, which loads the items through VisibleItems. + /// + [Fact] + public void Public_story_pages_never_follow_a_block_to_its_item() + { + var root = SourceRoot(); + var offenders = new List(); + foreach (var folder in new[] { "Pages/Stories", "Pages/Index.cshtml", "Pages/Index.cshtml.cs" }) + { + var path = Path.Combine(root, folder); + var files = Directory.Exists(path) ? Directory.EnumerateFiles(path, "*", SearchOption.AllDirectories) : File.Exists(path) ? [path] : []; + offenders.AddRange(files.Where(f => FollowsBlockToItem().IsMatch(File.ReadAllText(f))).Select(f => Path.GetRelativePath(root, f))); + } + + Assert.Empty(offenders); + } + + [GeneratedRegex(@"\.ArchiveItem")] + private static partial Regex FollowsBlockToItem(); + + [Fact] + public void The_guard_catches_the_ways_to_reach_a_story_or_a_block_around_the_visible_queries() + { + foreach (var line in new[] { "s.Status == StoryStatus.Published", "db.Stories.Where(x)", "db.StoryBlocks.ToList()", "story.Blocks.Select(b => 1)" }) + Assert.Matches(Forbidden(), line); + Assert.DoesNotMatch(Forbidden(), "await VisibleStoryBlocks.LoadAsync(db, id)"); + Assert.DoesNotMatch(Forbidden(), "db.VisibleStories.Where(x)"); + } + private static string SourceRoot() { var directory = new DirectoryInfo(AppContext.BaseDirectory);