From 3dbd7e88ea8c4fc5149817089f44873af5db0bb7 Mon Sep 17 00:00:00 2001 From: "Seb H." <138793908+SebHenn@users.noreply.github.com> Date: Sun, 15 Nov 2026 19:59:08 +0100 Subject: [PATCH 1/2] M25: spike result and plan for oral histories Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Seb H. <138793908+SebHenn@users.noreply.github.com> --- docs/roadmap.md | 362 +++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 361 insertions(+), 1 deletion(-) diff --git a/docs/roadmap.md b/docs/roadmap.md index 284b763..eeb9fff 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -511,7 +511,367 @@ shows the years of its published items. M19 is complete. **M25 Oral histories** -- Audio is recognised by content, stripped of metadata without re-encoding and served with range requests through the same +- **Spike result (part 1).** `ffmpeg` from Debian adds about 405 MB to the image (197 packages), five times what poppler + does, and a trimmed static build would be one more thing to build for x86 and ARM and keep patched. The metadata is + not hidden in the sound, though: it sits in a few well-known places (ID3 tags in MP3, `udta`/`meta` boxes in MP4, + `LIST` chunks in WAV, comment and picture blocks in FLAC). So no subprocess and no new package: small readers in the + app cut those out, the audio itself is copied byte for byte. They read only curators' files, never a contribution's. +- **Part 1: audio in, stripped copy out.** MP3, M4A, WAV and FLAC are recognised by content. The original stays with + curators like every original. Processing writes a stripped copy; visitors get only that, through the same published + check, with range requests so that the browser's own player can jump. A file whose structure the reader does not + understand fails with the retry button, and is never served unstripped. The item page shows the player; the curator + form accepts audio. Ogg/Opus is left for later: its comment lives inside pages with checksums, so it needs a rewriter + of its own and is not worth holding the rest up. +- **Part 2: the transcript.** An item with audio needs a transcript before it is published, or the "transcript to follow" + flag (the existing "needs transcription" flag). The transcript is searched and shown beside the player. The handbook + documents a local whisper.cpp workflow, as "Not planned" promises. + +**M26 Description history** | 3 | A curator sees who changed which field and when, and restores an earlier description. | +| **M27 Visibility levels** | 5 | An item can be public as a record without its media, or embargoed until a date. Every public query goes through `VisibleItems`. | +| **M28 Toward 1.0** | 3 | Commonage reads its own export, so archives can be merged. Dublin Core and a JSON alternate exist. A 1.0 checklist is met. | + +M22 to M28 were planned in November 2026, after M21, from the "Later" list. There are still no reports from groups or +testers, so the order is a judgement again: documents are the largest gap between what groups hold and what the app takes, +the helper role is cheap and makes volunteer evenings possible, and visibility levels come last because they rewrite the rule +that only published items are public and need the most careful review. + +The review after M14 also decides what comes next. PDF documents, audio or an earlier import may well replace M15 +onwards, depending on what the groups say. **Review, November 2026:** no group or tester has asked for any of those so far, and +the walk-through's tasks point at M15 (a letter cannot be read as a scan) and M19 (a decade is searched as a word), so the order +stays. The tasks are in [usability-test.md](usability-test.md), for the tester, and it changes if their reports call for it. + +### What each milestone holds + +Items marked *(can slip)* move to a later milestone when the time runs out. + +**M7 Nothing gets lost** + +- Bin: deleting an item or a photo sets `DeletedAt`; Restore; purge after 30 days. "Delete for good" stays for + personal-data requests. Query filters leave binned material out of every query unless a page asks for it. +- Disk guard for contributor and curator uploads: refuse early from `Content-Length` when free space on the media + volume or the temporary upload path is low, and add a daily limit on anonymous uploads per link. +- Optimistic concurrency (`xmin`) on `ArchiveItem`, with a translated message that keeps the typed text. +- `data-warn-unsaved` for all forms on the edit page. Uploading a photo must never save half-typed text, because on a + published item that would make it public. +- Login limit per address, generous enough for a shared connection. +- Backup age and free space as an admin notice: `backup.sh` writes a timestamp that the app can read. +- Contributors search also finds the photographer or author, and exports without personal data leave that name out. +- Correct the docs: what the README promises, the update advice in `security.md`, and moving servers by backup and + restore. + +**M8 Safety net** + +- `scripts/update.sh`: check free space, back up, pull, wait for `https://$COMMONAGE_DOMAIN/health` or a Compose + health check (the app has no open port in production), and roll back through `restore.sh --yes` plus the old version + and tag, warning that changes since the backup are lost. The script must survive replacing itself. +- CI starts the previous published image with `compose.production.yaml`, upgrades it to the candidate, and also forces + a failed upgrade. +- Playwright with axe in CI on the main pages at 390 and 1280 px, one smoke test per JavaScript behaviour, and a run + without JavaScript. A short manual zoom and screen reader checklist for each release. +- `SecurityHeaderTests` finds pages by itself instead of using a list, which today misses the contribution form, + Thanks and Login. +- A test that fails when a new domain property is neither exported nor explicitly excluded. +- A written update policy: how fast a security fix ships, how long an older minor version gets fixes, and how + operators follow releases. Pinned servers otherwise stop receiving fixes without noticing. + +**M9 Quick wins** + +- One shared way to show field errors, for all forms: a summary that lists them with links, `aria-describedby` merged + with existing help links, and focus on the summary. Today's `ModelOnly` summary stays empty after field errors. +- A rate-limited date check showing "Understood as …" on the contribution form and the curator form, before saving. + Saved items already show "Found when visitors filter by", so the wording can match. Sending is disabled after the + first click. +- A file picker in the page's language. The browser's own control follows the browser's language, so an English page + shows "Dateien auswählen" on a German computer, and the other way round. Use a translated button with the chosen + file names, keeping the native control without JavaScript. +- Text-only items get a designed tile showing that they are text. Today they appear as an empty grey box in search and + collections, which looks like a picture failed to load. +- Unambiguous dates and times in the curator pages. `en` shows `11/4/2026`, which means different days to American + and British readers. +- Small things seen on screen: the search placeholder is cut off on narrow phones in German ("Archiv durchsuch"), and + the Filters button on phones looks disabled. +- Remove the fixed root font size. Larger targets for the language buttons and tag pills, a heading on search results, + `aria-current` in the navigation. +- Collections and Search always visible on phones; a breadcrumb on collection pages; admin navigation on every admin + page, with touch-friendly controls. +- For curators: "Save and next" and "Save and add another", thumbnails and collection, tag and "needs" filters in the + item list, the review queue oldest first and moving on to the next contribution after a decision. On a review, the + photos come first: today they sit below the form and below the Publish and Reject buttons, about 1,400 px down. + The edit page's heading names the item instead of saying "Edit item". Draft preview *(can slip)*. + +**M10 Archive identity and trust pages** + +- `ArchiveSettings` with `DefaultLanguage` and texts stored per language from the start: name, tagline, intro, contact, + colour, logo. `DefaultLanguage` also becomes the fallback language, which today is always English. `lang` uses the + full culture name, so `pt-BR` and `zh-Hant` survive. +- The archive's time zone. Curator pages and the activity log use the server's clock, which is UTC in the Docker image + unless an operator sets `TZ`, and the docs do not mention it: in the walk-through, a German afternoon showed up an + hour early. Check that the image has the time zone data this needs. +- Logo: new image code sharing the NetVips helpers, since the preview pipeline only writes JPEG and is tied to + `MediaFile`. +- `/branding.css`, because inline styles are forbidden. It must set Bootstrap's button component variables, + `--bs-link-color-rgb` with hover and the focus ring, since `--bs-primary` alone changes neither buttons nor links. + Check contrast for link text, button text and hover, suggest a darker shade, version the address by settings hash, + and prove it with a browser test. +- The archive's name in the title, navigation and footer, with "Powered by Commonage" and the source link staying. +- Fixed pages: About, Contact and withdrawal, Privacy, Imprint. Plain text with auto-links. Empty pages stay unlinked, + and the checklist shows that they are unset. The consent text promises people can ask for removal, and today nothing + says how. +- "This form belongs to {0}" on the contribution form; a reference code on Thanks, which says that no email follows. +- The "allow search engines" switch works at once: `noindex` on public pages and a basic `robots.txt`. +- A "Getting started" checklist on the admin page: name, contact, legal pages, first collection, first link, backup + seen, restore tested. +- A short translatable curator handbook, including how to handle a removal request from someone in a photo, how to + describe a photo, and how to record offline donations. Extended with each workflow milestone. + +**M11 Look and feel** + +- First the structural part of languages, so the design is tested in both directions once: one `SupportedLanguages` + list, `dir` and Bootstrap's RTL stylesheet, a picker that scales, and pseudo and RTL test languages in the browser + tests. +- A cheap seeded benchmark at 5–10k items before adding home page queries. +- Design foundation: remove the template's `_Layout.cshtml.css` and its stylesheet link, and put tokens for accent, + surface, text, radius and spacing in `site.css`, on top of Bootstrap's variables. Readable body text, prose limited to + 68 characters, consistent cards with a visible focus state, logical properties only. System fonts only, because no + single font covers every script. New admin screens from M12 on are built on this. +- Home page: the group's name and intro, search, recently added photos, collection cards with images, tags last. + Today the first screen on a phone has no picture at all, and the page's heading is "Collections". +- Item page: on wide screens the text sits beside the photo. Today the description comes after every photo, so one + added portrait pushed it about 1,600 px down, and the first photo alone runs past the bottom of an 800 px high + screen. Photos stop sitting to one side with an empty column next to them. +- The language picker moves to the header. In the footer, a visitor who does not read the page's language has to find + it at the bottom of a long page. +- Clearer navigation: "Collections" means the public list in the top bar and the management page in the admin row, the + site name and "Collections" lead to the same place, and links dominate with large underlined blue headings. A + slimmer demo notice: with the header, it takes up about 130 px of a phone screen. +- Images: an 800 px thumbnail with `srcset`, `contain` instead of cropping, the first preview loaded eagerly, ETags. +- One regeneration mechanism, also behind "retry failed" and rotation later: published files stay Ready and keep + serving while new versions replace them atomically, because setting them back to Pending makes published photos + return 404. Decide the 800 and 3000 px sizes together and backfill once. +- Search: removable filter chips, selects that apply at once, a helpful empty state. Print stylesheet *(can slip)*. + +**M12 Catalogue fields** + +Comes before bulk entry so a shoebox evening does not create backfill work. + +- `Rights` as rightsstatements.org and Creative Commons URIs with plain labels, an archive-wide default, `RightsHolder` + and `Credit`. A contributor's answer can propose a statement; an open licence is never assumed. Publishing a credit + takes an explicit curator action, because those names were collected as curator-only. +- Reference number, where the original is kept, received from and when, internal notes, all curator-only and left out + of public search. Names here are covered by the personal-data tools. +- A plain `AltText` on the photo, and curators can correct contributor details. +- "Needs rights" and "needs alt text" filters. Export format bump; the existing `rights` CSV columns are renamed + deliberately, because they mean the contributor's answer. +- A simple spreadsheet import here if a tester or group reports needing it. + +**M13 Shoebox** + +- Files sent one at a time with progress, retry and safe resume; a documented limit for the path without JavaScript. + One large POST would hit the request limit with a few dozen TIFFs. +- Photos on the New item form, instead of "Save the item first, then add photos". "Save as draft" becomes the main + button there; today that is "Save and publish", on an item that cannot have photos yet. +- "Add many photos": one draft per file, with shared date, tags, rights and collection. A placeholder title is a flag + shown through the resource files, never stored text, and it blocks publishing. +- Bulk actions on the selection or the whole filter: publish, add tag, set date, move collection, set rights. One audit + entry per item, and a confirmation that shows the count. +- Duplicate warning through an index on `Sha256`, and a badge on contributions, never revealed to contributors. +- Previews appear without a reload, with visible queue progress. Tag suggestions *(can slip)*. + +**M14 Phone-first sending** + +- A shorter form with photos first. It is about 1,900 px long on a phone today and asks for a title before anything + else, while a person arrives with a photo in mind. A full-width Send button, and no repeated sentence about curators + looking at everything. +- `contribute.js` as progressive enhancement: file list, early checks, progress, no double sending. Thumbnails of + chosen files need `img-src blob:`, allowed only on these routes (the policy is one global string today). +- Text drafts in `localStorage`: title, date and description only, never name, email or rights holder, with an expiry + and a "Clear this draft" control, because events share devices. +- Try HEIC on a real iPhone. The browser may already convert it, and the bundled libvips probably has no HEVC decoder. + *Not tried yet, because it takes a real iPhone: it is on the tester's list. Until then, HEIC is refused in plain words.* +- A walk-through of new tasks, also given to the tester: send three photos over mobile data with a wrong date, read a + letter, find everything from the 1950s in one street. It would help to have someone over 70 and a screen reader user + try it, but nothing waits for that. A week of fixes follows, then decide what comes after this milestone. + +**M15 Readable items** + +- `Position`, `Caption` and `Rotation` on photos, Move earlier/later buttons, "use as cover". `AltText` per photo + closes the alt-text item. "Move to a new item" and photo descriptions from contributors *(can slip, and did: under "Later", + roughly by value)*. +- A public "large" image of about 3000 px, a per-archive setting, served through the published check, relying on + browser zoom instead of a lightbox. +- Numbered thumbnail strip with captions. Previous and next, "More from {0}", "From the same time". Dates link to + search. +- Description as the documented place for a transcript, with a "needs transcription" flag, since zoom helps only + sighted visitors and handwriting cannot be searched. +- A scanned letter in the demo archive. Its letter is typed text today, so "read a letter" cannot be tried there. + +**M16 Rights and sharing** + +- Rights and approved credit on item pages. An optional reuse question and new consent wording on the form; earlier + contributions stay under their stored text. Their consent covers "this website", which matters for harvesting later. +- "Cite this item", `rel=canonical`, a share button. +- Link previews, an Atom feed and a sitemap, all following the search engine switch. + +**M17 Language reach** + +The structural part is in M11. This is the rest of [Languages](#languages), reordered, since no group has asked for +a third language yet: + +- A spike on plurals first: Weblate's RESX format has no plural support and needs an English base file, which the + repository does not have, because English keys live in code. Compare ICU syntax in one value with other formats. +- A generated base file and a test that fails when a key is missing. +- Decide Weblate hosting, how its commits pass the sign-off check, and how translators accept the license. Consent and + privacy strings need a reviewer, because the consent text is what a person agreed to. +- `DateVocabulary` and the content-language setting. First define the policy (content languages plus the current + interface language), with regression tests that today's accepted dates stay accepted. +- Export README and demo content translated; a decision on language per item for mixed archives. +- A third language is a goal that does not block the milestone, since it depends on a volunteer. + +Until then, write counts in label form (`Photos: {0}`), which needs no plural grammar. + +**Done (November 2026):** ICU MessageFormat in RESX values, with CLDR rules in `Plurals.cs`; the base file and the tests +for missing, left-over, empty and broken translations; content languages for dates and `lang`, with a frozen copy of the +old date reader in the tests; the export README. The demo was already in both languages. + +- **Language per item: not now.** An archive chooses one main language for the material, or "several, none of them most", + which marks nothing. A language per item is wanted only if mixed archives ask for it, and M21's import could bring it. +- **Still open:** Weblate is not set up yet, so no translator has tried it. That is on the tester's list in + [usability-test.md](usability-test.md), once the maintainer has applied. No third language yet. + +**M18 Accounts and system** + +- Authenticator two-factor login with recovery codes, using a QR encoder that M20 reuses. Admins can require it. Setup + links stay the recovery path, because no email is sent. State where the secrets are protected. +- Data Protection keys encrypted with a key outside the database, including restore docs, the backup test (which + relies on old logins still working) and what happens if that key is lost. +- System page: version, disk use and growth, failed previews with retry, `unaccent` state, last migration. Storage + checks in `/health`, with a note for uptime monitors that a degraded answer is still HTTP 200. +- How long the activity log and Rejected or Withdrawn items are kept; activity log filters. + +**Done (November 2026), in two pull requests.** First, authenticator apps and the login keys encrypted with +`COMMONAGE_LOGIN_KEY`. A setup link still only sets a new password, so that someone who forgot it keeps their app. For a lost +phone, an admin turns the app off, and `reset-two-factor` on the server does it for the last admin or after the key was lost. +Second, the System page, the checks behind `/health` (media folder, disk and backup as well as the database), and how long the +activity log and rejected or withdrawn contributions are kept, with activity log filters. Both times start as "Always", so an +update deletes nothing; rejected contributions go to the bin rather than straight away, and the log keeps at least a year. A +missing newest original answers `Unhealthy`, which also makes `update.sh` roll back, because an unmounted media volume loses +every upload after it. + +**M19 Discovery** + +- Decade timeline with predefined CSS classes for bar widths, because the policy forbids inline styles. +- A decade or year typed into the search counts as a date. In the M14 walk-through, "Mill Street 1950s" found two items while the + year filter found three, since the tram of 1930–1955 does not contain the word. +- Tag page with rename, merge and delete unused. `Tag.Kind` (topic, place, person) with `/places` and `/people`. Naming + living people stays a curator's decision. +- Collections: order, date span, cover, default sort, delete when empty. + +**First part done (November 2026):** a year, decade, month or "circa 1950" typed into the search finds what is dated then, or +what has the words, for visitors and curators alike, and the page says how it understood the date. The decades are on the +start page and beside the results, each as a bar whose number is what tapping it finds; items with open ends such as "before +1945" reach to the edge, as in the year filter. "1950er Jahre" is one decade, as Germans often write it. + +**Second part done (November 2026):** each tag is a topic, place or person, set on the new Tags page, which also renames, +merges and deletes unused tags. Every item with a changed tag is brought up to date for the search, items in the bin +included, and a tag that only items in the bin have is not unused. `/places` and `/people` list from A to Z what published +items are tagged with, so a name only drafts have stays unseen; whether to name living people stays the curators' decision, +and the page and the handbook say that the People page lists names on their own. The export (version 4) has the tags with +their kinds. + +**Third part done (November 2026):** curators put the collections in order and give each one an order for its items, which +"previous" and "next" on an item follow, so the walk through a collection is the one its page shows. A cover is chosen from the +collection's photos, also a draft's ahead of publishing, but visitors only see it while its item is published and in the +collection. An empty collection can be deleted; one with an item in the bin or a contribution link cannot. Each collection +shows the years of its published items. M19 is complete. + +**M20 Community knowledge** + +- ✅ "Do you know more about this?", off by default: information, correction or removal request, stored as a private note, + protected like the contribution form, and covered by the personal-data tools. Notes sit in a curators' inbox (removal + requests first), can be dealt with, stripped of name and email, or deleted, appear in Contributors and in a full export, and + the activity log names only the item. +- ✅ "Help wanted" flag and a "Can you help?" page (only while visitors are asked; unpublished items are not listed, and the + export, version 5, carries the flag). Dashboard cards for what needs attention: notes (removal requests counted), items + waiting for a transcription, help wanted. +- ✅ Links: copy button, a printable poster with QR code (no inline styles), and an opt-in invitation on the collection page, + which gives up being unlisted. A clear page for closed links (`410`, showing nothing from the link). Contribution links are + not part of the export, so the invitation setting is not either. + +**M21 Import and scale** + +- CSV with its own template, without id or status columns, with defined handling of the apostrophe that exports add + for spreadsheet safety. ZIP or a folder on the media volume. A dry run lists unreadable dates, unknown collections, + missing files and duplicates. +- **Done (first part):** the import, as described in `development.md`. A language column was left out: the archive's language is + one setting, and a language per item stays unwanted until a mixed archive asks. +- **Done (second part):** the export streams its JSON and CSV and reads items 500 at a time. A benchmark, + `COMMONAGE_SCALE_ITEMS=50000 dotnet test tests/Commonage.Tests --filter ScaleTests`, fills the test database with that many + items and times the pages and the export. On the maintainer's PC against PostgreSQL in Docker, every public page answered in + under 0.5 s (start page and tag lists slowest, about 0.35 s; search 0.1-0.2 s; curator list under 0.1 s) and the export + of 50,000 items took 8 s, with memory use growing by 20-40 MB. It was **not** run on an ARM server. The expected fixes were + measured and left out: a composite index on status and publication date changed nothing, a deep page costs no more than + the first (the page number is clamped), and cached counts would let a just-unpublished or binned item's tags stay public + for the length of the cache. Counting tags over 45,000 items is the slowest remaining step; revisit it if a real server + is slow. + +**M22 Release and ARM** + +- Released v0.5.0 with `/release`, after the changelog is checked against M19 to M21. The notes say the export is version 5 and + that nothing needs regenerating. +- `scale-arm.yml` runs the benchmark by hand on GitHub's ARM runner. It is not a required check. A hosted runner is not a small + home server, and the numbers are recorded as that. **Run on that runner, 50,000 items:** seeding 4.7 s; public pages + 0.05-0.5 s (start page 0.4-0.5 s, `/places` 0.4 s, tag filter 0.35 s, search 0.1-0.25 s, deep pages 0.2 s); curator pages + 40-110 ms; the export 8.2 s into a 3 MB ZIP, with memory use growing by up to 104 MB (20-40 MB on the PC). So ARM works and + stays fast, and the export's memory is higher than the PC figure suggested but still far from filling a small server. Not + tested on a real Raspberry Pi. +- Weblate (open since M17) is set up once the maintainer's application is through. + +**M23 Documents** + +- **Spike, done.** The bundled NetVips (libvips 8.18) reads and writes GIF and AVIF, tested on Windows x64 with a round trip; + the Linux build in the image is checked by a test in the first part. It has no PDF loader, so PDFs need `poppler-utils`: + on the x86 base image, `apt install --no-install-recommends poppler-utils` adds about 83 MB (48 packages, including cairo, + fontconfig, nss and curl libraries). The ARM size was not measured (no ARM machine here); the first part measures it in CI. + Because of the size and the parser risk, the Dockerfile gets a build argument and Compose a documented way to leave poppler + out: a PDF is then refused with a clear message, and every other format works as before. +- **Second part, done.** PDF page previews, `MediaFile.PageCount`, the public route `/media/{id}/page/{n}`, export version 6, the `WITH_PDF` build argument. PDF tests need poppler and are skipped without it (CI installs it). +- **Third part, done.** The text of PDFs (`pdftotext`, first 300 pages, 200,000 characters) goes into the side table `ItemFileTexts`, matched by search for published items only and never shown; the item page shows PDF pages with "Page n of m". Left out: ranking by file text, and text for PDFs processed before this part. +- **Parts.** First: AVIF and GIF (magic bytes in `ImageFormats`, accepted by upload and contribution links, a GIF becomes one + still picture; no animation is kept). Second: PDF page previews and page count, with the migration and export version 6. + Third: the text from PDFs into search, and the page strip on the item page. +- PDFs are recognised by content. `pdftoppm` and `pdftotext` run as separate processes with a timeout, a page limit and a size + limit, driven by the existing background queue; a failure shows as a failed file with the existing retry. The parser risk + gets its row in `security.md`. +- Pages are previews stored next to the file and served through `MediaEndpoints` with the published check. The PDF itself + stays with curators, as every original does. The text goes into the search through the item, never for drafts. +- The export carries the page count (version 6) and leaves the text out, because it can be rebuilt. + +**M24 Helpers and accounts** + +- Part 1 is done: the `Helper` role. Part 2: `StaffProfiles` (display name, last login), shown to admins only; the activity log + keeps the email address as at the time, so it stays true after a rename. +- A `Helper` role: describes and uploads. Publishing, the bin, contributors, notes, export and settings stay with curators, + and contributors' names and email addresses are not shown. `EndpointAccessTests` checks every role against every admin + address. Display names and a last login for accounts. + +**M25 Oral histories** + +- **Spike result (part 1).** `ffmpeg` from Debian adds about 405 MB to the image (197 packages), five times what poppler + does, and a trimmed static build would be one more thing to build for x86 and ARM and keep patched. The metadata is + not hidden in the sound, though: it sits in a few well-known places (ID3 tags in MP3, `udta`/`meta` boxes in MP4, + `LIST` chunks in WAV, comment and picture blocks in FLAC). So no subprocess and no new package: small readers in the + app cut those out, the audio itself is copied byte for byte. They read only curators' files, never a contribution's. +- **Part 1: audio in, stripped copy out.** MP3, M4A, WAV and FLAC are recognised by content. The original stays with + curators like every original. Processing writes a stripped copy; visitors get only that, through the same published + check, with range requests so that the browser's own player can jump. A file whose structure the reader does not + understand fails with the retry button, and is never served unstripped. The item page shows the player; the curator + form accepts audio. Ogg/Opus is left for later: its comment lives inside pages with checksums, so it needs a rewriter + of its own and is not worth holding the rest up. +- **Part 2: the transcript.** An item with audio needs a transcript before it is published, or the "transcript to follow" + flag (the existing "needs transcription" flag). The transcript is searched and shown beside the player. The handbook + documents a local whisper.cpp workflow, as "Not planned" promises. + +- (Earlier wording) Audio is recognised by content, stripped of metadata without re-encoding and served with range requests through the same permission check, in the browser's own player. An item with audio needs a transcript before it is published, or the "transcript to follow" flag. A local whisper.cpp workflow is documented, as "Not planned" promises. From 80adfd85862156d67dd24117ffbf106505cba34e Mon Sep 17 00:00:00 2001 From: "Seb H." <138793908+SebHenn@users.noreply.github.com> Date: Sun, 15 Nov 2026 20:15:34 +0100 Subject: [PATCH 2/2] M25, first part: recordings with stripped copies Curators can upload MP3, M4A, FLAC and WAV recordings. Visitors hear a copy with tags and dates removed; the original stays curator-only. Contribution links refuse audio. Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Seb H. <138793908+SebHenn@users.noreply.github.com> --- CHANGELOG.md | 5 + docs/curator-handbook.md | 12 + docs/development.md | 5 + docs/handbuch-kuratoren.md | 12 + docs/roadmap.md | 2 + docs/security.md | 1 + src/Commonage.Web/Domain/MediaFile.cs | 7 +- src/Commonage.Web/Media/AudioTools.cs | 378 ++++++++++++++++++ src/Commonage.Web/Media/ImageFormats.cs | 2 +- src/Commonage.Web/Media/MediaEndpoints.cs | 36 +- src/Commonage.Web/Media/MediaProcessing.cs | 37 +- src/Commonage.Web/Media/MediaUploadService.cs | 2 + src/Commonage.Web/Pages/Admin/Bin.cshtml.cs | 2 +- .../Pages/Admin/Collections/Edit.cshtml.cs | 4 +- src/Commonage.Web/Pages/Admin/Index.cshtml.cs | 2 +- .../Pages/Admin/Items/Edit.cshtml.cs | 2 +- .../Pages/Admin/Items/_PhotoCard.cshtml | 22 +- .../Pages/Admin/Items/_UploadTexts.cshtml | 1 + .../Pages/Items/Details.cshtml.cs | 2 +- .../Pages/Shared/_ItemArticle.cshtml | 19 +- .../Resources/SharedResource.de.resx | 3 + .../Resources/SharedResource.resx | 3 + src/Commonage.Web/Search/AdminItemList.cs | 2 +- src/Commonage.Web/Search/ItemSummary.cs | 6 +- src/Commonage.Web/Search/PublicFeeds.cs | 4 +- src/Commonage.Web/wwwroot/css/site.css | 5 + src/Commonage.Web/wwwroot/js/uploads.js | 18 +- .../ReadableItemBrowserTests.cs | 20 + tests/Commonage.Tests/AudioTests.cs | 256 ++++++++++++ tests/Commonage.Tests/ContributionTests.cs | 13 + tests/Commonage.Tests/EndpointAccessTests.cs | 2 + tests/Commonage.Tests/ExportTests.cs | 2 +- 32 files changed, 860 insertions(+), 27 deletions(-) create mode 100644 src/Commonage.Web/Media/AudioTools.cs create mode 100644 tests/Commonage.Tests/AudioTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index f8c31dc..adc62f3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,11 @@ version may change things that need attention when updating, and these notes say itself is never shown. A PDF in the bin is not searched until it is restored. PDFs added before this version have no text; upload them again to make them searchable. - The item page shows a PDF as its pages, one under the other, each with "Page 3 of 20". +- Recordings can be uploaded by curators (not through contribution links): MP3, M4A (the voice recorders of phones), WAV and + FLAC. Visitors hear a copy in the item page's own player, which can jump about. Names, places, dates, cover pictures + and everything else the file carries in tags are cut out of that copy; the sound itself is not re-encoded. The original + stays with curators. A file whose structure the archive cannot follow is refused rather than served. OGG/Opus is not + accepted yet. Recordings are not yet searched or transcribed. ### For people running an archive diff --git a/docs/curator-handbook.md b/docs/curator-handbook.md index 012d4db..008b53c 100644 --- a/docs/curator-handbook.md +++ b/docs/curator-handbook.md @@ -53,6 +53,18 @@ needs to be entered for that. Visitors can open a photo at about 3000 pixels. Whether they can is a setting for the whole archive, under "Settings". +## Recordings + +A recording (MP3, M4A from a phone's voice recorder, WAV or FLAC) is added like a photo, on the item's page, by a curator or helper; +not through a contribution link. Visitors hear it with the player on the item page once the item is published. They get a copy +that has everything cut out that the file carries besides the sound: names, places, dates, the device and cover pictures. The +sound itself is exactly the original's. The original stays with curators ("Original" on the card). If the archive cannot make +sense of a file, it says "No preview could be created" and offers nothing to visitors: try saving it again from the recorder +or converting it to MP3 or WAV. OGG and Opus are not accepted yet. + +A recording cannot be searched. Write down in the description what is said, or at least who and where, and tick "Still needs a +transcription" until there is a transcript. + ## Rights, credit and what only you see Open **Rights and credit** on an item: diff --git a/docs/development.md b/docs/development.md index 2de9458..2a507bc 100644 --- a/docs/development.md +++ b/docs/development.md @@ -75,6 +75,11 @@ Originals and their previews are stored under `Storage:RootPath`. It defaults to `Media/MediaEndpoints.cs`, which checks permissions. The per-file limit is `Uploads:MaxFileSizeMegabytes` (default 200). +Recordings (`Media/AudioTools.cs`) have no pictures: `MediaProcessor` writes a copy without tags under `audio/{StorageId}` by +cutting tags out of the file's structure and copying the sound unchanged (no ffmpeg, which would add about 400 MB to the image). +Only that copy is served to visitors, from `/media/{id}/audio` with range requests. Every query that picks a cover skips +`audio/*` files. + Previews are generated in the background with [NetVips](https://github.com/kleisauke/net-vips) (libvips). They are rotated upright and contain no EXIF, so GPS coordinates stay in the private original. `MediaProcessor` works through them one at a time. Nothing a single file does may leave its loop, because an diff --git a/docs/handbuch-kuratoren.md b/docs/handbuch-kuratoren.md index f491b7a..860c265 100644 --- a/docs/handbuch-kuratoren.md +++ b/docs/handbuch-kuratoren.md @@ -60,6 +60,18 @@ Besucher sehen auf der Seite und der Karte einer Sammlung, aus welchen Jahren ih Besucher können ein Foto mit etwa 3000 Pixeln öffnen. Ob das möglich ist, gilt für das ganze Archiv und steht unter „Einstellungen“. +## Aufnahmen + +Eine Aufnahme (MP3, M4A vom Diktiergerät des Telefons, WAV oder FLAC) fügen Kuratoren und Helfer auf der Seite des Eintrags hinzu wie ein +Foto, nicht über einen Einsendelink. Besucher hören sie im Player auf der Seite des Eintrags, sobald er veröffentlicht ist. Sie bekommen +eine Kopie, aus der alles entfernt ist, was die Datei außer dem Ton enthält: Namen, Orte, Daten, das Gerät und Titelbilder. Der Ton selbst +ist genau der des Originals. Das Original bleibt bei den Kuratoren („Original“ auf der Karte). Kann das Archiv mit einer Datei nichts +anfangen, steht dort „Es konnte keine Vorschau erstellt werden“, und Besucher bekommen nichts: speichern Sie sie noch einmal aus dem +Aufnahmegerät oder wandeln Sie sie in MP3 oder WAV um. OGG und Opus werden noch nicht angenommen. + +Eine Aufnahme lässt sich nicht durchsuchen. Schreiben Sie in die Beschreibung, was gesagt wird, oder wenigstens wer und wo, und setzen Sie +den Haken bei „Muss noch abgeschrieben werden“, bis es eine Abschrift gibt. + ## Rechte, Nennung und was nur Sie sehen Öffnen Sie bei einem Eintrag **Rechte und Nennung**: diff --git a/docs/roadmap.md b/docs/roadmap.md index eeb9fff..79cb222 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -522,6 +522,8 @@ shows the years of its published items. M19 is complete. understand fails with the retry button, and is never served unstripped. The item page shows the player; the curator form accepts audio. Ogg/Opus is left for later: its comment lives inside pages with checksums, so it needs a rewriter of its own and is not worth holding the rest up. + *Built:* a recording is a `MediaFile` with an `audio/*` type and no picture sizes, so every query that picks a cover skips + it; its stripped copy is `audio/{StorageId}`. No new column, so no migration and no change to the export. - **Part 2: the transcript.** An item with audio needs a transcript before it is published, or the "transcript to follow" flag (the existing "needs transcription" flag). The transcript is searched and shown beside the player. The handbook documents a local whisper.cpp workflow, as "Not planned" promises. diff --git a/docs/security.md b/docs/security.md index 8a6cb17..d84c3e1 100644 --- a/docs/security.md +++ b/docs/security.md @@ -27,6 +27,7 @@ vulnerability, see [SECURITY.md](../SECURITY.md). | Staff names and last login | `StaffProfiles` holds an optional display name and the time of the last login per account, written after a successful login (password, authenticator code or recovery code). Read only on the admin-only Accounts pages, never on a public page, feed or link preview, and not in the export or the activity log (which keeps the email address). Changing a name is logged. The row goes with the account (cascade). `AccountTests`. | | Helpers | The `Helper` role (policy `Describe`) reaches only the item list, the item form, "Add many photos", the preview and the generated pictures under `/admin/media` (not the original). Everything else under `/Admin` needs `ManageArchive` (curator or admin) or `Administer`. A helper only gets draft items, in the list, the form, the preview and the pictures, never published, submitted, rejected or withdrawn ones: what visitors see changes only through a curator, and no contribution or contributor name or email reaches a helper (the contribution is not even loaded). The start page counts, the "already in the archive" file check and the reference-number check show a helper drafts only. Publishing, unpublishing, accepting, rejecting, deleting, withdrawing and removing a photo are refused with 403 on the server, not only hidden. Accepted: a helper can read "received from" and the internal notes of the items they open; the handbook says so. `HelperTests` (including a test that lists every `/Admin` address a helper can reach), `AccountTests`. | | Import | Only curators (the `/Admin` policy). The sheet and ZIP are kept in `import-staging` on the media volume, which is never served by path, for a day at most. A sheet is read as strict UTF-8, at most 20 MB and 100,000 rows; a ZIP at most 4 GB and 200,000 entries; every entry is counted as it is unpacked into a temporary file, and a name inside it is never used in a path. A folder to import from is chosen from a listing of `import/`, links and hidden files are skipped. Files go through the same checks as an upload. One import at a time. Everything imported is a draft; the activity log records each item and the import, never the spreadsheet or the contributors' details. `ImportTests`. | +| 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`). | | Browser | Strict Content Security Policy (no inline script or style, no framing, no plugins; only the contribution form may show `blob:` images, for the photos someone has chosen on their own device, and a picture opened on its own has no scripts at all but lets the browser's picture view style itself), `nosniff`, `Referrer-Policy: same-origin` (setup links never leak to other sites), `X-Frame-Options`, `Permissions-Policy`, `Cross-Origin-Opener-Policy`. No `Server` header. `SecurityHeaderTests` checks the headers and that no page contains inline script or style, so the policy can stay strict. | diff --git a/src/Commonage.Web/Domain/MediaFile.cs b/src/Commonage.Web/Domain/MediaFile.cs index 75f9ced..acb6c56 100644 --- a/src/Commonage.Web/Domain/MediaFile.cs +++ b/src/Commonage.Web/Domain/MediaFile.cs @@ -53,6 +53,9 @@ public class MediaFile public bool IsPdf => ContentType == PdfContentType; + /// A recording. It has no pictures; visitors hear a copy without tags, and the original stays with curators. + public bool IsAudio => ContentType.StartsWith("audio/", StringComparison.Ordinal); + /// The text read from a PDF, for search only. Never shown. Null for pictures and for PDFs without text. public string? ExtractedText { get; set; } @@ -87,6 +90,8 @@ public class MediaFile public DateTime? DeletedAt { get; set; } public string OriginalKey => $"originals/{StorageId:N}"; + /// The copy of a recording without its tags, the only one visitors can reach. + public string AudioKey => $"audio/{StorageId:N}"; public string PreviewKey => $"previews/{StorageId:N}.jpg"; public string ThumbnailKey => $"thumbnails/{StorageId:N}.jpg"; public string CardKey => $"cards/{StorageId:N}.jpg"; @@ -100,7 +105,7 @@ public class MediaFile /// Everything made from the original: the sizes of the picture and the pages of a PDF. public IEnumerable DerivativeKeys() => - new[] { PreviewKey, ThumbnailKey, CardKey, LargeKey }.Concat(Enumerable.Range(1, PageCount ?? 0).Select(PageKey)); + IsAudio ? [AudioKey] : new[] { PreviewKey, ThumbnailKey, CardKey, LargeKey }.Concat(Enumerable.Range(1, PageCount ?? 0).Select(PageKey)); /// Which picture sizes exist. Raising it makes the archive add the new ones in the background. public const int CurrentDerivativeVersion = 3; diff --git a/src/Commonage.Web/Media/AudioTools.cs b/src/Commonage.Web/Media/AudioTools.cs new file mode 100644 index 0000000..24e09f6 --- /dev/null +++ b/src/Commonage.Web/Media/AudioTools.cs @@ -0,0 +1,378 @@ +using System.Buffers.Binary; + +namespace Commonage.Web.Media; + +/// +/// Makes the copy of a recording that visitors may hear. Recordings carry names, places, dates, device serial numbers and +/// cover pictures in tags. These are cut out while the sound itself is copied byte for byte, so nothing is re-encoded and +/// no program outside the app is needed. A file whose structure is not understood is refused, never passed on as it is. +/// +public static class AudioTools +{ + public const string Mp3 = "audio/mpeg"; + public const string Mp4 = "audio/mp4"; + public const string Wav = "audio/wav"; + public const string Flac = "audio/flac"; + + /// Largest sound header (the "moov" box of an M4A) the app reads into memory. + private const int MaxHeaderBytes = 64 * 1024 * 1024; + + public static string? DetectContentType(ReadOnlySpan header) + { + if (header.StartsWith("ID3"u8)) + return Mp3; + // A frame of MP3 data without tags. 0xFFD8 is a JPEG, which is checked before this. + if (header.Length >= 2 && header[0] == 0xFF && (header[1] & 0xE0) == 0xE0 && (header[1] & 0x06) != 0) + return Mp3; + if (header.StartsWith("fLaC"u8)) + return Flac; + if (header.Length >= 12 && header[..4].SequenceEqual("RIFF"u8) && header[8..12].SequenceEqual("WAVE"u8)) + return Wav; + // Voice recorders and phones. Other brands of this container may hold video, which is not accepted. + if (header.Length >= 12 && header[4..8].SequenceEqual("ftyp"u8) + && (header[8..12].SequenceEqual("M4A "u8) || header[8..12].SequenceEqual("M4B "u8))) + return Mp4; + return null; + } + + public static bool IsAudio(string contentType) => contentType.StartsWith("audio/", StringComparison.Ordinal); + + /// Writes the copy without tags. The input must be seekable. + /// The file is not built the way its type says, so nothing can be said about what it holds. + public static void Strip(string contentType, Stream input, Stream output) + { + switch (contentType) + { + case Mp3: StripMp3(input, output); break; + case Mp4: StripMp4(input, output); break; + case Wav: StripWav(input, output); break; + case Flac: StripFlac(input, output); break; + default: throw new InvalidDataException("Not a recording this archive can read."); + } + } + + // ---- MP3 ------------------------------------------------------------------------------------------------------ + + private static void StripMp3(Stream input, Stream output) + { + var length = input.Length; + long start = 0; + var head = new byte[10]; + // Tags at the start, one after another if there are several. + while (start + 10 <= length && ReadAt(input, start, head) && head.AsSpan(0, 3).SequenceEqual("ID3"u8)) + { + var size = SyncSafe(head.AsSpan(6, 4)); + if (size < 0) + throw new InvalidDataException("The tag at the start of the recording is damaged."); + start += 10 + size + ((head[5] & 0x10) != 0 ? 10 : 0); + } + if (start >= length) + throw new InvalidDataException("The recording holds no sound."); + + var end = length; + // Tags at the end: ID3v1 (128 bytes), and APEv2 before or without it. + var tail = new byte[128]; + if (end - start >= 128 && ReadAt(input, end - 128, tail) && tail.AsSpan(0, 3).SequenceEqual("TAG"u8)) + end -= 128; + var footer = new byte[32]; + if (end - start >= 32 && ReadAt(input, end - 32, footer) && footer.AsSpan(0, 8).SequenceEqual("APETAGEX"u8)) + { + var size = (long)BinaryPrimitives.ReadUInt32LittleEndian(footer.AsSpan(12, 4)); + var hasHeader = (BinaryPrimitives.ReadUInt32LittleEndian(footer.AsSpan(20, 4)) & 0x80000000) != 0; + var total = size + (hasHeader ? 32 : 0); + if (total < 32 || total > end - start) + throw new InvalidDataException("The tag at the end of the recording is damaged."); + end -= total; + } + + // Other tag kinds that sit at the end (a Lyrics3 block, an enhanced "TAG+", an ID3v2 footer) are not + // understood here, so a file that carries one is refused rather than passed on with its text. + var window = (int)Math.Min(end - start, 64 * 1024); + if (window > 0) + { + var tailBytes = new byte[window]; + if (ReadAt(input, end - window, tailBytes) && HasForeignTag(tailBytes)) + throw new InvalidDataException("The recording carries a tag that cannot be removed."); + } + + // The sound has to begin with a frame, or this is not what it says it is. + var first = new byte[2]; + if (!ReadAt(input, start, first) || first[0] != 0xFF || (first[1] & 0xE0) != 0xE0) + throw new InvalidDataException("The recording does not begin with MP3 sound."); + + Copy(input, start, end - start, output); + } + + private static bool HasForeignTag(ReadOnlySpan bytes) => + bytes.IndexOf("LYRICSBEGIN"u8) >= 0 || bytes.IndexOf("LYRICS200"u8) >= 0 + || bytes.IndexOf("TAG+"u8) >= 0 || bytes.IndexOf("APETAGEX"u8) >= 0 + || bytes.IndexOf("3DI\u0004\u0000"u8) >= 0 || bytes.IndexOf("3DI\u0003\u0000"u8) >= 0; + + private static int SyncSafe(ReadOnlySpan bytes) + { + var value = 0; + foreach (var b in bytes) + { + if ((b & 0x80) != 0) + return -1; + value = (value << 7) | b; + } + return value; + } + + // ---- MP4 / M4A -------------------------------------------------------------------------------------------------- + + private static void StripMp4(Stream input, Stream output) + { + var length = input.Length; + long position = 0; + var header = new byte[16]; + var sawFtyp = false; + var sawMoov = false; + var sawMdat = false; + while (position < length) + { + if (length - position < 8 || !ReadAt(input, position, header.AsSpan(0, 8))) + throw new InvalidDataException("The recording ends in the middle of a part."); + var size = (long)BinaryPrimitives.ReadUInt32BigEndian(header.AsSpan(0, 4)); + var type = header.AsSpan(4, 4).ToArray(); + var headerSize = 8; + if (size == 1) + { + if (length - position < 16 || !ReadAt(input, position, header)) + throw new InvalidDataException("The recording ends in the middle of a part."); + size = (long)BinaryPrimitives.ReadUInt64BigEndian(header.AsSpan(8, 8)); + headerSize = 16; + } + else if (size == 0) + { + size = length - position; + } + if (size < headerSize || size > length - position) + throw new InvalidDataException("A part of the recording has an impossible size."); + + var name = System.Text.Encoding.Latin1.GetString(type); + switch (name) + { + case "ftyp": + if (position != 0) + throw new InvalidDataException("The parts of the recording are in an unexpected order."); + sawFtyp = true; + Copy(input, position, size, output); + break; + case "mdat": + sawMdat = true; + Copy(input, position, size, output); + break; + case "moov": + if (size > MaxHeaderBytes) + throw new InvalidDataException("The description of the recording is too large."); + var moov = new byte[size]; + ReadExactlyAt(input, position, moov); + CleanContainer(moov, headerSize, moov.Length, 0); + output.Write(moov); + sawMoov = true; + break; + case "moof": + case "mfra": + case "sidx": + // Recordings cut into fragments are not handled. Better refused than served with their tags. + throw new InvalidDataException("Recordings made of fragments are not supported."); + default: + // Padding, user data, XMP, anything unknown: the same size, but empty. + WriteFree(size, output); + break; + } + position += size; + } + if (!sawFtyp || !sawMoov || !sawMdat) + throw new InvalidDataException("The recording lacks a part it needs."); + } + + /// + /// Turns what carries tags into empty "free" boxes of the same size, so the positions of the sound inside the file stay what + /// the file's own tables say, and sets the dates in the headers to zero. + /// + private static void CleanContainer(byte[] buffer, int from, int to, int depth) + { + if (depth > 4) + throw new InvalidDataException("The recording is nested too deeply."); + var position = from; + while (position < to) + { + if (to - position < 8) + throw new InvalidDataException("A part of the recording is cut short."); + var size = (long)BinaryPrimitives.ReadUInt32BigEndian(buffer.AsSpan(position, 4)); + if (size < 8 || size > to - position) + throw new InvalidDataException("A part of the recording has an impossible size."); + var type = System.Text.Encoding.Latin1.GetString(buffer, position + 4, 4); + var boxEnd = position + (int)size; + switch (type) + { + case "trak": + case "mdia": + CleanContainer(buffer, position + 8, boxEnd, depth + 1); + break; + case "mvhd": + case "tkhd": + case "mdhd": + ZeroDates(buffer, position + 8, boxEnd); + break; + case "udta": + case "meta": + case "uuid": + case "free": + case "skip": + "free"u8.CopyTo(buffer.AsSpan(position + 4, 4)); + buffer.AsSpan(position + 8, (int)size - 8).Clear(); + break; + } + position = boxEnd; + } + } + + private static void ZeroDates(byte[] buffer, int contentStart, int boxEnd) + { + if (boxEnd - contentStart < 4) + return; + var wide = buffer[contentStart] == 1; + var width = wide ? 8 : 4; + // After version and flags come the time made and the time changed. + if (boxEnd - contentStart < 4 + 2 * width) + return; + buffer.AsSpan(contentStart + 4, 2 * width).Clear(); + } + + private static void WriteFree(long size, Stream output) + { + if (size > uint.MaxValue) + throw new InvalidDataException("A part of the recording is too large to be set aside."); + Span header = stackalloc byte[8]; + BinaryPrimitives.WriteUInt32BigEndian(header, (uint)size); + "free"u8.CopyTo(header[4..]); + output.Write(header); + var zeros = new byte[Math.Min(size - 8, 81920)]; + var remaining = size - 8; + while (remaining > 0) + { + var chunk = (int)Math.Min(remaining, zeros.Length); + output.Write(zeros, 0, chunk); + remaining -= chunk; + } + } + + // ---- WAV ------------------------------------------------------------------------------------------------------ + + private static readonly string[] WavKept = ["fmt ", "fact", "data"]; + + private static void StripWav(Stream input, Stream output) + { + var length = input.Length; + long position = 12; + var kept = new List<(long Start, long Size, string Id)>(); + var chunk = new byte[8]; + while (position + 8 <= length) + { + ReadExactlyAt(input, position, chunk); + var id = System.Text.Encoding.Latin1.GetString(chunk, 0, 4); + var size = (long)BinaryPrimitives.ReadUInt32LittleEndian(chunk.AsSpan(4, 4)); + if (position + 8 + size > length) + throw new InvalidDataException("A part of the recording runs past the end of the file."); + if (WavKept.Contains(id)) + kept.Add((position + 8, size, id)); + position += 8 + size + (size & 1); + } + if (!kept.Any(k => k.Id == "fmt ") || !kept.Any(k => k.Id == "data")) + throw new InvalidDataException("The recording lacks a part it needs."); + + long body = 4 + kept.Sum(k => 8 + k.Size + (k.Size & 1)); + if (body > uint.MaxValue) + throw new InvalidDataException("The recording is too large for this format."); + Span riff = stackalloc byte[12]; + "RIFF"u8.CopyTo(riff); + BinaryPrimitives.WriteUInt32LittleEndian(riff[4..], (uint)body); + "WAVE"u8.CopyTo(riff[8..]); + output.Write(riff); + foreach (var (start, size, id) in kept) + { + var head = new byte[8]; + System.Text.Encoding.Latin1.GetBytes(id, head); + BinaryPrimitives.WriteUInt32LittleEndian(head.AsSpan(4, 4), (uint)size); + output.Write(head); + Copy(input, start, size, output); + if ((size & 1) != 0) + output.WriteByte(0); + } + } + + // ---- FLAC ----------------------------------------------------------------------------------------------------- + + private static void StripFlac(Stream input, Stream output) + { + var length = input.Length; + long position = 4; + var blocks = new List<(byte Type, long Start, int Size)>(); + var head = new byte[4]; + while (true) + { + if (position + 4 > length) + throw new InvalidDataException("The recording ends in the middle of its description."); + ReadExactlyAt(input, position, head); + var type = (byte)(head[0] & 0x7F); + var last = (head[0] & 0x80) != 0; + var size = (head[1] << 16) | (head[2] << 8) | head[3]; + if (position + 4 + size > length) + throw new InvalidDataException("A part of the recording runs past the end of the file."); + // What the player needs, and the table for jumping about. Names, cover pictures, notes and all else stay out. + if (type is 0 or 3) + blocks.Add((type, position + 4, size)); + position += 4 + size; + if (last) + break; + } + if (blocks.Count == 0 || blocks[0].Type != 0 || blocks[0].Size != 34) + throw new InvalidDataException("The recording does not begin with its stream information."); + + output.Write("fLaC"u8); + for (var i = 0; i < blocks.Count; i++) + { + var (type, start, size) = blocks[i]; + var b = new byte[4]; + b[0] = (byte)(type | (i == blocks.Count - 1 ? 0x80 : 0)); + b[1] = (byte)(size >> 16); + b[2] = (byte)(size >> 8); + b[3] = (byte)size; + output.Write(b); + Copy(input, start, size, output); + } + Copy(input, position, length - position, output); + } + + // ---- helpers -------------------------------------------------------------------------------------------------- + + private static bool ReadAt(Stream input, long position, Span buffer) + { + input.Position = position; + return input.ReadAtLeast(buffer, buffer.Length, throwOnEndOfStream: false) == buffer.Length; + } + + private static void ReadExactlyAt(Stream input, long position, Span buffer) + { + if (!ReadAt(input, position, buffer)) + throw new InvalidDataException("The recording ends unexpectedly."); + } + + private static void Copy(Stream input, long start, long count, Stream output) + { + input.Position = start; + var buffer = new byte[81920]; + while (count > 0) + { + var read = input.Read(buffer, 0, (int)Math.Min(buffer.Length, count)); + if (read == 0) + throw new InvalidDataException("The recording ends unexpectedly."); + output.Write(buffer, 0, read); + count -= read; + } + } +} diff --git a/src/Commonage.Web/Media/ImageFormats.cs b/src/Commonage.Web/Media/ImageFormats.cs index 46248b0..b43903a 100644 --- a/src/Commonage.Web/Media/ImageFormats.cs +++ b/src/Commonage.Web/Media/ImageFormats.cs @@ -11,7 +11,7 @@ public static class ImageFormats public const string AcceptAttribute = "image/jpeg,image/png,image/tiff,image/webp,image/avif,image/gif"; /// For the curators' forms, which also take PDFs. - public const string AcceptWithDocumentsAttribute = AcceptAttribute + ",application/pdf"; + public const string AcceptWithDocumentsAttribute = AcceptAttribute + ",application/pdf,audio/mpeg,audio/mp4,audio/x-m4a,audio/wav,audio/x-wav,audio/flac"; public static bool IsPdf(ReadOnlySpan header) => header.StartsWith("%PDF-"u8); diff --git a/src/Commonage.Web/Media/MediaEndpoints.cs b/src/Commonage.Web/Media/MediaEndpoints.cs index 738d323..f86bf90 100644 --- a/src/Commonage.Web/Media/MediaEndpoints.cs +++ b/src/Commonage.Web/Media/MediaEndpoints.cs @@ -21,12 +21,14 @@ public static void MapMediaEndpoints(this WebApplication app) { app.MapGet($"/media/{{id:int}}/{VariantPattern}", ServePublicDerivativeAsync); app.MapGet("/media/{id:int}/page/{page:int}", ServePublicPageAsync); + app.MapGet("/media/{id:int}/audio", ServePublicAudioAsync); // Pictures made for the screen and the state of their making are for everyone who may describe items. The original, which // may hold what the pictures do not, is for curators. var describers = app.MapGroup("/admin/media").RequireAuthorization(Policies.Describe); describers.MapGet($"/{{id:int}}/{VariantPattern}", ServeDerivativeAsync); describers.MapGet("/{id:int}/page/{page:int}", ServePageAsync); + describers.MapGet("/{id:int}/audio", ServeAudioAsync); describers.MapGet("/status", PreviewStatusAsync); app.MapGroup("/admin/media").RequireAuthorization(Policies.ManageArchive).MapGet("/{id:int}/original", ServeOriginalAsync); } @@ -37,12 +39,13 @@ private static async Task PreviewStatusAsync(string? ids, CommonageDbCo var wanted = (ids ?? "").Split(',').Take(MaxStatusQuestions).Select(id => int.TryParse(id, out var number) ? number : 0).Where(id => id > 0).ToList(); var files = await db.MediaFiles .Where(f => wanted.Contains(f.Id)) - .Select(f => new { f.Id, f.Status, Turning = f.Rotation != f.RenderedRotation }) + .Select(f => new { f.Id, f.Status, Turning = f.Rotation != f.RenderedRotation, Audio = f.ContentType.StartsWith("audio/") }) .ToListAsync(); var waiting = await db.MediaFiles.CountAsync(f => f.Status == ProcessingStatus.Pending || (f.Status == ProcessingStatus.Ready && f.Rotation != f.RenderedRotation)); return Results.Json(new { ready = files.Where(f => f.Status == ProcessingStatus.Ready && !f.Turning).Select(f => f.Id), + audio = files.Where(f => f.Audio).Select(f => f.Id), failed = files.Where(f => f.Status == ProcessingStatus.Failed).Select(f => f.Id), waiting = files.Where(f => f.Status == ProcessingStatus.Pending || (f.Status == ProcessingStatus.Ready && f.Turning)).Select(f => f.Id), message = waiting == 0 ? "" : localizer["Previews still to be created: {0}", waiting].Value, @@ -55,7 +58,7 @@ private static async Task ServePublicDerivativeAsync( var file = await db.PublishedItems .SelectMany(i => i.MediaFiles) .FirstOrDefaultAsync(f => f.Id == id && f.Status == ProcessingStatus.Ready); - if (file is null) + if (file is null || file.IsAudio) return Results.NotFound(); if (variant == "large" && !(file.HasLarge && (await profile.GetAsync()).LargePhotos)) return Results.NotFound(); @@ -68,6 +71,33 @@ private static async Task ServePublicDerivativeAsync( entityTag: new EntityTagHeaderValue($"\"{file.StorageId:N}-{variant}-{file.DerivativeVersion}-{file.RenderedRotation}\"")); } + /// + /// The copy of a published recording without its tags, in parts if the player asks, so that it can jump about. The original is + /// never served here. + /// + private static async Task ServePublicAudioAsync(int id, CommonageDbContext db, IFileStorage storage, HttpContext context) + { + var file = await db.PublishedItems + .SelectMany(i => i.MediaFiles) + .FirstOrDefaultAsync(f => f.Id == id && f.Status == ProcessingStatus.Ready && f.ContentType.StartsWith("audio/")); + if (file is null || !storage.Exists(file.AudioKey)) + return Results.NotFound(); + + context.Response.Headers.CacheControl = "public, max-age=600"; + return Results.Stream(storage.OpenRead(file.AudioKey), file.ContentType, lastModified: file.UploadedAt, + entityTag: new EntityTagHeaderValue($"\"{file.StorageId:N}-audio\""), enableRangeProcessing: true); + } + + private static async Task ServeAudioAsync(int id, CommonageDbContext db, IFileStorage storage, HttpContext context) + { + var file = await FindForStaffAsync(db, id, context.User); + if (file is null || !file.IsAudio || !storage.Exists(file.AudioKey)) + return Results.NotFound(); + + context.Response.Headers.CacheControl = "private, no-store"; + return Results.Stream(storage.OpenRead(file.AudioKey), file.ContentType, enableRangeProcessing: true); + } + /// One page of a published PDF, drawn as a picture. The PDF itself is never served to visitors. private static async Task ServePublicPageAsync(int id, int page, CommonageDbContext db, IFileStorage storage, HttpContext context) { @@ -111,7 +141,7 @@ private static async Task ServeDerivativeAsync( { // Curators also see what is in the bin, to decide whether to restore it. var file = await FindForStaffAsync(db, id, context.User); - if (file is null) + if (file is null || file.IsAudio) return Results.NotFound(); context.Response.Headers.CacheControl = "private, no-store"; diff --git a/src/Commonage.Web/Media/MediaProcessing.cs b/src/Commonage.Web/Media/MediaProcessing.cs index 28086cf..3fb2b0b 100644 --- a/src/Commonage.Web/Media/MediaProcessing.cs +++ b/src/Commonage.Web/Media/MediaProcessing.cs @@ -325,7 +325,13 @@ private async Task ProcessAsync(int mediaFileId, CancellationToken cancellationT try { - if (file.IsPdf) + if (file.IsAudio) + { + await MakeAudioCopyAsync(file, cancellationToken); + // Nothing to draw, and nothing for the later passes over older files to do. + file.DerivativeVersion = MediaFile.CurrentDerivativeVersion; + } + else if (file.IsPdf) { // The size of what poppler draws is set by us, whatever size the pages claim to have. await RenderPagesAsync(file, cancellationToken); @@ -339,7 +345,8 @@ private async Task ProcessAsync(int mediaFileId, CancellationToken cancellationT throw new VipsException($"The image has {header.Width} × {header.Height} pixels, more than the limit of {options.Value.MaxPreviewMegapixels} megapixels."); } - await RenderAllAsync(file, await LargeIsWantedAsync(db, cancellationToken), cancellationToken); + if (!file.IsAudio) + await RenderAllAsync(file, await LargeIsWantedAsync(db, cancellationToken), cancellationToken); file.Status = ProcessingStatus.Ready; file.ProcessingError = null; } @@ -378,6 +385,32 @@ private async Task ProcessAsync(int mediaFileId, CancellationToken cancellationT } } + /// + /// Writes the copy of a recording that visitors hear, without its tags. It goes through a temporary file, because a recording + /// can be hundreds of megabytes and the copy is only stored once it is whole. + /// + private async Task MakeAudioCopyAsync(MediaFile file, CancellationToken cancellationToken) + { + var temporary = Path.GetTempFileName(); + try + { + await using (var original = storage.OpenRead(file.OriginalKey)) + await using (var target = new FileStream(temporary, FileMode.Create, FileAccess.Write, FileShare.None)) + { + // The stripper jumps about, so the stream has to allow that. Files in the local storage do. + if (!original.CanSeek) + throw new InvalidOperationException("The storage does not allow reading a recording in parts."); + AudioTools.Strip(file.ContentType, original, target); + } + await using var done = File.OpenRead(temporary); + await storage.SaveAsync(file.AudioKey, done, cancellationToken); + } + finally + { + File.Delete(temporary); + } + } + /// Shrinks the image to fit a square of the given size, applying the EXIF rotation and then the given one, and drops all metadata. private static byte[] Resize(Stream source, int size, int rotation, out int width, out int height) { diff --git a/src/Commonage.Web/Media/MediaUploadService.cs b/src/Commonage.Web/Media/MediaUploadService.cs index 5dbba33..f3fa7b0 100644 --- a/src/Commonage.Web/Media/MediaUploadService.cs +++ b/src/Commonage.Web/Media/MediaUploadService.cs @@ -167,6 +167,8 @@ public async Task DeleteAsync(MediaFile file, CancellationToken cancellationToke return (UploadError.None, contentType); if (documents && ImageFormats.IsPdf(header.AsSpan(0, headerLength))) return pdf.IsAvailable ? (UploadError.None, MediaFile.PdfContentType) : (UploadError.PdfUnavailable, null); + if (documents && AudioTools.DetectContentType(header.AsSpan(0, headerLength)) is { } audio) + return (UploadError.None, audio); return (ImageFormats.IsHeic(header.AsSpan(0, headerLength)) ? UploadError.Heic : UploadError.UnsupportedFormat, null); } diff --git a/src/Commonage.Web/Pages/Admin/Bin.cshtml.cs b/src/Commonage.Web/Pages/Admin/Bin.cshtml.cs index 2e8e580..70aa783 100644 --- a/src/Commonage.Web/Pages/Admin/Bin.cshtml.cs +++ b/src/Commonage.Web/Pages/Admin/Bin.cshtml.cs @@ -27,7 +27,7 @@ public async Task OnGetAsync(CancellationToken cancellationToken) Items = await db.BinnedItems .AsNoTracking() .Include(i => i.Collection) - .Include(i => i.MediaFiles.Where(f => f.Status == ProcessingStatus.Ready && f.DeletedAt == null).OrderBy(f => f.Position).ThenBy(f => f.Id).Take(1)) + .Include(i => i.MediaFiles.Where(f => f.Status == ProcessingStatus.Ready && f.DeletedAt == null && !f.ContentType.StartsWith("audio/")).OrderBy(f => f.Position).ThenBy(f => f.Id).Take(1)) .OrderByDescending(i => i.DeletedAt) .Take(MaxShown) .ToListAsync(cancellationToken); diff --git a/src/Commonage.Web/Pages/Admin/Collections/Edit.cshtml.cs b/src/Commonage.Web/Pages/Admin/Collections/Edit.cshtml.cs index bda4eed..8f714f4 100644 --- a/src/Commonage.Web/Pages/Admin/Collections/Edit.cshtml.cs +++ b/src/Commonage.Web/Pages/Admin/Collections/Edit.cshtml.cs @@ -83,7 +83,7 @@ public async Task OnPostAsync(int? id, CancellationToken cancella // Only a photo of one of the collection's own items. A new collection has none yet. if (Input.CoverMediaFileId is { } cover && cover != collection?.CoverMediaFileId - && (id is null || !await db.MediaFiles.AnyAsync(f => f.Id == cover && f.ArchiveItem.CollectionId == id, cancellationToken))) + && (id is null || !await db.MediaFiles.AnyAsync(f => f.Id == cover && f.ArchiveItem.CollectionId == id && !f.ContentType.StartsWith("audio/"), cancellationToken))) ModelState.AddModelError("Input.CoverMediaFileId", localizer["Please choose one of the photos shown."]); if (!ModelState.IsValid) @@ -165,7 +165,7 @@ await db.ArchiveItems.IgnoreQueryFilters().CountAsync(i => i.CollectionId == id // The chosen one first, so it is always offered, then published items' photos, newest item first, each item's in order. var current = collection.CoverMediaFileId; CoverChoices = await db.MediaFiles - .Where(f => f.ArchiveItem.CollectionId == id && f.Status == ProcessingStatus.Ready) + .Where(f => f.ArchiveItem.CollectionId == id && f.Status == ProcessingStatus.Ready && !f.ContentType.StartsWith("audio/")) .OrderByDescending(f => f.Id == current) .ThenByDescending(f => f.ArchiveItem.Status == ItemStatus.Published) .ThenByDescending(f => f.ArchiveItemId).ThenBy(f => f.Position).ThenBy(f => f.Id) diff --git a/src/Commonage.Web/Pages/Admin/Index.cshtml.cs b/src/Commonage.Web/Pages/Admin/Index.cshtml.cs index 0e63ef1..8d50d98 100644 --- a/src/Commonage.Web/Pages/Admin/Index.cshtml.cs +++ b/src/Commonage.Web/Pages/Admin/Index.cshtml.cs @@ -112,7 +112,7 @@ public async Task OnGetAsync(CancellationToken cancellationToken) i.Collection.Title, i.Status, i.UpdatedAt, - i.MediaFiles.Where(f => f.Status == ProcessingStatus.Ready).OrderBy(f => f.Id).Select(f => (int?)f.Id).FirstOrDefault(), + i.MediaFiles.Where(f => f.Status == ProcessingStatus.Ready && !f.ContentType.StartsWith("audio/")).OrderBy(f => f.Id).Select(f => (int?)f.Id).FirstOrDefault(), i.MediaFiles.Count, i.Title == "" ? i.MediaFiles.OrderBy(f => f.Id).Select(f => f.OriginalFileName).FirstOrDefault() : null, // Worth a look before a decision on a contribution. Contributors are never told. diff --git a/src/Commonage.Web/Pages/Admin/Items/Edit.cshtml.cs b/src/Commonage.Web/Pages/Admin/Items/Edit.cshtml.cs index bb58aa0..9caf00c 100644 --- a/src/Commonage.Web/Pages/Admin/Items/Edit.cshtml.cs +++ b/src/Commonage.Web/Pages/Admin/Items/Edit.cshtml.cs @@ -551,7 +551,7 @@ public async Task OnPostTurnPhotoAsync(int id, int mediaFileId, C var file = await db.MediaFiles.Include(f => f.ArchiveItem).FirstOrDefaultAsync(f => f.Id == mediaFileId && f.ArchiveItemId == id, cancellationToken); if (file is null || IsOutOfReach(file.ArchiveItem)) return NotFound(); - if (file.Status != ProcessingStatus.Ready) + if (file.Status != ProcessingStatus.Ready || file.IsAudio) return BadRequest(); file.Rotation = (file.Rotation + 90) % 360; diff --git a/src/Commonage.Web/Pages/Admin/Items/_PhotoCard.cshtml b/src/Commonage.Web/Pages/Admin/Items/_PhotoCard.cshtml index 2d9e100..d32554b 100644 --- a/src/Commonage.Web/Pages/Admin/Items/_PhotoCard.cshtml +++ b/src/Commonage.Web/Pages/Admin/Items/_PhotoCard.cshtml @@ -9,7 +9,19 @@
- @if (file is { Status: ProcessingStatus.Ready, IsBeingTurned: true }) + @if (file is { Status: ProcessingStatus.Ready, IsAudio: true }) + { + + } + else if (file is { Status: ProcessingStatus.Pending, IsAudio: true }) + { + @* uploads.js puts the player here when the copy is there. *@ +
+ @T["Preparing the recording…"] +
+ } + else if (file is { Status: ProcessingStatus.Ready, IsBeingTurned: true }) { @* uploads.js replaces this with the picture when it is there. *@
- @T["Photo {0} of {1}", Model.Number, Model.Total] + @(file.IsAudio ? T["Recording {0} of {1}", Model.Number, Model.Total] : T["Photo {0} of {1}", Model.Number, Model.Total])
@file.OriginalFileName
@@ -50,9 +62,12 @@ + @if (!file.IsAudio) + { + }
@@ -60,10 +75,13 @@
@* Hidden until there is a preview to turn. uploads.js shows it when one arrives. *@ + @if (!file.IsAudio) + { + }
@if (Commonage.Web.Identity.Roles.MayManage(User)) { diff --git a/src/Commonage.Web/Pages/Admin/Items/_UploadTexts.cshtml b/src/Commonage.Web/Pages/Admin/Items/_UploadTexts.cshtml index a213a16..7b0276e 100644 --- a/src/Commonage.Web/Pages/Admin/Items/_UploadTexts.cshtml +++ b/src/Commonage.Web/Pages/Admin/Items/_UploadTexts.cshtml @@ -16,4 +16,5 @@ data-too-large="@T["{0} is too large."]" data-queue-label="@T["Photos on their way"]" data-photo-number="@T["Photo {0} of {1}"]" + data-recording-number="@T["Recording {0} of {1}"]" data-turning="@T["Turning the photo…"]">
diff --git a/src/Commonage.Web/Pages/Items/Details.cshtml.cs b/src/Commonage.Web/Pages/Items/Details.cshtml.cs index 91254a4..1763039 100644 --- a/src/Commonage.Web/Pages/Items/Details.cshtml.cs +++ b/src/Commonage.Web/Pages/Items/Details.cshtml.cs @@ -41,7 +41,7 @@ public async Task OnGetAsync(int id, CancellationToken cancellati Citation = string.Join(". ", new[] { item.Credit, item.Title, item.DateText, identity.Name }.Where(part => !string.IsNullOrWhiteSpace(part))) + $". {Address} ({localizer["accessed {0}", Dates.Day(DateTime.UtcNow)]})"; // A title is what the link itself says already. The rest depends on what the contributor agreed to. - var photo = item.MayTravel ? item.MediaFiles.FirstOrDefault() : null; + var photo = item.MayTravel ? item.MediaFiles.FirstOrDefault(f => !f.IsAudio) : null; Preview = new LinkPreview( item.Title, item.MayTravel ? LinkPreview.Shorten(item.Description) : null, diff --git a/src/Commonage.Web/Pages/Shared/_ItemArticle.cshtml b/src/Commonage.Web/Pages/Shared/_ItemArticle.cshtml index 20256b7..8e75ab0 100644 --- a/src/Commonage.Web/Pages/Shared/_ItemArticle.cshtml +++ b/src/Commonage.Web/Pages/Shared/_ItemArticle.cshtml @@ -5,7 +5,10 @@ @{ var mediaAddress = ViewData["MediaAddress"] as string ?? "/media"; var title = ArchiveItem.ShownTitle(T, Model.Title); - var count = Model.MediaFiles.Count; + // Recordings are heard, not looked at: they have no pictures to count, number or put in the strip. + var pictures = Model.MediaFiles.Where(f => !f.IsAudio).ToList(); + var recordings = Model.MediaFiles.Where(f => f.IsAudio).ToList(); + var count = pictures.Count; var number = 0; var identity = await Profile.GetAsync(); var largePhotos = identity.LargePhotos; @@ -38,7 +41,7 @@ } - @foreach (var file in Model.MediaFiles) + @foreach (var file in recordings) + { +
+ + @if (file.Caption is not null) + { +
@file.Caption
+ } +
+ } + @foreach (var file in pictures) { number++; var alt = file.AltText ?? (count > 1 ? T["{0}, photo {1} of {2}", title, number, count].Value : title); diff --git a/src/Commonage.Web/Resources/SharedResource.de.resx b/src/Commonage.Web/Resources/SharedResource.de.resx index 6885229..5943702 100644 --- a/src/Commonage.Web/Resources/SharedResource.de.resx +++ b/src/Commonage.Web/Resources/SharedResource.de.resx @@ -992,4 +992,7 @@ Letzte Anmeldung Namen speichern Wird Admins auf dieser Seite und in der Liste der Konten gezeigt, nie Besucherinnen und Besuchern. + Aufnahme: {0} + Aufnahme wird vorbereitet… + Aufnahme {0} von {1} diff --git a/src/Commonage.Web/Resources/SharedResource.resx b/src/Commonage.Web/Resources/SharedResource.resx index 4da5519..117daab 100644 --- a/src/Commonage.Web/Resources/SharedResource.resx +++ b/src/Commonage.Web/Resources/SharedResource.resx @@ -549,6 +549,7 @@ Please write your message. Poster to print Poster: {0} + Preparing the recording… Preview Preview. This item is public. Preview. Visitors cannot see this item. @@ -574,6 +575,8 @@ Received from Received when Recently added + Recording of {0} + Recording {0} of {1} Reference Reference for them: {0} Reference number diff --git a/src/Commonage.Web/Search/AdminItemList.cs b/src/Commonage.Web/Search/AdminItemList.cs index ab034eb..72c366f 100644 --- a/src/Commonage.Web/Search/AdminItemList.cs +++ b/src/Commonage.Web/Search/AdminItemList.cs @@ -72,7 +72,7 @@ public static async Task> QueryAsync(this CommonageDbCon ItemNeed.Tags => items.Where(i => i.TagNames == null), ItemNeed.Photos => items.Where(i => !i.MediaFiles.Any()), ItemNeed.PreviewFailed => items.Where(i => i.MediaFiles.Any(f => f.Status == ProcessingStatus.Failed)), - ItemNeed.AltText => items.Where(i => i.MediaFiles.Any(f => f.AltText == null)), + ItemNeed.AltText => items.Where(i => i.MediaFiles.Any(f => f.AltText == null && !f.ContentType.StartsWith("audio/"))), ItemNeed.Title => items.Where(i => i.Title == ""), ItemNeed.Transcription => items.Where(i => i.NeedsTranscription), ItemNeed.HelpWanted => items.Where(i => i.HelpWanted), diff --git a/src/Commonage.Web/Search/ItemSummary.cs b/src/Commonage.Web/Search/ItemSummary.cs index 68c7408..7ee9435 100644 --- a/src/Commonage.Web/Search/ItemSummary.cs +++ b/src/Commonage.Web/Search/ItemSummary.cs @@ -12,7 +12,7 @@ public record ItemSummary(int Id, string Title, string? DateText, int? Thumbnail i.Id, i.Title, i.DateText, - i.MediaFiles.Where(f => f.Status == ProcessingStatus.Ready).OrderBy(f => f.Position).ThenBy(f => f.Id).Select(f => (int?)f.Id).FirstOrDefault(), + i.MediaFiles.Where(f => f.Status == ProcessingStatus.Ready && !f.ContentType.StartsWith("audio/")).OrderBy(f => f.Position).ThenBy(f => f.Id).Select(f => (int?)f.Id).FirstOrDefault(), i.Collection.Title); } @@ -41,12 +41,12 @@ public static IQueryable ToCards(this IQueryable col c.Items.Count(i => i.Status == ItemStatus.Published), c.Items.Where(i => i.Status == ItemStatus.Published) .SelectMany(i => i.MediaFiles) - .Where(f => f.Status == ProcessingStatus.Ready && f.Id == c.CoverMediaFileId) + .Where(f => f.Status == ProcessingStatus.Ready && f.Id == c.CoverMediaFileId && !f.ContentType.StartsWith("audio/")) .Select(f => (int?)f.Id) .FirstOrDefault() ?? c.Items.Where(i => i.Status == ItemStatus.Published) .SelectMany(i => i.MediaFiles) - .Where(f => f.Status == ProcessingStatus.Ready) + .Where(f => f.Status == ProcessingStatus.Ready && !f.ContentType.StartsWith("audio/")) .OrderBy(f => f.ArchiveItemId).ThenBy(f => f.Position).ThenBy(f => f.Id) .Select(f => (int?)f.Id) .FirstOrDefault(), diff --git a/src/Commonage.Web/Search/PublicFeeds.cs b/src/Commonage.Web/Search/PublicFeeds.cs index 897c5c5..8832251 100644 --- a/src/Commonage.Web/Search/PublicFeeds.cs +++ b/src/Commonage.Web/Search/PublicFeeds.cs @@ -66,7 +66,7 @@ private static async Task ServeFeedAsync( // What people agreed to before this existed was "this website". A feed is copied to other places, so those stay out of it. var items = await db.PublishedItems .Where(i => i.Contribution == null || i.Contribution.ConsentCoversSharing) - .Include(i => i.MediaFiles.Where(f => f.Status == ProcessingStatus.Ready).OrderBy(f => f.Position).ThenBy(f => f.Id).Take(1)) + .Include(i => i.MediaFiles.Where(f => f.Status == ProcessingStatus.Ready && !f.ContentType.StartsWith("audio/")).OrderBy(f => f.Position).ThenBy(f => f.Id).Take(1)) .OrderByDescending(i => i.PublishedAt).ThenByDescending(i => i.Id) .Take(FeedLength) .AsNoTracking() @@ -102,7 +102,7 @@ private static XElement Entry(ArchiveItem item, string address, ArchiveIdentity new XElement(Atom + "rights", XmlText(rights))); var content = new StringBuilder(); - if (item.MediaFiles.FirstOrDefault() is { } photo) + if (item.MediaFiles.FirstOrDefault(f => !f.IsAudio) is { } photo) { var alt = photo.AltText ?? item.Title; content.Append(CultureInfo.InvariantCulture, $"""

{WebUtility.HtmlEncode(alt)}

"""); diff --git a/src/Commonage.Web/wwwroot/css/site.css b/src/Commonage.Web/wwwroot/css/site.css index 7a4d2e6..96da1b4 100644 --- a/src/Commonage.Web/wwwroot/css/site.css +++ b/src/Commonage.Web/wwwroot/css/site.css @@ -267,6 +267,11 @@ main:focus { padding: .5rem .25rem .25rem; } +.item-recording audio { + display: block; + inline-size: 100%; +} + /* The pages of a PDF, one under the other, each as wide as the column. */ .pdf-page img { display: block; diff --git a/src/Commonage.Web/wwwroot/js/uploads.js b/src/Commonage.Web/wwwroot/js/uploads.js index 9bd66d5..c6d593c 100644 --- a/src/Commonage.Web/wwwroot/js/uploads.js +++ b/src/Commonage.Web/wwwroot/js/uploads.js @@ -310,7 +310,21 @@ const answer = await response.json(); for (const placeholder of asked) { const id = Number(placeholder.dataset.previewPending); - if (answer.ready.includes(id)) { + if (answer.ready.includes(id) && answer.audio?.includes(id)) { + // A recording has no picture: the card gets its player, and a row in the upload list just loses its placeholder. + if (placeholder.closest('[data-photo-card]')) { + const player = document.createElement('audio'); + player.controls = true; + player.preload = 'none'; + player.src = `/admin/media/${id}/audio`; + player.className = placeholder.dataset.previewClass; + player.setAttribute('aria-label', placeholder.dataset.previewAlt ?? ''); + placeholder.replaceWith(player); + numberPhotos(); + } else { + placeholder.remove(); + } + } else if (answer.ready.includes(id)) { const picture = new Image(); // A new address, because a photo that was turned has the same one as before. picture.src = `/admin/media/${id}/thumbnail?shown=${Date.now()}`; @@ -344,7 +358,7 @@ function numberPhotos() { const cards = [...document.querySelectorAll('[data-photo-card]')]; cards.forEach((card, index) => { - card.querySelector('[data-photo-number]').textContent = say(texts.photoNumber, index + 1, cards.length); + card.querySelector('[data-photo-number]').textContent = say(card.querySelector('audio') ? texts.recordingNumber : texts.photoNumber, index + 1, cards.length); card.querySelector('[data-photo-cover]').hidden = index !== 0; card.querySelector('button[value=earlier]').disabled = index === 0; card.querySelector('button[value=later]').disabled = index === cards.length - 1; diff --git a/tests/Commonage.BrowserTests/ReadableItemBrowserTests.cs b/tests/Commonage.BrowserTests/ReadableItemBrowserTests.cs index 431240f..8089f3a 100644 --- a/tests/Commonage.BrowserTests/ReadableItemBrowserTests.cs +++ b/tests/Commonage.BrowserTests/ReadableItemBrowserTests.cs @@ -48,6 +48,26 @@ private async Task ItemWithPhotosAsync(string title, params string[] name return page; } + [Fact] + public async Task A_recording_gets_a_player_where_a_photo_gets_its_picture() + { + var page = await app.LogInAsync(); + await page.GotoAsync("/Admin/Items/Edit"); + await page.FillAsync("[name='Input.Title']", "An interview"); + await page.SelectOptionAsync("[name='Input.CollectionId']", new SelectOptionValue { Index = 1 }); + await page.ClickAsync("#item-form button[type=submit]:text-is('Save as draft')"); + await page.WaitForSelectorAsync(".alert-success"); + + byte[] recording = [.. "ID3"u8, 4, 0, 0, 0, 0, 0, 0, 0xFF, 0xFB, 0x90, 0, .. Guid.NewGuid().ToByteArray(), .. new byte[400]]; + await page.SetInputFilesAsync("#photo-upload", new FilePayload { Name = "interview.mp3", MimeType = "audio/mpeg", Buffer = recording }); + await page.ClickAsync("form[data-upload-queue] button[type=submit]"); + + await page.WaitForSelectorAsync("[data-photo-card] audio[src^='/admin/media/']", new PageWaitForSelectorOptions { Timeout = 30000 }); + Assert.Equal(0, await page.Locator("[data-photo-card] img").CountAsync()); + Assert.Equal(0, await page.Locator("[data-photo-turn]").CountAsync()); + Assert.Contains("Recording 1 of 1", await page.InnerTextAsync("[data-photo-card]")); + } + private static Task OrderAsync(IPage page) => page.EvaluateAsync("[...document.querySelectorAll('[data-photo-card] .text-truncate')].map(name => name.textContent.trim())"); diff --git a/tests/Commonage.Tests/AudioTests.cs b/tests/Commonage.Tests/AudioTests.cs new file mode 100644 index 0000000..9c99edd --- /dev/null +++ b/tests/Commonage.Tests/AudioTests.cs @@ -0,0 +1,256 @@ +using System.Buffers.Binary; +using System.Net; +using System.Net.Http.Headers; +using System.Text; +using Commonage.Web.Domain; +using Commonage.Web.Media; +using Microsoft.EntityFrameworkCore; + +namespace Commonage.Tests; + +/// The copy of a recording that visitors hear has none of the tags, and the sound is the original's, byte for byte. +public class AudioToolsTests +{ + private static readonly byte[] Secret = "SECRET-NAME-OF-THE-INTERVIEWEE"u8.ToArray(); + private static readonly byte[] Sound = Enumerable.Range(0, 300).Select(i => (byte)(i * 7 + 3)).ToArray(); + + private static byte[] Stripped(string contentType, byte[] original) + { + using var input = new MemoryStream(original); + using var output = new MemoryStream(); + AudioTools.Strip(contentType, input, output); + return output.ToArray(); + } + + private static int IndexOf(byte[] haystack, byte[] needle) => haystack.AsSpan().IndexOf(needle); + + private static byte[] Box(string type, params byte[][] content) + { + var body = content.SelectMany(c => c).ToArray(); + var box = new byte[8 + body.Length]; + BinaryPrimitives.WriteUInt32BigEndian(box, (uint)box.Length); + Encoding.ASCII.GetBytes(type).CopyTo(box, 4); + body.CopyTo(box, 8); + return box; + } + + private static byte[] Mp3(bool tags) + { + var frame = new byte[] { 0xFF, 0xFB, 0x90, 0x00 }.Concat(Sound).ToArray(); + if (!tags) + return frame; + var tag = Secret.Concat(new byte[50]).ToArray(); + var header = new byte[] { (byte)'I', (byte)'D', (byte)'3', 4, 0, 0, 0, 0, (byte)(tag.Length >> 7), (byte)(tag.Length & 0x7F) }; + var v1 = new byte[128]; + "TAG"u8.CopyTo(v1); + Secret.CopyTo(v1, 3); + return header.Concat(tag).Concat(frame).Concat(v1).ToArray(); + } + + [Fact] + public void An_MP3_loses_its_tags_at_both_ends_and_keeps_the_sound() + { + var original = Mp3(tags: true); + Assert.Equal("audio/mpeg", AudioTools.DetectContentType(original)); + + var copy = Stripped(AudioTools.Mp3, original); + + Assert.Equal(-1, IndexOf(copy, Secret)); + Assert.Equal(Mp3(tags: false), copy); + } + + [Theory] + [InlineData("LYRICSBEGIN")] + [InlineData("TAG+")] + [InlineData("3DI\u0004\u0000")] + public void An_MP3_with_a_tag_kind_that_cannot_be_removed_is_refused(string marker) + { + var withTag = Mp3(tags: false).Concat(Encoding.ASCII.GetBytes(marker)).Concat(Secret).ToArray(); + Assert.Throws(() => Stripped(AudioTools.Mp3, withTag)); + } + + [Fact] + public void An_M4A_loses_user_data_and_dates_but_every_part_keeps_its_place() + { + var mvhd = Box("mvhd", [0, 0, 0, 0], [0xAA, 0xAA, 0xAA, 0xAA], [0xBB, 0xBB, 0xBB, 0xBB], new byte[80]); + var udta = Box("udta", Box("meta", [0, 0, 0, 0], Secret)); + var ftyp = Box("ftyp", "M4A "u8.ToArray(), new byte[4], "M4A "u8.ToArray()); + var moov = Box("moov", mvhd, Box("trak", Box("udta", Secret)), udta); + var xmp = Box("uuid", new byte[16], Secret); + var mdat = Box("mdat", Sound); + var original = ftyp.Concat(moov).Concat(xmp).Concat(mdat).ToArray(); + Assert.Equal("audio/mp4", AudioTools.DetectContentType(original)); + + var copy = Stripped(AudioTools.Mp4, original); + + Assert.Equal(original.Length, copy.Length); + Assert.Equal(-1, IndexOf(copy, Secret)); + Assert.Equal(-1, IndexOf(copy, [0xAA, 0xAA, 0xAA, 0xAA])); + // The sound is where the file's own tables say it is. + Assert.Equal(IndexOf(original, Sound), IndexOf(copy, Sound)); + } + + [Fact] + public void A_WAV_keeps_only_what_a_player_needs() + { + static byte[] Chunk(string id, byte[] data) + { + var chunk = new byte[8 + data.Length + (data.Length & 1)]; + Encoding.ASCII.GetBytes(id).CopyTo(chunk, 0); + BinaryPrimitives.WriteUInt32LittleEndian(chunk.AsSpan(4), (uint)data.Length); + data.CopyTo(chunk, 8); + return chunk; + } + var body = "WAVE"u8.ToArray().Concat(Chunk("fmt ", new byte[16])).Concat(Chunk("LIST", Secret)).Concat(Chunk("bext", Secret)) + .Concat(Chunk("data", Sound[..201])).ToArray(); + var original = "RIFF"u8.ToArray().Concat(BitConverter.GetBytes(body.Length)).Concat(body).ToArray(); + Assert.Equal("audio/wav", AudioTools.DetectContentType(original)); + + var copy = Stripped(AudioTools.Wav, original); + + Assert.Equal(-1, IndexOf(copy, Secret)); + Assert.Equal(-1, IndexOf(copy, "LIST"u8.ToArray())); + Assert.NotEqual(-1, IndexOf(copy, Sound[..201])); + Assert.Equal(copy.Length - 8, BitConverter.ToInt32(copy, 4)); + } + + [Fact] + public void A_FLAC_loses_comments_and_pictures_and_still_ends_its_description() + { + static byte[] Block(int type, bool last, byte[] data) => + new byte[] { (byte)(type | (last ? 0x80 : 0)), (byte)(data.Length >> 16), (byte)(data.Length >> 8), (byte)data.Length }.Concat(data).ToArray(); + var original = "fLaC"u8.ToArray().Concat(Block(0, false, new byte[34])).Concat(Block(4, false, Secret)).Concat(Block(6, true, Secret)).Concat(Sound).ToArray(); + Assert.Equal("audio/flac", AudioTools.DetectContentType(original)); + + var copy = Stripped(AudioTools.Flac, original); + + Assert.Equal(-1, IndexOf(copy, Secret)); + Assert.Equal(0x80, copy[4]); + Assert.Equal(4 + 4 + 34 + Sound.Length, copy.Length); + } + + [Theory] + [InlineData("audio/mpeg")] + [InlineData("audio/mp4")] + [InlineData("audio/wav")] + [InlineData("audio/flac")] + public void A_file_that_is_not_built_as_its_type_says_is_refused_not_passed_on(string contentType) + { + var junk = Secret.Concat(new byte[40]).ToArray(); + Assert.Throws(() => Stripped(contentType, junk)); + // Cut short in the middle of its parts. + var short_ = contentType == AudioTools.Flac ? "fLaC"u8.ToArray().Concat(new byte[] { 0, 0, 1, 0 }).ToArray() + : contentType == AudioTools.Wav ? "RIFF\0\0\0\0WAVEfmt \xFF\0\0\0"u8.ToArray() + : contentType == AudioTools.Mp4 ? new byte[] { 0, 0, 1, 0, (byte)'f', (byte)'t', (byte)'y', (byte)'p' } + : "ID3\x04\0\0\0\0\x7F\x7F"u8.ToArray(); + Assert.Throws(() => Stripped(contentType, short_)); + } + + [Fact] + public void A_picture_is_not_taken_for_a_recording() + { + Assert.Null(AudioTools.DetectContentType([0xFF, 0xD8, 0xFF, 0xE0, 0, 0, 0, 0, 0, 0, 0, 0])); + } +} + +[Collection(nameof(AppCollection))] +public class AudioTests(CommonageAppFactory app) +{ + private async Task<(int ItemId, MediaFile File)> UploadAsync(HttpClient curator, string name, byte[] bytes) + { + var item = await app.CreateContributionAsync(ItemStatus.Draft); + await Browser.UploadAsync(curator, $"/Admin/Items/Edit/{item.Id}", "Upload", name, bytes); + var deadline = DateTime.UtcNow.AddSeconds(60); + while (true) + { + var file = await app.WithDbAsync(db => db.MediaFiles.AsNoTracking().SingleAsync(f => f.ArchiveItemId == item.Id)); + if (file.Status != ProcessingStatus.Pending || DateTime.UtcNow > deadline) + return (item.Id, file); + await Task.Delay(100); + } + } + + private static byte[] RecordingWithTags() + { + var tag = "SECRET-NAME-OF-THE-INTERVIEWEE"u8.ToArray(); + var header = new byte[] { (byte)'I', (byte)'D', (byte)'3', 4, 0, 0, 0, 0, 0, (byte)tag.Length }; + var sound = new byte[] { 0xFF, 0xFB, 0x90, 0x00 }.Concat(Enumerable.Range(0, 2000).Select(i => (byte)(i % 251))).ToArray(); + return header.Concat(tag).Concat(sound).ToArray(); + } + + [Fact] + public async Task Visitors_hear_a_published_recording_without_its_tags_and_never_the_original() + { + using var curator = app.CreateClient(); + await Browser.LogInAsCuratorAsync(curator); + var original = RecordingWithTags(); + + var (itemId, file) = await UploadAsync(curator, "interview.mp3", original); + + Assert.Equal(ProcessingStatus.Ready, file.Status); + Assert.Equal("audio/mpeg", file.ContentType); + Assert.Equal(original, await curator.GetByteArrayAsync($"/admin/media/{file.Id}/original")); + + using var visitor = app.CreateClient(new Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactoryClientOptions { AllowAutoRedirect = false }); + Assert.Equal(HttpStatusCode.NotFound, (await visitor.GetAsync($"/media/{file.Id}/audio")).StatusCode); + // A curator can listen to a draft from the admin address. + Assert.Equal(HttpStatusCode.OK, (await curator.GetAsync($"/admin/media/{file.Id}/audio")).StatusCode); + + await app.WithDbAsync(async db => + { + var stored = await db.ArchiveItems.SingleAsync(i => i.Id == itemId); + stored.Publish(DateTime.UtcNow); + return await db.SaveChangesAsync(); + }); + + var heard = await visitor.GetAsync($"/media/{file.Id}/audio"); + Assert.Equal(HttpStatusCode.OK, heard.StatusCode); + Assert.Equal("audio/mpeg", heard.Content.Headers.ContentType?.MediaType); + var bytes = await heard.Content.ReadAsByteArrayAsync(); + Assert.Equal(-1, bytes.AsSpan().IndexOf("SECRET"u8)); + Assert.Equal(original.Length - 10 - 30, bytes.Length); + + // The player jumps about by asking for parts. + var request = new HttpRequestMessage(HttpMethod.Get, $"/media/{file.Id}/audio") { Headers = { Range = new RangeHeaderValue(100, 199) } }; + var part = await visitor.SendAsync(request); + Assert.Equal(HttpStatusCode.PartialContent, part.StatusCode); + Assert.Equal(bytes[100..200], await part.Content.ReadAsByteArrayAsync()); + + // No pictures exist for a recording, and the original stays with curators. + Assert.Equal(HttpStatusCode.NotFound, (await visitor.GetAsync($"/media/{file.Id}/preview")).StatusCode); + Assert.NotEqual(HttpStatusCode.OK, (await visitor.GetAsync($"/admin/media/{file.Id}/original")).StatusCode); + + var page = await visitor.GetStringAsync($"/items/{itemId}"); + Assert.Contains($"src=\"/media/{file.Id}/audio\"", page); + Assert.DoesNotContain($"/media/{file.Id}/thumbnail", page); + + // Back to a draft: the recording is gone again for visitors. + await app.WithDbAsync(async db => + { + var stored = await db.ArchiveItems.SingleAsync(i => i.Id == itemId); + stored.Status = ItemStatus.Draft; + return await db.SaveChangesAsync(); + }); + Assert.Equal(HttpStatusCode.NotFound, (await visitor.GetAsync($"/media/{file.Id}/audio")).StatusCode); + } + + [Fact] + public async Task A_recording_that_is_not_built_as_it_says_fails_without_a_copy_for_anyone() + { + using var curator = app.CreateClient(); + await Browser.LogInAsCuratorAsync(curator); + var broken = "ID3\x04\0\0\0\0\0\x05SECRET-not-followed-by-sound"u8.ToArray(); + + var (itemId, file) = await UploadAsync(curator, "broken.mp3", broken); + + Assert.Equal(ProcessingStatus.Failed, file.Status); + await app.WithDbAsync(async db => + { + var stored = await db.ArchiveItems.SingleAsync(i => i.Id == itemId); + stored.Publish(DateTime.UtcNow); + return await db.SaveChangesAsync(); + }); + using var visitor = app.CreateClient(new Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactoryClientOptions { AllowAutoRedirect = false }); + Assert.Equal(HttpStatusCode.NotFound, (await visitor.GetAsync($"/media/{file.Id}/audio")).StatusCode); + } +} diff --git a/tests/Commonage.Tests/ContributionTests.cs b/tests/Commonage.Tests/ContributionTests.cs index a78c5ab..a8b4bb5 100644 --- a/tests/Commonage.Tests/ContributionTests.cs +++ b/tests/Commonage.Tests/ContributionTests.cs @@ -107,6 +107,19 @@ public async Task A_PDF_is_not_taken_from_a_stranger() Assert.Equal(0, await CountContributionsAsync(token)); } + [Fact] + public async Task A_recording_is_not_taken_from_a_stranger() + { + var token = await CreateLinkAsync(); + using var visitor = app.CreateClient(); + var recording = new byte[] { (byte)'I', (byte)'D', (byte)'3', 4, 0, 0, 0, 0, 0, 0, 0xFF, 0xFB, 0x90, 0 }; + + var sent = await Browser.SendFormWithFilesAsync(visitor, $"/contribute/{token}", ValidFields("Interview"), ("interview.mp3", recording)); + + Assert.DoesNotContain("Thank you", await sent.Content.ReadAsStringAsync()); + Assert.Equal(0, await CountContributionsAsync(token)); + } + [Fact] public async Task Name_rights_and_consent_are_required() { diff --git a/tests/Commonage.Tests/EndpointAccessTests.cs b/tests/Commonage.Tests/EndpointAccessTests.cs index ddd8d9e..e8d6f57 100644 --- a/tests/Commonage.Tests/EndpointAccessTests.cs +++ b/tests/Commonage.Tests/EndpointAccessTests.cs @@ -19,6 +19,8 @@ public class EndpointAccessTests(CommonageAppFactory app) "/{slug:regex(^(about|contact|privacy|imprint)$)}", "/SetLanguage", "/Error/{code:int?}", // Published pictures only, see MediaTests. "/media/{id:int}/{variant:regex(^(preview|thumbnail|card|large)$)}", "/media/{id:int}/page/{page:int}", + // The tag-free copy of a recording, published items only, see AudioTests. + "/media/{id:int}/audio", "/branding.css", "/branding/{id:guid}/{variant}", "/robots.txt", "/feed.xml", "/sitemap.xml", "/health", "/date-check", // Open to whoever has the link. "/contribute/{token}", "/contribute/{token}/thanks", "/Account/SetPassword", diff --git a/tests/Commonage.Tests/ExportTests.cs b/tests/Commonage.Tests/ExportTests.cs index 76edab0..743f1f2 100644 --- a/tests/Commonage.Tests/ExportTests.cs +++ b/tests/Commonage.Tests/ExportTests.cs @@ -106,7 +106,7 @@ public async Task Without_personal_data_no_name_or_email_is_in_the_export() "Collection: by collectionId. MediaFiles: as files. DateText, DateFrom, DateTo: as date. TagNames: repeats tags. " + "CanBePublished: follows from status. IsUntitled: follows from the empty title. MayTravel: follows from the contribution. FileText: the text of the PDFs, found again from the files. DeletedAt: the bin is not exported. Version: only for open forms.")] [InlineData(typeof(MediaFile), "file", "id originalFileName contentType sizeBytes sha256 uploadedAt altText caption position rotation pageCount", - "ArchiveItemId, ArchiveItem: the file is listed under its item. StorageId, OriginalKey, PreviewKey, ThumbnailKey: storage details. DerivativeKeys, StoredKeys, PageKey, IsPdf, PdfContentType, MaxPdfPages: follow from the file or are fixed values. ExtractedText: the text of a PDF, found again from the file. " + "ArchiveItemId, ArchiveItem: the file is listed under its item. StorageId, OriginalKey, PreviewKey, ThumbnailKey: storage details. DerivativeKeys, StoredKeys, PageKey, AudioKey, IsAudio, IsPdf, PdfContentType, MaxPdfPages: follow from the file or are fixed values. ExtractedText: the text of a PDF, found again from the file. " + "Status, ProcessingError, ProcessingAttempts, MaxProcessingAttempts, PreviewWidth, PreviewHeight, CardKey, LargeKey, HasLarge, RenderedRotation, IsBeingTurned, DerivativeVersion, CurrentDerivativeVersion, MaxCaptionLength: previews are made anew. DeletedAt: the bin is not exported.")] [InlineData(typeof(ArchiveSettings), "settings", "defaultLanguage contentLanguage otherContentLanguages accentColor timeZone defaultRightsUri allowSearchEngines requireTwoFactor largePhotos privacyReviewed imprintNotNeeded restoreTestedAt activityLogKeptYears rejectedKeptMonths acceptVisitorNotes logo texts", "Id, TheOnlyId: there is only one. LogoId: as logo.")]