Compare commits

...

20 Commits

Author SHA1 Message Date
Paul Nothaft 292dd4fa09 chore(stable): release 3.46.5 (#1193)
Build and Push Docker Images / build-backend (linux/amd64, ubuntu-latest) (push) Waiting to run
Build and Push Docker Images / build-backend (linux/arm64, ubuntu-24.04-arm) (push) Waiting to run
Build and Push Docker Images / merge-backend (push) Blocked by required conditions
Build and Push Docker Images / build-frontend (linux/amd64, ubuntu-latest) (push) Waiting to run
Build and Push Docker Images / build-frontend (linux/arm64, ubuntu-24.04-arm) (push) Waiting to run
Build and Push Docker Images / merge-frontend (push) Blocked by required conditions
Build and Push Docker Images / summary (push) Blocked by required conditions
2026-08-26 21:44:17 +02:00
Paul Nothaft 5559cd333d fix(images): respect EXIF orientation in thumbnails, heroes, previews and watermarks (#1185) (#1202)
Stable twin of #1194.

generateThumbnail, generateHeroImage and generatePreviewImage went straight
from sharp(imagePath) to .resize(), so a photo whose Orientation tag is not 1 —
routine for portrait shots on bodies that tag rather than rotate the sensor
data — was resized from the raw frame and came out sideways. The same pipelines
then call .withMetadata(false), stripping the tag from the output, so nothing
downstream could correct it either. The download path already had this right,
which is why the same photo looked correct on download and rotated in the
gallery.

watermarkService had it too, and it is the one a guest actually sees:
gallery.js serves photos.watermark_path ahead of the original when branding
watermarking is on. Two details there — metadata() is read from a separate
unrotated handle, because .rotate() does not change what it reports and every
use of those numbers is positioning; and the composite offsets are floored,
because getPositionCoordinates returns fractional pixels, sharp rejects them,
and applyWatermark catches its own error and silently returns the image
unwatermarked.

The rotate is unconditional in the thumbnail and hero generators — neither
passes `animated: true`, so both already flatten a multi-frame source and
guarding there would protect an animation that was being discarded anyway.
generatePreviewImage keeps the guard, since it genuinely does preserve
animation.

photos.width/height were stored from sharp's metadata, which reports pixels as
STORED, not displayed. For orientation 5-8 those are swapped, so a portrait
photo landed in the database as landscape and masonry sized its tile with the
wrong aspect ratio on top of the image being unrotated. A shared
orientedDimensions() helper now does the conversion at all eight image ingest
sites. The video path is deliberately untouched: its dimensions come from
ffprobe, where EXIF orientation does not apply.

Existing rows keep their pre-rotation dimensions until reprocessed; the backfill
for those is #1199 on main and is not ported here yet.

Co-authored-by: Paul Nothaft <paul@MacStudio-von-Paul.local>
2026-08-26 21:13:08 +02:00
Paul Nothaft ac7ef266dc fix(admin): make "Storage used" report storage used (#1164) (#1177)
* fix(admin): make "Storage used" report storage used (#1164)

Stable twin of #1170.

The tile summed photos.size_bytes — the catalogued size of the ORIGINALS,
which in reference mode live on external storage and have no relationship to
the disk PicPeak runs on. The reporter's tile read ~80 GB against 21 GB of
real usage. Worse than the label: the same number drove the soft-limit warning
bar and, via /storage/info, the recommended soft limit — so a reference-mode
install got a disk-capacity recommendation computed from bytes that are not on
the disk.

- new localStorageUsage service walks the storage root and reports the total
  plus a breakdown. Walking rather than summing DB columns is the point:
  thumbnail/preview/hero rows record a key and never a byte count, and orphans
  from a deleted event or an interrupted import are real bytes.
- the external media root is excluded when it sits inside the storage root.
  Its compose default is <storage>/external-media, where the NAS is
  bind-mounted — a plain directory, not a symlink — so walking it would put
  every referenced original back into a figure whose purpose is to leave them
  out. Symlinks are not followed either.
- .download-cache gets its own line: it lives inside the event directory, so
  the naive rule files a multi-GB zip as photography.
- concurrent cold-cache callers share one walk; the dashboard, /storage/info
  and the sidebar are routinely requested together.
- S3 installs keep the catalogued figure and the walk is skipped before it
  runs, since the objects are in the bucket and STORAGE_PATH holds only
  incidental local files.
- an absent measurement reads as "unavailable" and a partial one is marked
  `+` across the dashboard, analytics, sidebar and status tab — a floor
  silently compared against a soft limit reads as "safely under".

Verified on this branch: 11 new service tests, dashboardScope updated for the
changed contract, full suite leaves the same 5 pre-existing failures as
origin/stable. Frontend 20 files / 104 tests, tsc clean.

* fix(admin): tell "no disk to measure" apart from "the measurement failed" (#1164)

External review found both of these on this branch.

Both were reported as `storage_measurement: 'catalog'`, so a failed local walk
made the dashboard claim the objects live in S3. They are different things —
one is a fact about the install, the other is a fault — and there is now an
`unavailable` state for the second.

The analytics percentage could reach the billions. `safeSoftLimit` fell back to
`storageUsed || 1`, and on S3 that is null → 1, while the figure beside it came
from `catalogedBytes`. An editor or viewer holds `analytics.view` but not
`settings.view`, so `/storage/info` 403s for them and `storageInfo` is
undefined — which is exactly when that fallback fires. It now falls back to the
measured figure, and suppresses the percentage entirely when there is no real
limit rather than dividing usage by itself and always reading 100%.

---------

Co-authored-by: Paul Nothaft <paul@MacStudio-von-Paul.local>
2026-08-26 09:14:48 +02:00
Paul Nothaft 9ffbe2f98f fix(previews): preserve alpha and animation in the preview tier (#1176)
* fix(gallery): stop the lightbox loading originals to display a photo (#1166)

Stable twin of #1169.

The lightbox read preview_url, which the server only emits once an admin has
flipped lightbox_preview_enabled — off by default. So a stock install fell
straight through to url, the untouched original: a reporter measured 16.5 MB
for a photo whose preview is 345 KB. The lightbox renders its neighbours too,
so opening one photo pulled three originals.

slideshow_url is the same /preview/:id URL, watermark query included, and has
been emitted unconditionally for images since #1015. Preferring it fixes every
existing install with no migration and no admin action.

Two other surfaces bypass PhotoLightbox entirely and had the same bug:

- premium galleries build their own slides with `src: photo.url`. Fixing that
  also required carrying the photo id on the slide, because the download
  handler recovered the photo by matching slide.src against photo.url — a
  derivative src would have made Download a silent no-op.
- the Story layout rendered the full original as its GRID TILE, at
  object-cover in a small card, and its hero rendered one as a full-bleed
  background when hero_url exists for exactly that. Cards now use the preview
  tier (not the thumbnail: thumbnail_fit is seeded to 'cover', so a thumbnail
  would be cropped a second time and reframe every photo) and only load once
  within 200px of the viewport, since every card mounts at page load.

GIF, APNG and PNG keep the original: generatePreviewImage encodes JPEG, which
has neither a second frame nor an alpha channel. The backend fix that removes
this list is the next commit in this stack.

Divergence from the main twin: no responsive `?w=` tiers. #1095 is main-only,
so `lightboxImageUrl` here selects a URL and nothing more. It lives in
`imageTiers.ts` under the same path main uses, so that backporting #1095 later
merges into this file rather than landing beside it.

Verified on this branch: 8 new tests; frontend suite 21 files / 113 tests,
tsc clean.

* fix(gallery): make the Story hero fix actually work on external galleries (#1166)

External review. Same two fixes as the main twin.

hero_url was inert for external media. ensureHeroImage only ever called
resolvePhotoStorageKey, which returns null for external/reference photos by
design — and that null was handed straight to withLocalCopy, which throws, so
the hero route caught it and redirected to the full ORIGINAL. #1078 fixed
exactly this shape for ensurePreviewImage and nobody carried it across. It
stayed invisible until this PR pointed the Story hero at hero_url: on a
managed gallery that is a real saving, on a reference-mode gallery it quietly
changed nothing.

Needed one extra piece here that main already had: generateHeroImage on this
branch ignores outputBasename and always derives the key from the source
basename, so two events referencing the same NAS filename would clobber each
other's hero. It now honours the option, matching generateThumbnail and
generatePreviewImage.

The format bypass trusted mime_type, which is not trustworthy: migration 039
backfilled every pre-existing photo to image/jpeg regardless of what it was,
and adminExternalMedia inserts rows with no mime_type at all — so a
mislabelled PNG sailed past the guard and came back flattened. It now checks
the filename extension as well.

* fix(previews): preserve alpha and animation in the preview tier

Stable twin of #1171. Stacked on the #1166 twin, whose format bypass this
removes.

generatePreviewImage encoded JPEG unconditionally. JPEG has no alpha channel
and no second frame, so a transparent PNG came back flattened onto a solid
background and an animated GIF came back as its first frame — for every
consumer of this tier, not just the lightbox. It was only invisible by default
because the lightbox served originals.

Sources with alpha, or more than one page, are now encoded as WebP, which
carries both and is still far smaller than the original. Ordinary photos stay
JPEG.

- the output extension matches what was written. A PNG source previously
  produced `preview_foo.png` holding JPEG bytes; harmless while the route
  hard-coded image/jpeg, wrong once the encoding varies. Existing keys keep
  working — they are still JPEG and still served as such.
- the preview route derives Content-Type from the key. With nosniff set,
  mislabelling would show a broken image rather than being silently corrected.
  The watermark branch re-encodes to JPEG and now says so.

The frontend guess-by-MIME goes away entirely, including the case it could
never get right: a still and an animated WebP declare the same type.

Divergence from the main twin: no width-tier case. The responsive `?w=`
renditions (#1095) are main-only, so this branch has a single canonical
preview per photo.

Verified on this branch: 5 new backend tests against real Sharp output;
frontend 21 files / 114 tests; full backend suite leaves the same 5
pre-existing failures as origin/stable.

* fix(previews): retire the legacy preview keys, and stop mislabelling watermarked ones

External review. Same two defects as the main twin.

Legacy keys collide with the new naming. The old generator kept the SOURCE
basename verbatim while always writing JPEG, so a `.webp` upload produced
`previews/preview_shot.webp` holding a JPEG. The claim that pre-existing keys
have no .webp suffix was simply wrong. The route now derives Content-Type from
the key and the response carries nosniff, so every photo uploaded as WebP
would have rendered as a broken image in the lightbox. Legacy `.png` keys are
wrong the other way: flattened JPEGs of what may have been transparent
sources, which isPreviewValid would have let stand forever.

Migration 178 clears photos.preview_path outright — all of it, not just the
suspicious extensions, because a `.jpg` key can equally be a flattened
rendition and nothing in the key says so. Previews regenerate lazily on next
view under the new encoder.

The watermark branch mislabelled its output. applyWatermark PRESERVES the
source format on this branch too (watermarkService.js: png stays png, webp
stays webp), and its input is the preview — so the output already matches the
key the header was derived from. Forcing image/jpeg mislabelled every
watermarked WebP preview, and nosniff means the browser would not correct it.

Numbered 178, not 176: this stack does not carry the external-media
migrations, but that stack takes 176 and 177 on this same branch, and two
files sharing a numeric prefix would be confusing even though both would run.

---------

Co-authored-by: Paul Nothaft <paul@MacStudio-von-Paul.local>
2026-08-26 09:14:42 +02:00
Paul Nothaft 75facb4d67 fix(gallery): stop the lightbox loading originals to display a photo (#1166) (#1175)
* fix(gallery): stop the lightbox loading originals to display a photo (#1166)

Stable twin of #1169.

The lightbox read preview_url, which the server only emits once an admin has
flipped lightbox_preview_enabled — off by default. So a stock install fell
straight through to url, the untouched original: a reporter measured 16.5 MB
for a photo whose preview is 345 KB. The lightbox renders its neighbours too,
so opening one photo pulled three originals.

slideshow_url is the same /preview/:id URL, watermark query included, and has
been emitted unconditionally for images since #1015. Preferring it fixes every
existing install with no migration and no admin action.

Two other surfaces bypass PhotoLightbox entirely and had the same bug:

- premium galleries build their own slides with `src: photo.url`. Fixing that
  also required carrying the photo id on the slide, because the download
  handler recovered the photo by matching slide.src against photo.url — a
  derivative src would have made Download a silent no-op.
- the Story layout rendered the full original as its GRID TILE, at
  object-cover in a small card, and its hero rendered one as a full-bleed
  background when hero_url exists for exactly that. Cards now use the preview
  tier (not the thumbnail: thumbnail_fit is seeded to 'cover', so a thumbnail
  would be cropped a second time and reframe every photo) and only load once
  within 200px of the viewport, since every card mounts at page load.

GIF, APNG and PNG keep the original: generatePreviewImage encodes JPEG, which
has neither a second frame nor an alpha channel. The backend fix that removes
this list is the next commit in this stack.

Divergence from the main twin: no responsive `?w=` tiers. #1095 is main-only,
so `lightboxImageUrl` here selects a URL and nothing more. It lives in
`imageTiers.ts` under the same path main uses, so that backporting #1095 later
merges into this file rather than landing beside it.

Verified on this branch: 8 new tests; frontend suite 21 files / 113 tests,
tsc clean.

* fix(gallery): make the Story hero fix actually work on external galleries (#1166)

External review. Same two fixes as the main twin.

hero_url was inert for external media. ensureHeroImage only ever called
resolvePhotoStorageKey, which returns null for external/reference photos by
design — and that null was handed straight to withLocalCopy, which throws, so
the hero route caught it and redirected to the full ORIGINAL. #1078 fixed
exactly this shape for ensurePreviewImage and nobody carried it across. It
stayed invisible until this PR pointed the Story hero at hero_url: on a
managed gallery that is a real saving, on a reference-mode gallery it quietly
changed nothing.

Needed one extra piece here that main already had: generateHeroImage on this
branch ignores outputBasename and always derives the key from the source
basename, so two events referencing the same NAS filename would clobber each
other's hero. It now honours the option, matching generateThumbnail and
generatePreviewImage.

The format bypass trusted mime_type, which is not trustworthy: migration 039
backfilled every pre-existing photo to image/jpeg regardless of what it was,
and adminExternalMedia inserts rows with no mime_type at all — so a
mislabelled PNG sailed past the guard and came back flattened. It now checks
the filename extension as well.

* test(gallery): the hero fixture follows the root-relative relpath contract (#1166)

Same fix as the main twin: external_relpath has been resolved from
EXTERNAL_MEDIA_ROOT rather than from event.external_path since #1163 landed,
and this fixture still carried the base-relative form, so the two tests stopped
resolving the moment that stack merged. Production was never affected.

---------

Co-authored-by: Paul Nothaft <paul@MacStudio-von-Paul.local>
2026-08-26 09:08:50 +02:00
Paul Nothaft 58ccecc304 fix(admin): move the maintenance sweeps' run state into the database (#1181) (#1188)
Stable twin of #1184. Both photo sweeps tracked whether they were running in a
module-level variable, which is invisible to every other replica: a status poll
routed to an idle replica reports isRunning false while another is mid-run, and
the next POST starts a second pass over the whole library.

Migration 179 adds one row per job, claimed with a conditional UPDATE whose
affected-row count is the answer. The lease is fenced on a per-claim token so a
runner superseded by a stale takeover cannot renew a claim it has lost or
release one it no longer owns; renewal runs on a timer spanning the claim
through release, since one hung NAS read can outlast the stale window inside a
single iteration. maintenance_jobs is excluded from .picpeak archives.

Gated on settings.edit / settings.view rather than main's system.manage, which
does not exist on this branch — they are what settings.edit was later split
into, so both branches let the same people through.

Co-authored-by: Paul Nothaft <paul@MacStudio-von-Paul.local>
2026-08-26 09:08:14 +02:00
Paul Nothaft 7f0ed23ea4 fix(external-media): record captured_at on import and add a backfill (stable) (#1183)
* fix(external-media): record captured_at on import and add a backfill (#1172)

Stable twin of #1179.

External media never went through photoProcessor, so captured_at stayed NULL
for every externally imported photo. The gallery's "Date Taken" sort then
degraded into import order through its own COALESCE fallback — a library
imported in two batches showed the first days of a trip after the last ones.

Ported whole:
- adminExternalMedia.js reads the capture date at import, off the file it has
  already opened for the dimensions. Best-effort, like the dimensions.
- A backfill endpoint for photos imported before this, so existing installs
  can fix historical rows rather than only new imports. Managed originals go
  through resolvePhotoStorageKey + withLocalCopy so S3 installs work; archived
  events are excluded because archiving deletes their originals; the run flag
  is claimed before the candidate query so two POSTs cannot both start.
- gallery.js carries photos.id as a tiebreaker on all three sorts. A bulk
  import writes hundreds of rows inside the same second, so uploaded_at ties
  are the normal case and the grid reshuffled between page loads.

One deliberate difference from main: the backfill is gated on settings.edit /
settings.view rather than system.manage / system.view, which do not exist on
this branch. They are what settings.edit was later split into, and main's
migration 175 projects every settings.edit holder forward onto system.manage,
so both branches let exactly the same people through.

* fix(external-media): gate the status card on the permission the button needs (#1172)

The built-in admin role holds settings.view but not settings.edit
(056_add_role_permissions_table.js:63), and StatusTab renders its card and
enabled button purely on a successful status payload. Gating the status
endpoint on settings.view therefore showed every admin a Backfill button whose
every click 403s with no error surfaced.

* fix(gallery): make the Date Taken sort correct on SQLite (#1172)

Same defect as the main twin: photos.captured_at holds three storage classes on
SQLite — an epoch-millisecond integer from managed uploads (photoProcessor.js:441
hands knex a Date), ISO text from external imports and the backfill, and null
falling through to uploaded_at's 'YYYY-MM-DD HH:MM:SS' text. SQLite sorts
INTEGER before TEXT unconditionally, so a 2027 capture came back before a 2020
one, and within the text values the 'T' separator outranked the space.

Normalised in the ORDER BY; Postgres keeps the plain COALESCE, its column being
a real timestamp. Regression tests drive the real gallery route on real SQLite.

* fix(gallery): normalise epoch-integer uploaded_at too, and stop polling a 403 (#1172)

Both follow-ups from the main twin's review, ported.

uploaded_at is not always text on SQLite: a .picpeak restore can carry epoch
milliseconds in from an install that stored them that way, and the fallback
branch read it with substr(), comparing '1830297600000' against
'2020-01-01 00:00:00' as text. Both columns now get the integer/real branch.

The status card also polled every ten seconds regardless of permission. On this
branch that hits every built-in admin — they hold settings.view but not
settings.edit — so each would have had a 403 and a logged denial every ten
seconds for a panel they were never shown.

* style: quote convention in the capture-sort test (#1172)

* fix(capture-dates): skip watcher-imported videos, and make the status counts consistent (#1172)

All three follow-ups from the main twin, ported: the three-marker video filter
(fileWatcher sets type/mime but not media_type, so those rows sat in the
backlog forever), the single-aggregate status counts (two queries could report
a negative backlog mid-import), and the card's render gated on settings.edit as
well as the cached payload.

---------

Co-authored-by: Paul Nothaft <paul@MacStudio-von-Paul.local>
2026-08-26 09:04:18 +02:00
Paul Nothaft 2b1c3588ae fix(external-media): store external paths from the media root (#1163) (#1174)
* fix(external-media): store external paths from the media root (#1163)

Stable twin of #1168. Stacked on the #1162 twin, which supplies
deleteDuplicatePhotos.

Importing a second folder into an event silently invalidated every photo
already in it. external_relpath was stored relative to events.external_path,
and every import overwrites that column, so the older rows were rebased onto
the new folder. Nothing errored and the grid still rendered — thumbnails are
written to local storage during the import while the base path is still
correct — so only the things that need the original broke. The reporter had
7547 of 8004 rows pointing into the void.

- external_relpath is now relative to EXTERNAL_MEDIA_ROOT, so a row is
  self-describing and nothing an admin does to the event can move it.
- migration 177 folds each event's base into its rows. Where the current
  resolution is missing it walks up for an ancestor holding a file of the same
  name AND the size the import recorded — existence alone would let a deleted
  file adopt an unrelated namesake and serve the wrong original. Rows it
  cannot place keep resolving where they resolve today, and the probe is
  skipped entirely when the mount is unreachable.
- probing is read-only and runs first; the rewrites and the marker commit
  together, so an interrupted fold cannot be folded twice.
- rewrites are staged through a per-row parking value, because a final path
  can equal another row's current one; and migration 177 re-throws without the
  driver's error code, which run-migrations-safe would otherwise read as
  "schema already exists".
- the fold also runs after a .picpeak restore, since knex_migrations is
  excluded from the archive, and a failure there is reported rather than
  presented as a clean restore.
- drops the duplicate-leaf-segment guess in photoResolver, which papered over
  this same double-prefixing.

Divergence from the main twin: no face-scan requeue reordering. Face
recognition is main-only, so the hazard of queueing rows against unconverted
paths does not exist on this branch — in picpeakImportService or in
restoreService.

Verified on this branch: 23 new tests pass, and the four suites carrying
base-relative fixtures were updated. Full suite leaves the same 5 pre-existing
failures as origin/stable, unchanged.

* fix(external-media): the fold's staging value must be storable on Postgres (#1163)

External review found this on this branch first; it was on both.

The two-pass rewrite parks each row on a temporary value, and that value was
written with a leading NUL. SQLite stores NUL in TEXT without complaint;
Postgres rejects it outright — "invalid byte sequence for encoding UTF8: 0x00"
— so migration 177 rolled back on exactly the installs that need the two-pass
repair, and only on the engine most of them run. Restores hit the same wall
and reported the conversion as failed.

The prefix is ordinary text now. Adds a gated Postgres test alongside the
existing picpeakRestorePg one, because a SQLite-only suite structurally cannot
catch this class: restoring the NUL makes exactly the two-pass repair case
fail with that error, and nothing else.

---------

Co-authored-by: Paul Nothaft <paul@MacStudio-von-Paul.local>
2026-08-26 09:00:05 +02:00
Paul Nothaft e9fcf4960e fix(external-media): one row per external file per event (#1162) (#1173)
* fix(external-media): one row per external file per event (#1162)

Stable twin of #1167.

Two overlapping import-external runs against the same event inserted every
file twice. The route checked for an existing external_relpath and then
inserted, with an fs.stat and a sharp().metadata() read sitting in between — a
window wide enough for both runs to see "not there". A reporter's event held
8004 rows for 6012 distinct paths. Nothing at the storage layer stopped it:
migration 041 created only a NON-unique (event_id, source_origin) index.

- migration 176 removes the existing duplicates and adds a partial unique
  index on (event_id, external_relpath), verified against the catalog
  afterwards — a failed CREATE INDEX raises 23505 on Postgres, which
  run-migrations-safe treats as "schema already exists" and would record as
  applied on an install that never got the index.
- dependent rows are removed explicitly rather than by cascade: PicPeak never
  sets `PRAGMA foreign_keys = ON`, so on SQLite the declared CASCADE is inert
  and a bare delete strands feedback and access-log rows. Guest feedback moves
  to the survivor instead of being discarded, keyed on guest identity the way
  feedbackService defines it, and the survivor's denormalized counters are
  recomputed.
- the route treats a unique violation as a skip, so a writer this process
  cannot see converges instead of duplicating, and a second import while one
  is running gets a 409.
- a .picpeak taken before migration 176 carries exactly these duplicates, and
  suspending FK enforcement does not suspend a unique index — so the restore
  drops the index for the load and rebuilds it after running the same dedupe.

Divergences from the main twin, both because the feature is absent here:
faces (no faceProcessor, so no purgePhotoFaces reconciliation — the rows are
still deleted so nothing dangles), admin marks, transfer membership, and
photos.view_count/download_count. The service guards each on hasTable /
hasColumn, so those branches simply do not fire.

Verified on this branch: 36 new tests pass; full suite leaves the same 5
pre-existing failures as origin/stable, unchanged.

* fix(external-media): invalidate the download zip when duplicates are removed (#1162)

External review. Same fix as the main twin.

The pre-built "download everything" archive still contained the duplicate rows
the dedupe had just deleted, so guests kept receiving them. Every ordinary
photo-deletion path calls downloadZipService.invalidate for exactly this
reason.

The columns are cleared rather than the service being called: that service
carries debounce timers and a regeneration queue, which a migration should not
start. getZipInfo already treats a cleared record as a cache miss and rebuilds
on the next request. The stale object is left in storage, as elsewhere.

---------

Co-authored-by: Paul Nothaft <paul@MacStudio-von-Paul.local>
2026-08-26 08:55:17 +02:00
Paul Nothaft f83d144f28 chore(stable): release 3.46.4 (#1159)
Build and Push Docker Images / build-backend (linux/amd64, ubuntu-latest) (push) Waiting to run
Build and Push Docker Images / build-backend (linux/arm64, ubuntu-24.04-arm) (push) Waiting to run
Build and Push Docker Images / merge-backend (push) Blocked by required conditions
Build and Push Docker Images / build-frontend (linux/amd64, ubuntu-latest) (push) Waiting to run
Build and Push Docker Images / build-frontend (linux/arm64, ubuntu-24.04-arm) (push) Waiting to run
Build and Push Docker Images / merge-frontend (push) Blocked by required conditions
Build and Push Docker Images / summary (push) Blocked by required conditions
2026-08-24 20:34:25 +02:00
Paul Nothaft b62cd2c290 fix(gallery): a guest's own hidden feedback is hidden from them too (#1150) (#1157)
Stable twin of #1153.

Everything in the system treats a hidden row as absent, but the per-viewer is_liked heart read the row without looking at is_hidden — so a like the photographer had hidden still showed as liked on a photo whose like_count was zero.

Making that agree exposes the second half: the duplicate check behind like/favorite toggling did not skip hidden rows either, so the now-empty heart, when clicked, found the hidden row and toggled it OFF. Skipping hidden rows there makes the click create a fresh, visible row.

Also carried from review: the per-guest caps, /my-feedback and getEventFeedbackSummary no longer count hidden rows, and unhiding collapses the guest's replacement — skipped when there is no stable identity, since that fallback was 'guest_identifier IS NULL', i.e. other visitors' rows.

Not carried: the my_color_label badge (colour labels are #1044) and the clearScope / singleValueScope visibility fix, neither of which exists on this branch.

Merged with admin privileges: the author cannot self-approve.
2026-08-23 22:09:41 +02:00
Paul Nothaft eaa8b41ba3 fix(gallery): guest filters respect show_feedback_to_guests (#1044) (#1156)
Stable twin of #1147, filter half only.

Every filter token on /photos is an OR of two halves: what THIS viewer marked, and what ANYONE marked. The fields built from the second half are gated on show_feedback_to_guests; the filter was not, so with the setting off ?filter=liked still returned exactly the photos other people liked — the membership instead of the count, one token at a time.

The half it left standing was also the wrong half: it read guest_identifier from the guest_id query parameter, which never matched anything, and accepting a caller-supplied identifier was a way back through the gate. Resolved from the request now, hidden rows excluded to match what the viewer can see.

Not carried: the color: token and the photo_admin_marks concurrent-write fix — colour labels and admin marks are not on this branch.

Merged with admin privileges: the author cannot self-approve.
2026-08-23 22:08:23 +02:00
Paul Nothaft d46397d92a fix(gallery): no Logout button on galleries that don't require a password (#1149) (#1154)
Stable twin of #1152. The reporter is on v3.46.1, so this branch is where the bug was actually seen.

showLogout was hard-coded true, so a gallery with no password showed a Logout button, and clicking it stranded the visitor on the loading skeleton — GalleryPage's auto-login is a one-shot latch that never re-fires.

The button is gated at both call sites, including the full-page layouts which render it on the callback rather than a flag. accessLevel and viaCustomer now come from /auth/session instead of per-tab sessionStorage, which silently downgraded a PIN-client session in a second tab. The public-gallery branch shows a reason and a Retry once auto-login has run and failed, instead of a skeleton that never stops.

Carries the full main fix including viaCustomer, even though reveal mode does not exist here, so the branches do not drift.

Merged with admin privileges: the author cannot self-approve.
2026-08-23 22:07:05 +02:00
Paul Nothaft e46260ad07 fix(scripts): regenerate-thumbnails resolves external sources through ensureThumbnail (#1148) (#1155)
Stable twin of #1151.

The script here carried the identical defect: it computed `storage/events/active/<photo.path>` and fs.access'd it, which does not exist for external or reference rows. #1129 already landed on this branch, so the route was fixed and the script was the remaining half.

Resolution goes through ensureThumbnail, which stable already exports with the external branch intact. Also carried: videos skipped on every marker, skip-vs-generate asked from isThumbnailValid, and a nonzero exit when a photo could not be built.

Not carried: the responsive-tier backfill — THUMBNAIL_WIDTHS and ensureThumbnailAtWidth are #1095/#1109 and do not exist on this branch.

Merged with admin privileges: the author cannot self-approve.
2026-08-23 22:06:30 +02:00
Paul Nothaft e9fadd2ef4 chore(stable): release 3.46.3 (#1143)
Build and Push Docker Images / build-backend (linux/amd64, ubuntu-latest) (push) Waiting to run
Build and Push Docker Images / build-backend (linux/arm64, ubuntu-24.04-arm) (push) Waiting to run
Build and Push Docker Images / merge-backend (push) Blocked by required conditions
Build and Push Docker Images / build-frontend (linux/amd64, ubuntu-latest) (push) Waiting to run
Build and Push Docker Images / build-frontend (linux/arm64, ubuntu-24.04-arm) (push) Waiting to run
Build and Push Docker Images / merge-frontend (push) Blocked by required conditions
Build and Push Docker Images / summary (push) Blocked by required conditions
2026-08-23 20:23:29 +02:00
Paul Nothaft d977e3e296 fix(gallery): give masonry tiles their real shape back (#1130, #1131)
Two independent causes of the same symptom — an aspect-ratio layout that does
not lay anything out.

gallery-premium discarded the tile height MasonryPhotoAlbum computed from
photos.width/height and set height:auto on both card and image, so the rendered
shape came from whatever rendition was served. With thumbnail_fit seeded 'cover'
every rendition is square, so the masonry drew identical squares.

The bundled CSS templates pinned images to a fixed pixel height, which beats the
.h-full utility six of the seven layouts rely on. Elegant Dark is seeded
is_default, so that was the out-of-the-box result for any layout other than
grid/timeline.

Migrations 052/053 corrected for fresh installs; 175 repairs the rows already
seeded. The repair is whitespace-tolerant because sanitizeCSS strips newlines
from any template ever saved through the editor, matches the height property
with a lookbehind so line-height/max-height are untouched, handles grouped
selectors and skips nested rules.

Stable twin of #1135.
2026-08-22 21:36:51 +02:00
Paul Nothaft da44f1947b fix(gallery): a missing file must not take the backend down (#1128)
LocalFsStorage.get() returns an fs.createReadStream, which is lazy: it resolves
immediately and opens the file on a later tick, so an ENOENT arrives after the
await returned and outside the route's try/catch. An unhandled 'error' event is
a process-level throw Express cannot catch — the backend exits and every gallery
goes blank until the container restarts.

gallery.js had ten .pipe(res) calls and zero error handlers.

pipeStreamToResponse attaches the missing handler: a vanished source becomes a
404 (410 for a prepared zip), anything else a 500, and a source that dies
mid-response destroys the connection rather than rewriting a status already on
the wire. Headers staged for the file are cleared first — Express does not
overwrite an existing Content-Type, and a surviving Cache-Control would let a
transient 404 be cached as a broken tile for up to an hour. It also releases the
source when a client hangs up.

Applied to all eight streaming responses, not just the thumbnail route.

Stable twin of #1133, reduced: the tier-race half does not apply here because
ensureThumbnailAtWidth does not exist on this branch.
2026-08-22 21:36:43 +02:00
Paul Nothaft dc9e3cdc5e fix(thumbnails): regenerate external photos, and stop destroying good ones (#1129)
POST /admin/thumbnails/regenerate resolved every source as
storage/events/active/<photo.path> and fs.access'd it. External and reference
rows are not there — their originals live under events.external_path — so every
one failed the check and was counted as an error, while the UI reported success
because the response is sent before the background loop starts.

It now goes through ensureThumbnail, which resolves both source kinds and writes
thumbnail_path back itself. Nulling thumbnail_path stops it short-circuiting on
isThumbnailValid, which matters because the old thumbnail is normally still
readable at exactly the moment someone presses regenerate.

And the half that destroys data: generateThumbnail deleted the target BEFORE
sharp had opened the source, and again in its catch. A source that could not be
read — a NAS mount that blipped — left the previous rendition gone and the
database pointing at it. Across a bulk regenerate that is the whole gallery.
Neither delete was needed: put stages to a temp file and renames atomically, and
put is the last statement in the try so no partial object can exist.

Also: videos filtered out, and the superseded rendition removed only when the
storage key actually moved, compared through the same canonicalisation the
backends apply.

Stable twin of #1134.
2026-08-22 21:36:19 +02:00
Paul Nothaft 7598e20f55 chore(stable): release 3.46.2 (#1121)
Build and Push Docker Images / build-backend (linux/amd64, ubuntu-latest) (push) Waiting to run
Build and Push Docker Images / build-backend (linux/arm64, ubuntu-24.04-arm) (push) Waiting to run
Build and Push Docker Images / merge-backend (push) Blocked by required conditions
Build and Push Docker Images / build-frontend (linux/amd64, ubuntu-latest) (push) Waiting to run
Build and Push Docker Images / build-frontend (linux/arm64, ubuntu-24.04-arm) (push) Waiting to run
Build and Push Docker Images / merge-frontend (push) Blocked by required conditions
Build and Push Docker Images / summary (push) Blocked by required conditions
2026-08-21 20:30:47 +02:00
Paul Nothaft 32db1c8052 fix(ui): stop iOS Safari zooming in on 14px form fields (#1114)
Closes #1105.

iOS Safari zooms the whole page in when a focused form control computes to
under 16px, and it does not zoom back out. Unlocking a gallery is a
client-side transition rather than a document navigation, so the zoom the
password field triggers carries straight into the gallery: the layout pans
horizontally and the header actions sit off-screen until the visitor
pinch-zooms out by hand. A real page load would have reset it.

`.input` and `.input-themed` are `text-sm`, so the field is 14px on every
phone, and GalleryPage inverts the breakpoint on top of that
(`text-sm sm:text-base` — 14px below 640px, where iOS zooms, and 16px above
it, where it never does).

Keyed to the POINTER, not a width. The zoom depends on the computed font size
and a touch device, never on how wide the viewport is — and a phone in
landscape is 667-956 CSS px, above any width you could call "phone". Measured
on the admin login page, which has no `sm:` override:

  main   portrait 390x844    14px    zooms
  main   landscape 844x390   14px    zooms
  main   iPad 820x1180       14px    zooms
  fixed  all three           16px
  fixed  desktop (mouse)     14px    unchanged, no zoom off touch

One media query rather than flipping each call site. `.input` alone backs 334
`<Input>` usages, but there are also ~440 raw inputs, selects and textareas
carrying their own `text-sm`, and Tailwind utilities sit in a later layer than
@layer components — so a fix at the component definition misses most controls
and any new `text-sm` silently reintroduces the bug.

The `:not()` on each selector is load-bearing, not decoration: it buys the
specificity to beat a utility class. Measured in a browser —

  input.text-sm     16px   (0,2,1 beats .text-sm)
  select.text-sm    14px   (0,0,1 loses)
  textarea.text-sm  14px   (0,0,1 loses)

24 selects and textareas in the tree carry `text-sm`, so the bare form would
have left them zooming. Checkbox and radio stay excluded so font-size never
sizes their box.

max(16px, 1em, 1rem) is a FLOOR, not a size. A flat 16px would make controls
that are already bigger smaller: Typography -> Large sets --font-size-base to
18px on body, so anything inheriting it would be clamped down and the setting
quietly ignored. Each term covers a case the others miss:

  normal (body 16)       16px      Large theme (body 18)    18px
  Small theme (body 14)  16px      browser default 20px     20px

The viewport meta is deliberately left alone: `maximum-scale=1` would suppress
the zoom by disabling pinch-to-zoom for everyone.
2026-08-21 19:25:33 +02:00
88 changed files with 8265 additions and 459 deletions
+1 -1
View File
@@ -1 +1 @@
{".":"3.46.1"}
{".":"3.46.5"}
+40
View File
@@ -5,6 +5,46 @@ All notable changes to PicPeak will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [3.46.5](https://github.com/PicPeak/picpeak/compare/v3.46.4...v3.46.5) (2026-08-26)
### Bug Fixes
* **admin:** make "Storage used" report storage used ([#1164](https://github.com/PicPeak/picpeak/issues/1164)) ([#1177](https://github.com/PicPeak/picpeak/issues/1177)) ([ac7ef26](https://github.com/PicPeak/picpeak/commit/ac7ef266dcd0d2b146c9739710c7631e672ef40f))
* **admin:** move the maintenance sweeps' run state into the database ([#1181](https://github.com/PicPeak/picpeak/issues/1181)) ([#1188](https://github.com/PicPeak/picpeak/issues/1188)) ([58ccecc](https://github.com/PicPeak/picpeak/commit/58ccecc304ff308bac3d334553ca5c7ef282eae2))
* **external-media:** one row per external file per event ([#1162](https://github.com/PicPeak/picpeak/issues/1162)) ([#1173](https://github.com/PicPeak/picpeak/issues/1173)) ([e9fcf49](https://github.com/PicPeak/picpeak/commit/e9fcf4960eb998c7e18528d773239f08e42e53bf))
* **external-media:** record captured_at on import and add a backfill (stable) ([#1183](https://github.com/PicPeak/picpeak/issues/1183)) ([7f0ed23](https://github.com/PicPeak/picpeak/commit/7f0ed23ea4c1d9379272b7267da74bc3addc1318))
* **external-media:** store external paths from the media root ([#1163](https://github.com/PicPeak/picpeak/issues/1163)) ([#1174](https://github.com/PicPeak/picpeak/issues/1174)) ([2b1c358](https://github.com/PicPeak/picpeak/commit/2b1c3588aeb26b1503445698efc6ffe4f483e645))
* **gallery:** stop the lightbox loading originals to display a photo ([#1166](https://github.com/PicPeak/picpeak/issues/1166)) ([#1175](https://github.com/PicPeak/picpeak/issues/1175)) ([75facb4](https://github.com/PicPeak/picpeak/commit/75facb4d67d026d312a99252abc7a6c420b864fb))
* **images:** respect EXIF orientation in thumbnails, heroes, previews and watermarks ([#1185](https://github.com/PicPeak/picpeak/issues/1185)) ([#1202](https://github.com/PicPeak/picpeak/issues/1202)) ([5559cd3](https://github.com/PicPeak/picpeak/commit/5559cd333d1a1f0b5ae22ad3361c13b3954ce344))
* **previews:** preserve alpha and animation in the preview tier ([#1176](https://github.com/PicPeak/picpeak/issues/1176)) ([9ffbe2f](https://github.com/PicPeak/picpeak/commit/9ffbe2f98fba53b22200081ae1b6ad2f94003345))
## [3.46.4](https://github.com/PicPeak/picpeak/compare/v3.46.3...v3.46.4) (2026-08-23)
### Bug Fixes
* **gallery:** a guest's own hidden feedback is hidden from them too ([#1150](https://github.com/PicPeak/picpeak/issues/1150)) ([#1157](https://github.com/PicPeak/picpeak/issues/1157)) ([b62cd2c](https://github.com/PicPeak/picpeak/commit/b62cd2c290d54820e8f58d11719d48592a1cd1f1))
* **gallery:** guest filters respect show_feedback_to_guests ([#1044](https://github.com/PicPeak/picpeak/issues/1044)) ([#1156](https://github.com/PicPeak/picpeak/issues/1156)) ([eaa8b41](https://github.com/PicPeak/picpeak/commit/eaa8b41ba323c7eac22e04947fead8e468e9c6c2))
* **gallery:** no Logout button on galleries that don't require a password ([#1149](https://github.com/PicPeak/picpeak/issues/1149)) ([#1154](https://github.com/PicPeak/picpeak/issues/1154)) ([d46397d](https://github.com/PicPeak/picpeak/commit/d46397d92a7648910075fb774b14abf77d893865))
* **scripts:** regenerate-thumbnails resolves external sources through ensureThumbnail ([#1148](https://github.com/PicPeak/picpeak/issues/1148)) ([#1155](https://github.com/PicPeak/picpeak/issues/1155)) ([e46260a](https://github.com/PicPeak/picpeak/commit/e46260ad0799bd411a4158c4cc31d587ba85d4ca))
## [3.46.3](https://github.com/PicPeak/picpeak/compare/v3.46.2...v3.46.3) (2026-08-22)
### Bug Fixes
* **gallery:** a missing file must not take the backend down ([#1128](https://github.com/PicPeak/picpeak/issues/1128)) ([da44f19](https://github.com/PicPeak/picpeak/commit/da44f1947b8317b47271f4f2a98b284b25d752c1))
* **gallery:** give masonry tiles their real shape back ([#1130](https://github.com/PicPeak/picpeak/issues/1130), [#1131](https://github.com/PicPeak/picpeak/issues/1131)) ([d977e3e](https://github.com/PicPeak/picpeak/commit/d977e3e296deeb19c26f1e5a98258eec323d120d))
* **thumbnails:** regenerate external photos, and stop destroying good ones ([#1129](https://github.com/PicPeak/picpeak/issues/1129)) ([dc9e3cd](https://github.com/PicPeak/picpeak/commit/dc9e3cdc5e00ac634f581e8d6b13107fe4839152))
## [3.46.2](https://github.com/PicPeak/picpeak/compare/v3.46.1...v3.46.2) (2026-08-21)
### Bug Fixes
* **ui:** stop iOS Safari zooming in on 14px form fields ([#1114](https://github.com/PicPeak/picpeak/issues/1114)) ([32db1c8](https://github.com/PicPeak/picpeak/commit/32db1c8052d324b09462a17859c7adb5ccfe56e3))
## [3.46.1](https://github.com/PicPeak/picpeak/compare/v3.46.0...v3.46.1) (2026-08-19)
@@ -0,0 +1,246 @@
/**
* POST /admin/thumbnails/regenerate for external/reference photos (#1129).
*
* STABLE TWIN. Diverges from the main version in one place: stable has no
* responsive ?w= tiers (#1095/#1109), so there is no deleteThumbnailTiers call
* to assert and the "drops the tiers first" test is absent here. Everything
* else — the external rebuild, the thumbnail_path:null contract, video
* skipping, per-event scoping and the superseded-key deletion — is identical.
*
* The route used to resolve every source as `storage/events/active/<path>` and
* `fs.access` it. External and reference rows do not live there — their
* originals sit under `events.external_path` — so every one of them failed the
* check and was counted as an error.
*
* That alone would be inert. What made it destructive is that the tier
* deletion runs FIRST (deliberately, so S3 and external rows are not skipped):
* on a reference install the button dropped every ?w= tier and rebuilt
* nothing, while the UI reported success — the response is sent before the
* background loop starts.
*
* The background work is fired with setImmediate, so every assertion here has
* to wait for it to drain rather than trusting the response.
*/
const fs = require('fs');
const path = require('path');
const os = require('os');
const express = require('express');
const request = require('supertest');
describe('admin thumbnail regeneration (#1129)', () => {
let tmpDir; let db; let cleanup; let app; let imageProcessor; let storage;
beforeAll(async () => {
tmpDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'picpeak-regen-'));
process.env.NODE_ENV = 'test';
process.env.TEST_DATABASE_PATH = path.join(tmpDir, 'data', 'test.db');
process.env.STORAGE_PATH = path.join(tmpDir, 'storage');
await fs.promises.mkdir(path.dirname(process.env.TEST_DATABASE_PATH), { recursive: true });
await fs.promises.mkdir(process.env.STORAGE_PATH, { recursive: true });
jest.resetModules();
jest.doMock('../../src/middleware/auth', () => ({
adminAuth: (req, _res, next) => { req.admin = { id: 1, username: 'tester' }; next(); },
}));
jest.doMock('../../src/middleware/permissions', () => ({
requirePermission: () => (_req, _res, next) => next(),
}));
// One instance, not a fresh object per call — the route and the
// assertions have to be looking at the same mock.
jest.doMock('../../src/services/storage', () => {
const instance = { delete: jest.fn().mockResolvedValue(undefined) };
return { getStorage: () => instance };
});
jest.doMock('../../src/services/imageProcessor', () => ({
ensureThumbnail: jest.fn().mockResolvedValue('thumbnails/thumb_ext1_shot.jpg'),
ensurePreviewImage: jest.fn().mockResolvedValue('previews/p.jpg'),
deletePreviewTiers: jest.fn().mockResolvedValue(undefined),
}));
// bootCrmDb, not run-migrations: the latter calls process.exit(0) on
// success, which ends the jest worker mid-suite.
({ db, cleanup } = await require('./helpers/crmDb').bootCrmDb());
imageProcessor = require('../../src/services/imageProcessor');
storage = require('../../src/services/storage').getStorage();
app = express();
app.use(express.json());
app.use('/admin/thumbnails', require('../../src/routes/adminThumbnails'));
}, 180000);
afterAll(async () => {
if (cleanup) await cleanup();
await fs.promises.rm(tmpDir, { recursive: true, force: true }).catch(() => {});
});
beforeEach(async () => {
jest.clearAllMocks();
await db('photos').del();
await db('events').del();
});
async function seedEvent() {
const [row] = await db('events').insert({
slug: 'nas-wedding', event_type: 'wedding', event_name: 'nas',
event_date: '2026-01-01', host_email: 'h@example.com', admin_email: 'a@example.com',
password_hash: 'x', share_link: 'nas-share', expires_at: new Date().toISOString(),
source_mode: 'reference', external_path: 'weddings/2026-08',
}).returning('id');
return typeof row === 'object' ? row.id : row;
}
async function seedPhoto(eventId, overrides = {}) {
const [row] = await db('photos').insert({
event_id: eventId, filename: 'shot.jpg', path: 'nas-wedding/shot.jpg',
type: 'individual', ...overrides,
}).returning('id');
return typeof row === 'object' ? row.id : row;
}
/** The work runs in setImmediate; give it room to finish. */
const drain = () => new Promise((resolve) => setTimeout(resolve, 150));
it('rebuilds the canonical thumbnail for an external photo instead of erroring', async () => {
const eventId = await seedEvent();
await seedPhoto(eventId, {
source_origin: 'external',
external_relpath: 'shot.jpg',
thumbnail_path: 'thumbnails/stale.jpg',
});
const res = await request(app).post('/admin/thumbnails/regenerate').send({});
expect(res.status).toBe(200);
await drain();
// The whole bug: this used to be zero calls and one logged
// "Original file not found" per photo.
expect(imageProcessor.ensureThumbnail).toHaveBeenCalledTimes(1);
});
it('nulls thumbnail_path so the valid-thumbnail short-circuit cannot skip the rebuild', async () => {
const eventId = await seedEvent();
await seedPhoto(eventId, {
source_origin: 'external',
external_relpath: 'shot.jpg',
thumbnail_path: 'thumbnails/still-on-disk.jpg',
});
await request(app).post('/admin/thumbnails/regenerate').send({});
await drain();
// Without this the endpoint is a no-op whenever the OLD thumbnail is still
// readable — which is the normal case after a settings change, and exactly
// when the admin pressed the button.
const [photoArg] = imageProcessor.ensureThumbnail.mock.calls[0];
expect(photoArg.thumbnail_path).toBeNull();
expect(photoArg.source_origin).toBe('external');
// Carried through so ensureThumbnail can resolve off the mount rather than
// under events/active.
expect(photoArg.external_relpath).toBe('shot.jpg');
});
it('leaves videos alone rather than handing a container file to Sharp', async () => {
const eventId = await seedEvent();
await seedPhoto(eventId, { source_origin: 'managed', media_type: 'video', filename: 'clip.mp4' });
await seedPhoto(eventId, { source_origin: 'managed', filename: 'still.jpg' });
const res = await request(app).post('/admin/thumbnails/regenerate').send({});
await drain();
expect(res.body.count).toBe(1);
expect(imageProcessor.ensureThumbnail).toHaveBeenCalledTimes(1);
expect(imageProcessor.ensureThumbnail.mock.calls[0][0].filename).toBe('still.jpg');
});
/**
* On S3, ensureThumbnail downloads the source to a randomly-named temp file,
* and for non-RAW input withProcessableImage passes no outputBasename — so
* generateThumbnail derives the key from that random name and it differs on
* every run. Nulling thumbnail_path hides the old key from everything that
* would otherwise clean it up, so each regeneration would strand a full
* thumbnail in the bucket, once per photo per run.
*/
describe('superseded canonical renditions', () => {
it('removes the old thumbnail when the key moved', async () => {
const eventId = await seedEvent();
await seedPhoto(eventId, {
source_origin: 'managed',
thumbnail_path: 'thumbnails/thumb_OLDRANDOM_shot.jpg',
});
imageProcessor.ensureThumbnail.mockResolvedValueOnce('thumbnails/thumb_NEWRANDOM_shot.jpg');
await request(app).post('/admin/thumbnails/regenerate').send({});
await drain();
expect(storage.delete).toHaveBeenCalledWith('thumbnails/thumb_OLDRANDOM_shot.jpg');
});
it('does NOT delete when the key is unchanged — that is the new file', async () => {
const eventId = await seedEvent();
await seedPhoto(eventId, {
source_origin: 'managed',
thumbnail_path: 'thumbnails/thumb_stable.jpg',
});
// Local storage resolves to a stable path, so the key is identical.
imageProcessor.ensureThumbnail.mockResolvedValueOnce('thumbnails/thumb_stable.jpg');
await request(app).post('/admin/thumbnails/regenerate').send({});
await drain();
expect(storage.delete).not.toHaveBeenCalled();
});
it.each([
['a Windows-style legacy path', 'thumbnails\\thumb_ext1_shot.jpg'],
['a leading ./', './thumbnails/thumb_ext1_shot.jpg'],
['a doubled separator', 'thumbnails//thumb_ext1_shot.jpg'],
])('does not delete the file it just wrote when the old path is %s', async (_name, stored) => {
const eventId = await seedEvent();
await seedPhoto(eventId, { source_origin: 'managed', thumbnail_path: stored });
// Both storage backends fold these to the same key, so this is the SAME
// object — deleting it would remove the freshly generated thumbnail and
// leave the row pointing at nothing.
imageProcessor.ensureThumbnail.mockResolvedValueOnce('thumbnails/thumb_ext1_shot.jpg');
await request(app).post('/admin/thumbnails/regenerate').send({});
await drain();
expect(storage.delete).not.toHaveBeenCalled();
});
it('counts the photo as regenerated even if the old object cannot be removed', async () => {
const eventId = await seedEvent();
await seedPhoto(eventId, {
source_origin: 'managed',
thumbnail_path: 'thumbnails/thumb_OLD.jpg',
});
imageProcessor.ensureThumbnail.mockResolvedValueOnce('thumbnails/thumb_NEW.jpg');
storage.delete.mockRejectedValueOnce(new Error('bucket said no'));
await request(app).post('/admin/thumbnails/regenerate').send({});
await drain();
// Losing the old object is untidy; the regeneration itself succeeded.
expect(imageProcessor.ensureThumbnail).toHaveBeenCalledTimes(1);
});
});
it('scopes to one event when asked', async () => {
const a = await seedEvent();
await seedPhoto(a, { source_origin: 'external', external_relpath: 'a.jpg' });
const [b] = await db('events').insert({
slug: 'other', event_type: 'wedding', event_name: 'other', event_date: '2026-01-01',
host_email: 'h@example.com', admin_email: 'a@example.com', password_hash: 'x',
share_link: 'other-share', expires_at: new Date().toISOString(),
}).returning('id');
await seedPhoto(typeof b === 'object' ? b.id : b, { source_origin: 'managed' });
const res = await request(app).post('/admin/thumbnails/regenerate').send({ eventId: a });
await drain();
expect(res.body.count).toBe(1);
expect(imageProcessor.ensureThumbnail).toHaveBeenCalledTimes(1);
});
});
@@ -0,0 +1,202 @@
/**
* Backfilling captured_at on a library imported before #1172.
*
* The point of the endpoint, rather than a migration: it resolves originals
* through resolvePhotoFilePath, which is the only path that reaches an
* external row. The thumbnail regenerator resolves under
* storage/events/active/<photo.path>, which never exists for those (#1129) —
* so it cannot be the model.
*/
const fs = require('fs');
const path = require('path');
const os = require('os');
const express = require('express');
const request = require('supertest');
const sharp = require('sharp');
describe('capture date backfill (#1172)', () => {
let tmpDir; let db; let app; let mediaRoot;
const writeJpegWithExif = async (abs, iso) => {
await fs.promises.mkdir(path.dirname(abs), { recursive: true });
const d = new Date(iso);
const pad = (n) => String(n).padStart(2, '0');
const exifDate = `${d.getUTCFullYear()}:${pad(d.getUTCMonth() + 1)}:${pad(d.getUTCDate())} `
+ `${pad(d.getUTCHours())}:${pad(d.getUTCMinutes())}:${pad(d.getUTCSeconds())}`;
await sharp({ create: { width: 60, height: 40, channels: 3, background: { r: 9, g: 9, b: 9 } } })
.withExif({ IFD2: { DateTimeOriginal: exifDate } }).jpeg().toFile(abs);
};
const settle = async () => { for (let i = 0; i < 60; i++) { await new Promise((r) => setTimeout(r, 50)); const s = await status(); if (!s.body.isRunning) return s; } throw new Error('backfill did not settle'); };
const status = () => request(app).get('/api/admin/photos/repair-capture-dates/status');
beforeAll(async () => {
tmpDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'picpeak-capfill-'));
mediaRoot = path.join(tmpDir, 'media');
await fs.promises.mkdir(mediaRoot, { recursive: true });
process.env.NODE_ENV = 'test';
process.env.TEST_DATABASE_PATH = path.join(tmpDir, 'data', 'db.sqlite');
await fs.promises.mkdir(path.dirname(process.env.TEST_DATABASE_PATH), { recursive: true });
process.env.STORAGE_PATH = path.join(tmpDir, 'storage');
process.env.EXTERNAL_MEDIA_ROOT = mediaRoot;
process.env.JWT_SECRET = process.env.JWT_SECRET || 'capfill-secret';
jest.resetModules();
jest.doMock('../../src/middleware/auth', () => ({
adminAuth: (req, _res, next) => { req.admin = { id: 1, username: 'tester', roleName: 'admin' }; next(); },
}));
jest.doMock('../../src/middleware/permissions', () => ({
requirePermission: () => (_req, _res, next) => next(),
}));
jest.doMock('../../src/utils/logger', () => ({
debug: jest.fn(), info: jest.fn(), warn: jest.fn(), error: jest.fn(),
}));
({ db } = await require('./helpers/crmDb').bootCrmDb());
app = express();
app.use(express.json());
app.use('/api/admin/photos', require('../../src/routes/adminPhotoDimensions'));
}, 180000);
afterAll(async () => {
if (db) await db.destroy?.();
await fs.promises.rm(tmpDir, { recursive: true, force: true }).catch(() => {});
});
async function seed({ relpath, exifIso, writeFile = true, archived = false }) {
await db('photos').del();
await db('events').del();
const [e] = await db('events').insert({
slug: 'capfill', event_type: 'wedding', event_name: 'capfill', event_date: '2026-01-01',
host_email: 'h@example.com', admin_email: 'a@example.com', password_hash: 'x',
share_link: `capfill-${Math.random()}`, expires_at: new Date().toISOString(),
source_mode: 'reference', external_path: 'trip', is_archived: archived,
}).returning('id');
const eventId = typeof e === 'object' ? e.id : e;
if (writeFile) await writeJpegWithExif(path.join(mediaRoot, 'trip', relpath), exifIso);
const [p] = await db('photos').insert({
event_id: eventId, filename: path.basename(relpath), path: `capfill/${path.basename(relpath)}`,
// Root-relative, as this branch stores it (#1163) — the file lives at
// <mediaRoot>/trip/<relpath>.
type: 'individual', source_origin: 'external', external_relpath: `trip/${relpath}`,
uploaded_at: new Date().toISOString(), captured_at: null,
}).returning('id');
return { eventId, photoId: typeof p === 'object' ? p.id : p };
}
it('fills captured_at for an external photo the thumbnail regenerator cannot reach', async () => {
const { photoId } = await seed({ relpath: 'a.jpg', exifIso: '2026-06-01T09:45:03Z' });
const res = await request(app).post('/api/admin/photos/repair-capture-dates');
expect(res.status).toBe(200);
expect(res.body.count).toBe(1);
const done = await settle();
expect(done.body.lastResult.success).toBe(1);
expect((await db('photos').where({ id: photoId }).first()).captured_at).toBeTruthy();
});
it('counts a photo with no EXIF separately from a failure', async () => {
// "The mount is broken" and "these files carry no date" need different
// answers from an operator, so they are not the same number.
await db('photos').del(); await db('events').del();
const { photoId } = await seed({ relpath: 'plain.jpg', exifIso: '2026-06-01T09:45:03Z', writeFile: false });
await sharp({ create: { width: 40, height: 30, channels: 3, background: { r: 1, g: 1, b: 1 } } })
.jpeg().toFile(path.join(mediaRoot, 'trip', 'plain.jpg'));
await request(app).post('/api/admin/photos/repair-capture-dates');
const done = await settle();
expect(done.body.lastResult).toMatchObject({ success: 0, noExif: 1, failed: 0 });
expect((await db('photos').where({ id: photoId }).first()).captured_at).toBeNull();
});
it('counts an unreachable original as a failure, not as missing EXIF', async () => {
await seed({ relpath: 'gone.jpg', exifIso: '2026-06-01T09:45:03Z', writeFile: false });
await request(app).post('/api/admin/photos/repair-capture-dates');
const done = await settle();
expect(done.body.lastResult).toMatchObject({ success: 0, noExif: 0, failed: 1 });
});
it('reports nothing to do once every photo has a date', async () => {
const { photoId } = await seed({ relpath: 'b.jpg', exifIso: '2026-06-02T09:00:00Z' });
await db('photos').where({ id: photoId }).update({ captured_at: new Date().toISOString() });
const res = await request(app).post('/api/admin/photos/repair-capture-dates');
expect(res.body.count).toBe(0);
expect((await status()).body.withoutCaptureDate).toBe(0);
});
it('skips a watcher-imported video, which carries media_type "image"', async () => {
// fileWatcher.processNewPhoto sets type='video' and a video/* mime but
// never media_type (fileWatcher.js:128-130), so the row keeps the 'image'
// default from migration 048. Filtering on media_type alone queued it every
// run: extractCaptureDate returns null for a video, captured_at stays null,
// and the backlog never cleared.
const { eventId } = await seed({ relpath: 'clip.jpg', exifIso: '2026-06-01T09:45:03Z', writeFile: false });
await db('photos').del();
await db('photos').insert({
event_id: eventId, filename: 'clip.mp4', path: 'capfill/clip.mp4',
type: 'video', media_type: 'image', mime_type: 'video/mp4',
source_origin: 'external', external_relpath: 'trip/clip.mp4',
uploaded_at: new Date().toISOString(), captured_at: null,
});
const res = await request(app).post('/api/admin/photos/repair-capture-dates');
expect(res.body.count).toBe(0);
const s = await status();
// And it is not counted as a permanent backlog either.
expect(s.body.total).toBe(0);
expect(s.body.withoutCaptureDate).toBe(0);
});
it('never reports more dated photos than it has photos', async () => {
// Both counts come from one aggregate; as two queries an import committing
// between them produced withCaptureDate > total and a negative backlog.
const { photoId } = await seed({ relpath: 'counted.jpg', exifIso: '2026-06-05T08:00:00Z' });
await db('photos').where({ id: photoId }).update({ captured_at: new Date().toISOString() });
const s = await status();
expect(s.body.total).toBe(1);
expect(s.body.withCaptureDate).toBe(1);
expect(s.body.withoutCaptureDate).toBe(0);
expect(s.body.withoutCaptureDate).toBeGreaterThanOrEqual(0);
});
it('skips archived events instead of failing them on every run', async () => {
// Archiving deletes the originals and keeps the rows, so an archived photo
// can never get a date. Counting it would fail it every pass and leave the
// status endpoint permanently reporting a backlog.
await seed({ relpath: 'archived.jpg', exifIso: '2026-06-04T09:00:00Z', archived: true });
const res = await request(app).post('/api/admin/photos/repair-capture-dates');
expect(res.body.count).toBe(0);
const s = await status();
expect(s.body.total).toBe(0);
expect(s.body.withoutCaptureDate).toBe(0);
expect(s.body.isRunning).toBe(false);
});
it('does not overwrite a date written while it was running', async () => {
// whereNull on the update: an import or a replacement finishing mid-run has
// already written a better value than this pass would.
const { photoId } = await seed({ relpath: 'c.jpg', exifIso: '2026-06-03T09:00:00Z' });
const claimed = '2020-01-01T00:00:00.000Z';
const res = await request(app).post('/api/admin/photos/repair-capture-dates');
expect(res.body.count).toBe(1);
await db('photos').where({ id: photoId }).update({ captured_at: claimed });
const done = await settle();
expect(new Date((await db('photos').where({ id: photoId }).first()).captured_at).toISOString()).toBe(claimed);
expect(done.body.lastResult.success).toBe(0);
});
});
@@ -0,0 +1,161 @@
/**
* External imports must record captured_at (#1172).
*
* Managed uploads get it from photoProcessor, which external media never goes
* through — so every externally imported photo carried captured_at NULL, and
* the gallery's "Date Taken" sort fell back to uploaded_at through its
* COALESCE. On a library imported in two batches that ordered a 12-day trip by
* which folder was imported first: the reporter's first two days landed at
* positions 4204-5296 of 5555.
*
* Driven through the real route against real files carrying real EXIF, because
* the whole question is whether the import reads the file it already has open.
*/
const fs = require('fs');
const path = require('path');
const os = require('os');
const express = require('express');
const request = require('supertest');
const sharp = require('sharp');
describe('external import capture dates (#1172)', () => {
let tmpDir; let db; let app; let mediaRoot;
/**
* A real JPEG carrying DateTimeOriginal.
*
* IFD2, not IFD0 — DateTimeOriginal lives in the Exif IFD, and exifr does not
* see it anywhere else (IFD0 takes plain DateTime, which surfaces as
* ModifyDate instead).
*/
const writeJpegWithExif = async (rel, iso) => {
const full = path.join(mediaRoot, rel);
await fs.promises.mkdir(path.dirname(full), { recursive: true });
const d = new Date(iso);
const pad = (n) => String(n).padStart(2, '0');
const exifDate = `${d.getUTCFullYear()}:${pad(d.getUTCMonth() + 1)}:${pad(d.getUTCDate())} `
+ `${pad(d.getUTCHours())}:${pad(d.getUTCMinutes())}:${pad(d.getUTCSeconds())}`;
await sharp({ create: { width: 60, height: 40, channels: 3, background: { r: 10, g: 20, b: 30 } } })
.withExif({ IFD2: { DateTimeOriginal: exifDate } })
.jpeg()
.toFile(full);
return full;
};
const writeJpegNoExif = async (rel) => {
const full = path.join(mediaRoot, rel);
await fs.promises.mkdir(path.dirname(full), { recursive: true });
await sharp({ create: { width: 60, height: 40, channels: 3, background: { r: 200, g: 10, b: 10 } } })
.jpeg().toFile(full);
};
beforeAll(async () => {
tmpDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'picpeak-capdate-'));
mediaRoot = path.join(tmpDir, 'media');
await fs.promises.mkdir(mediaRoot, { recursive: true });
process.env.NODE_ENV = 'test';
process.env.TEST_DATABASE_PATH = path.join(tmpDir, 'data', 'db.sqlite');
await fs.promises.mkdir(path.dirname(process.env.TEST_DATABASE_PATH), { recursive: true });
process.env.STORAGE_PATH = path.join(tmpDir, 'storage');
process.env.EXTERNAL_MEDIA_ROOT = mediaRoot;
process.env.JWT_SECRET = process.env.JWT_SECRET || 'capdate-secret';
jest.resetModules();
jest.doMock('../../src/middleware/auth', () => ({
adminAuth: (req, _res, next) => { req.admin = { id: 1, username: 'tester', roleName: 'admin' }; next(); },
}));
jest.doMock('../../src/middleware/permissions', () => ({
requirePermission: () => (_req, _res, next) => next(),
}));
jest.doMock('../../src/middleware/ownership', () => ({
requireEventOwnership: (_req, _res, next) => next(),
}));
jest.doMock('../../src/services/imageProcessor', () => {
const actual = jest.requireActual('../../src/services/imageProcessor');
return { ...actual, generateThumbnail: jest.fn(async () => 'thumbnails/mock.jpg'), ensureThumbnail: jest.fn() };
});
jest.doMock('../../src/utils/logger', () => ({
debug: jest.fn(), info: jest.fn(), warn: jest.fn(), error: jest.fn(),
}));
({ db } = await require('./helpers/crmDb').bootCrmDb());
app = express();
app.use(express.json());
app.use('/api/admin/external-media', require('../../src/routes/adminExternalMedia'));
}, 180000);
afterAll(async () => {
if (db) await db.destroy?.();
await fs.promises.rm(tmpDir, { recursive: true, force: true }).catch(() => {});
});
async function seedEvent() {
await db('photos').del();
await db('events').del();
await fs.promises.rm(mediaRoot, { recursive: true, force: true });
await fs.promises.mkdir(mediaRoot, { recursive: true });
const [e] = await db('events').insert({
slug: `capdate-${Math.random().toString(36).slice(2, 8)}`,
event_type: 'wedding', event_name: 'capdate', event_date: '2026-01-01',
host_email: 'h@example.com', admin_email: 'a@example.com', password_hash: 'x',
share_link: `capdate-${Math.random()}`, expires_at: new Date().toISOString(),
source_mode: 'reference',
}).returning('id');
return typeof e === 'object' ? e.id : e;
}
const runImport = (eventId, external_path) => request(app)
.post(`/api/admin/external-media/events/${eventId}/import-external`)
.send({ external_path, recursive: true });
it('records the EXIF capture date on import', async () => {
const eventId = await seedEvent();
await writeJpegWithExif('trip/a.jpg', '2026-06-01T09:45:03Z');
await runImport(eventId, 'trip');
const photo = await db('photos').where({ event_id: eventId }).first();
expect(photo.captured_at).toBeTruthy();
// NOT asserted as an absolute instant. EXIF carries a naive wall-clock
// time and exifr resolves it against the HOST timezone, so the stored UTC
// value differs between a CEST developer machine and a UTC runner. What
// this fix is about is that the field is populated and orders correctly;
// that captured_at is not a true instant is a separate, pre-existing
// problem shared with managed uploads (#1172's own footnote).
expect(new Date(photo.captured_at).getUTCFullYear()).toBe(2026);
expect(new Date(photo.captured_at).getUTCMonth()).toBe(5); // June
});
it('imports a photo with no EXIF date rather than failing it', async () => {
// Plenty of sources carry none; that must stay an import, not an error.
const eventId = await seedEvent();
await writeJpegNoExif('trip/plain.jpg');
const res = await runImport(eventId, 'trip');
expect(res.body.imported).toBe(1);
const photo = await db('photos').where({ event_id: eventId }).first();
expect(photo.captured_at).toBeNull();
});
it('orders a two-batch import by capture time, not by batch', async () => {
// The reported shape: the FIRST days of the trip imported second. Sorting
// on COALESCE(captured_at, uploaded_at) put them after the last days,
// because uploaded_at is the import timestamp.
const eventId = await seedEvent();
await writeJpegWithExif('late/day12.jpg', '2026-06-12T10:00:00Z');
await runImport(eventId, 'late');
await writeJpegWithExif('early/day01.jpg', '2026-06-01T10:00:00Z');
await runImport(eventId, 'early');
const rows = await db('photos')
.where({ event_id: eventId })
.orderByRaw('COALESCE(captured_at, uploaded_at) asc')
.select('filename');
expect(rows.map((r) => r.filename)).toEqual(['day01.jpg', 'day12.jpg']);
});
});
@@ -0,0 +1,205 @@
/**
* Two overlapping external imports insert every file twice (#1162).
*
* The route checked for an existing external_relpath and then inserted, with
* an fs.stat and a `sharp().metadata()` read sitting in between. A reporter
* double-clicked a slow import of a 6012-file tree and got 8004 rows.
*
* Both halves of the fix are driven here through the real route:
*
* - the in-flight guard, which turns the second click into a 409 instead of
* a second full walk of the tree;
* - convergence when the guard cannot help (another replica, another
* process), which is the unique index from migration 186 firing and the
* loop counting a skip rather than dying or duplicating.
*
* The second is exercised by inserting a competing row from inside the mocked
* `sharp().metadata()` call — literally inside the window the bug lived in.
*/
const fs = require('fs');
const path = require('path');
const os = require('os');
const express = require('express');
const request = require('supertest');
describe('concurrent external imports (#1162)', () => {
let tmpDir; let db; let app; let mediaRoot;
// When set, the mocked sharp metadata read inserts this row first — the
// other run winning the race between our SELECT and our INSERT.
let stealDuringMetadata = null;
let thumbnailDelayMs = 0;
beforeAll(async () => {
tmpDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'picpeak-extdup-'));
mediaRoot = path.join(tmpDir, 'media');
await fs.promises.mkdir(path.join(mediaRoot, 'nas', 'individual'), { recursive: true });
for (const name of ['a.jpg', 'b.jpg', 'c.jpg']) {
await fs.promises.writeFile(path.join(mediaRoot, 'nas', 'individual', name), 'not-a-real-jpeg');
}
process.env.NODE_ENV = 'test';
process.env.TEST_DATABASE_PATH = path.join(tmpDir, 'data', 'db.sqlite');
await fs.promises.mkdir(path.dirname(process.env.TEST_DATABASE_PATH), { recursive: true });
process.env.STORAGE_PATH = path.join(tmpDir, 'storage');
process.env.EXTERNAL_MEDIA_ROOT = mediaRoot;
process.env.JWT_SECRET = process.env.JWT_SECRET || 'extdup-secret';
jest.resetModules();
jest.doMock('../../src/middleware/auth', () => ({
adminAuth: (req, _res, next) => { req.admin = { id: 1, username: 'tester', roleName: 'admin' }; next(); },
}));
jest.doMock('../../src/middleware/permissions', () => ({
requirePermission: () => (_req, _res, next) => next(),
}));
jest.doMock('../../src/middleware/ownership', () => ({
requireEventOwnership: (_req, _res, next) => next(),
}));
// The window. In production this is a real decode of a NAS-hosted file —
// hundreds of milliseconds during which the row we just proved absent can
// appear. Standing in for the other run here makes that deterministic.
jest.doMock('sharp', () => () => ({
metadata: async () => {
if (stealDuringMetadata) {
const { db: liveDb } = require('../../src/database/db');
await liveDb('photos').insert(stealDuringMetadata);
stealDuringMetadata = null;
}
return { width: 100, height: 200 };
},
}));
jest.doMock('../../src/services/imageProcessor', () => ({
generateThumbnail: jest.fn(async () => {
if (thumbnailDelayMs) await new Promise((r) => setTimeout(r, thumbnailDelayMs));
return 'thumbnails/mock.jpg';
}),
ensureThumbnail: jest.fn(),
}));
jest.doMock('../../src/utils/logger', () => ({
debug: jest.fn(), info: jest.fn(), warn: jest.fn(), error: jest.fn(),
}));
({ db } = await require('./helpers/crmDb').bootCrmDb());
app = express();
app.use(express.json());
app.use('/api/admin/external-media', require('../../src/routes/adminExternalMedia'));
}, 180000);
afterAll(async () => {
if (db) await db.destroy?.();
await fs.promises.rm(tmpDir, { recursive: true, force: true }).catch(() => {});
});
async function seedEvent() {
await db('photos').del();
await db('events').del();
stealDuringMetadata = null;
thumbnailDelayMs = 0;
const [e] = await db('events').insert({
slug: `extdup-${Math.random().toString(36).slice(2, 8)}`,
event_type: 'wedding',
event_name: 'extdup',
event_date: '2026-01-01',
host_email: 'h@example.com',
admin_email: 'a@example.com',
password_hash: 'x',
share_link: `extdup-${Math.random()}`,
expires_at: new Date().toISOString(),
source_mode: 'reference',
}).returning('id');
return typeof e === 'object' ? e.id : e;
}
const runImport = (eventId) => request(app)
.post(`/api/admin/external-media/events/${eventId}/import-external`)
.send({ external_path: 'nas', recursive: true });
async function relpathCounts(eventId) {
const rows = await db('photos').where({ event_id: eventId }).select('external_relpath');
const counts = new Map();
for (const r of rows) counts.set(r.external_relpath, (counts.get(r.external_relpath) || 0) + 1);
return counts;
}
it('rejects a second import while the first is still running', async () => {
const eventId = await seedEvent();
// Enough to keep the first request inside its loop while the second
// arrives — the "slow import looks hung, so I clicked again" case.
thumbnailDelayMs = 20;
const [first, second] = await Promise.all([runImport(eventId), runImport(eventId)]);
const statuses = [first.status, second.status].sort();
expect(statuses).toEqual([200, 409]);
const rejected = first.status === 409 ? first : second;
expect(rejected.body.error).toMatch(/already running/i);
});
it('leaves exactly one row per file after both runs', async () => {
const eventId = await seedEvent();
thumbnailDelayMs = 20;
await Promise.all([runImport(eventId), runImport(eventId)]);
const counts = await relpathCounts(eventId);
expect(counts.size).toBe(3);
expect([...counts.values()]).toEqual([1, 1, 1]);
});
it('releases the event once the import finishes, so a re-import still works', async () => {
const eventId = await seedEvent();
expect((await runImport(eventId)).status).toBe(200);
// Not 409 — the guard is per run, not a permanent lock on the event.
const second = await runImport(eventId);
expect(second.status).toBe(200);
expect(second.body.imported).toBe(0);
expect(second.body.skipped).toBe(3);
});
it('converges when another writer wins the race mid-file', async () => {
// The guard is in-process, so it cannot see a second replica. This is what
// the unique index is for: the insert bounces, and the file is counted as
// skipped rather than duplicated or lost to a 500.
const eventId = await seedEvent();
stealDuringMetadata = {
event_id: eventId,
filename: 'a.jpg',
path: 'x/a.jpg',
type: 'individual',
source_origin: 'external',
external_relpath: path.join('nas', 'individual', 'a.jpg'),
};
const res = await runImport(eventId);
expect(res.status).toBe(200);
const counts = await relpathCounts(eventId);
expect(counts.get(path.join('nas', 'individual', 'a.jpg'))).toBe(1);
// Two imported by us, one lost to the other writer and reported honestly.
expect(res.body.imported).toBe(2);
expect(res.body.skipped).toBe(1);
});
it('does not let one contended file abort the rest of the import', async () => {
const eventId = await seedEvent();
stealDuringMetadata = {
event_id: eventId,
filename: 'a.jpg',
path: 'x/a.jpg',
type: 'individual',
source_origin: 'external',
external_relpath: path.join('nas', 'individual', 'a.jpg'),
};
await runImport(eventId);
// All three files present — the contended one via the other writer's row.
expect((await relpathCounts(eventId)).size).toBe(3);
});
});
@@ -0,0 +1,175 @@
/**
* Importing a second folder must not move the photos already in the event (#1163).
*
* events.external_path is overwritten by every import, and external_relpath
* used to be stored relative to it — so a second import silently rebased every
* existing row onto the new folder. The reporter had 7547 of 8004 originals
* pointing at files that do not exist, and nothing said so: thumbnails are
* written to local storage during the import while the base path is still
* correct, so the grid carries on rendering.
*
* Driven through the real route and the real resolver, against a real
* directory tree — the failure is entirely about whether a file is where the
* app looks for it.
*/
const fs = require('fs');
const path = require('path');
const os = require('os');
const express = require('express');
const request = require('supertest');
describe('a second external import (#1163)', () => {
let tmpDir; let db; let app; let mediaRoot; let resolvePhotoFilePath;
const touch = async (rel) => {
const full = path.join(mediaRoot, rel);
await fs.promises.mkdir(path.dirname(full), { recursive: true });
await fs.promises.writeFile(full, 'not-a-real-jpeg');
};
beforeAll(async () => {
tmpDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'picpeak-ext2nd-'));
mediaRoot = path.join(tmpDir, 'media');
await fs.promises.mkdir(mediaRoot, { recursive: true });
process.env.NODE_ENV = 'test';
process.env.TEST_DATABASE_PATH = path.join(tmpDir, 'data', 'db.sqlite');
await fs.promises.mkdir(path.dirname(process.env.TEST_DATABASE_PATH), { recursive: true });
process.env.STORAGE_PATH = path.join(tmpDir, 'storage');
process.env.EXTERNAL_MEDIA_ROOT = mediaRoot;
process.env.JWT_SECRET = process.env.JWT_SECRET || 'ext2nd-secret';
jest.resetModules();
jest.doMock('../../src/middleware/auth', () => ({
adminAuth: (req, _res, next) => { req.admin = { id: 1, username: 'tester', roleName: 'admin' }; next(); },
}));
jest.doMock('../../src/middleware/permissions', () => ({
requirePermission: () => (_req, _res, next) => next(),
}));
jest.doMock('../../src/middleware/ownership', () => ({
requireEventOwnership: (_req, _res, next) => next(),
}));
jest.doMock('sharp', () => () => ({ metadata: async () => ({ width: 100, height: 200 }) }));
jest.doMock('../../src/services/imageProcessor', () => ({
generateThumbnail: jest.fn(async () => 'thumbnails/mock.jpg'),
ensureThumbnail: jest.fn(),
}));
jest.doMock('../../src/utils/logger', () => ({
debug: jest.fn(), info: jest.fn(), warn: jest.fn(), error: jest.fn(),
}));
({ db } = await require('./helpers/crmDb').bootCrmDb());
({ resolvePhotoFilePath } = require('../../src/services/photoResolver'));
app = express();
app.use(express.json());
app.use('/api/admin/external-media', require('../../src/routes/adminExternalMedia'));
}, 180000);
afterAll(async () => {
if (db) await db.destroy?.();
await fs.promises.rm(tmpDir, { recursive: true, force: true }).catch(() => {});
});
async function seedEvent() {
await db('photos').del();
await db('events').del();
await fs.promises.rm(mediaRoot, { recursive: true, force: true });
await fs.promises.mkdir(mediaRoot, { recursive: true });
const [e] = await db('events').insert({
slug: `ext2nd-${Math.random().toString(36).slice(2, 8)}`,
event_type: 'wedding',
event_name: 'ext2nd',
event_date: '2026-01-01',
host_email: 'h@example.com',
admin_email: 'a@example.com',
password_hash: 'x',
share_link: `ext2nd-${Math.random()}`,
expires_at: new Date().toISOString(),
source_mode: 'reference',
}).returning('id');
return typeof e === 'object' ? e.id : e;
}
const runImport = (eventId, external_path) => request(app)
.post(`/api/admin/external-media/events/${eventId}/import-external`)
.send({ external_path, recursive: true });
/** Where the app would go looking for this photo's original, right now. */
async function resolved(eventId, filename) {
const event = await db('events').where({ id: eventId }).first();
const photo = await db('photos').where({ event_id: eventId, filename }).first();
return resolvePhotoFilePath(event, photo);
}
it('stores paths relative to the media root, not to the imported folder', async () => {
const eventId = await seedEvent();
await touch('Trip/Leknes/old.jpg');
await runImport(eventId, 'Trip');
const photo = await db('photos').where({ event_id: eventId }).first();
expect(photo.external_relpath).toBe(path.join('Trip', 'Leknes', 'old.jpg'));
});
it('leaves the first folders originals reachable after a second import', async () => {
const eventId = await seedEvent();
await touch('Trip/Leknes/old.jpg');
await touch('Trip/Sub/new.jpg');
await runImport(eventId, 'Trip');
const before = await resolved(eventId, 'old.jpg');
await runImport(eventId, 'Trip/Sub');
const after = await resolved(eventId, 'old.jpg');
// The regression: `after` used to be <root>/Trip/Sub/Leknes/old.jpg.
expect(after).toBe(before);
expect(fs.existsSync(after)).toBe(true);
});
it('every original in the event is still on disk afterwards', async () => {
const eventId = await seedEvent();
await touch('Trip/Leknes/a.jpg');
await touch('Trip/Leknes/b.jpg');
await touch('Trip/Sub/c.jpg');
await runImport(eventId, 'Trip');
await runImport(eventId, 'Trip/Sub');
const event = await db('events').where({ id: eventId }).first();
const photos = await db('photos').where({ event_id: eventId });
expect(photos).toHaveLength(3);
for (const photo of photos) {
expect(fs.existsSync(resolvePhotoFilePath(event, photo))).toBe(true);
}
});
it('does not re-insert a file the first import already took', async () => {
// The dedupe check compares stored paths, so it has to be comparing the
// same shape the insert writes.
const eventId = await seedEvent();
await touch('Trip/Sub/c.jpg');
await runImport(eventId, 'Trip');
const second = await runImport(eventId, 'Trip/Sub');
expect(second.body.imported).toBe(0);
expect(second.body.skipped).toBe(1);
expect(await db('photos').where({ event_id: eventId }).count('* as c').first()).toEqual({ c: 1 });
});
it('resolves a subfolder that repeats its parents name', async () => {
// The old resolver stripped the relpath's first segment when it matched the
// base path's last one, which broke exactly this layout.
const eventId = await seedEvent();
await touch('Trip/Trip/x.jpg');
await runImport(eventId, 'Trip');
const event = await db('events').where({ id: eventId }).first();
const photo = await db('photos').where({ event_id: eventId }).first();
expect(resolvePhotoFilePath(event, photo)).toBe(path.join(mediaRoot, 'Trip', 'Trip', 'x.jpg'));
});
});
@@ -0,0 +1,121 @@
/**
* PostgreSQL integration test for the external-path fold (#1163).
*
* Gated the same way as picpeakRestorePg: runs only when PICPEAK_PG_TEST_URL
* points at a throwaway Postgres DB, e.g.
* PICPEAK_PG_TEST_URL="postgres://picpeak:picpeak_secure_pass_2024@127.0.0.1:7102/picpeak_fold_test" \
* npx jest __tests__/integration/externalRelpathFoldPg.test.js
*
* This exists because of a defect SQLite could not have caught. The two-pass
* rewrite parks each row on a temporary value, and that value was first written
* with a leading NUL. SQLite stores NUL in TEXT without complaint; Postgres
* rejects it outright ("invalid byte sequence for encoding UTF8"), so migration
* 187 would have rolled back on exactly the installs needing the repair — and
* only on the engine most of them run.
*
* The staging value is therefore an engine-level contract, not an
* implementation detail, and it is pinned here on the engine that constrains it.
*/
const knex = require('knex');
const fs = require('fs');
const os = require('os');
const path = require('path');
const PG_URL = process.env.PICPEAK_PG_TEST_URL;
const maybe = PG_URL ? describe : describe.skip;
maybe('external relpath fold on Postgres', () => {
let pgDb; let mediaRoot; let fold;
const touch = async (rel, bytes) => {
const full = path.join(mediaRoot, rel);
await fs.promises.mkdir(path.dirname(full), { recursive: true });
await fs.promises.writeFile(full, Buffer.alloc(bytes));
return bytes;
};
beforeAll(async () => {
mediaRoot = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'picpeak-foldpg-'));
process.env.EXTERNAL_MEDIA_ROOT = mediaRoot;
jest.resetModules();
({ foldExternalRelpaths: fold } = require('../../src/services/externalRelpathFold'));
pgDb = knex({ client: 'pg', connection: PG_URL });
}, 60000);
afterAll(async () => {
if (pgDb) await pgDb.destroy();
await fs.promises.rm(mediaRoot, { recursive: true, force: true }).catch(() => {});
delete process.env.EXTERNAL_MEDIA_ROOT;
});
beforeEach(async () => {
await pgDb.raw('DROP TABLE IF EXISTS photos, events, app_settings CASCADE');
await pgDb.schema.createTable('events', (t) => {
t.increments('id');
t.text('external_path');
});
await pgDb.schema.createTable('photos', (t) => {
t.increments('id');
t.integer('event_id');
t.text('external_relpath');
t.bigInteger('size_bytes');
t.string('source_origin').defaultTo('managed');
});
await pgDb.schema.createTable('app_settings', (t) => {
t.increments('id');
t.string('setting_key');
t.text('setting_value');
t.string('setting_type');
t.string('updated_at');
});
await fs.promises.rm(mediaRoot, { recursive: true, force: true });
await fs.promises.mkdir(mediaRoot, { recursive: true });
});
const relpaths = async () =>
(await pgDb('photos').orderBy('id').select('external_relpath')).map((r) => r.external_relpath);
it('completes the two-pass repair that a NUL staging value would abort', async () => {
// The exact shape that forces staging: `photo.jpg` repairs up to
// `Trip/photo.jpg`, while the row already holding `Trip/photo.jpg` folds
// deeper. Every final value is distinct, but a final value equals another
// row's current one, so the rewrite has to park first.
const a = await touch('Trip/photo.jpg', 11);
const b = await touch('Trip/Sub/Trip/photo.jpg', 22);
await pgDb('events').insert({ id: 1, external_path: 'Trip/Sub' });
await pgDb('photos').insert([
{ event_id: 1, external_relpath: 'photo.jpg', size_bytes: a, source_origin: 'external' },
{ event_id: 1, external_relpath: 'Trip/photo.jpg', size_bytes: b, source_origin: 'external' },
]);
await fold(pgDb);
expect(await relpaths()).toEqual(['Trip/photo.jpg', 'Trip/Sub/Trip/photo.jpg']);
});
it('leaves no staging value behind', async () => {
await touch('Trip/a.jpg', 8);
await pgDb('events').insert({ id: 1, external_path: 'Trip' });
await pgDb('photos').insert({ event_id: 1, external_relpath: 'a.jpg', size_bytes: 8, source_origin: 'external' });
await fold(pgDb);
const rows = await relpaths();
expect(rows).toEqual(['Trip/a.jpg']);
expect(rows.some((r) => r.includes('staging'))).toBe(false);
});
it('folds and marks in one transaction', async () => {
await touch('Trip/a.jpg', 8);
await pgDb('events').insert({ id: 1, external_path: 'Trip' });
await pgDb('photos').insert({ event_id: 1, external_relpath: 'a.jpg', size_bytes: 8, source_origin: 'external' });
await fold(pgDb);
// Second run is a no-op: the marker committed with the rewrites.
await fold(pgDb);
expect(await relpaths()).toEqual(['Trip/a.jpg']);
});
});
@@ -0,0 +1,216 @@
/**
* Guest filters must respect show_feedback_to_guests (#1044 follow-up).
*
* Every filter token on /photos is an OR of two halves: what THIS viewer
* marked, and what ANYONE marked. The response fields built from the second
* half — like_count, comment_count — are all gated on
* show_feedback_to_guests. The FILTER was not.
*
* So with the setting off, the numbers were hidden but `?filter=liked` still
* returned exactly the photos other people had liked: the same information as
* a set instead of a count, one token at a time. These tests pin the gate on
* every token, and pin that the viewer's own half is never gated — filtering
* by what you yourself marked is yours to do regardless.
*/
const request = require('supertest');
const express = require('express');
const cookieParser = require('cookie-parser');
const jwt = require('jsonwebtoken');
const { bootCrmDb, seedMinimal } = require('./helpers/crmDb');
process.env.JWT_SECRET = process.env.JWT_SECRET || 'filter-visibility-secret';
const SLUG = 'filter-visibility-event';
const ME = 'guest-me-identifier';
const SOMEONE_ELSE = 'guest-other-identifier';
describe('guest filters and show_feedback_to_guests (#1044)', () => {
let db;
let cleanup;
let app;
let eventId;
let mine;
let theirs;
let myGuestRowId;
const galleryToken = () => jwt.sign(
{ eventId, eventSlug: SLUG, type: 'gallery' },
process.env.JWT_SECRET,
{ expiresIn: '1h', issuer: 'picpeak-auth' }
);
const setVisibility = (visible) => db('event_feedback_settings')
.where({ event_id: eventId })
.update({ show_feedback_to_guests: visible });
// A real verified guest, which is how the viewer's own feedback is actually
// identified — NOT the `guest_id` query parameter the frontend invents.
const guestToken = () => jwt.sign(
{ type: 'guest', guestId: myGuestRowId, eventId },
process.env.JWT_SECRET,
{ expiresIn: '1h', issuer: 'picpeak-auth' }
);
const filter = async (token, { as = 'me', claimGuestId } = {}) => {
const req = request(app)
.get(`/api/gallery/${SLUG}/photos`)
.query({ filter: token, ...(claimGuestId ? { guest_id: claimGuestId } : {}) })
.set('Authorization', `Bearer ${galleryToken()}`);
if (as === 'me') req.set('x-guest-token', guestToken());
const res = await req;
expect(res.status).toBe(200);
const photos = Array.isArray(res.body) ? res.body : res.body.photos;
return (photos || []).map((p) => p.id).sort((a, b) => a - b);
};
beforeAll(async () => {
({ db, cleanup } = await bootCrmDb());
await seedMinimal(db);
const inserted = await db('events').insert({
slug: SLUG,
event_type: 'wedding',
event_name: 'Filter Visibility',
event_date: '2026-08-01',
host_email: 'host@example.com',
admin_email: 'admin@example.com',
password_hash: 'x',
share_link: `/gallery/${SLUG}/share`,
share_token: 'filter-visibility-share',
expires_at: new Date(Date.now() + 7 * 24 * 3600 * 1000).toISOString(),
is_active: 1,
is_archived: 0,
is_draft: 0,
created_at: new Date().toISOString(),
}).returning('id');
eventId = inserted[0]?.id ?? inserted[0];
const addPhoto = async (name) => {
const p = await db('photos').insert({
event_id: eventId,
filename: name,
path: `events/filter/${name}`,
type: 'individual',
uploaded_at: new Date().toISOString(),
}).returning('id');
return p[0]?.id ?? p[0];
};
mine = await addPhoto('mine.jpg');
theirs = await addPhoto('theirs.jpg');
await db('event_feedback_settings').insert({
event_id: eventId,
feedback_enabled: true,
allow_likes: true,
allow_comments: true,
allow_ratings: true,
allow_favorites: true,
moderate_comments: false,
show_feedback_to_guests: true,
});
const guestRow = await db('gallery_guests').insert({
event_id: eventId,
name: 'Me',
identifier: ME,
created_at: new Date().toISOString(),
last_seen_at: new Date().toISOString(),
is_deleted: false,
}).returning('id');
myGuestRowId = guestRow[0]?.id ?? guestRow[0];
const feedback = (photoId, who, type, extra = {}) => db('photo_feedback').insert({
photo_id: photoId,
event_id: eventId,
guest_identifier: who,
// Submission links to the per-person guest row when one is present, and
// that is the column the viewer's own half resolves through.
guest_id: who === ME ? myGuestRowId : null,
feedback_type: type,
is_approved: true,
is_hidden: false,
created_at: new Date().toISOString(),
...extra,
});
// Everything on `theirs` belongs to somebody else; `mine` is this viewer's.
await feedback(mine, ME, 'like');
await feedback(theirs, SOMEONE_ELSE, 'like');
await feedback(theirs, SOMEONE_ELSE, 'favorite');
await feedback(theirs, SOMEONE_ELSE, 'comment', { comment_text: 'lovely' });
await feedback(theirs, SOMEONE_ELSE, 'rating', { rating: 5 });
// The denormalized counters the aggregate half of the filter reads.
await db('photos').where('id', theirs).update({
like_count: 1, favorite_count: 1, comment_count: 1, average_rating: 5,
});
await db('photos').where('id', mine).update({ like_count: 1 });
app = express();
app.use(express.json());
app.use(cookieParser());
app.use('/api/gallery', require('../../src/routes/gallery'));
}, 120000);
afterAll(async () => {
if (cleanup) await cleanup();
});
describe('with feedback visible to guests', () => {
beforeAll(() => setVisibility(true));
it('shows other people\'s marks through every token, as before', async () => {
expect(await filter('liked')).toEqual([mine, theirs].sort((a, b) => a - b));
expect(await filter('favorited')).toEqual([theirs]);
expect(await filter('rated')).toEqual([theirs]);
expect(await filter('commented')).toEqual([theirs]);
});
});
describe('with feedback hidden from guests', () => {
beforeAll(() => setVisibility(false));
it('stops every token from selecting on other people\'s marks', async () => {
// `theirs` is the photo only other guests marked. It must not come back
// through any token — a filter that selects on hidden feedback reports
// that feedback just as surely as a count would.
expect(await filter('favorited')).toEqual([]);
expect(await filter('rated')).toEqual([]);
expect(await filter('commented')).toEqual([]);
});
it('still filters by what the viewer marked themselves', async () => {
// The viewer's own half is never gated: this is their own action, and
// hiding it would break "show me the ones I liked" for no privacy gain.
expect(await filter('liked')).toEqual([mine]);
});
it('drops the viewer\'s own feedback once an admin hides it', async () => {
// Moderation has to reach the filter too. getPhotoFeedback excludes
// hidden rows for the guest's OWN feedback, so a photo matching here
// would come back with nothing visible on it to explain why.
await db('photo_feedback')
.where({ photo_id: mine, guest_id: myGuestRowId, feedback_type: 'like' })
.update({ is_hidden: true });
expect(await filter('liked')).toEqual([]);
await db('photo_feedback')
.where({ photo_id: mine, guest_id: myGuestRowId, feedback_type: 'like' })
.update({ is_hidden: false });
expect(await filter('liked')).toEqual([mine]);
});
it('ignores a guest_id supplied by the caller', async () => {
// The own-half is resolved from the request identity. If it honoured the
// query string instead, anyone holding another guest's identifier could
// read that guest's hidden memberships one token at a time — straight
// back through the gate this file exists to pin.
expect(await filter('favorited', { claimGuestId: SOMEONE_ELSE })).toEqual([]);
// And an anonymous caller claiming to be me gets nothing of mine.
expect(await filter('liked', { as: 'anon', claimGuestId: ME })).toEqual([]);
});
});
});
@@ -0,0 +1,245 @@
/**
* Hidden feedback, seen from the guest who left it (#1150).
*
* Everything in the system treats a hidden row as absent: getPhotoFeedback
* drops it even for the guest's own feedback, the /photos filters drop it, and
* updatePhotoFeedbackStats does not count it. One place disagreed — the
* per-viewer `is_liked` heart — so a like the photographer had hidden still
* showed as liked on a photo whose like_count was zero. (The `my_color_label`
* badge has the same shape on main; colour labels are not on this branch.)
*
* Making those two agree exposes the second half: the duplicate check that
* powers like/favorite toggling did NOT skip hidden rows, so the now-empty
* heart, when clicked, found the hidden row and toggled it OFF. The click
* appeared to do nothing and it took two more to get back to a filled heart.
*
* Hiding a non-comment is deliberate, not an accident of the raw route: #839
* and #1044 both ship it, with tests asserting that a hidden reaction or
* colour label stops counting. So the fix is to make hidden mean absent
* consistently — not to stop admins hiding these.
*/
const request = require('supertest');
const express = require('express');
const cookieParser = require('cookie-parser');
const jwt = require('jsonwebtoken');
const { bootCrmDb, seedMinimal } = require('./helpers/crmDb');
process.env.JWT_SECRET = process.env.JWT_SECRET || 'hidden-feedback-secret';
const SLUG = 'hidden-own-feedback';
const ME = 'guest-me-identifier';
describe('a guest\'s own hidden feedback (#1150)', () => {
let db; let cleanup; let app; let feedbackService;
let eventId; let photoId; let myGuestRowId;
const galleryToken = () => jwt.sign(
{ eventId, eventSlug: SLUG, type: 'gallery' },
process.env.JWT_SECRET,
{ expiresIn: '1h', issuer: 'picpeak-auth' }
);
const guestToken = () => jwt.sign(
{ type: 'guest', guestId: myGuestRowId, eventId },
process.env.JWT_SECRET,
{ expiresIn: '1h', issuer: 'picpeak-auth' }
);
const getPhoto = async () => {
const res = await request(app)
.get(`/api/gallery/${SLUG}/photos`)
.set('Authorization', `Bearer ${galleryToken()}`)
.set('x-guest-token', guestToken());
expect(res.status).toBe(200);
const photos = Array.isArray(res.body) ? res.body : res.body.photos;
return (photos || []).find((p) => p.id === photoId);
};
beforeAll(async () => {
({ db, cleanup } = await bootCrmDb());
await seedMinimal(db);
feedbackService = require('../../src/services/feedbackService');
const [ev] = await db('events').insert({
slug: SLUG,
event_type: 'wedding',
event_name: 'Hidden Own Feedback',
event_date: '2026-08-01',
host_email: 'h@example.com',
admin_email: 'a@example.com',
password_hash: 'x',
share_link: `/gallery/${SLUG}/share`,
share_token: 'hidden-own-share',
expires_at: new Date(Date.now() + 7 * 24 * 3600 * 1000).toISOString(),
is_active: 1, is_archived: 0, is_draft: 0,
created_at: new Date().toISOString(),
}).returning('id');
eventId = typeof ev === 'object' ? ev.id : ev;
const [p] = await db('photos').insert({
event_id: eventId, filename: 'shot.jpg', path: 'events/hidden/shot.jpg',
type: 'individual', uploaded_at: new Date().toISOString(),
}).returning('id');
photoId = typeof p === 'object' ? p.id : p;
const [g] = await db('gallery_guests').insert({
event_id: eventId, name: 'Me', identifier: ME,
created_at: new Date().toISOString(), last_seen_at: new Date().toISOString(),
is_deleted: false,
}).returning('id');
myGuestRowId = typeof g === 'object' ? g.id : g;
await db('event_feedback_settings').insert({
event_id: eventId, feedback_enabled: true, allow_likes: true,
moderate_comments: false,
show_feedback_to_guests: true,
});
app = express();
app.use(express.json());
app.use(cookieParser());
app.use('/api/gallery', require('../../src/routes/gallery'));
app.use('/api/gallery', require('../../src/routes/galleryFeedback'));
}, 180000);
afterAll(async () => { if (cleanup) await cleanup(); });
const like = () => db('photo_feedback').insert({
photo_id: photoId, event_id: eventId, guest_identifier: ME,
guest_id: myGuestRowId, feedback_type: 'like',
is_approved: true, is_hidden: false, created_at: new Date().toISOString(),
});
beforeEach(async () => {
await db('photo_feedback').where({ photo_id: photoId }).del();
await db('photos').where('id', photoId).update({ like_count: 0 });
});
describe('the read surfaces agree with each other', () => {
it('un-fills the heart once the like is hidden', async () => {
await like();
await feedbackService.updatePhotoFeedbackStats(photoId);
expect((await getPhoto()).is_liked).toBe(true);
await db('photo_feedback')
.where({ photo_id: photoId, feedback_type: 'like' })
.update({ is_hidden: true });
await feedbackService.updatePhotoFeedbackStats(photoId);
const photo = await getPhoto();
// like_count already ignored hidden rows, so the heart was the only
// thing still claiming this photo was liked.
expect(photo.like_count).toBe(0);
expect(photo.is_liked).toBe(false);
});
});
describe('and every other surface agrees', () => {
it('keeps a hidden like out of /my-feedback', async () => {
await like();
await db('photo_feedback')
.where({ photo_id: photoId, feedback_type: 'like' })
.update({ is_hidden: true });
const res = await request(app)
.get(`/api/gallery/${SLUG}/my-feedback`)
.set('Authorization', `Bearer ${galleryToken()}`)
.set('x-guest-token', guestToken());
expect(res.status).toBe(200);
// In guest identity mode the Liked/Favorited/Rated chips and their
// filters are built from THIS array, not from is_liked — so a hidden
// like left an empty heart while the chip still counted it.
expect(res.body.filter((f) => f.feedback_type === 'like')).toHaveLength(0);
});
it('does not count a hidden row against the guest cap', async () => {
await db('event_feedback_settings')
.where({ event_id: eventId }).update({ max_likes_per_guest: 1 });
await like();
await db('photo_feedback')
.where({ photo_id: photoId, feedback_type: 'like' })
.update({ is_hidden: true });
// The hidden row is room, not an occupant: the guest sees an empty
// heart, and meeting that click with limit_reached leaves the control
// dead until they un-like something they can still see.
const result = await feedbackService.submitFeedback(photoId, eventId, {
feedback_type: 'like', guest_identifier: ME, guest_id: myGuestRowId,
});
expect(result.limit_reached).toBeUndefined();
await db('event_feedback_settings')
.where({ event_id: eventId }).update({ max_likes_per_guest: null });
});
it('leaves other anonymous rows alone when there is no identity to scope by', async () => {
// With neither guest_id nor guest_identifier the collapse scope degrades
// to `guest_identifier IS NULL` — every identifier-less row on the
// photo, i.e. other people's.
const anon = (extra) => ({
photo_id: photoId, event_id: eventId, feedback_type: 'like',
is_approved: true, created_at: new Date().toISOString(), ...extra,
});
const [h] = await db('photo_feedback').insert(anon({ is_hidden: true })).returning('id');
const hiddenId = typeof h === 'object' ? h.id : h;
await db('photo_feedback').insert(anon({ is_hidden: false }));
await db('photo_feedback').insert(anon({ is_hidden: false }));
await feedbackService.moderateFeedback(hiddenId, 'approve', 1);
expect(await db('photo_feedback')
.where({ photo_id: photoId, feedback_type: 'like', is_hidden: false }))
.toHaveLength(3);
});
it('collapses the replacement when an admin unhides the original', async () => {
await like();
const original = await db('photo_feedback').where({ photo_id: photoId }).first();
await db('photo_feedback').where('id', original.id).update({ is_hidden: true });
await feedbackService.submitFeedback(photoId, eventId, {
feedback_type: 'like', guest_identifier: ME, guest_id: myGuestRowId,
});
expect(await db('photo_feedback').where({ photo_id: photoId })).toHaveLength(2);
await feedbackService.moderateFeedback(original.id, 'approve', 1);
// Two visible rows for one guest would double-count in the tallies and
// need two toggles to clear, since each deletes a single row.
const visible = await db('photo_feedback')
.where({ photo_id: photoId, feedback_type: 'like', is_hidden: false });
expect(visible).toHaveLength(1);
expect(visible[0].id).toBe(original.id);
});
});
describe('and clicking still works afterwards', () => {
it('re-liking creates a fresh row instead of toggling the hidden one off', async () => {
await like();
await db('photo_feedback')
.where({ photo_id: photoId, feedback_type: 'like' })
.update({ is_hidden: true });
// What the guest sees is an empty heart, so this is an ADD.
const result = await feedbackService.submitFeedback(photoId, eventId, {
feedback_type: 'like',
guest_identifier: ME,
guest_id: myGuestRowId,
});
// Before this, the duplicate check found the hidden row and deleted it —
// `removed: true` — so the click did nothing visible and the moderation
// was silently undone.
expect(result.removed).toBeUndefined();
const visible = await db('photo_feedback')
.where({ photo_id: photoId, feedback_type: 'like', is_hidden: false });
expect(visible).toHaveLength(1);
expect((await getPhoto()).is_liked).toBe(true);
});
});
});
@@ -0,0 +1,233 @@
/**
* Shared run state for the maintenance sweeps (#1181).
*
* The behaviour that matters here cannot be observed from one process holding
* a module-level flag, which is exactly why the flag moved into the database.
* A second replica is simulated the only way that is honest in a single-process
* test: by asserting on the shared row itself, and by driving claim() twice —
* a second caller getting null is precisely what a second replica gets.
*/
const fs = require('fs');
const path = require('path');
const os = require('os');
const express = require('express');
const request = require('supertest');
describe('maintenance job state (#1181)', () => {
let tmpDir; let db; let app; let jobs;
const dimStatus = () => request(app).get('/api/admin/photos/repair-dimensions/status');
const capStatus = () => request(app).get('/api/admin/photos/repair-capture-dates/status');
beforeAll(async () => {
tmpDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'picpeak-mjs-'));
process.env.NODE_ENV = 'test';
process.env.TEST_DATABASE_PATH = path.join(tmpDir, 'data', 'db.sqlite');
await fs.promises.mkdir(path.dirname(process.env.TEST_DATABASE_PATH), { recursive: true });
process.env.STORAGE_PATH = path.join(tmpDir, 'storage');
process.env.JWT_SECRET = process.env.JWT_SECRET || 'mjs-secret';
jest.resetModules();
jest.doMock('../../src/middleware/auth', () => ({
adminAuth: (req, _res, next) => { req.admin = { id: 1, username: 'tester', roleName: 'admin' }; next(); },
}));
jest.doMock('../../src/middleware/permissions', () => ({
requirePermission: () => (_req, _res, next) => next(),
}));
jest.doMock('../../src/utils/logger', () => ({
debug: jest.fn(), info: jest.fn(), warn: jest.fn(), error: jest.fn(),
}));
({ db } = await require('./helpers/crmDb').bootCrmDb());
jobs = require('../../src/services/maintenanceJobState');
app = express();
app.use(express.json());
app.use('/api/admin/photos', require('../../src/routes/adminPhotoDimensions'));
}, 180000);
afterAll(async () => {
if (db) await db.destroy?.();
await fs.promises.rm(tmpDir, { recursive: true, force: true }).catch(() => {});
});
beforeEach(async () => {
await db('maintenance_jobs').update({
is_running: false, started_at: null, heartbeat_at: null, finished_at: null, last_result: null, owner: null, claim_token: null,
});
});
test('the lease table is kept out of .picpeak archives', () => {
// It is live state, not data. An archive taken mid-sweep would otherwise
// carry is_running = true and a claim token owned by a process on the
// SOURCE install; restored inside the staleness window, the target reports
// the job as running and refuses new POSTs with no runner to release it.
// The importer filters on this same set, so archives written before the
// exclusion are skipped on restore too.
const { EXCLUDED_TABLES } = require('../../src/services/picpeakExportService');
expect(EXCLUDED_TABLES.has('maintenance_jobs')).toBe(true);
});
test('the migration seeds a row for each job', async () => {
const names = await db('maintenance_jobs').pluck('job_name');
expect(names.sort()).toEqual(['photo_capture_date_backfill', 'photo_dimension_repair']);
});
test('a second claim is refused while the first is alive', async () => {
expect(await jobs.claim(jobs.JOB_DIMENSION_REPAIR)).toEqual(expect.any(String));
// What a second replica's POST does. Nothing about the first claim lives in
// this process, so this is the same question the other replica asks.
expect(await jobs.claim(jobs.JOB_DIMENSION_REPAIR)).toBeNull();
});
test('the two jobs claim independently', async () => {
expect(await jobs.claim(jobs.JOB_DIMENSION_REPAIR)).toEqual(expect.any(String));
expect(await jobs.claim(jobs.JOB_CAPTURE_DATE_BACKFILL)).toEqual(expect.any(String));
});
test('each claim gets a distinct token', async () => {
const first = await jobs.claim(jobs.JOB_DIMENSION_REPAIR);
await jobs.release(jobs.JOB_DIMENSION_REPAIR, first);
const second = await jobs.claim(jobs.JOB_DIMENSION_REPAIR);
// Same process, same pid — so an owner string would have collided here and
// the fencing below would be worthless.
expect(second).not.toBe(first);
});
test('a claim whose heartbeat has gone quiet can be taken over', async () => {
expect(await jobs.claim(jobs.JOB_DIMENSION_REPAIR)).toEqual(expect.any(String));
expect(await jobs.claim(jobs.JOB_DIMENSION_REPAIR)).toBeNull();
// The replica holding it was killed: no release, no further heartbeats.
const longAgo = new Date(Date.now() - jobs.DEFAULT_STALE_MS - 60000).toISOString();
await db('maintenance_jobs').where({ job_name: jobs.JOB_DIMENSION_REPAIR }).update({ heartbeat_at: longAgo });
expect(await jobs.claim(jobs.JOB_DIMENSION_REPAIR)).toEqual(expect.any(String));
});
test('a superseded runner cannot renew its lease', async () => {
const oldToken = await jobs.claim(jobs.JOB_DIMENSION_REPAIR);
const longAgo = new Date(Date.now() - jobs.DEFAULT_STALE_MS - 60000).toISOString();
await db('maintenance_jobs').where({ job_name: jobs.JOB_DIMENSION_REPAIR }).update({ heartbeat_at: longAgo });
const newToken = await jobs.claim(jobs.JOB_DIMENSION_REPAIR);
expect(newToken).toEqual(expect.any(String));
// The old runner is still alive and mid-loop. Its renewal must tell it so,
// which is what makes the route loop stop instead of running alongside the
// new owner.
expect(await jobs.heartbeat(jobs.JOB_DIMENSION_REPAIR, oldToken)).toBe(false);
expect(await jobs.heartbeat(jobs.JOB_DIMENSION_REPAIR, newToken)).toBe(true);
});
test('a superseded runner cannot release the new owner\'s claim', async () => {
const oldToken = await jobs.claim(jobs.JOB_CAPTURE_DATE_BACKFILL);
const longAgo = new Date(Date.now() - jobs.DEFAULT_STALE_MS - 60000).toISOString();
await db('maintenance_jobs').where({ job_name: jobs.JOB_CAPTURE_DATE_BACKFILL }).update({ heartbeat_at: longAgo });
const newToken = await jobs.claim(jobs.JOB_CAPTURE_DATE_BACKFILL);
// The old runner finishes late and tries to write its result. Unfenced,
// this cleared is_running under the new owner and let a THIRD sweep start.
expect(await jobs.release(jobs.JOB_CAPTURE_DATE_BACKFILL, oldToken, { success: 999, noExif: 0, failed: 0 })).toBe(false);
const state = await jobs.read(jobs.JOB_CAPTURE_DATE_BACKFILL);
expect(state.isRunning).toBe(true);
expect(state.lastResult).toBeNull();
// And the row is still the new owner's to release.
expect(await jobs.release(jobs.JOB_CAPTURE_DATE_BACKFILL, newToken, { success: 1, noExif: 0, failed: 0 })).toBe(true);
});
test('a stale run reads as not running, so the button comes back', async () => {
await jobs.claim(jobs.JOB_DIMENSION_REPAIR);
expect((await jobs.read(jobs.JOB_DIMENSION_REPAIR)).isRunning).toBe(true);
const longAgo = new Date(Date.now() - jobs.DEFAULT_STALE_MS - 60000).toISOString();
await db('maintenance_jobs').where({ job_name: jobs.JOB_DIMENSION_REPAIR }).update({ heartbeat_at: longAgo });
// is_running is still true in the row — nothing released it — but a status
// poll must not leave the operator staring at a job that cannot finish.
expect((await db('maintenance_jobs').where({ job_name: jobs.JOB_DIMENSION_REPAIR }).first()).is_running).toBeTruthy();
expect((await jobs.read(jobs.JOB_DIMENSION_REPAIR)).isRunning).toBe(false);
});
test('a heartbeat keeps a long run claimed', async () => {
const token = await jobs.claim(jobs.JOB_DIMENSION_REPAIR);
const longAgo = new Date(Date.now() - jobs.DEFAULT_STALE_MS - 60000).toISOString();
await db('maintenance_jobs').where({ job_name: jobs.JOB_DIMENSION_REPAIR }).update({ heartbeat_at: longAgo });
expect(await jobs.heartbeat(jobs.JOB_DIMENSION_REPAIR, token)).toBe(true);
expect(await jobs.claim(jobs.JOB_DIMENSION_REPAIR)).toBeNull();
expect((await jobs.read(jobs.JOB_DIMENSION_REPAIR)).isRunning).toBe(true);
});
test('release stores the result and read gives it back parsed', async () => {
const token = await jobs.claim(jobs.JOB_CAPTURE_DATE_BACKFILL);
await jobs.release(jobs.JOB_CAPTURE_DATE_BACKFILL, token, { success: 3, noExif: 2, failed: 1 });
const state = await jobs.read(jobs.JOB_CAPTURE_DATE_BACKFILL);
expect(state.isRunning).toBe(false);
expect(state.lastResult).toEqual({ success: 3, noExif: 2, failed: 1 });
});
test('releasing without a result keeps the previous run visible', async () => {
const first = await jobs.claim(jobs.JOB_CAPTURE_DATE_BACKFILL);
await jobs.release(jobs.JOB_CAPTURE_DATE_BACKFILL, first, { success: 7, noExif: 0, failed: 0 });
// The "nothing to do" path: claimed, found no candidates, released. It must
// not blank the numbers the last real run reported.
const second = await jobs.claim(jobs.JOB_CAPTURE_DATE_BACKFILL);
await jobs.release(jobs.JOB_CAPTURE_DATE_BACKFILL, second);
expect((await jobs.read(jobs.JOB_CAPTURE_DATE_BACKFILL)).lastResult).toEqual({ success: 7, noExif: 0, failed: 0 });
});
test('a malformed result does not take the status endpoint down', async () => {
await db('maintenance_jobs').where({ job_name: jobs.JOB_DIMENSION_REPAIR }).update({ last_result: 'not json' });
const state = await jobs.read(jobs.JOB_DIMENSION_REPAIR);
expect(state.lastResult).toBeNull();
expect(state.isRunning).toBe(false);
});
test('both status endpoints report the shared row, not process memory', async () => {
await jobs.claim(jobs.JOB_DIMENSION_REPAIR);
const capToken = await jobs.claim(jobs.JOB_CAPTURE_DATE_BACKFILL);
await jobs.release(jobs.JOB_CAPTURE_DATE_BACKFILL, capToken, { success: 1, noExif: 0, failed: 0 });
// Written straight to the row, exactly as another replica would have.
const dim = await dimStatus();
expect(dim.status).toBe(200);
expect(dim.body.isRunning).toBe(true);
const cap = await capStatus();
expect(cap.status).toBe(200);
expect(cap.body.isRunning).toBe(false);
expect(cap.body.lastResult).toEqual({ success: 1, noExif: 0, failed: 0 });
});
test('a POST is refused while another replica holds the claim', async () => {
// The claim was taken by "another replica" — this process knows nothing
// about it beyond the row.
await jobs.claim(jobs.JOB_CAPTURE_DATE_BACKFILL);
const res = await request(app).post('/api/admin/photos/repair-capture-dates');
expect(res.status).toBe(409);
const dimRes = await request(app).post('/api/admin/photos/repair-dimensions');
// The other job is untouched by that claim, so it is free to start.
expect(dimRes.status).toBe(200);
});
test('the no-op path releases the claim it took', async () => {
// No photos at all, so both endpoints take their "nothing to do" exit.
await db('photos').del();
const res = await request(app).post('/api/admin/photos/repair-capture-dates');
expect(res.body.count).toBe(0);
const row = await db('maintenance_jobs').where({ job_name: jobs.JOB_CAPTURE_DATE_BACKFILL }).first();
expect(row.is_running).toBeFalsy();
// ...and a second POST is therefore accepted rather than 409ing forever.
expect((await request(app).post('/api/admin/photos/repair-capture-dates')).status).toBe(200);
});
});
@@ -0,0 +1,102 @@
/**
* PostgreSQL checks for the shared maintenance-job state (#1181).
* Gated: runs only when PICPEAK_PG_TEST_URL points at a throwaway database, e.g.
* PICPEAK_PG_TEST_URL="postgres://picpeak:picpeak_secure_pass_2024@127.0.0.1:7102/picpeak_mjs_test" \
* npx jest __tests__/integration/maintenanceJobStatePg.test.js
*
* What SQLite cannot answer: the claim leans on comparing a `timestamp` column
* against an ISO-8601 string, and on an UPDATE ... WHERE guard being atomic
* under real concurrent connections. SQLite compares those strings
* lexicographically and serialises writes anyway, so it would pass either way —
* exactly the shape of divergence that has bitten this repo before.
*/
const knex = require('knex');
const PG_URL = process.env.PICPEAK_PG_TEST_URL;
const maybe = PG_URL ? describe : describe.skip;
maybe('maintenance job state on Postgres', () => {
let pgDb;
let jobs;
const JOB = 'photo_dimension_repair';
beforeAll(async () => {
pgDb = knex({ client: 'pg', connection: PG_URL, pool: { min: 0, max: 10 } });
await pgDb.raw('DROP TABLE IF EXISTS maintenance_jobs');
await require('../../migrations/core/179_maintenance_job_state').up(pgDb);
jest.resetModules();
jest.doMock('../../src/database/db', () => ({ db: pgDb }));
jest.doMock('../../src/utils/logger', () => ({
debug: jest.fn(), info: jest.fn(), warn: jest.fn(), error: jest.fn(),
}));
jobs = require('../../src/services/maintenanceJobState');
}, 60000);
afterAll(async () => {
jest.dontMock('../../src/database/db');
if (pgDb) await pgDb.destroy();
});
beforeEach(async () => {
await pgDb('maintenance_jobs').update({
is_running: false, started_at: null, heartbeat_at: null, finished_at: null, last_result: null, owner: null, claim_token: null,
});
});
test('the ISO-string cutoff really compares as a timestamp, not as text', async () => {
expect(await jobs.claim(JOB)).toEqual(expect.any(String));
expect(await jobs.claim(JOB)).toBeNull();
await pgDb('maintenance_jobs').where({ job_name: JOB })
.update({ heartbeat_at: new Date(Date.now() - jobs.DEFAULT_STALE_MS - 60000).toISOString() });
// If Postgres had rejected or mis-cast the ISO string this would either
// throw or never match.
expect(await jobs.claim(JOB)).toEqual(expect.any(String));
const row = await pgDb('maintenance_jobs').where({ job_name: JOB }).first();
expect(row.heartbeat_at).toBeInstanceOf(Date);
});
test('concurrent claims on real connections produce exactly one winner', async () => {
// The whole point of the conditional UPDATE. Ten connections race; nine
// must lose. SQLite cannot demonstrate this — it serialises writers.
const results = await Promise.all(Array.from({ length: 10 }, () => jobs.claim(JOB)));
expect(results.filter(Boolean)).toHaveLength(1);
// ...and the winner holds a token nobody else can forge.
expect(results.find(Boolean)).toEqual(expect.any(String));
});
test('a released job can be re-claimed exactly once again', async () => {
const token = await jobs.claim(JOB);
await jobs.release(JOB, token, { success: 2, failed: 0 });
const results = await Promise.all(Array.from({ length: 5 }, () => jobs.claim(JOB)));
expect(results.filter(Boolean)).toHaveLength(1);
expect((await jobs.read(JOB)).lastResult).toEqual({ success: 2, failed: 0 });
});
test('a superseded runner is fenced out on real Postgres', async () => {
const oldToken = await jobs.claim(JOB);
await pgDb('maintenance_jobs').where({ job_name: JOB })
.update({ heartbeat_at: new Date(Date.now() - jobs.DEFAULT_STALE_MS - 60000).toISOString() });
const newToken = await jobs.claim(JOB);
expect(await jobs.heartbeat(JOB, oldToken)).toBe(false);
expect(await jobs.release(JOB, oldToken, { success: 999, failed: 0 })).toBe(false);
// The new owner still holds it, with its result unwritten.
expect((await jobs.read(JOB)).isRunning).toBe(true);
expect(await jobs.release(JOB, newToken, { success: 4, failed: 0 })).toBe(true);
});
test('read() reports a live claim as running and a stale one as not', async () => {
await jobs.claim(JOB);
expect((await jobs.read(JOB)).isRunning).toBe(true);
await pgDb('maintenance_jobs').where({ job_name: JOB })
.update({ heartbeat_at: new Date(Date.now() - jobs.DEFAULT_STALE_MS - 1000).toISOString() });
expect((await jobs.read(JOB)).isRunning).toBe(false);
});
});
@@ -0,0 +1,260 @@
/**
* scripts/regenerate-thumbnails.js against external photos (#1148).
*
* The same defect #1129 fixed in the admin route, still standing in the CLI
* fallback: the script resolved every source as
* `storage/events/active/<photo.path>` and fs.access'd it. External and
* reference rows do not live there — their originals sit under
* `events.external_path` — so every one failed the check and was counted as an
* error. On an install where all photos are external the script did nothing at
* all, while reporting one error per photo.
*
* Driven against a REAL file on a REAL external mount with the real
* imageProcessor, not a mock: the whole point is that the source resolves off
* the mount, and a mocked ensureThumbnail would assert nothing about that.
*
* Responsive tiers (#1095/#1109) do not exist on this branch, so the tier
* backfill in the main twin has nothing to port. Everything else does.
*/
const fs = require('fs');
const path = require('path');
const os = require('os');
const sharp = require('sharp');
const { execFile } = require('child_process');
describe('regenerate-thumbnails script (#1148)', () => {
let tmpDir; let db; let cleanup; let regenerateThumbnails;
let eventId; let externalPhotoId; let videoPhotoId; let watcherVideoId; let repairPhotoId;
let vanishingPhotoId;
let externalRoot;
beforeAll(async () => {
tmpDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'picpeak-regen-script-'));
process.env.NODE_ENV = 'test';
process.env.TEST_DATABASE_PATH = path.join(tmpDir, 'data', 'test.db');
process.env.STORAGE_PATH = path.join(tmpDir, 'storage');
// External sources are sandboxed under EXTERNAL_MEDIA_ROOT. Rows carry a
// path relative to that root (#1163), so the 'wedding/' prefix on each
// external_relpath below is the event folder, not decoration.
process.env.EXTERNAL_MEDIA_ROOT = path.join(tmpDir, 'media');
externalRoot = path.join(process.env.EXTERNAL_MEDIA_ROOT, 'wedding');
await fs.promises.mkdir(path.dirname(process.env.TEST_DATABASE_PATH), { recursive: true });
await fs.promises.mkdir(process.env.STORAGE_PATH, { recursive: true });
await fs.promises.mkdir(externalRoot, { recursive: true });
jest.resetModules();
({ db, cleanup } = await require('./helpers/crmDb').bootCrmDb());
// A real image on the external mount — never under events/active.
await sharp({
create: { width: 1200, height: 800, channels: 3, background: { r: 10, g: 90, b: 160 } },
}).jpeg().toFile(path.join(externalRoot, 'shot.jpg'));
const [ev] = await db('events').insert({
slug: 'regen-script-event',
event_type: 'wedding',
event_name: 'Regen Script',
event_date: '2026-08-01',
host_email: 'h@example.com',
admin_email: 'a@example.com',
password_hash: 'x',
share_link: '/gallery/regen-script-event/share',
expires_at: new Date(Date.now() + 7 * 24 * 3600 * 1000).toISOString(),
source_mode: 'reference',
external_path: 'wedding',
created_at: new Date().toISOString(),
}).returning('id');
eventId = typeof ev === 'object' ? ev.id : ev;
const [p] = await db('photos').insert({
event_id: eventId,
filename: 'shot.jpg',
// `path` is what the old script joined onto events/active. Left
// populated on purpose: the fix must ignore it for an external row.
path: 'regen-script-event/shot.jpg',
type: 'individual',
source_origin: 'external',
external_relpath: 'wedding/shot.jpg',
uploaded_at: new Date().toISOString(),
}).returning('id');
externalPhotoId = typeof p === 'object' ? p.id : p;
const [v] = await db('photos').insert({
event_id: eventId,
filename: 'clip.mp4',
path: 'regen-script-event/clip.mp4',
type: 'individual',
media_type: 'video',
mime_type: 'video/mp4',
source_origin: 'external',
external_relpath: 'wedding/clip.mp4',
uploaded_at: new Date().toISOString(),
}).returning('id');
videoPhotoId = typeof v === 'object' ? v.id : v;
// How fileWatcher.processNewPhoto actually writes a video: `type` and
// `mime_type` set, media_type left to its 'image' default. A media_type-only
// filter lets this through and hands the container to Sharp.
//
// The file has to EXIST, otherwise the row fails resolution and looks
// skipped for the wrong reason — the bug is Sharp being handed a video, not
// a missing source. Real MP4 header bytes, no image in sight.
await fs.promises.writeFile(
path.join(externalRoot, 'watched.mp4'),
Buffer.from('00000018667479706d70343200000000', 'hex')
);
const [wv] = await db('photos').insert({
event_id: eventId,
filename: 'watched.mp4',
path: 'regen-script-event/watched.mp4',
type: 'video',
mime_type: 'video/mp4',
source_origin: 'external',
external_relpath: 'wedding/watched.mp4',
uploaded_at: new Date().toISOString(),
}).returning('id');
watcherVideoId = typeof wv === 'object' ? wv.id : wv;
expect((await db('photos').where('id', watcherVideoId).first()).media_type).not.toBe('video');
// A photo whose thumbnail_path points at something that is no longer there.
await sharp({
create: { width: 900, height: 600, channels: 3, background: { r: 200, g: 40, b: 40 } },
}).jpeg().toFile(path.join(externalRoot, 'repair.jpg'));
const [rp] = await db('photos').insert({
event_id: eventId,
filename: 'repair.jpg',
path: 'regen-script-event/repair.jpg',
type: 'individual',
thumbnail_path: 'thumbnails/thumb_ext_missing_repair.jpg',
source_origin: 'external',
external_relpath: 'wedding/repair.jpg',
uploaded_at: new Date().toISOString(),
}).returning('id');
repairPhotoId = typeof rp === 'object' ? rp.id : rp;
// A photo whose source is not on the mount at all — an unavailable mount,
// which is the failure an operator most needs to hear about.
const [vp] = await db('photos').insert({
event_id: eventId,
filename: 'missing.jpg',
path: 'regen-script-event/missing.jpg',
type: 'individual',
source_origin: 'external',
external_relpath: 'missing.jpg',
uploaded_at: new Date().toISOString(),
}).returning('id');
vanishingPhotoId = typeof vp === 'object' ? vp.id : vp;
({ regenerateThumbnails } = require('../../scripts/regenerate-thumbnails'));
}, 180000);
afterAll(async () => {
if (cleanup) await cleanup();
await fs.promises.rm(tmpDir, { recursive: true, force: true }).catch(() => {});
});
it('builds a thumbnail for an external photo instead of erroring on events/active', async () => {
// The location the old script computed and fs.access'd. Nothing is there,
// which is the whole defect — it is not where an external original lives.
// (The old script cannot be driven from a test directly: it had no export
// and ran on require, calling process.exit. Making it importable is part
// of this fix.)
const legacyPath = path.join(process.env.STORAGE_PATH, 'events/active', 'regen-script-event/shot.jpg');
expect(fs.existsSync(legacyPath)).toBe(false);
const result = await regenerateThumbnails(eventId);
// The old script reported an error for this photo and wrote nothing.
// The unresolvable row fails; the external photo and the repair row build.
expect(result.errorCount).toBe(1);
expect(result.successCount).toBe(2);
const row = await db('photos').where('id', externalPhotoId).first();
expect(row.thumbnail_path).toBeTruthy();
const onDisk = path.join(process.env.STORAGE_PATH, row.thumbnail_path);
expect(fs.existsSync(onDisk)).toBe(true);
// Named per-photo so two events referencing one NAS basename cannot
// clobber each other — the property ensureThumbnail owns and the reason
// the script must not build this name itself.
expect(path.basename(row.thumbnail_path)).toContain(`ext${externalPhotoId}_`);
});
it('leaves videos alone', async () => {
// A video thumbnail is a poster frame from videoProcessor; handing the
// container to Sharp produced one error per video row.
const row = await db('photos').where('id', videoPhotoId).first();
expect(row.thumbnail_path).toBeFalsy();
});
it('leaves a watcher-imported video alone, which carries no media_type', async () => {
// fileWatcher writes type + mime_type and lets media_type default to
// 'image', so filtering on media_type alone still fed these to Sharp. The
// signal is errorCount: the images are already done by now, so the only
// NEW thing that could fail this run is a video reaching Sharp. One error
// is the deliberately unresolvable row; two would be the video.
const result = await regenerateThumbnails(eventId);
expect(result.errorCount).toBe(1);
const row = await db('photos').where('id', watcherVideoId).first();
expect(row.thumbnail_path).toBeFalsy();
});
it('is idempotent — a second run skips instead of rebuilding', async () => {
const before = await db('photos').where('id', externalPhotoId).first();
const result = await regenerateThumbnails(eventId);
expect(result.errorCount).toBe(1);
expect(result.successCount).toBe(0);
expect(result.skipCount).toBe(2);
const after = await db('photos').where('id', externalPhotoId).first();
expect(after.thumbnail_path).toBe(before.thumbnail_path);
});
it('counts a repaired thumbnail as generated, not skipped', async () => {
// Both images are valid at this point. Destroy ONE thumbnail object while
// leaving thumbnail_path pointing at it — the corrupt/missing case.
const row = await db('photos').where('id', repairPhotoId).first();
const onDisk = path.join(process.env.STORAGE_PATH, row.thumbnail_path);
await fs.promises.rm(onDisk);
const result = await regenerateThumbnails(eventId);
// On local and external storage the rebuilt key is identical, so inferring
// "skipped" from an unchanged path reports this repair as already valid —
// the one number an operator running this is actually reading.
expect(result.successCount).toBe(1);
expect(result.skipCount).toBe(1);
expect(result.errorCount).toBe(1);
expect(fs.existsSync(onDisk)).toBe(true);
});
/** Run the CLI the way cron does, and hand back its exit status. */
const runCli = (args = []) => new Promise((resolve) => {
execFile(
process.execPath,
[path.join(__dirname, '..', '..', 'scripts', 'regenerate-thumbnails.js'), ...args],
{ env: { ...process.env }, cwd: path.join(__dirname, '..', '..') },
(error, stdout, stderr) => resolve({ code: error?.code ?? 0, stdout, stderr })
);
});
it('exits nonzero when a photo could not be built', async () => {
// Exit status is the only thing a cron job reads, and `missing.jpg` has no
// source on the mount.
const failed = await runCli([String(eventId)]);
expect(failed.code).toBe(1);
expect(failed.stderr).toContain('completed with failures');
}, 120000);
it('exits zero when every photo resolves', async () => {
// Drop the unresolvable row: a clean run must not cry wolf at automation.
await db('photos').where('id', vanishingPhotoId).del();
const ok = await runCli([String(eventId)]);
expect(ok.code).toBe(0);
expect(ok.stdout).toContain('Script completed successfully');
}, 120000);
});
@@ -0,0 +1,242 @@
/**
* Repairing the bundled templates' fixed image height (#1131).
*
* The risk in a migration that rewrites user-visible CSS is doing too much,
* so most of what is pinned here is what it must NOT touch: the other pixel
* heights inside the very same templates (a 1px divider, an 8px scrollbar),
* and any rule a user wrote themselves.
*/
const path = require('path');
const fs = require('fs');
const os = require('os');
const migration = require('../../migrations/core/175_fix_css_template_photo_height');
const ELEGANT_DARK = `
.photo-card {
border-radius: 12px;
}
.photo-card img {
width: 100%;
height: 200px;
object-fit: cover;
transition: transform 0.3s ease;
}
`;
const LIQUID_GLASS_DARK = `
.gallery-page::after {
content: '';
height: 1px;
background: linear-gradient(90deg, transparent, #fff, transparent);
}
.photo-card img {
width: 100%;
height: 240px;
object-fit: cover;
filter: brightness(0.9);
}
.gallery-page ::-webkit-scrollbar {
width: 8px;
height: 8px;
}
@media (max-width: 640px) {
.photo-card img {
height: 180px;
}
}
`;
describe('migration 175 — CSS template image height (#1131)', () => {
let knex; let tmpDir;
beforeAll(async () => {
tmpDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'picpeak-mig175-'));
knex = require('knex')({
client: 'sqlite3',
connection: { filename: path.join(tmpDir, 'db.sqlite') },
useNullAsDefault: true,
});
await knex.schema.createTable('css_templates', (t) => {
t.increments('id').primary();
t.string('name');
t.text('css_content');
});
});
afterAll(async () => {
if (knex) await knex.destroy();
await fs.promises.rm(tmpDir, { recursive: true, force: true }).catch(() => {});
});
beforeEach(async () => { await knex('css_templates').del(); });
const contentOf = async (name) =>
(await knex('css_templates').where({ name }).first()).css_content;
it('relaxes the default template so the layouts h-full can win', async () => {
await knex('css_templates').insert({ name: 'Elegant Dark', css_content: ELEGANT_DARK });
await migration.up(knex);
const css = await contentOf('Elegant Dark');
expect(css).toContain('height: 100%');
expect(css).not.toContain('height: 200px');
// Everything else about the rule survives.
expect(css).toContain('object-fit: cover');
expect(css).toContain('transition: transform 0.3s ease');
});
it('fixes both the base rule and the mobile override of the dark glass template', async () => {
await knex('css_templates').insert({ name: 'Liquid Glass Dark', css_content: LIQUID_GLASS_DARK });
await migration.up(knex);
const css = await contentOf('Liquid Glass Dark');
expect(css).not.toContain('height: 240px');
expect(css).not.toContain('height: 180px');
expect(css.match(/height: 100%/g)).toHaveLength(2);
});
it('leaves the divider and the scrollbar alone', async () => {
await knex('css_templates').insert({ name: 'Liquid Glass Dark', css_content: LIQUID_GLASS_DARK });
await migration.up(knex);
// The whole reason this matches full rule bodies rather than every
// `height: <n>px`: these are in the same stylesheet and are correct.
const css = await contentOf('Liquid Glass Dark');
expect(css).toContain('height: 1px');
expect(css).toContain('width: 8px');
expect(css).toContain('height: 8px');
});
/**
* The case that forced the scope wider. `sanitizeCSS` strips control
* characters, so any template ever saved through the editor — including a
* save that only changed its name — has had every newline REMOVED. An
* exact-text migration finds nothing on those installs, is recorded as
* applied, and leaves them broken permanently.
*/
it('fixes a template that has been through the editor, newlines and all', async () => {
const { sanitizeCSS } = require('../../src/utils/cssSanitizer');
const { sanitized } = sanitizeCSS(ELEGANT_DARK);
// Precondition: the sanitizer really did flatten it.
expect(sanitized).not.toContain('\n');
expect(sanitized).toContain('height: 200px');
await knex('css_templates').insert({ name: 'Saved Once', css_content: sanitized });
await migration.up(knex);
const css = await contentOf('Saved Once');
expect(css).not.toContain('200px');
expect(css).toContain('height: 100%');
});
it('relaxes a user-authored fixed height too, but only on .photo-card img', async () => {
// Deliberately broader than the seeded text — see the migration header. A
// pixel height on the image cannot be right under any of the seven
// layouts, whoever wrote it; a height anywhere else is none of our
// business.
const mine = '.photo-card img {\n height: 220px;\n}\n.hero { height: 400px; }';
await knex('css_templates').insert({ name: 'My Own', css_content: mine });
await migration.up(knex);
const css = await contentOf('My Own');
expect(css).toContain('height: 100%');
expect(css).not.toContain('220px');
expect(css).toContain('.hero { height: 400px; }');
});
it('does not rewrite other properties that merely end in -height', async () => {
// `line-height: 200px` contains `height: 200px` as a substring, so an
// unanchored pattern silently rewrites it — in a migration that cannot be
// undone.
const mine = [
'.photo-card img {',
' line-height: 200px;',
' max-height: 300px;',
' min-height: 14px;',
' --tile-height: 220px;',
' height: 200px;',
'}',
].join('\n');
await knex('css_templates').insert({ name: 'Adjacent Props', css_content: mine });
await migration.up(knex);
const css = await contentOf('Adjacent Props');
expect(css).toContain('line-height: 200px');
expect(css).toContain('max-height: 300px');
expect(css).toContain('min-height: 14px');
expect(css).toContain('--tile-height: 220px');
// Only the real one moved.
expect(css).toContain('height: 100%');
expect(css).not.toMatch(/(?<![\w-])height:\s*200px/);
});
it('handles a grouped selector list', async () => {
// Requiring `{` straight after `img` skipped these entirely — and the
// migration is still recorded as applied, so the template kept the bug.
const mine = '.photo-card img, .thumbnail img {\n height: 200px;\n}';
await knex('css_templates').insert({ name: 'Grouped', css_content: mine });
await migration.up(knex);
const css = await contentOf('Grouped');
expect(css).toContain('.photo-card img, .thumbnail img {');
expect(css).toContain('height: 100%');
expect(css).not.toContain('200px');
});
it('skips a nested rule rather than rewriting the wrong declaration', async () => {
// Valid nested CSS that passes the validator. A brace-greedy body would
// capture the inner block and rewrite the CAPTION's height, which cannot
// be undone. Leaving it untouched is the lesser evil.
const mine = '.photo-card img {\n & + .caption { height: 200px; }\n}';
await knex('css_templates').insert({ name: 'Nested', css_content: mine });
await migration.up(knex);
expect(await contentOf('Nested')).toBe(mine);
});
it('leaves non-pixel heights on the image alone', async () => {
const mine = '.photo-card img { height: 50vh; }\n.photo-card img { height: auto; }';
await knex('css_templates').insert({ name: 'Relative', css_content: mine });
await migration.up(knex);
expect(await contentOf('Relative')).toBe(mine);
});
it('is idempotent and safe on a row with no CSS', async () => {
await knex('css_templates').insert([
{ name: 'Elegant Dark', css_content: ELEGANT_DARK },
{ name: 'Empty', css_content: null },
]);
await migration.up(knex);
const once = await contentOf('Elegant Dark');
await migration.up(knex);
expect(await contentOf('Elegant Dark')).toBe(once);
expect(await contentOf('Empty')).toBeNull();
});
it('no-ops when the table does not exist yet', async () => {
await knex.schema.dropTable('css_templates');
await expect(migration.up(knex)).resolves.toBeUndefined();
await knex.schema.createTable('css_templates', (t) => {
t.increments('id').primary();
t.string('name');
t.text('css_content');
});
});
});
@@ -0,0 +1,546 @@
/**
* One row per external file per event (#1162).
*
* The migration has two halves and they fail differently: the cleanup can take
* out the wrong row of a pair (losing a thumbnail, orphaning an event's hero),
* and the index can fail to be created at all — leaving an install that looks
* migrated and is still racing. Both are pinned here.
*/
const path = require('path');
const fs = require('fs');
const os = require('os');
const migration = require('../../migrations/core/176_external_relpath_unique');
describe('migration 176 — unique (event_id, external_relpath) (#1162)', () => {
let knex; let tmpDir;
beforeAll(async () => {
tmpDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'picpeak-mig186-'));
knex = require('knex')({
client: 'sqlite3',
connection: { filename: path.join(tmpDir, 'db.sqlite') },
useNullAsDefault: true,
});
});
afterAll(async () => {
if (knex) await knex.destroy();
await fs.promises.rm(tmpDir, { recursive: true, force: true }).catch(() => {});
});
beforeEach(async () => {
for (const table of [
'photos', 'events', 'photo_categories', 'photo_feedback',
'photo_admin_marks', 'photo_faces', 'image_access_logs', 'transfer_files',
]) {
await knex.schema.dropTableIfExists(table);
}
await knex.schema.createTable('events', (t) => {
t.increments('id').primary();
t.integer('hero_photo_id');
t.string('download_zip_path');
t.string('download_zip_generated_at');
});
await knex.schema.createTable('photo_categories', (t) => {
t.increments('id').primary();
t.integer('hero_photo_id');
});
await knex.schema.createTable('photos', (t) => {
t.increments('id').primary();
t.integer('event_id');
t.string('external_relpath');
t.string('thumbnail_path');
t.string('source_origin').defaultTo('managed');
t.integer('feedback_count').defaultTo(0);
t.integer('like_count').defaultTo(0);
t.decimal('average_rating', 3, 2).defaultTo(0);
t.integer('favorite_count').defaultTo(0);
t.integer('reaction_count').defaultTo(0);
t.integer('color_label_count').defaultTo(0);
t.string('face_status');
t.integer('view_count').defaultTo(0);
t.integer('download_count').defaultTo(0);
t.integer('face_count');
t.string('face_started_at');
t.text('face_error');
});
// Declared exactly as the real schema declares them — CASCADE and all.
// The point of these tables here is that SQLite does NOT enforce any of
// it (PicPeak never sets `PRAGMA foreign_keys = ON`), so a bare delete of
// the photo row leaves every one of them dangling.
await knex.schema.createTable('photo_feedback', (t) => {
t.increments('id').primary();
t.integer('photo_id').references('id').inTable('photos').onDelete('CASCADE');
t.integer('event_id');
t.string('feedback_type');
t.text('comment_text');
t.string('guest_identifier');
// Per-person guest identity (migration 078). Nullable: galleries without
// guest identity leave it NULL and fall back to guest_identifier.
t.integer('guest_id');
t.integer('rating');
t.boolean('is_hidden').defaultTo(false);
t.boolean('is_approved').defaultTo(true);
});
await knex.schema.createTable('photo_admin_marks', (t) => {
t.increments('id').primary();
t.integer('photo_id').notNullable().references('id').inTable('photos').onDelete('CASCADE');
t.integer('event_id');
t.integer('admin_id');
t.integer('rating');
// Independently writable alongside rating, per photoAdminMarksService.
t.string('color_label', 16);
t.unique(['photo_id', 'admin_id'], 'photo_admin_marks_photo_admin_uniq');
});
await knex.schema.createTable('photo_faces', (t) => {
t.increments('id').primary();
t.integer('photo_id').references('id').inTable('photos').onDelete('CASCADE');
t.integer('event_id');
// purgePhotoFaces rebuilds the people that lose members, so the cluster
// link and the vectors recomputeCentroid reads have to be here for this
// to exercise the real path rather than a stub.
t.integer('person_id');
t.binary('embedding');
t.float('det_score');
});
await knex.schema.createTable('image_access_logs', (t) => {
t.increments('id').primary();
t.integer('photo_id');
});
await knex.schema.createTable('transfer_files', (t) => {
t.increments('id').primary();
t.integer('transfer_id');
t.integer('photo_id');
t.unique(['transfer_id', 'photo_id'], 'transfer_files_unique');
});
});
/** Two duplicate rows for the same file: id 1 survives, id 2 is doomed. */
const seedPair = async () => {
await knex('photos').insert([
{ event_id: 1, external_relpath: 'a/x.jpg', thumbnail_path: 't', source_origin: 'external' },
{ event_id: 1, external_relpath: 'a/x.jpg', thumbnail_path: 't', source_origin: 'external' },
]);
};
const rows = () => knex('photos').orderBy('id', 'asc').select('*');
it('collapses a duplicated pair to one row and leaves distinct paths alone', async () => {
await knex('photos').insert([
{ event_id: 1, external_relpath: 'a/x.jpg', thumbnail_path: 't1', source_origin: 'external' },
{ event_id: 1, external_relpath: 'a/x.jpg', thumbnail_path: 't2', source_origin: 'external' },
{ event_id: 1, external_relpath: 'a/y.jpg', thumbnail_path: 't3', source_origin: 'external' },
]);
await migration.up(knex);
const after = await rows();
expect(after.map((r) => r.external_relpath)).toEqual(['a/x.jpg', 'a/y.jpg']);
// Lowest id survives when both sides are equally complete.
expect(after[0].id).toBe(1);
});
it('does not collapse the same path across different events', async () => {
// The constraint is per event. Two events referencing the same NAS folder
// is a supported setup, and treating those as duplicates would delete one
// event's entire library.
await knex('photos').insert([
{ event_id: 1, external_relpath: 'a/x.jpg', source_origin: 'external' },
{ event_id: 2, external_relpath: 'a/x.jpg', source_origin: 'external' },
]);
await migration.up(knex);
expect(await knex('photos').count('* as c').first()).toEqual({ c: 2 });
});
it('never touches managed rows, however many carry NULL', async () => {
// Every managed photo has external_relpath NULL. Grouping on it without
// the NOT NULL filter would make them all one enormous "duplicate" group
// and delete the entire library bar one row.
await knex('photos').insert([
{ event_id: 1, external_relpath: null, source_origin: 'managed' },
{ event_id: 1, external_relpath: null, source_origin: 'managed' },
{ event_id: 1, external_relpath: null, source_origin: 'managed' },
]);
await migration.up(knex);
expect(await knex('photos').count('* as c').first()).toEqual({ c: 3 });
});
it('keeps the row that has a thumbnail, not merely the lowest id', async () => {
// An import killed mid-flight leaves rows without a thumbnail. Dropping
// the completed one would blank a tile in the grid for no reason.
await knex('photos').insert([
{ event_id: 1, external_relpath: 'a/x.jpg', thumbnail_path: null, source_origin: 'external' },
{ event_id: 1, external_relpath: 'a/x.jpg', thumbnail_path: 'thumb.jpg', source_origin: 'external' },
]);
await migration.up(knex);
const after = await rows();
expect(after).toHaveLength(1);
expect(after[0].thumbnail_path).toBe('thumb.jpg');
});
it('repoints a hero that pointed at the row being removed', async () => {
// events.hero_photo_id is ON DELETE SET NULL, so without this the cleanup
// silently strips the event's hero image — a visible regression caused
// entirely by the fix.
await knex('photos').insert([
{ event_id: 1, external_relpath: 'a/x.jpg', thumbnail_path: 't', source_origin: 'external' },
{ event_id: 1, external_relpath: 'a/x.jpg', thumbnail_path: 't', source_origin: 'external' },
]);
await knex('events').insert({ id: 1, hero_photo_id: 2 });
await knex('photo_categories').insert({ id: 1, hero_photo_id: 2 });
await migration.up(knex);
expect((await knex('events').where({ id: 1 }).first()).hero_photo_id).toBe(1);
expect((await knex('photo_categories').where({ id: 1 }).first()).hero_photo_id).toBe(1);
});
it('leaves a hero that pointed at the survivor untouched', async () => {
await knex('photos').insert([
{ event_id: 1, external_relpath: 'a/x.jpg', thumbnail_path: 't', source_origin: 'external' },
{ event_id: 1, external_relpath: 'a/x.jpg', thumbnail_path: 't', source_origin: 'external' },
]);
await knex('events').insert({ id: 1, hero_photo_id: 1 });
await migration.up(knex);
expect((await knex('events').where({ id: 1 }).first()).hero_photo_id).toBe(1);
});
it('makes a second insert of the same path impossible afterwards', async () => {
// The whole point. Without this the route is still racing, and the
// migration is recorded as applied.
await knex('photos').insert({ event_id: 1, external_relpath: 'a/x.jpg', source_origin: 'external' });
await migration.up(knex);
await expect(
knex('photos').insert({ event_id: 1, external_relpath: 'a/x.jpg', source_origin: 'external' })
).rejects.toThrow(/unique/i);
});
it('still admits managed rows once the index exists', async () => {
await migration.up(knex);
await knex('photos').insert([
{ event_id: 1, external_relpath: null, source_origin: 'managed' },
{ event_id: 1, external_relpath: null, source_origin: 'managed' },
]);
expect(await knex('photos').count('* as c').first()).toEqual({ c: 2 });
});
it('leaves nothing dangling behind the deleted row', async () => {
// SQLite never enforces the ON DELETE CASCADE these tables declare, so a
// bare delete strands biometric embeddings, feedback and marks pointing at
// a photo id that no longer exists — on every SQLite install.
await seedPair();
await knex('photo_faces').insert({ photo_id: 2, event_id: 1 });
await knex('image_access_logs').insert({ photo_id: 2 });
await migration.up(knex);
expect(await knex('photo_faces').where('photo_id', 2).first()).toBeUndefined();
expect(await knex('image_access_logs').where('photo_id', 2).first()).toBeUndefined();
});
it('does not carry the duplicate\'s faces over to the survivor', async () => {
// Both rows were scanned independently, so the survivor already holds its
// own embeddings. Moving these would fabricate a second copy of every face
// and split the person clusters built from them.
await seedPair();
await knex('photo_faces').insert([{ photo_id: 1, event_id: 1 }, { photo_id: 2, event_id: 1 }]);
await migration.up(knex);
expect(await knex('photo_faces').count('* as c').first()).toEqual({ c: 1 });
});
it('moves a guest comment to the survivor rather than deleting it', async () => {
// The duplicates were separate tiles in the grid, so a guest could have
// commented on either. Silently dropping that inside a fix for silent data
// loss would be its own bug.
await seedPair();
await knex('photo_feedback').insert({
photo_id: 2, event_id: 1, feedback_type: 'comment',
comment_text: 'lovely shot', guest_identifier: 'guest-a',
});
await migration.up(knex);
const rows = await knex('photo_feedback');
expect(rows).toHaveLength(1);
expect(rows[0].photo_id).toBe(1);
expect(rows[0].comment_text).toBe('lovely shot');
});
it('keeps both comments when the same guest commented on both tiles', async () => {
await seedPair();
await knex('photo_feedback').insert([
{ photo_id: 1, event_id: 1, feedback_type: 'comment', comment_text: 'one', guest_identifier: 'g' },
{ photo_id: 2, event_id: 1, feedback_type: 'comment', comment_text: 'two', guest_identifier: 'g' },
]);
await migration.up(knex);
const rows = await knex('photo_feedback').orderBy('id');
expect(rows.map((r) => r.comment_text)).toEqual(['one', 'two']);
expect(rows.every((r) => r.photo_id === 1)).toBe(true);
});
it('does not double-count a like the same guest left on both tiles', async () => {
// Unlike comments, a like is a per-guest toggle: moving it would show two
// likes from one person.
await seedPair();
await knex('photo_feedback').insert([
{ photo_id: 1, event_id: 1, feedback_type: 'like', guest_identifier: 'g' },
{ photo_id: 2, event_id: 1, feedback_type: 'like', guest_identifier: 'g' },
]);
await migration.up(knex);
expect(await knex('photo_feedback').count('* as c').first()).toEqual({ c: 1 });
});
it('moves a like from a guest the survivor has never seen', async () => {
await seedPair();
await knex('photo_feedback').insert({
photo_id: 2, event_id: 1, feedback_type: 'like', guest_identifier: 'other',
});
await migration.up(knex);
const rows = await knex('photo_feedback');
expect(rows).toHaveLength(1);
expect(rows[0].photo_id).toBe(1);
});
it('moves an admin mark, and drops it when that admin already marked the survivor', async () => {
// photo_admin_marks is UNIQUE(photo_id, admin_id), so a blind move would
// throw and abort the migration.
await seedPair();
await knex('photo_admin_marks').insert([
{ photo_id: 1, event_id: 1, admin_id: 7, rating: 5 },
{ photo_id: 2, event_id: 1, admin_id: 7, rating: 2 },
{ photo_id: 2, event_id: 1, admin_id: 9, rating: 4 },
]);
await migration.up(knex);
const rows = await knex('photo_admin_marks').orderBy('admin_id');
expect(rows.map((r) => [r.admin_id, r.rating])).toEqual([[7, 5], [9, 4]]);
expect(rows.every((r) => r.photo_id === 1)).toBe(true);
});
it('respects the transfer_files uniqueness when moving membership', async () => {
await seedPair();
await knex('transfer_files').insert([
{ transfer_id: 3, photo_id: 1 },
{ transfer_id: 3, photo_id: 2 },
{ transfer_id: 4, photo_id: 2 },
]);
await migration.up(knex);
const rows = await knex('transfer_files').orderBy('transfer_id');
expect(rows.map((r) => r.transfer_id)).toEqual([3, 4]);
expect(rows.every((r) => r.photo_id === 1)).toBe(true);
});
it('recomputes the survivor\'s feedback totals after reparenting rows', async () => {
// photos carries denormalized counters (migration 033). A survivor that
// now OWNS the feedback but still renders zero is the visible half of
// getting this wrong.
await seedPair();
await knex('photo_feedback').insert([
{ photo_id: 2, event_id: 1, feedback_type: 'like', guest_identifier: 'g1' },
{ photo_id: 2, event_id: 1, feedback_type: 'rating', rating: 4, guest_identifier: 'g1' },
]);
await migration.up(knex);
const survivor = await knex('photos').where('id', 1).first();
expect(survivor.like_count).toBe(1);
expect(Number(survivor.average_rating)).toBe(4);
expect(survivor.feedback_count).toBe(1);
});
it('keeps two people who share a device apart', async () => {
// guest_identifier is per-device; guest_id is per-person (migration 078),
// and feedbackService scopes by guest_id when it is present. Keying on the
// identifier alone would read these as one person and delete a rating.
await seedPair();
await knex('photo_feedback').insert([
{ photo_id: 1, event_id: 1, feedback_type: 'rating', rating: 5, guest_identifier: 'shared', guest_id: 10 },
{ photo_id: 2, event_id: 1, feedback_type: 'rating', rating: 2, guest_identifier: 'shared', guest_id: 11 },
]);
await migration.up(knex);
const rows = await knex('photo_feedback').orderBy('guest_id');
expect(rows.map((r) => [r.guest_id, r.rating])).toEqual([[10, 5], [11, 2]]);
});
it('still dedupes one person voting on both tiles', async () => {
await seedPair();
await knex('photo_feedback').insert([
{ photo_id: 1, event_id: 1, feedback_type: 'like', guest_identifier: 'shared', guest_id: 10 },
{ photo_id: 2, event_id: 1, feedback_type: 'like', guest_identifier: 'shared', guest_id: 10 },
]);
await migration.up(knex);
expect(await knex('photo_feedback').count('* as c').first()).toEqual({ c: 1 });
});
it('still clears face rows on a branch that has no face feature', async () => {
// DIVERGES FROM MAIN, deliberately. Face recognition (#1090) is main-only:
// there is no faceProcessor on this branch, so purgePhotoFaces cannot be
// called and there are no event_people counts or centroids to reconcile.
// What still matters is the half that is not optional — the rows must not
// dangle, because SQLite never enforces the CASCADE that would remove
// them. The service reaches for purgePhotoFaces, finds nothing, and falls
// back to a plain delete; this pins that fallback.
//
// If faces are ever backported, main's version of this test comes with
// them.
await seedPair();
await knex('photo_faces').insert({ photo_id: 2, event_id: 1, person_id: 5 });
await migration.up(knex);
expect(await knex('photo_faces').count('* as c').first()).toEqual({ c: 0 });
});
it('keeps a hidden moderation record from swallowing the visible replacement', async () => {
// feedbackService lets both coexist and counts only the visible one.
await seedPair();
await knex('photo_feedback').insert([
{ photo_id: 1, event_id: 1, feedback_type: 'like', guest_identifier: 'g', is_hidden: true },
{ photo_id: 2, event_id: 1, feedback_type: 'like', guest_identifier: 'g', is_hidden: false },
]);
await migration.up(knex);
expect(await knex('photo_feedback').count('* as c').first()).toEqual({ c: 2 });
});
it('merges the independent halves of one admin\'s mark', async () => {
// rating and color_label are written independently, so the same admin can
// have rated one tile and coloured the other.
await seedPair();
await knex('photo_admin_marks').insert([
{ photo_id: 1, event_id: 1, admin_id: 7, rating: 5, color_label: null },
{ photo_id: 2, event_id: 1, admin_id: 7, rating: null, color_label: 'red' },
]);
await migration.up(knex);
const rows = await knex('photo_admin_marks');
expect(rows).toHaveLength(1);
expect([rows[0].rating, rows[0].color_label]).toEqual([5, 'red']);
});
it('requeues the survivor when the duplicate held the only scan', async () => {
// Otherwise the sole embeddings go with the purge and nothing re-queues:
// the photo just silently stops having a face.
await seedPair();
await knex('photo_faces').insert({ photo_id: 2, event_id: 1 });
await migration.up(knex);
expect((await knex('photos').where('id', 1).first()).face_status).toBe('pending');
});
it('carries the duplicate\'s views and downloads over', async () => {
await seedPair();
await knex('photos').where('id', 1).update({ view_count: 2, download_count: 1 });
await knex('photos').where('id', 2).update({ view_count: 5, download_count: 3 });
await migration.up(knex);
const survivor = await knex('photos').where('id', 1).first();
expect([survivor.view_count, survivor.download_count]).toEqual([7, 4]);
});
it('fails loudly rather than recording itself applied without the index', async () => {
// Swallowing a failed CREATE INDEX would leave the install permanently
// racy — the in-flight guard only covers one process — with nothing to
// trigger a retry. Driven through the helper the migration calls, against
// a table that still holds duplicates — i.e. what it would face if the
// dedupe above had not achieved uniqueness.
await seedPair();
const { createExternalRelpathIndex } = require('../../src/services/externalPhotoDedupe');
await expect(createExternalRelpathIndex(knex)).rejects.toThrow(/unique/i);
});
it('invalidates the pre-built download zip for the affected event', async () => {
// The cached archive still contains the rows just removed, and every
// ordinary photo-deletion path invalidates it for exactly that reason.
// getZipInfo treats a cleared record as a miss and rebuilds on request.
await seedPair();
await knex('events').insert({
id: 1, download_zip_path: 'events/active/x/.download-cache/all.zip',
download_zip_generated_at: '2026-01-01',
});
await migration.up(knex);
const ev = await knex('events').where('id', 1).first();
expect(ev.download_zip_path).toBeNull();
expect(ev.download_zip_generated_at).toBeNull();
});
it('leaves an untouched event\'s zip alone', async () => {
await seedPair();
await knex('events').insert([
{ id: 1, download_zip_path: 'a.zip', download_zip_generated_at: '2026-01-01' },
{ id: 2, download_zip_path: 'b.zip', download_zip_generated_at: '2026-01-01' },
]);
await migration.up(knex);
expect((await knex('events').where('id', 2).first()).download_zip_path).toBe('b.zip');
});
it('is idempotent', async () => {
await knex('photos').insert([
{ event_id: 1, external_relpath: 'a/x.jpg', source_origin: 'external' },
{ event_id: 1, external_relpath: 'a/x.jpg', source_origin: 'external' },
]);
await migration.up(knex);
const once = await rows();
await migration.up(knex);
expect(await rows()).toEqual(once);
});
it('rolls back to an unconstrained table', async () => {
await migration.up(knex);
await migration.down(knex);
await knex('photos').insert([
{ event_id: 1, external_relpath: 'a/x.jpg', source_origin: 'external' },
{ event_id: 1, external_relpath: 'a/x.jpg', source_origin: 'external' },
]);
expect(await knex('photos').count('* as c').first()).toEqual({ c: 2 });
});
it('no-ops before 041 has added the column', async () => {
await knex.schema.dropTableIfExists('photos');
await knex.schema.createTable('photos', (t) => { t.increments('id').primary(); });
await expect(migration.up(knex)).resolves.toBeUndefined();
});
});
@@ -0,0 +1,364 @@
/**
* Folding the event's base path into every external row (#1163).
*
* Two things can go wrong and both are silent, which is why they are pinned
* here rather than left to review: folding a path that was ALREADY folded
* (every original moves), and "repairing" a healthy install because the media
* root happened to be unmounted when the migration ran (every original moves).
*
* The repair itself is driven against a real temp directory tree, because the
* whole mechanism is "is this file actually there" and a mocked fs would only
* be testing the mock.
*/
const path = require('path');
const fs = require('fs');
const os = require('os');
describe('migration 177 — external_relpath from the media root (#1163)', () => {
let knex; let tmpDir; let mediaRoot; let migration;
/** Writes `bytes` bytes and returns the size, so fixtures can record it the
* way an import would have. */
const touch = async (rel, bytes = 8) => {
const full = path.join(mediaRoot, rel);
await fs.promises.mkdir(path.dirname(full), { recursive: true });
await fs.promises.writeFile(full, Buffer.alloc(bytes));
return bytes;
};
beforeAll(async () => {
tmpDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'picpeak-mig187-'));
mediaRoot = path.join(tmpDir, 'media');
await fs.promises.mkdir(mediaRoot, { recursive: true });
process.env.EXTERNAL_MEDIA_ROOT = mediaRoot;
// The service caches the root on first call, so it must not have been
// resolved before EXTERNAL_MEDIA_ROOT was set above.
jest.resetModules();
migration = require('../../migrations/core/177_external_relpath_from_root');
knex = require('knex')({
client: 'sqlite3',
connection: { filename: path.join(tmpDir, 'db.sqlite') },
useNullAsDefault: true,
});
});
afterAll(async () => {
if (knex) await knex.destroy();
await fs.promises.rm(tmpDir, { recursive: true, force: true }).catch(() => {});
delete process.env.EXTERNAL_MEDIA_ROOT;
});
beforeEach(async () => {
await knex.schema.dropTableIfExists('photos');
await knex.schema.dropTableIfExists('events');
await knex.schema.dropTableIfExists('app_settings');
await knex.schema.createTable('events', (t) => {
t.increments('id').primary();
t.string('external_path');
});
await knex.schema.createTable('photos', (t) => {
t.increments('id').primary();
t.integer('event_id');
t.string('external_relpath');
t.integer('size_bytes');
t.string('source_origin').defaultTo('managed');
});
await knex.schema.createTable('app_settings', (t) => {
t.increments('id').primary();
t.string('setting_key');
t.text('setting_value');
t.string('setting_type');
t.string('updated_at');
});
await fs.promises.rm(mediaRoot, { recursive: true, force: true });
await fs.promises.mkdir(mediaRoot, { recursive: true });
});
const relpaths = async () =>
(await knex('photos').orderBy('id', 'asc').select('external_relpath'))
.map((r) => r.external_relpath);
it('folds the base path into every row of a healthy event', async () => {
await touch('Trip/Leknes/a.jpg');
await touch('Trip/Leknes/b.jpg');
await knex('events').insert({ id: 1, external_path: 'Trip' });
await knex('photos').insert([
{ event_id: 1, external_relpath: 'Leknes/a.jpg', source_origin: 'external' },
{ event_id: 1, external_relpath: 'Leknes/b.jpg', source_origin: 'external' },
]);
await migration.up(knex);
expect(await relpaths()).toEqual(['Trip/Leknes/a.jpg', 'Trip/Leknes/b.jpg']);
});
it('repairs rows an earlier import had rebased', async () => {
// The reported shape: a parent imported first, a child imported second, so
// events.external_path is the child and the parent's rows resolve into a
// path that does not exist.
const oldSize = await touch('Trip/Leknes/old.jpg', 11); // from the first import
const newSize = await touch('Trip/Sub/new.jpg', 22); // from the second
await knex('events').insert({ id: 1, external_path: 'Trip/Sub' });
await knex('photos').insert([
{ event_id: 1, external_relpath: 'Leknes/old.jpg', size_bytes: oldSize, source_origin: 'external' },
{ event_id: 1, external_relpath: 'new.jpg', size_bytes: newSize, source_origin: 'external' },
]);
await migration.up(knex);
// The old row is placed where the file actually is; the new one keeps
// resolving exactly where it resolved before.
expect(await relpaths()).toEqual(['Trip/Leknes/old.jpg', 'Trip/Sub/new.jpg']);
});
it('refuses an ancestor whose file is a different size', async () => {
// The dangerous case: the row's own file was simply deleted, and an
// UNRELATED file one directory up happens to share its name. Adopting it
// would make downloads serve the wrong original — worse than a dead link.
await touch('Trip/photo.jpg', 999);
await knex('events').insert({ id: 1, external_path: 'Trip/Sub' });
await knex('photos').insert({
event_id: 1, external_relpath: 'photo.jpg', size_bytes: 42, source_origin: 'external',
});
await migration.up(knex);
expect(await relpaths()).toEqual(['Trip/Sub/photo.jpg']);
});
it('refuses an ancestor when the row records no size to check against', async () => {
// Nothing to verify provenance with, so the row stays where it resolves
// today rather than adopting a same-named stranger.
await touch('Trip/photo.jpg', 100);
await knex('events').insert({ id: 1, external_path: 'Trip/Sub' });
await knex('photos').insert({
event_id: 1, external_relpath: 'photo.jpg', size_bytes: null, source_origin: 'external',
});
await migration.up(knex);
expect(await relpaths()).toEqual(['Trip/Sub/photo.jpg']);
});
it('leaves nothing folded when a rewrite fails partway', async () => {
// Without a transaction, a crash between the first event's UPDATE and the
// marker leaves mixed formats behind — and the next run folds the already
// folded rows a second time, putting every original one directory deeper.
await touch('A/one.jpg');
await touch('B/two.jpg');
await knex('events').insert([
{ id: 1, external_path: 'A' },
{ id: 2, external_path: 'B' },
]);
await knex('photos').insert([
{ event_id: 1, external_relpath: 'one.jpg', source_origin: 'external' },
{ event_id: 2, external_relpath: 'two.jpg', source_origin: 'external' },
]);
// app_settings is written last, in the same transaction as the rewrites.
await knex.schema.dropTableIfExists('app_settings_backup');
await knex.raw('CREATE TRIGGER fail_marker BEFORE INSERT ON app_settings '
+ "BEGIN SELECT RAISE(ABORT, 'boom'); END");
await expect(migration.up(knex)).rejects.toThrow(/boom/);
await knex.raw('DROP TRIGGER fail_marker');
// Every row still base-relative, and no marker — so a retry is correct.
expect(await relpaths()).toEqual(['one.jpg', 'two.jpg']);
expect(await knex('app_settings').where('setting_key', 'external_relpath_root_relative').first())
.toBeUndefined();
});
it('removes the losing row when two paths converge, instead of stranding it', async () => {
// Trip/Sub/c.jpg imported once via `Trip` (as `Sub/c.jpg`) and once via
// `Trip/Sub` (as `c.jpg`). Both fold to the same path. Skipping the loser
// would leave it base-relative under a root-only resolver — pointing at
// <root>/c.jpg — with the marker claiming the conversion is complete.
const size = await touch('Trip/Sub/c.jpg', 33);
await knex('events').insert({ id: 1, external_path: 'Trip/Sub' });
await knex('photos').insert([
{ event_id: 1, external_relpath: 'Sub/c.jpg', size_bytes: size, source_origin: 'external' },
{ event_id: 1, external_relpath: 'c.jpg', size_bytes: size, source_origin: 'external' },
]);
await migration.up(knex);
const rows = await knex('photos').select('external_relpath');
expect(rows).toHaveLength(1);
expect(rows[0].external_relpath).toBe('Trip/Sub/c.jpg');
});
it('survives a final path that equals another row\'s current path', async () => {
// `photo.jpg` repairs to `Trip/photo.jpg` while the row already holding
// `Trip/photo.jpg` folds to `Trip/Sub/Trip/photo.jpg`. Every FINAL value is
// distinct, but a one-pass rewrite collides halfway through — and on
// Postgres that 23505 is misread by the migration runner as "already
// applied", leaving everything unconverted.
const a = await touch('Trip/photo.jpg', 11);
const b = await touch('Trip/Sub/Trip/photo.jpg', 22);
await knex('events').insert({ id: 1, external_path: 'Trip/Sub' });
await knex('photos').insert([
{ event_id: 1, external_relpath: 'photo.jpg', size_bytes: a, source_origin: 'external' },
{ event_id: 1, external_relpath: 'Trip/photo.jpg', size_bytes: b, source_origin: 'external' },
]);
await migration.up(knex);
expect(await relpaths()).toEqual(['Trip/photo.jpg', 'Trip/Sub/Trip/photo.jpg']);
});
it('does not re-prefix a row inserted while the probe was running', async () => {
// Phase 1 runs outside the transaction and can take minutes on a cold
// mount. An import finishing in that window writes an already
// root-relative row, which a `where event_id` bulk update would prefix a
// second time with the stale base.
await touch('Trip/a.jpg');
await knex('events').insert({ id: 1, external_path: 'Trip' });
await knex('photos').insert({ event_id: 1, external_relpath: 'a.jpg', source_origin: 'external' });
const { foldExternalRelpaths } = require('../../src/services/externalRelpathFold');
const realStat = fs.promises.stat;
let injected = false;
jest.spyOn(fs.promises, 'access').mockImplementation(async (...args) => {
if (!injected) {
injected = true;
await knex('photos').insert({
event_id: 1, external_relpath: 'Trip/late.jpg', source_origin: 'external',
});
}
return realStat(args[0]).then(() => undefined);
});
await foldExternalRelpaths(knex);
fs.promises.access.mockRestore();
expect((await relpaths()).sort()).toEqual(['Trip/a.jpg', 'Trip/late.jpg']);
});
it('leaves a row it cannot place resolving where it resolves today', async () => {
// Never guess below current behaviour: a file that is genuinely gone must
// not have its path rewritten to some other file that happens to exist.
await touch('Trip/Sub/present.jpg');
await knex('events').insert({ id: 1, external_path: 'Trip/Sub' });
await knex('photos').insert([
{ event_id: 1, external_relpath: 'present.jpg', source_origin: 'external' },
{ event_id: 1, external_relpath: 'vanished.jpg', source_origin: 'external' },
]);
await migration.up(knex);
expect(await relpaths()).toEqual(['Trip/Sub/present.jpg', 'Trip/Sub/vanished.jpg']);
});
it('folds without repairing when the media root is unmounted', async () => {
// An unmounted share leaves the mountpoint as an empty directory, so every
// file looks missing. Repairing off that signal would move every original
// on a perfectly healthy install.
await knex('events').insert({ id: 1, external_path: 'Trip/Sub' });
await knex('photos').insert([
{ event_id: 1, external_relpath: 'Leknes/a.jpg', source_origin: 'external' },
]);
// mediaRoot is empty — see beforeEach.
await migration.up(knex);
expect(await relpaths()).toEqual(['Trip/Sub/Leknes/a.jpg']);
});
it('leaves managed rows alone', async () => {
await touch('Trip/a.jpg');
await knex('events').insert({ id: 1, external_path: 'Trip' });
await knex('photos').insert([
{ event_id: 1, external_relpath: null, source_origin: 'managed' },
{ event_id: 1, external_relpath: 'a.jpg', source_origin: 'external' },
]);
await migration.up(knex);
expect(await relpaths()).toEqual([null, 'Trip/a.jpg']);
});
it('leaves an event with no base path alone — its rows are already root-relative', async () => {
await touch('a.jpg');
await knex('events').insert({ id: 1, external_path: null });
await knex('photos').insert({ event_id: 1, external_relpath: 'a.jpg', source_origin: 'external' });
await migration.up(knex);
expect(await relpaths()).toEqual(['a.jpg']);
});
it('folds each event with its own base', async () => {
await touch('A/one.jpg');
await touch('B/two.jpg');
await knex('events').insert([
{ id: 1, external_path: 'A' },
{ id: 2, external_path: 'B' },
]);
await knex('photos').insert([
{ event_id: 1, external_relpath: 'one.jpg', source_origin: 'external' },
{ event_id: 2, external_relpath: 'two.jpg', source_origin: 'external' },
]);
await migration.up(knex);
expect(await relpaths()).toEqual(['A/one.jpg', 'B/two.jpg']);
});
it('tolerates a base path with stray slashes', async () => {
await touch('Trip/a.jpg');
await knex('events').insert({ id: 1, external_path: '/Trip/' });
await knex('photos').insert({ event_id: 1, external_relpath: 'a.jpg', source_origin: 'external' });
await migration.up(knex);
expect(await relpaths()).toEqual(['Trip/a.jpg']);
});
it('does not fold twice when run again', async () => {
// The failure this guards is total: every original on the install moves one
// directory deeper, and there is no undo.
await touch('Trip/a.jpg');
await knex('events').insert({ id: 1, external_path: 'Trip' });
await knex('photos').insert({ event_id: 1, external_relpath: 'a.jpg', source_origin: 'external' });
await migration.up(knex);
await migration.up(knex);
expect(await relpaths()).toEqual(['Trip/a.jpg']);
});
it('does not fold twice when the base repeats in the relpath', async () => {
// The inference this migration deliberately does NOT use: `Trip/x.jpg`
// under base `Trip` already "starts with the base", but has not been
// folded — it is a subfolder that shares its parent's name.
await touch('Trip/Trip/x.jpg');
await knex('events').insert({ id: 1, external_path: 'Trip' });
await knex('photos').insert({ event_id: 1, external_relpath: 'Trip/x.jpg', source_origin: 'external' });
await migration.up(knex);
expect(await relpaths()).toEqual(['Trip/Trip/x.jpg']);
});
it('rollback does not clear the marker, so a re-run cannot double-fold', async () => {
await touch('Trip/a.jpg');
await knex('events').insert({ id: 1, external_path: 'Trip' });
await knex('photos').insert({ event_id: 1, external_relpath: 'a.jpg', source_origin: 'external' });
await migration.up(knex);
await migration.down(knex);
await migration.up(knex);
expect(await relpaths()).toEqual(['Trip/a.jpg']);
});
it('no-ops before 041 has added the column', async () => {
await knex.schema.dropTableIfExists('photos');
await knex.schema.createTable('photos', (t) => { t.increments('id').primary(); });
await expect(migration.up(knex)).resolves.toBeUndefined();
});
});
@@ -0,0 +1,83 @@
/**
* Legacy preview keys must not survive the encoder change.
*
* The old generator kept the SOURCE basename verbatim while always writing
* JPEG, so a `.webp` upload produced `preview_shot.webp` holding a JPEG. The
* route now derives Content-Type from the key, and sets `nosniff` — so that
* legacy object would be announced as image/webp and render as a broken image.
*/
const path = require('path');
const fs = require('fs');
const os = require('os');
const migration = require('../../migrations/core/178_reset_legacy_preview_paths');
describe('migration 178 — legacy preview keys (#1166 follow-up)', () => {
let knex; let tmpDir;
beforeAll(async () => {
tmpDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'picpeak-mig188-'));
knex = require('knex')({
client: 'sqlite3',
connection: { filename: path.join(tmpDir, 'db.sqlite') },
useNullAsDefault: true,
});
});
afterAll(async () => {
if (knex) await knex.destroy();
await fs.promises.rm(tmpDir, { recursive: true, force: true }).catch(() => {});
});
beforeEach(async () => {
await knex.schema.dropTableIfExists('photos');
await knex.schema.createTable('photos', (t) => {
t.increments('id').primary();
t.string('preview_path');
t.string('thumbnail_path');
});
});
it('clears the mislabelled .webp keys that would render broken', async () => {
await knex('photos').insert({ preview_path: 'previews/preview_shot.webp' });
await migration.up(knex);
expect((await knex('photos').first()).preview_path).toBeNull();
});
it('clears .jpg keys too, because a byte-correct one can still be flattened', async () => {
// A legacy .jpg key is valid JPEG, but it may be a flattened rendition of a
// transparent or animated source, and nothing in the key says so. One lazy
// regeneration is cheaper than reasoning about which of them lied.
await knex('photos').insert([
{ preview_path: 'previews/preview_a.jpg' },
{ preview_path: 'previews/preview_b.png' },
]);
await migration.up(knex);
expect(await knex('photos').whereNotNull('preview_path').count('* as c').first()).toEqual({ c: 0 });
});
it('leaves thumbnails alone — they are a different cache', async () => {
await knex('photos').insert({ preview_path: 'previews/p.jpg', thumbnail_path: 'thumbnails/t.jpg' });
await migration.up(knex);
expect((await knex('photos').first()).thumbnail_path).toBe('thumbnails/t.jpg');
});
it('is idempotent and safe with nothing to clear', async () => {
await migration.up(knex);
await expect(migration.up(knex)).resolves.toBeUndefined();
});
it('no-ops before 104 has added the column', async () => {
await knex.schema.dropTableIfExists('photos');
await knex.schema.createTable('photos', (t) => { t.increments('id').primary(); });
await expect(migration.up(knex)).resolves.toBeUndefined();
});
});
@@ -135,9 +135,9 @@ function signAdminToken({ id = 1, username = 'admin', iat, exp }) {
);
}
function signGalleryToken({ eventId = 100, eventSlug = 'wedding' } = {}) {
function signGalleryToken({ eventId = 100, eventSlug = 'wedding', ...extra } = {}) {
return jwt.sign(
{ eventId, eventSlug, type: 'gallery' },
{ eventId, eventSlug, type: 'gallery', ...extra },
process.env.JWT_SECRET,
{ expiresIn: '1h', issuer: 'picpeak-auth' }
);
@@ -288,6 +288,56 @@ describe('GET /auth/session — symmetry with protected middleware', () => {
expect(res.body.valid).toBe(true);
});
/**
* What KIND of gallery session this is (#1149).
*
* The frontend used to keep this in sessionStorage, which is per-TAB while
* the cookie is per-browser: a gallery reopened in a second tab lost
* 'client' even though the backend still served it as one, and the UI hid
* the only control that clears the privileged cookie. Reported from the
* token so a restored session knows what it actually is.
*/
describe('gallery session kind', () => {
beforeEach(() => {
fakeDb.events.push({
id: 100,
slug: 'wedding',
is_active: true,
is_archived: false,
expires_at: new Date(Date.now() + 86400_000),
});
});
it('reports a PIN-client session as client', async () => {
const res = await request(makeApp())
.get('/auth/session?slug=wedding')
.set('Authorization', `Bearer ${signGalleryToken({ accessLevel: 'client' })}`);
expect(res.body.valid).toBe(true);
expect(res.body.accessLevel).toBe('client');
expect(res.body.viaCustomer).toBe(false);
});
it('reports a customer-portal session, which looks like a guest', async () => {
const res = await request(makeApp())
.get('/auth/session?slug=wedding')
.set('Authorization', `Bearer ${signGalleryToken({ via: 'customer', customerId: 7 })}`);
expect(res.body.valid).toBe(true);
expect(res.body.accessLevel).toBe('guest');
expect(res.body.viaCustomer).toBe(true);
});
it('reports a plain guest as neither', async () => {
// The flags have to discriminate, or they would just hand every visitor
// a Logout button back.
const res = await request(makeApp())
.get('/auth/session?slug=wedding')
.set('Authorization', `Bearer ${signGalleryToken()}`);
expect(res.body.valid).toBe(true);
expect(res.body.accessLevel).toBe('guest');
expect(res.body.viaCustomer).toBe(false);
});
});
it('returns valid:false when the token is revoked', async () => {
fakeDb.adminUsers.push({
id: 1,
@@ -127,7 +127,44 @@ describe('dashboard scoping (GHSA-c2jj / gqx7 / jhcf)', () => {
expect(res.status).toBe(200);
expect(Number(res.body.totalEvents)).toBe(1);
expect(Number(res.body.totalPhotos)).toBe(1);
expect(Number(res.body.storageUsed)).toBe(1000);
// The catalogued original bytes — this is what carries the per-event
// scoping, and what `storageUsed` reported before #1164.
expect(Number(res.body.catalogedBytes)).toBe(1000);
});
it('/stats reports disk usage unscoped, because disk is not per-event', async () => {
// storageUsed is a measurement of the storage root (#1164), so it is the
// same number for every admin by design. Pinned so a future reviewer
// reading "everything on this endpoint is scoped" does not turn it into a
// sum of this editor's photos again — which is the bug that was fixed.
const res = await request(app)
.get('/api/admin/dashboard/stats')
.set('Authorization', `Bearer ${editorToken}`);
expect(res.status).toBe(200);
expect(res.body.storageUsed).not.toBe(1000);
expect(res.body).toHaveProperty('storageBreakdown');
});
it('/stats reports the catalogued figure on an S3 backend, not a near-zero disk walk', async () => {
// STORAGE_PATH holds only incidental local files when objects live in a
// bucket, so walking it would report near-zero and drag the soft-limit
// recommendation with it.
const prev = process.env.STORAGE_BACKEND;
process.env.STORAGE_BACKEND = 's3';
try {
const res = await request(app)
.get('/api/admin/dashboard/stats')
.set('Authorization', `Bearer ${editorToken}`);
expect(res.status).toBe(200);
expect(res.body.storageUsed).toBeNull();
expect(res.body.storageMeasurement).toBe('catalog');
expect(Number(res.body.catalogedBytes)).toBe(1000);
} finally {
if (prev === undefined) delete process.env.STORAGE_BACKEND;
else process.env.STORAGE_BACKEND = prev;
}
});
it('/analytics does not expose a foreign gallery name or slug', async () => {
@@ -0,0 +1,170 @@
/**
* "Date Taken" ordering across SQLite's storage classes (#1172).
*
* photos.captured_at does not hold one type on SQLite. Three writers put three
* different things in it:
*
* integer managed uploads — photoProcessor.js:441 hands knex a Date, which
* the sqlite3 binding stores as epoch milliseconds
* text external imports and the capture-date backfill, which write
* ISO-8601 ('2026-06-03T01:15:00.000Z')
* null no capture date, so the sort falls through to uploaded_at —
* itself text, in knex's 'YYYY-MM-DD HH:MM:SS' shape
*
* A plain COALESCE over that mixture is not an ordering. SQLite sorts INTEGER
* before TEXT unconditionally, so every managed photo carrying EXIF came back
* ahead of every photo that did not, whatever the dates said. And among the
* text values 'T' (0x54) outranks the space (0x20), so a same-day ISO 01:15
* sorted behind a fallback 23:00.
*
* Both failures predate #1172 — the first needs only two managed photos — but
* the sort is what that issue is about, so they are fixed and pinned here.
* Every test below fails on the unfixed ORDER BY.
*/
const path = require('path');
const fs = require('fs');
const os = require('os');
process.env.NODE_ENV = 'test';
process.env.TEST_DATABASE_PATH = path.join(
fs.mkdtempSync(path.join(os.tmpdir(), 'picpeak-capsort-')), 'db.sqlite',
);
process.env.JWT_SECRET = process.env.JWT_SECRET || 'capsort-test-secret';
process.env.STORAGE_PATH = fs.mkdtempSync(path.join(os.tmpdir(), 'picpeak-capsort-storage-'));
const request = require('supertest');
const express = require('express');
const cookieParser = require('cookie-parser');
const { bootCrmDb, seedMinimal } = require('../integration/helpers/crmDb');
const SLUG = 'capsort-gallery';
describe('capture-date ordering on SQLite (#1172)', () => {
let db; let cleanup; let app; let eventId;
// Managed uploads store an epoch-millisecond INTEGER, because
// photoProcessor.js:441 hands knex a Date and the sqlite3 binding converts
// it. That conversion cannot be reproduced from inside jest — there the
// binding's type dispatch misses sandbox-created Dates and writes the string
// "[object Object]" instead (CLAUDE.md). Verified outside jest: a Date lands
// as {"c":1830211200000,"ty":"integer"}. So these tests write the integer
// production would have written, rather than a Date that jest mangles.
const managed = (iso) => new Date(iso).getTime();
const addPhoto = async (filename, capturedAt, uploadedAt) => {
const row = await db('photos').insert({
event_id: eventId,
filename,
path: `${SLUG}/${filename}`,
type: 'individual',
captured_at: capturedAt,
uploaded_at: uploadedAt,
}).returning('id');
return row[0]?.id ?? row[0];
};
const orderedFilenames = async (order = 'asc') => {
const res = await request(app).get(`/api/gallery/${SLUG}/photos?sort=capture_date&order=${order}`);
expect(res.status).toBe(200);
return res.body.photos.map((p) => p.filename);
};
beforeAll(async () => {
({ db, cleanup } = await bootCrmDb());
await seedMinimal(db);
const ev = await db('events').insert({
slug: SLUG,
event_type: 'wedding',
event_name: 'Capture Sort',
event_date: '2026-08-01',
host_email: 'h@example.com',
admin_email: 'a@example.com',
password_hash: 'x',
share_link: `/gallery/${SLUG}/s`,
share_token: 'capsort-share',
expires_at: new Date(Date.now() + 7 * 864e5).toISOString(),
is_active: 1,
is_archived: 0,
is_draft: 0,
require_password: 0,
created_at: new Date().toISOString(),
}).returning('id');
eventId = ev[0]?.id ?? ev[0];
app = express();
app.use(express.json());
app.use(cookieParser());
app.use('/api/gallery', require('../../src/routes/gallery'));
}, 120000);
afterAll(async () => { if (cleanup) await cleanup(); });
beforeEach(async () => { await db('photos').where({ event_id: eventId }).del(); });
test('the fixture really does put three storage classes in one column', async () => {
expect(['sqlite3', 'better-sqlite3']).toContain(db.client.config.client);
await addPhoto('m.jpg', managed('2026-06-03T01:15:00Z'), '2026-01-01 00:00:00');
await addPhoto('e.jpg', '2020-01-01T00:00:00.000Z', '2026-01-01 00:00:00');
await addPhoto('n.jpg', null, '2026-01-01 00:00:00');
const rows = await db.raw('select filename, typeof(captured_at) as t from photos order by filename');
const byName = Object.fromEntries((rows.rows || rows).map((r) => [r.filename, r.t]));
// Exactly the mixture that made COALESCE meaningless.
expect(byName).toEqual({ 'm.jpg': 'integer', 'e.jpg': 'text', 'n.jpg': 'null' });
});
test('a managed EXIF date does not outrank an earlier one stored as text', async () => {
// The pre-existing failure, reachable with managed photos alone: integer
// beat text regardless of the dates, so this came back exactly reversed.
await addPhoto('managed-2027.jpg', managed('2027-12-31T00:00:00Z'), '2026-01-01 00:00:00');
await addPhoto('external-2020.jpg', '2020-01-01T00:00:00.000Z', '2026-01-01 00:00:00');
expect(await orderedFilenames('asc')).toEqual(['external-2020.jpg', 'managed-2027.jpg']);
expect(await orderedFilenames('desc')).toEqual(['managed-2027.jpg', 'external-2020.jpg']);
});
test('a photo with no capture date sorts by its upload time, not ahead of everything', async () => {
await addPhoto('has-exif-2027.jpg', managed('2027-12-31T00:00:00Z'), '2027-12-31 00:00:00');
await addPhoto('no-exif-2020.jpg', null, '2020-01-01 00:00:00');
expect(await orderedFilenames('asc')).toEqual(['no-exif-2020.jpg', 'has-exif-2027.jpg']);
});
test('an ISO capture time and a fallback upload time compare by clock, not by separator', async () => {
// Same day: 'T' vs ' ' decided this before, so 01:15 sorted after 23:00.
await addPhoto('iso-0115.jpg', '2026-06-03T01:15:00.000Z', '2026-06-03 05:00:00');
await addPhoto('fallback-2300.jpg', null, '2026-06-03 23:00:00');
expect(await orderedFilenames('asc')).toEqual(['iso-0115.jpg', 'fallback-2300.jpg']);
});
test('an epoch-integer uploaded_at is compared as a date, not as its digits', async () => {
// uploaded_at is not always text either: a legacy archive restore leaves
// epoch milliseconds in it (a .picpeak restore from an install that stored them that way).
// Reading that with substr() would have compared the string '1830297600000'
// against '2020-01-01 00:00:00', putting the 2028 row first.
await addPhoto('epoch-upload-2028.jpg', null, new Date('2028-01-01T00:00:00Z').getTime());
await addPhoto('captured-2020.jpg', managed('2020-01-01T00:00:00Z'), '2020-01-01 00:00:00');
const [row] = await db.raw('select typeof(uploaded_at) as t from photos where filename = \'epoch-upload-2028.jpg\'');
expect((row.t || row).toString()).toBe('integer');
expect(await orderedFilenames('asc')).toEqual(['captured-2020.jpg', 'epoch-upload-2028.jpg']);
});
test('all three storage classes order together correctly', async () => {
await addPhoto('c-managed-2026-08.jpg', managed('2026-08-15T12:00:00Z'), '2026-09-01 00:00:00');
await addPhoto('a-external-2026-06.jpg', '2026-06-03T01:15:00.000Z', '2026-09-01 00:00:00');
await addPhoto('d-fallback-2026-09.jpg', null, '2026-09-01 00:00:00');
await addPhoto('b-managed-2026-07.jpg', managed('2026-07-04T09:30:00Z'), '2026-09-01 00:00:00');
expect(await orderedFilenames('asc')).toEqual([
'a-external-2026-06.jpg',
'b-managed-2026-07.jpg',
'c-managed-2026-08.jpg',
'd-fallback-2026-09.jpg',
]);
});
});
@@ -0,0 +1,116 @@
/**
* ensureHeroImage must work for external/reference photos (#1166 follow-up).
*
* resolvePhotoStorageKey returns null for external photos by design, and that
* null used to be handed straight to withLocalCopy, which throws — so the hero
* route caught it and redirected to the full ORIGINAL. #1078 fixed exactly
* this shape for ensurePreviewImage and nobody carried it across.
*
* It only became visible when the Story hero started asking for hero_url
* instead of photo.url: on a managed gallery that is a real saving, on a
* reference-mode gallery it quietly changed nothing.
*/
const path = require('path');
const fs = require('fs').promises;
const os = require('os');
const sharp = require('sharp');
const EXTERNAL_ROOT = path.join(os.tmpdir(), `picpeak-hero-ext-${process.pid}`);
process.env.EXTERNAL_MEDIA_ROOT = EXTERNAL_ROOT;
jest.mock('../../src/database/db', () => {
const state = { event: null, updates: [] };
const api = (table) => {
if (table === 'events') return { where: () => ({ first: async () => state.event }) };
if (table === 'photos') {
return { where: (criteria) => ({ update: async (values) => { state.updates.push({ criteria, values }); return 1; } }) };
}
throw new Error(`unexpected table in test: ${table}`);
};
api.__state = state;
return { db: api };
});
const LocalFsStorage = require('../../src/services/storage/LocalFsStorage');
const storageModule = require('../../src/services/storage');
const { db } = require('../../src/database/db');
const EVENT = { id: 7, slug: 'nas-wedding', source_mode: 'reference', external_path: 'weddings/2026-08' };
async function writeSourceJpeg(absPath, { width = 2400, height = 1600 } = {}) {
await fs.mkdir(path.dirname(absPath), { recursive: true });
const buf = Buffer.alloc(width * height * 3);
for (let i = 0; i < buf.length; i++) buf[i] = (i * 7) % 256;
await sharp(buf, { raw: { width, height, channels: 3 } }).jpeg({ quality: 90 }).toFile(absPath);
}
describe('ensureHeroImage — external sources', () => {
let storage; let storageRoot; let imageProcessor;
beforeAll(async () => {
storageRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'picpeak-hero-store-'));
storage = new LocalFsStorage({ root: storageRoot });
await storage.init();
storageModule.setStorageForTesting(storage);
delete require.cache[require.resolve('../../src/services/imageProcessor')];
imageProcessor = require('../../src/services/imageProcessor');
await fs.mkdir(path.join(EXTERNAL_ROOT, EVENT.external_path), { recursive: true });
}, 30000);
afterAll(async () => {
storageModule.resetStorage();
await fs.rm(storageRoot, { recursive: true, force: true }).catch(() => {});
await fs.rm(EXTERNAL_ROOT, { recursive: true, force: true }).catch(() => {});
});
beforeEach(() => { db.__state.event = EVENT; db.__state.updates = []; });
it.each(['external', 'reference'])('generates a hero for a %s photo off the mount', async (sourceOrigin) => {
const name = `${sourceOrigin}-hero.jpg`;
await writeSourceJpeg(path.join(EXTERNAL_ROOT, EVENT.external_path, name));
const photo = {
id: sourceOrigin === 'external' ? 301 : 302,
event_id: EVENT.id,
source_origin: sourceOrigin,
// Root-relative, as stored since #1163: external_relpath is resolved
// from EXTERNAL_MEDIA_ROOT, not from event.external_path. The base-
// relative form this fixture used to carry stopped resolving the moment
// that landed, and ensureHeroImage returned null.
external_relpath: path.join(EVENT.external_path, name),
filename: name,
hero_path: null,
};
const key = await imageProcessor.ensureHeroImage(photo);
// The regression: this returned null and the route redirected to the
// full original.
expect(key).toBeTruthy();
expect(await storage.exists(key)).toBe(true);
// Per-photo basename, so two events sharing a NAS filename cannot clobber
// each other — same rule as the preview tier.
expect(key).toContain(`ext${photo.id}_`);
expect(db.__state.updates).toEqual([{ criteria: { id: photo.id }, values: { hero_path: key } }]);
});
it('returns null rather than throwing when the external source is gone', async () => {
const photo = {
id: 303, event_id: EVENT.id, source_origin: 'external',
external_relpath: path.join(EVENT.external_path, 'not-on-the-mount.jpg'), filename: 'not-on-the-mount.jpg', hero_path: null,
};
await expect(imageProcessor.ensureHeroImage(photo)).resolves.toBeNull();
expect(db.__state.updates).toEqual([]);
});
it('returns null for a reference-mode row with no source_origin', async () => {
// Mode falls back to the event's, so resolvePhotoStorageKey yields null.
// That used to reach withLocalCopy and throw out of the function.
const photo = {
id: 304, event_id: EVENT.id, source_origin: null, external_relpath: null,
filename: 'orphan.jpg', path: 'nas-wedding/individual/orphan.jpg', hero_path: null,
};
await expect(imageProcessor.ensureHeroImage(photo)).resolves.toBeNull();
});
});
@@ -91,15 +91,16 @@ describe('ensurePreviewImage — external/reference sources (#1078)', () => {
it.each(['external', 'reference'])(
'generates a downscaled preview for a %s photo off the media mount',
async (sourceOrigin) => {
const relpath = `${sourceOrigin}-shot.jpg`;
await writeSourceJpeg(path.join(EXTERNAL_ROOT, EVENT.external_path, relpath));
const name = `${sourceOrigin}-shot.jpg`;
await writeSourceJpeg(path.join(EXTERNAL_ROOT, EVENT.external_path, name));
const photo = {
id: sourceOrigin === 'external' ? 101 : 102,
event_id: EVENT.id,
source_origin: sourceOrigin,
external_relpath: relpath,
filename: relpath,
// Relative to the media ROOT, not to event.external_path (#1163).
external_relpath: path.join(EVENT.external_path, name),
filename: name,
preview_path: null,
};
@@ -107,7 +108,7 @@ describe('ensurePreviewImage — external/reference sources (#1078)', () => {
// Per-photo basename so two events referencing the same NAS filename
// can't clobber each other's preview.
expect(key).toBe(`previews/preview_ext${photo.id}_${relpath}`);
expect(key).toBe(`previews/preview_ext${photo.id}_${name}`);
expect(await storage.exists(key)).toBe(true);
const meta = await sharp(storage.resolveLocalPath(key)).metadata();
@@ -124,14 +125,14 @@ describe('ensurePreviewImage — external/reference sources (#1078)', () => {
);
it('short-circuits on an existing valid preview instead of regenerating', async () => {
const relpath = 'already-previewed.jpg';
await writeSourceJpeg(path.join(EXTERNAL_ROOT, EVENT.external_path, relpath));
const name = 'already-previewed.jpg';
await writeSourceJpeg(path.join(EXTERNAL_ROOT, EVENT.external_path, name));
const photo = {
id: 103,
event_id: EVENT.id,
source_origin: 'external',
external_relpath: relpath,
filename: relpath,
external_relpath: path.join(EVENT.external_path, name),
filename: name,
preview_path: null,
};
@@ -179,19 +180,19 @@ describe('ensurePreviewImage — external/reference sources (#1078)', () => {
// Pins why the /regenerate-previews caller must select source_origin:
// an external row missing that column takes the managed path, where
// resolvePhotoStorageKey yields null and generation is skipped.
const relpath = 'column-starved.jpg';
await writeSourceJpeg(path.join(EXTERNAL_ROOT, EVENT.external_path, relpath));
const name = 'column-starved.jpg';
await writeSourceJpeg(path.join(EXTERNAL_ROOT, EVENT.external_path, name));
const starved = {
id: 106,
event_id: EVENT.id,
external_relpath: relpath,
external_relpath: path.join(EVENT.external_path, name),
preview_path: null,
};
await expect(imageProcessor.ensurePreviewImage(starved)).resolves.toBeNull();
await expect(
imageProcessor.ensurePreviewImage({ ...starved, source_origin: 'external', filename: relpath })
).resolves.toBe(`previews/preview_ext106_${relpath}`);
imageProcessor.ensurePreviewImage({ ...starved, source_origin: 'external', filename: name })
).resolves.toBe(`previews/preview_ext106_${name}`);
});
it('still routes managed photos through the storage backend', async () => {
@@ -0,0 +1,92 @@
/**
* A pre-#1162 backup must still restore (#1162 review).
*
* `replaceAllTables` suspends FOREIGN KEY enforcement for the load — Postgres
* via `session_replication_role = replica`, SQLite via `defer_foreign_keys` —
* but neither of those suspends a UNIQUE index. An archive taken before
* migration 186 carries exactly the duplicate photo rows that migration
* removes, so the batchInsert would hit the new index and roll the entire
* restore back, after every table had already been emptied.
*
* These pin the drop → load → dedupe → recreate sequence the restore now
* performs, and the failure it exists to prevent.
*/
const path = require('path');
const fs = require('fs');
const os = require('os');
const {
dedupeExternalPhotos,
createExternalRelpathIndex,
dropExternalRelpathIndex,
} = require('../../src/services/externalPhotoDedupe');
describe('restoring an archive that predates the unique index (#1162)', () => {
let knex; let tmpDir;
// What a pre-186 archive's photos.ndjson holds for a racing import: the same
// file twice, sub-millisecond apart.
const ARCHIVE_ROWS = [
{ id: 1, event_id: 1, external_relpath: 'Trip/a.jpg', source_origin: 'external' },
{ id: 2, event_id: 1, external_relpath: 'Trip/a.jpg', source_origin: 'external' },
{ id: 3, event_id: 1, external_relpath: 'Trip/b.jpg', source_origin: 'external' },
];
beforeAll(async () => {
tmpDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'picpeak-restore-dedupe-'));
knex = require('knex')({
client: 'sqlite3',
connection: { filename: path.join(tmpDir, 'db.sqlite') },
useNullAsDefault: true,
});
});
afterAll(async () => {
if (knex) await knex.destroy();
await fs.promises.rm(tmpDir, { recursive: true, force: true }).catch(() => {});
});
beforeEach(async () => {
await knex.schema.dropTableIfExists('photos');
await knex.schema.createTable('photos', (t) => {
t.integer('id').primary();
t.integer('event_id');
t.string('external_relpath');
t.string('thumbnail_path');
t.string('source_origin').defaultTo('managed');
});
await createExternalRelpathIndex(knex);
});
it('would abort the whole restore without the drop', async () => {
// The regression, stated directly: this is what the target instance does
// today when handed a legacy archive.
await expect(knex.batchInsert('photos', ARCHIVE_ROWS, 100)).rejects.toThrow(/unique/i);
});
it('loads, dedupes and comes back constrained', async () => {
await dropExternalRelpathIndex(knex);
await knex.batchInsert('photos', ARCHIVE_ROWS, 100);
const removed = await dedupeExternalPhotos(knex);
await createExternalRelpathIndex(knex);
expect(removed).toBe(1);
expect((await knex('photos').orderBy('id')).map((r) => r.external_relpath))
.toEqual(['Trip/a.jpg', 'Trip/b.jpg']);
// The target must not be left unprotected by the restore that dropped it.
await expect(
knex('photos').insert({ id: 9, event_id: 1, external_relpath: 'Trip/b.jpg', source_origin: 'external' })
).rejects.toThrow(/unique/i);
});
it('is a no-op for an archive that has no duplicates', async () => {
await dropExternalRelpathIndex(knex);
await knex.batchInsert('photos', ARCHIVE_ROWS.slice(1), 100);
expect(await dedupeExternalPhotos(knex)).toBe(0);
await expect(createExternalRelpathIndex(knex)).resolves.toBeUndefined();
expect(await knex('photos').count('* as c').first()).toEqual({ c: 2 });
});
});
@@ -0,0 +1,134 @@
/**
* The preview tier must not destroy what it is previewing.
*
* generatePreviewImage encoded JPEG unconditionally. JPEG has no alpha channel
* and no second frame, so a transparent PNG came back flattened onto a solid
* background and an animated GIF came back as its first frame — for every
* consumer of this tier, not just the lightbox: the slideshow (#1015), admin
* previews, and the face avatars that read it as a whole-frame rendition.
*
* Driven against real Sharp output, because the whole question is what is in
* the encoded bytes.
*/
const path = require('path');
const fs = require('fs').promises;
const os = require('os');
const sharp = require('sharp');
const LocalFsStorage = require('../../src/services/storage/LocalFsStorage');
const storageModule = require('../../src/services/storage');
/** A 2x2 GIF89a with two frames and a NETSCAPE loop block. */
const ANIMATED_GIF = Buffer.from([
0x47, 0x49, 0x46, 0x38, 0x39, 0x61,
0x02, 0x00, 0x02, 0x00,
0xF0, 0x00, 0x00,
0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF,
0x21, 0xFF, 0x0B, 0x4E, 0x45, 0x54, 0x53, 0x43, 0x41, 0x50, 0x45,
0x32, 0x2E, 0x30, 0x03, 0x01, 0x00, 0x00, 0x00,
0x21, 0xF9, 0x04, 0x00, 0x0A, 0x00, 0x00, 0x00,
0x2C, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x02, 0x00, 0x00,
0x02, 0x02, 0x44, 0x01, 0x00,
0x21, 0xF9, 0x04, 0x00, 0x0A, 0x00, 0x00, 0x00,
0x2C, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x02, 0x00, 0x00,
0x02, 0x02, 0x4C, 0x01, 0x00,
0x3B,
]);
// No width-tier case here: the responsive `?w=` renditions (#1095) are
// main-only, so this branch has a single canonical preview per photo.
describe('generatePreviewImage encodes for the source (#1166 follow-up)', () => {
let storage; let storageRoot; let srcDir; let imageProcessor;
beforeAll(async () => {
storageRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'picpeak-prevfmt-store-'));
srcDir = await fs.mkdtemp(path.join(os.tmpdir(), 'picpeak-prevfmt-src-'));
storage = new LocalFsStorage({ root: storageRoot });
await storage.init();
storageModule.setStorageForTesting(storage);
delete require.cache[require.resolve('../../src/services/imageProcessor')];
imageProcessor = require('../../src/services/imageProcessor');
}, 30000);
afterAll(async () => {
storageModule.resetStorage();
await fs.rm(storageRoot, { recursive: true, force: true }).catch(() => {});
await fs.rm(srcDir, { recursive: true, force: true }).catch(() => {});
});
const outMeta = async (key) => sharp(storage.resolveLocalPath(key)).metadata();
it('keeps transparency, as WebP, for a PNG with alpha', async () => {
const src = path.join(srcDir, 'logo.png');
await sharp({
create: { width: 800, height: 600, channels: 4, background: { r: 0, g: 0, b: 0, alpha: 0 } },
}).png().toFile(src);
const key = await imageProcessor.generatePreviewImage(src, { regenerate: true });
expect(key).toBe('previews/preview_logo.webp');
const meta = await outMeta(key);
expect(meta.format).toBe('webp');
// The regression, stated directly: JPEG would have flattened this.
expect(meta.hasAlpha).toBe(true);
});
it('keeps every frame, as WebP, for an animated GIF', async () => {
const src = path.join(srcDir, 'wave.gif');
// Hand-assembled rather than produced by Sharp: writing a multi-page image
// needs pageHeight threaded through the pipeline, and a fixture that
// silently comes out single-page would make this test pass for the wrong
// reason. 2x2, two frames, black then white.
await fs.writeFile(src, ANIMATED_GIF);
// Precondition: the fixture really is animated.
expect((await sharp(src, { animated: true }).metadata()).pages).toBe(2);
const key = await imageProcessor.generatePreviewImage(src, { regenerate: true });
expect(key).toBe('previews/preview_wave.webp');
const meta = await sharp(storage.resolveLocalPath(key), { animated: true }).metadata();
expect(meta.format).toBe('webp');
// The regression, stated directly: JPEG kept only the first frame.
expect(meta.pages).toBe(2);
});
it('still writes plain JPEG for an ordinary photo', async () => {
// The common path must not pay for the two cases above: JPEG is smaller
// than WebP at the quality this tier uses, and every existing preview is
// one.
const src = path.join(srcDir, 'shot.jpg');
await sharp({ create: { width: 2400, height: 1600, channels: 3, background: { r: 90, g: 90, b: 90 } } })
.jpeg().toFile(src);
const key = await imageProcessor.generatePreviewImage(src, { regenerate: true });
expect(key).toBe('previews/preview_shot.jpg');
const meta = await outMeta(key);
expect(meta.format).toBe('jpeg');
// 2400x1600 capped at the 1920 long edge, aspect preserved — unchanged.
expect([meta.width, meta.height]).toEqual([1920, 1280]);
});
it('names the output for what it wrote, not for the source', async () => {
// A PNG source used to produce `preview_x.png` holding JPEG bytes. Harmless
// while the route hard-coded image/jpeg; wrong once the encoding varies,
// and the route now reads the extension.
const src = path.join(srcDir, 'opaque.png');
await sharp({ create: { width: 400, height: 400, channels: 3, background: { r: 1, g: 2, b: 3 } } })
.png().toFile(src);
const key = await imageProcessor.generatePreviewImage(src, { regenerate: true });
expect(key).toBe('previews/preview_opaque.jpg');
expect((await outMeta(key)).format).toBe('jpeg');
});
it('returns null on an unreadable source instead of throwing', async () => {
const src = path.join(srcDir, 'not-an-image.jpg');
await fs.writeFile(src, 'plain text');
await expect(imageProcessor.generatePreviewImage(src, { regenerate: true })).resolves.toBeNull();
});
});
@@ -0,0 +1,90 @@
/**
* Regeneration must not destroy a good thumbnail when the source is
* unreadable (#1129).
*
* The old code deleted the target BEFORE sharp opened the source, so a NAS
* mount that blipped mid-run left the previous rendition gone and the database
* still pointing at it. Across a bulk regenerate that is the whole gallery,
* and it is precisely the "worse than before you pressed it" outcome #1129 is
* about.
*/
const path = require('path');
const fs = require('fs').promises;
const os = require('os');
const sharp = require('sharp');
jest.mock('../../src/database/db', () => ({
db: () => ({ where: () => ({ first: async () => null, update: async () => 1 }) }),
}));
const LocalFsStorage = require('../../src/services/storage/LocalFsStorage');
const storageModule = require('../../src/services/storage');
describe('generateThumbnail — regenerate is non-destructive (#1129)', () => {
let storage; let root; let imageProcessor; let srcDir;
beforeAll(async () => {
root = await fs.mkdtemp(path.join(os.tmpdir(), 'picpeak-regen-store-'));
srcDir = await fs.mkdtemp(path.join(os.tmpdir(), 'picpeak-regen-src-'));
storage = new LocalFsStorage({ root });
await storage.init();
storageModule.setStorageForTesting(storage);
delete require.cache[require.resolve('../../src/services/imageProcessor')];
imageProcessor = require('../../src/services/imageProcessor');
}, 30000);
afterAll(async () => {
storageModule.resetStorage();
await fs.rm(root, { recursive: true, force: true }).catch(() => {});
await fs.rm(srcDir, { recursive: true, force: true }).catch(() => {});
});
async function writeSource(name, size = 400) {
const p = path.join(srcDir, name);
await sharp({ create: { width: size, height: size, channels: 3, background: { r: 1, g: 2, b: 3 } } })
.jpeg().toFile(p);
return p;
}
it('keeps the existing thumbnail when the source cannot be read', async () => {
const src = await writeSource('present.jpg');
const key = await imageProcessor.generateThumbnail(src, { regenerate: true });
expect(key).toBeTruthy();
expect(await storage.exists(key)).toBe(true);
const before = await storage.get(key).then((s) => new Promise((res) => {
const c = []; s.on('data', (d) => c.push(d)); s.on('end', () => res(Buffer.concat(c)));
}));
// The mount goes away between runs.
await fs.unlink(src);
const second = await imageProcessor.generateThumbnail(src, { regenerate: true })
.catch(() => null);
expect(second).toBeFalsy();
// The old rendition is still there and still serves. Previously it had
// been deleted before sharp ever looked at the source.
expect(await storage.exists(key)).toBe(true);
const after = await storage.get(key).then((s) => new Promise((res) => {
const c = []; s.on('data', (d) => c.push(d)); s.on('end', () => res(Buffer.concat(c)));
}));
expect(after.equals(before)).toBe(true);
});
it('still replaces the thumbnail when the source IS readable', async () => {
const src = await writeSource('replaceme.jpg', 400);
const key = await imageProcessor.generateThumbnail(src, { regenerate: true });
const firstSize = (await storage.stat(key)).size;
// Same key, different source content — the atomic rename in put() is what
// makes the pre-delete unnecessary.
await fs.rm(src);
await sharp({ create: { width: 400, height: 400, channels: 3, background: { r: 250, g: 40, b: 9 } } })
.jpeg().toFile(src);
const again = await imageProcessor.generateThumbnail(src, { regenerate: true });
expect(again).toBe(key);
expect((await storage.stat(key)).size).not.toBe(firstSize);
});
});
@@ -0,0 +1,159 @@
/**
* EXIF orientation in the gallery-facing generators (#1185).
*
* sharp decodes the pixels as stored, not as displayed. A photo whose
* Orientation tag is not 1 — routine for portrait shots on bodies that tag
* rather than rotate the sensor data — therefore resizes from the raw frame
* and comes out sideways. The generators then call `.withMetadata(false)`,
* which strips the tag from the output, so the browser has no hint left to
* correct it either: nothing downstream can recover it.
*
* The download path (`resizeToBox`) always got this right. These three did
* not, which is why the same photo looked correct on download and rotated in
* the gallery.
*
* Every assertion here fails on the unfixed generators.
*/
const fs = require('fs').promises;
const path = require('path');
const os = require('os');
const sharp = require('sharp');
// imageProcessor reads its thumbnail settings from app_settings, so without a
// db the require() alone hangs the run. Same shape the other generator tests
// use (ensureHeroImage.external.test.js).
jest.mock('../../src/database/db', () => {
const api = (table) => {
if (table === 'app_settings') {
return { where: () => ({ whereIn: () => [], first: async () => null }), whereIn: async () => [] };
}
if (table === 'events') return { where: () => ({ first: async () => null }) };
if (table === 'photos') return { where: () => ({ update: async () => 1, first: async () => null }) };
return { where: () => ({ first: async () => null }) };
};
return { db: api };
});
const LocalFsStorage = require('../../src/services/storage/LocalFsStorage');
const storageModule = require('../../src/services/storage');
describe('EXIF orientation in thumbnails, heroes and previews (#1185)', () => {
let tmpDir;
let imageProcessor;
let landscapeTaggedPortrait;
// 400x200 as stored, Orientation 6 (90° CW) — so it DISPLAYS as 200x400.
// This is exactly the shape the reporter's Sony bodies produce: the sensor
// data is landscape and the tag carries the rotation.
const W = 400;
const H = 200;
let storageRoot;
beforeAll(async () => {
tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'picpeak-orient-'));
storageRoot = path.join(tmpDir, 'storage');
await fs.mkdir(storageRoot, { recursive: true });
process.env.STORAGE_PATH = storageRoot;
const storage = new LocalFsStorage({ root: storageRoot });
await storage.init();
storageModule.setStorageForTesting(storage);
landscapeTaggedPortrait = path.join(tmpDir, 'portrait-tagged.jpg');
await sharp({
create: { width: W, height: H, channels: 3, background: { r: 120, g: 80, b: 40 } },
})
.withMetadata({ orientation: 6 })
.jpeg()
.toFile(landscapeTaggedPortrait);
delete require.cache[require.resolve('../../src/services/imageProcessor')];
imageProcessor = require('../../src/services/imageProcessor');
}, 60000);
afterAll(async () => {
await fs.rm(tmpDir, { recursive: true, force: true }).catch(() => {});
});
test('the fixture really is stored landscape with a rotation tag', async () => {
const m = await sharp(landscapeTaggedPortrait).metadata();
expect(m.width).toBe(W);
expect(m.height).toBe(H);
expect(m.orientation).toBe(6);
});
test('orientedDimensions reports what a viewer sees, not what is stored', async () => {
const m = await sharp(landscapeTaggedPortrait).metadata();
// Swapped: this is what the grid needs to size a tile, and what the
// database should hold.
expect(imageProcessor.orientedDimensions(m)).toEqual({ width: H, height: W });
});
test('orientedDimensions leaves an untagged image alone', async () => {
const plain = path.join(tmpDir, 'plain.jpg');
await sharp({ create: { width: W, height: H, channels: 3, background: { r: 1, g: 2, b: 3 } } })
.jpeg().toFile(plain);
const m = await sharp(plain).metadata();
expect(imageProcessor.orientedDimensions(m)).toEqual({ width: W, height: H });
});
test('orientedDimensions survives metadata it cannot use', () => {
expect(imageProcessor.orientedDimensions(null)).toEqual({ width: null, height: null });
expect(imageProcessor.orientedDimensions({})).toEqual({ width: null, height: null });
});
test('the thumbnail comes out portrait, not sideways', async () => {
const rel = await imageProcessor.generateThumbnail(landscapeTaggedPortrait, {
outputBasename: 'orient-thumb.jpg',
regenerate: true,
});
expect(rel).toBeTruthy();
const out = await sharp(path.join(storageRoot, rel)).metadata();
// Unfixed, this came back wider than tall — the raw frame, resized.
expect(out.height).toBeGreaterThan(out.width);
});
test('the preview tier comes out portrait too', async () => {
const rel = await imageProcessor.generatePreviewImage(landscapeTaggedPortrait, {
outputBasename: 'orient-preview.jpg',
});
expect(rel).toBeTruthy();
const out = await sharp(path.join(storageRoot, rel)).metadata();
expect(out.height).toBeGreaterThan(out.width);
});
test('the watermarked rendition is oriented too', async () => {
// gallery.js serves photos.watermark_path ahead of the original when
// branding watermarking is on, so this is the rendition a guest actually
// sees — and it went through its own sharp pipeline that nobody had
// rotated.
const watermarkService = require('../../src/services/watermarkService');
const buf = await watermarkService.applyWatermark(landscapeTaggedPortrait, {
enabled: true, position: 'bottom-right', opacity: 50, size: 15,
// companyName, not text — the SVG branch reads this one, and without it
// the service falls through without compositing anything.
companyName: 'PicPeak',
});
expect(Buffer.isBuffer(buf)).toBe(true);
const out = await sharp(buf).metadata();
// 400x200 stored, tagged 6 — so the watermarked output must be portrait.
expect(out.height).toBeGreaterThan(out.width);
});
test('the orientation tag is gone from the output, so nothing double-rotates', async () => {
// The pixels are corrected now, so a surviving tag would make a viewer
// rotate an already-rotated image. withMetadata(false) strips it; this
// pins that the two changes agree.
const rel = await imageProcessor.generateThumbnail(landscapeTaggedPortrait, {
outputBasename: 'orient-thumb-tag.jpg',
regenerate: true,
});
const out = await sharp(path.join(storageRoot, rel)).metadata();
expect(out.orientation === undefined || out.orientation === 1).toBe(true);
});
});
@@ -0,0 +1,201 @@
/**
* "Storage used" has to mean storage used (#1164).
*
* The tile summed photos.size_bytes, so on a reference-mode install it
* reported the size of files sitting on a NAS — the reporter's read ~80 GB
* against 21 GB of real local usage — while omitting everything PicPeak does
* write locally, including an 11.8 GB download-cache zip.
*
* These pin the measurement against a real directory tree, since the whole
* point is counting bytes that are actually there.
*/
const path = require('path');
const fs = require('fs');
const os = require('os');
const {
measureLocalStorageUsage,
resetLocalStorageUsageCache,
} = require('../../src/services/localStorageUsage');
describe('localStorageUsage (#1164)', () => {
let root;
const write = async (rel, bytes) => {
const full = path.join(root, rel);
await fs.promises.mkdir(path.dirname(full), { recursive: true });
await fs.promises.writeFile(full, Buffer.alloc(bytes));
};
beforeEach(async () => {
root = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'picpeak-usage-'));
process.env.STORAGE_PATH = root;
delete process.env.EXTERNAL_MEDIA_ROOT;
jest.resetModules();
resetLocalStorageUsageCache();
});
afterEach(async () => {
await fs.promises.rm(root, { recursive: true, force: true }).catch(() => {});
delete process.env.STORAGE_PATH;
delete process.env.EXTERNAL_MEDIA_ROOT;
resetLocalStorageUsageCache();
});
it('counts every byte under the storage root', async () => {
await write(path.join('events', 'active', 'wed', 'individual', 'a.jpg'), 1000);
await write(path.join('thumbnails', 'a.jpg'), 100);
await write(path.join('previews', 'a.jpg'), 300);
const usage = await measureLocalStorageUsage();
expect(usage.total).toBe(1400);
expect(usage.files).toBe(3);
});
it('breaks the total down by what the bytes are', async () => {
// The specific complaint: the derived artefacts PicPeak writes were
// invisible, so "what is filling my disk" had no answer in the UI.
await write(path.join('events', 'active', 'wed', 'individual', 'a.jpg'), 1000);
await write(path.join('events', 'archived', 'old.zip'), 5000);
await write(path.join('thumbnails', 'a.jpg'), 100);
await write(path.join('previews', 'a.jpg'), 300);
await write(path.join('heroes', 'a.jpg'), 200);
await write(path.join('watermarks', 'a.jpg'), 700);
await write(path.join('uploads', 'logo.png'), 50);
const { breakdown } = await measureLocalStorageUsage();
expect(breakdown).toMatchObject({
originals: 1000,
archives: 5000,
thumbnails: 100,
previews: 300,
heroes: 200,
watermarks: 700,
uploads: 50,
});
});
it('files the download cache separately from the originals it sits among', async () => {
// `.download-cache` lives INSIDE the event directory, so the naive rule
// files an 11.8 GB zip as photography. It is the one bucket that is pure
// disposable cache and the one an admin most needs to see.
await write(path.join('events', 'active', 'wed', 'individual', 'a.jpg'), 1000);
await write(path.join('events', 'active', 'wed', '.download-cache', 'all.zip'), 9000);
const { breakdown, total } = await measureLocalStorageUsage();
expect(breakdown.downloadCache).toBe(9000);
expect(breakdown.originals).toBe(1000);
expect(total).toBe(10000);
});
it('counts orphans no database row knows about', async () => {
// A deleted event's leftovers and an interrupted import's thumbnails are
// real bytes on a real disk. Summing DB columns would miss them, which is
// half of why this walks instead.
await write(path.join('thumbnails', 'ext999_gone.jpg'), 777);
expect((await measureLocalStorageUsage()).total).toBe(777);
});
it('reports zero on a fresh install rather than failing', async () => {
const usage = await measureLocalStorageUsage();
expect(usage.total).toBe(0);
expect(usage.partial).toBe(false);
});
it('survives a storage root that does not exist', async () => {
process.env.STORAGE_PATH = path.join(root, 'nope');
resetLocalStorageUsageCache();
const usage = await measureLocalStorageUsage();
// ENOENT on the root is a fresh/misconfigured install, not a partial read.
expect(usage.total).toBe(0);
expect(usage.partial).toBe(false);
});
it('does not walk the media share bind-mounted under the storage root', async () => {
// The compose default puts EXTERNAL_MEDIA_ROOT at <storage>/external-media,
// where the NAS is bind-mounted — a plain directory, not a symlink. Walking
// it would put every referenced original back into a figure that exists to
// leave them out, which is the over-count this measurement replaces.
await write(path.join('thumbnails', 'a.jpg'), 100);
await write(path.join('external-media', 'nas', 'huge.jpg'), 50000);
process.env.EXTERNAL_MEDIA_ROOT = path.join(root, 'external-media');
jest.resetModules();
const svc = require('../../src/services/localStorageUsage');
svc.resetLocalStorageUsageCache();
const usage = await svc.measureLocalStorageUsage();
expect(usage.total).toBe(100);
expect(usage.excludedExternalRoot).toBe(path.join(root, 'external-media'));
});
it('still counts a directory that merely looks like the media share', async () => {
// Only the CONFIGURED root is skipped. An install whose media lives
// elsewhere keeps whatever is in this directory in the total, because
// those really are local bytes.
await write(path.join('external-media', 'leftover.jpg'), 700);
// The production shape: the share is mounted well outside the storage root.
const elsewhere = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'picpeak-nas-elsewhere-'));
process.env.EXTERNAL_MEDIA_ROOT = elsewhere;
jest.resetModules();
const svc = require('../../src/services/localStorageUsage');
svc.resetLocalStorageUsageCache();
const usage = await svc.measureLocalStorageUsage();
expect(usage.total).toBe(700);
expect(usage.excludedExternalRoot).toBeNull();
await fs.promises.rm(elsewhere, { recursive: true, force: true });
});
it('shares one walk between concurrent cold-cache callers', async () => {
// /dashboard/stats and /storage/info are routinely requested together, and
// the sidebar adds a third. Each starting its own full stat-per-file walk
// multiplies the cost on exactly the large libraries where it hurts.
await write(path.join('thumbnails', 'a.jpg'), 100);
const readdir = jest.spyOn(fs.promises, 'readdir');
const [a, b, c] = await Promise.all([
measureLocalStorageUsage(),
measureLocalStorageUsage(),
measureLocalStorageUsage(),
]);
expect([a.total, b.total, c.total]).toEqual([100, 100, 100]);
// One walk: the storage root plus its one subdirectory.
expect(readdir).toHaveBeenCalledTimes(2);
readdir.mockRestore();
});
it('caches, and honours force', async () => {
await write(path.join('thumbnails', 'a.jpg'), 100);
expect((await measureLocalStorageUsage()).total).toBe(100);
await write(path.join('thumbnails', 'b.jpg'), 400);
// One stat per file is not free; the dashboard polls.
expect((await measureLocalStorageUsage()).total).toBe(100);
expect((await measureLocalStorageUsage({ force: true })).total).toBe(500);
});
it('does not follow a symlink out of the storage root', async () => {
// A link into EXTERNAL_MEDIA_ROOT would add the NAS back into the local
// total — reinstating the exact confusion this replaces.
const outside = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'picpeak-nas-'));
await fs.promises.writeFile(path.join(outside, 'huge.jpg'), Buffer.alloc(50000));
await fs.promises.mkdir(path.join(root, 'events'), { recursive: true });
await fs.promises.symlink(outside, path.join(root, 'events', 'nas'), 'dir');
const usage = await measureLocalStorageUsage();
expect(usage.total).toBe(0);
await fs.promises.rm(outside, { recursive: true, force: true });
});
});
@@ -72,6 +72,15 @@ jest.mock('../../src/services/imageProcessor', () => {
return {
generateThumbnail: mockGenerateThumbnail,
extractCaptureDate: mockExtractCaptureDate,
// processPhoto routes stored dimensions through this to get the displayed
// ones (#1185). Mirrored rather than requireActual'd, because pulling the
// real module in here would drag its database dependency into the mock
// factory. Kept faithful to imageProcessor.orientedDimensions.
orientedDimensions: jest.fn((m) => {
if (!m || !m.width || !m.height) return { width: null, height: null };
const swap = m.orientation >= 5 && m.orientation <= 8;
return { width: swap ? m.height : m.width, height: swap ? m.width : m.height };
}),
withLocalCopy: jest.fn(async (key, fn) =>
fn(`/tmp/local-copy-${require('path').basename(key)}`)
),
@@ -2,10 +2,10 @@ const path = require('path');
const mockPath = path;
jest.mock('../../src/services/externalMediaService', () => ({
resolveExternalPath: jest.fn((event, relPath) => mockPath.join('/mock/external', event.external_path || '', relPath || '')),
resolveExternalPhotoPath: jest.fn((photo) => mockPath.join('/mock/external', photo.external_relpath || '')),
}));
const { resolveExternalPath } = require('../../src/services/externalMediaService');
const { resolveExternalPhotoPath } = require('../../src/services/externalMediaService');
const { resolvePhotoFilePath } = require('../../src/services/photoResolver');
describe('resolvePhotoFilePath', () => {
@@ -46,24 +46,34 @@ describe('resolvePhotoFilePath', () => {
expect(result).toBe(path.join(backendRoot, 'storage', 'events/active', 'wedding-party', 'hero.jpg'));
});
it('delegates external photos to external media resolver', () => {
it('resolves an external photo from the media root, ignoring the event', () => {
const event = { slug: 'fashion-show', source_mode: 'reference', external_path: 'picsum-demo' };
const photo = { source_origin: 'external', external_relpath: 'individual/look-01.jpg' };
const photo = { source_origin: 'external', external_relpath: 'picsum-demo/individual/look-01.jpg' };
const result = resolvePhotoFilePath(event, photo);
expect(resolveExternalPath).toHaveBeenCalledWith(event, 'individual/look-01.jpg');
expect(resolveExternalPhotoPath).toHaveBeenCalledWith(photo);
expect(result).toBe(path.join('/mock/external', 'picsum-demo', 'individual', 'look-01.jpg'));
});
it('deduplicates folder names when event external path already ends with segment', () => {
const event = { slug: 'fashion-show', source_mode: 'reference', external_path: 'picsum-demo/individual' };
const photo = { source_origin: 'external', external_relpath: 'individual/look-02.jpg' };
it('does not move a photo when the event is repointed at another folder (#1163)', () => {
// The regression. Both events below hold the SAME row; only
// events.external_path differs, which is what a second import overwrites.
const photo = { source_origin: 'external', external_relpath: 'Trip/Leknes/_DSC0818.JPG' };
const before = { slug: 'trip', source_mode: 'reference', external_path: 'Trip' };
const after = { slug: 'trip', source_mode: 'reference', external_path: 'Trip/Subfolder' };
const result = resolvePhotoFilePath(event, photo);
expect(resolvePhotoFilePath(before, photo)).toBe(resolvePhotoFilePath(after, photo));
});
expect(resolveExternalPath).toHaveBeenCalledWith(event, 'look-02.jpg');
expect(result).toBe(path.join('/mock/external', 'picsum-demo/individual', 'look-02.jpg'));
it('keeps a first segment that repeats the base path', () => {
// The old duplicate-leaf-segment normalisation stripped this, which is
// corruption once the relpath is root-relative: `Trip/Trip/x.jpg` is a real
// layout, and the file is not at `Trip/x.jpg`.
const event = { slug: 'trip', source_mode: 'reference', external_path: 'Trip' };
const photo = { source_origin: 'external', external_relpath: 'Trip/Trip/x.jpg' };
expect(resolvePhotoFilePath(event, photo)).toBe(path.join('/mock/external', 'Trip', 'Trip', 'x.jpg'));
});
it('falls back to managed storage when external metadata is missing', () => {
@@ -72,7 +82,7 @@ describe('resolvePhotoFilePath', () => {
const result = resolvePhotoFilePath(event, photo);
expect(resolveExternalPath).not.toHaveBeenCalled();
expect(resolveExternalPhotoPath).not.toHaveBeenCalled();
expect(result).toBe(path.join(backendRoot, 'storage', 'events/active', 'fashion-show', 'new-upload.jpg'));
});
@@ -0,0 +1,160 @@
/**
* The contract that matters here is negative: a source that disappears must
* NOT be able to end the process (#1128).
*
* `fs.createReadStream` is lazy, so its ENOENT lands on a later tick, outside
* the route's try/catch. An EventEmitter emitting 'error' with no listener
* throws, and an uncaught throw from an I/O callback exits Node — which is how
* one missing thumbnail tier took every gallery on the install down.
*
* These use a REAL fs stream over a real missing path rather than a fake
* emitter: the point under test is the lazy-open timing, and a hand-rolled
* mock that emits synchronously would pass while proving nothing.
*/
const fs = require('fs');
const os = require('os');
const path = require('path');
const { Readable } = require('stream');
const { EventEmitter } = require('events');
const { pipeStreamToResponse } = require('../../src/utils/streamResponse');
jest.mock('../../src/utils/logger', () => ({
warn: jest.fn(), error: jest.fn(), info: jest.fn(), debug: jest.fn(),
}));
/** Minimal Express-ish response that records what happened to it. */
function makeRes() {
const res = new EventEmitter();
res.headers = { 'Content-Length': '1234', ETag: '"x"' };
res.statusCode = 200;
res.headersSent = false;
res.writableEnded = false;
res.body = null;
res.destroyed = false;
res.removeHeader = (h) => { delete res.headers[h]; };
res.setHeader = (h, v) => { res.headers[h] = v; };
res.status = (code) => { res.statusCode = code; return res; };
res.json = (payload) => { res.body = payload; res.writableEnded = true; return res; };
res.destroy = () => { res.destroyed = true; };
// pipe() target surface
res.write = () => true;
res.end = () => { res.writableEnded = true; };
res.on = EventEmitter.prototype.on.bind(res);
res.emit = EventEmitter.prototype.emit.bind(res);
return res;
}
const settle = () => new Promise((resolve) => setTimeout(resolve, 50));
describe('pipeStreamToResponse (#1128)', () => {
it('turns a missing file into a 404 instead of an unhandled error', async () => {
const missing = path.join(os.tmpdir(), `picpeak-not-here-${Date.now()}.jpg`);
const res = makeRes();
pipeStreamToResponse(stream_(missing), res, { context: 'thumbnail for photo 1' });
await settle();
expect(res.statusCode).toBe(404);
expect(res.body).toEqual({ error: 'File not found' });
});
// How this test discriminates, since the failure mode is a process-level
// one: replacing the call above with a bare `stream.pipe(res)` — what the
// thumbnail route did — makes jest fail this suite on the unhandled 'error'
// event before either assertion runs. Verified by doing exactly that.
// Catching the throw with a process.on('uncaughtException') listener does
// NOT work here and would be theatre: the runner installs its own handling,
// so such a listener never sees it and the assertion could never fail.
function stream_(p) { return fs.createReadStream(p); }
it('strips every header that described the file it can no longer send', async () => {
const res = makeRes();
// What the image and zip routes actually stage before streaming.
res.headers = {
'Content-Length': '1234',
ETag: '"x"',
'Content-Type': 'image/jpeg',
'Content-Disposition': 'attachment; filename="gallery.zip"',
'Cache-Control': 'private, max-age=1800',
};
const stream = fs.createReadStream(path.join(os.tmpdir(), `gone-${Date.now()}.jpg`));
pipeStreamToResponse(stream, res);
await settle();
expect(res.headers['Content-Length']).toBeUndefined();
expect(res.headers.ETag).toBeUndefined();
// Express does NOT overwrite an existing Content-Type, so leaving it makes
// res.json() emit JSON labelled image/jpeg — or a corrupt .zip download.
expect(res.headers['Content-Type']).toBeUndefined();
expect(res.headers['Content-Disposition']).toBeUndefined();
});
it('does not let a transient 404 be cached as a broken tile', async () => {
const res = makeRes();
// The thumbnail route stages 30 minutes; the hero route an hour.
res.headers = { 'Cache-Control': 'private, max-age=1800' };
const stream = fs.createReadStream(path.join(os.tmpdir(), `gone3-${Date.now()}.jpg`));
pipeStreamToResponse(stream, res);
await settle();
// The regeneration race is transient by definition: the tier exists moments
// later. Caching this 404 would keep the tile broken long after the file is
// back — the opposite of what this helper is for.
expect(res.headers['Cache-Control']).toBe('no-store');
});
it('honours a caller that wants a different missing-status', async () => {
const res = makeRes();
const stream = fs.createReadStream(path.join(os.tmpdir(), `gone2-${Date.now()}.zip`));
pipeStreamToResponse(stream, res, { missingStatus: 410 });
await settle();
expect(res.statusCode).toBe(410);
});
it('destroys the response instead of rewriting a status that is already sent', async () => {
const res = makeRes();
res.headersSent = true;
const stream = new Readable({ read() {} });
pipeStreamToResponse(stream, res, { context: 'photo 9' });
stream.emit('error', Object.assign(new Error('ENOENT'), { code: 'ENOENT' }));
await settle();
// Once bytes are on the wire a 404 is not available; a truncated image the
// client would cache is worse than a broken connection.
expect(res.destroyed).toBe(true);
expect(res.statusCode).toBe(200);
expect(res.body).toBeNull();
});
it('reports a non-ENOENT failure as a 500 rather than a 404', async () => {
const res = makeRes();
const stream = new Readable({ read() {} });
pipeStreamToResponse(stream, res);
stream.emit('error', Object.assign(new Error('disk exploded'), { code: 'EIO' }));
await settle();
expect(res.statusCode).toBe(500);
expect(res.body).toEqual({ error: 'Failed to serve file' });
});
it('releases the source when the client hangs up mid-download', async () => {
const res = makeRes();
let destroyed = false;
const stream = new Readable({ read() {}, destroy(err, cb) { destroyed = true; cb(err); } });
pipeStreamToResponse(stream, res);
res.emit('close');
await settle();
// Otherwise an abandoned grid leaks one open fd per tile.
expect(destroyed).toBe(true);
});
});
@@ -77,7 +77,11 @@ const DEFAULT_CSS_TEMPLATE = `/*
.photo-card img {
width: 100%;
height: 200px;
/* 100%, not a fixed pixel height: every aspect-ratio layout (masonry,
justified, mosaic, gallery-premium) gives .photo-card a definite height
computed from photos.width/height, and this rule's specificity (0,1,1)
beats the .h-full utility (0,1,0) the layouts rely on — #1131. */
height: 100%;
object-fit: cover;
transition: transform 0.3s ease;
}
@@ -503,7 +503,9 @@ const LIQUID_GLASS_DARK = `/*
.photo-card img {
width: 100%;
height: 240px;
/* See #1131: a fixed height here beats the layouts' .h-full utility and
detaches the image from its aspect-ratio-sized card. */
height: 100%;
object-fit: cover;
transition: transform 0.4s ease, filter 0.4s ease;
filter: brightness(0.9);
@@ -639,7 +641,7 @@ const LIQUID_GLASS_DARK = `/*
}
.photo-card img {
height: 180px;
height: 100%;
}
/* Reduce animation complexity on mobile */
@@ -0,0 +1,123 @@
/**
* The bundled CSS templates pinned every gallery image to a fixed pixel
* height, which broke every aspect-ratio layout (#1131).
*
* Six of the seven layouts size a tile by putting a computed pixel height on
* `.photo-card` and letting the image fill it with `h-full`. A template rule
* of `.photo-card img { height: 200px }` has specificity (0,1,1) and beats
* `.h-full` at (0,1,0), so the image detached from its card: masonry rendered
* correctly-shaped cards with a 200px image glued to the top and empty
* background below — or, where the computed card was shorter than 200px, an
* image taller than its own container.
*
* "Elegant Dark" is seeded `is_default = true`, so this was the out-of-the-box
* result for anyone choosing any layout other than grid/timeline (where a
* fixed square happens to look deliberate).
*
* Migrations 052 and 053 are corrected for fresh installs; this repairs the
* rows already seeded. Templates are referenced by `events.css_template_id`
* and read at serve time rather than copied onto the event, so fixing the row
* fixes every gallery using it.
*
* SCOPE: every `.photo-card img` rule that carries a fixed PIXEL height, in
* every template — not just the two we seeded, and not just their pristine
* copies.
*
* That is broader than it first looks, and deliberately so. It is also not the
* scope this started with: matching the exact seeded text missed every install
* where the template had ever been saved through the editor, because
* `sanitizeCSS` strips newlines. Those are the majority, and a migration that
* silently no-ops on them while being recorded as applied is worse than none.
*
* The cost is that a fixed pixel height a user wrote themselves is rewritten
* too. That is judged acceptable because there is no layout it can be right
* for: all seven give `.photo-card` a definite height and expect the image to
* fill it, so a pixel height on the image can only detach it from its card.
* Anything that is not a fixed px height — %, vh, auto — is left alone, as is
* every declaration outside a `.photo-card img` body.
*/
/**
* Every `.photo-card img { … }` rule body, however it is spaced.
*
* Matching the exact seeded text does NOT work, and the reason is worth
* stating: `sanitizeCSS` strips all control characters (cssSanitizer.js:61),
* so the moment an admin saves a template through the editor — even only to
* rename it or toggle it — every newline is REMOVED from the stored CSS. The
* shipped `.photo-card img {\n height: 200px;` becomes
* `.photo-card img { height: 200px;`. An exact-match migration would find
* nothing on those installs, be recorded as applied, and leave the galleries
* broken with no second chance.
*
* Scoped to the rule body rather than the whole stylesheet, so the other pixel
* heights in these same templates — a 1px gradient divider, an 8px scrollbar —
* are untouched.
*/
/*
* Two details in this pattern are deliberate:
*
* * the selector part is a LIST, so `.photo-card img, .thumbnail img { … }`
* is recognised. Requiring `{` straight after `img` skipped grouped
* selectors entirely — and the migration would still be recorded as
* applied, so the template kept the bug with no second chance.
*
* * the body excludes braces, so a rule containing a NESTED block is not
* matched at all. `.photo-card img { & + .caption { height: 200px } }` is
* valid, passes the validator, and a `[^}]*` body would have captured the
* nested block and rewritten the caption's height instead. Skipping it
* means such a template keeps a fixed image height; corrupting unrelated
* declarations in a migration that cannot be undone is the worse of the
* two, and nesting does not appear in anything we ship.
*/
const PHOTO_CARD_IMG_RULE = /([^{}]*\.photo-card\s+img[^{}]*)\{([^{}]*)\}/g;
/**
* Only a fixed PIXEL height is wrong here; %, vh, auto and the rest stay.
*
* The lookbehind is load-bearing rather than defensive: without it the pattern
* matches the TAIL of `line-height`, `max-height`, `min-height` and any custom
* property ending in `-height`, and silently rewrites those instead — in a
* migration whose down() is deliberately irreversible.
*/
const FIXED_PX_HEIGHT = /(?<![\w-])height\s*:\s*\d+(?:\.\d+)?px/gi;
function relaxFixedImageHeights(css) {
return css.replace(PHOTO_CARD_IMG_RULE, (whole, selectors, body) => {
// .test() on a /g regex advances lastIndex, so it is reset on both sides
// of the check — leaving it set makes the NEXT rule start matching from an
// arbitrary offset and silently skip declarations.
FIXED_PX_HEIGHT.lastIndex = 0;
if (!FIXED_PX_HEIGHT.test(body)) return whole;
FIXED_PX_HEIGHT.lastIndex = 0;
return `${selectors}{${body.replace(FIXED_PX_HEIGHT, 'height: 100%')}}`;
});
}
exports.up = async function up(knex) {
if (!(await knex.schema.hasTable('css_templates'))) return;
const rows = await knex('css_templates').select('id', 'css_content');
let fixed = 0;
for (const row of rows) {
const original = row.css_content;
if (!original || typeof original !== 'string') continue;
const updated = relaxFixedImageHeights(original);
if (updated !== original) {
await knex('css_templates').where({ id: row.id }).update({ css_content: updated });
fixed += 1;
}
}
if (fixed > 0) {
console.log(` 175: relaxed the fixed image height in ${fixed} CSS template(s)`);
}
};
exports.down = async function down() {
// Deliberately irreversible. Putting the pixel heights back would re-break
// every aspect-ratio layout, and the rows may have been edited since — there
// is no version of "restore" here that is safer than doing nothing.
};
@@ -0,0 +1,60 @@
/**
* Migration 176: one row per external file per event (#1162).
*
* The import route checked for an existing external_relpath and then inserted,
* with an fs.stat and a sharp().metadata() call sitting in between — a window
* wide enough that two overlapping imports of the same folder each see "not
* there" and both insert. Nothing at the storage layer stopped them: 041
* created only a NON-unique (event_id, source_origin) index. A reporter's
* event ended up holding 8004 rows for 6012 distinct paths.
*
* So this does two things: clear the duplicates that already exist, and add
* the constraint that makes the race unwinnable from here on.
*
* The work — which row survives, what happens to the guest feedback and admin
* marks hanging off the loser, and why the dependent rows are deleted by hand
* rather than left to ON DELETE CASCADE — lives in
* services/externalPhotoDedupe.js, because a .picpeak restore has to run it
* too: the archive carries the photos table verbatim, so a pre-#1162 backup
* would otherwise hit the unique index mid-restore and roll the whole thing
* back.
*
* Irreversible by design: down() drops the index but cannot resurrect the
* deleted rows. They were never distinct data — the same file counted twice.
*
* What it does NOT do is delete the duplicates' thumbnail files. Those are
* `ext<id>_<name>` keys under the thumbnail root, and a migration is the wrong
* place to reach into storage — the backend may be pointed at S3, and a failed
* object delete must not fail the schema change. They are left behind as
* unreferenced bytes; the storage figures on the dashboard count them, which
* is the correct answer to "what is on the disk".
*/
const {
dedupeExternalPhotos,
createExternalRelpathIndex,
dropExternalRelpathIndex,
} = require('../../src/services/externalPhotoDedupe');
exports.up = async function(knex) {
if (!(await knex.schema.hasTable('photos'))) return;
if (!(await knex.schema.hasColumn('photos', 'external_relpath'))) return;
const removed = await dedupeExternalPhotos(knex);
if (removed) {
console.log(`176_external_relpath_unique: removed ${removed} duplicate external photo row(s)`);
}
// Deliberately unguarded. Recording this migration as applied without the
// index would leave the install permanently racy — the in-flight set only
// covers one process, and the route's unique-violation path cannot converge
// without a constraint to violate — with nothing to trigger a retry. A
// failure here means the dedupe above did not achieve uniqueness, which is
// worth stopping the upgrade for.
await createExternalRelpathIndex(knex);
};
exports.down = async function(knex) {
if (!(await knex.schema.hasTable('photos'))) return;
await dropExternalRelpathIndex(knex);
};
@@ -0,0 +1,52 @@
/**
* Migration 177: external_relpath becomes relative to EXTERNAL_MEDIA_ROOT (#1163).
*
* It used to be relative to events.external_path, which every import
* overwrites — so importing a second folder into an event rebased every photo
* already in it onto the new folder. Nothing errored. Thumbnails are written to
* local storage during the import while the base path is still correct, so the
* grid kept rendering and only the things that need the ORIGINAL broke: preview
* generation, the lightbox, downloads. The reporter had 7547 of 8004 rows
* resolving to files that do not exist, and spent a while chasing it as a CPU
* problem.
*
* The work — including the on-disk repair of events that have already been
* rebased, and why it refuses to guess below current behaviour — lives in
* services/externalRelpathFold.js, because a .picpeak restore has to run it
* too: knex_migrations is excluded from the archive, so a pre-#1163 backup
* lands base-relative rows on an instance that has already migrated.
*/
const { foldExternalRelpaths } = require('../../src/services/externalRelpathFold');
exports.up = async function(knex) {
try {
await foldExternalRelpaths(knex, (msg) => console.log(`177_external_relpath_from_root: ${msg}`));
} catch (err) {
// Re-thrown WITHOUT the driver's error code. run-migrations-safe.js treats
// 23505 / 42P07 / 42701 / 42710 as "schema already exists" and marks the
// migration applied (run-migrations-safe.js:138) — so a unique-violation
// rolling this fold back would be recorded as a success, leaving every
// external path in the old format under a resolver that reads them
// differently, with nothing to trigger a retry.
throw new Error(
`177_external_relpath_from_root failed and was rolled back: ${err.message}. `
+ 'External photo paths are unchanged; resolve the cause and re-run the migration.'
);
}
};
/**
* Irreversible by design, and a deliberate no-op rather than a partial undo.
*
* The base each row was folded with is not recorded anywhere:
* events.external_path holds whatever the LAST import set, which for a
* repaired row is the wrong answer and is exactly what broke these installs.
* Stripping it back off would re-break them.
*
* The idempotency marker stays for the same reason — clearing it would let
* up() run a second time and fold every path twice.
*/
exports.down = async function() {
console.log('177_external_relpath_from_root: rollback is a no-op (see header)');
};
@@ -0,0 +1,55 @@
/**
* Migration 178: drop preview keys written by the old generator.
*
* generatePreviewImage used to keep the SOURCE basename verbatim, extension and
* all, while always writing JPEG bytes. So a `.webp` upload produced
* `previews/preview_shot.webp` holding a JPEG, and a `.png` upload produced
* `preview_logo.png` holding a JPEG.
*
* That was harmless while the preview route hard-coded `Content-Type:
* image/jpeg`. It stopped being harmless the moment the encoding started
* varying: the route now reads the extension, so a legacy `.webp` key is
* announced as `image/webp` while containing JPEG — and the response carries
* `X-Content-Type-Options: nosniff`, so the browser will not quietly correct
* it. The lightbox shows a broken image for every photo that happened to be
* uploaded as WebP.
*
* The legacy `.png`-keyed previews are wrong in the other direction: they are
* flattened JPEGs of what may have been a transparent source, which is the
* defect the new encoder fixes and which `isPreviewValid` would otherwise let
* stand forever.
*
* Clearing the column is the whole repair. Previews are lazily regenerated by
* ensurePreviewImage on the next open, under the new naming and the new
* encoder, so the only cost is one regeneration per photo that is actually
* viewed. Nothing is deleted from storage — a migration is the wrong place to
* reach into a backend that may be S3 — so the old objects linger as
* unreferenced bytes, which the storage breakdown counts honestly.
*
* Deliberately clears ALL of them, not just the ones whose extension looks
* suspicious. A `.jpg`-keyed legacy preview is byte-correct, but it may still
* be a flattened rendition of a transparent or animated source, and there is
* no way to tell from the key. One lazy regeneration is cheaper than reasoning
* about which of them lied.
*/
exports.up = async function(knex) {
if (!(await knex.schema.hasTable('photos'))) return;
if (!(await knex.schema.hasColumn('photos', 'preview_path'))) return;
const cleared = await knex('photos')
.whereNotNull('preview_path')
.update({ preview_path: null });
if (cleared) {
console.log(`178_reset_legacy_preview_paths: cleared ${cleared} preview key(s); they regenerate on next view`);
}
};
/**
* Irreversible by design, and harmless: the column held a cache key, and the
* cache rebuilds itself. There is nothing to restore.
*/
exports.down = async function() {
console.log('178_reset_legacy_preview_paths: rollback is a no-op (preview keys are a regenerable cache)');
};
@@ -0,0 +1,73 @@
/**
* Migration 179: shared run state for the maintenance sweeps (#1181).
*
* Both photo maintenance jobs — the dimension repair and the capture-date
* backfill — tracked whether they were running in a module-level variable. On
* a single-replica install that is correct. Behind a load balancer it is not:
* the flag lives in one process, so a status poll routed to any other replica
* answers `isRunning: false`, the UI re-enables the button, and the next POST
* lands somewhere else and starts a second pass over the whole library. Both
* replicas then read and parse every original off S3 or the NAS mount. The
* `.whereNull(...)` guards on the writes mean nothing is corrupted — the cost
* is the duplicated I/O, and an operator who cannot tell whether a job is
* running.
*
* One row per job, claimed with a conditional UPDATE so the claim itself is
* the mutual exclusion — the same UPDATE-with-guard shape backgroundProcessor
* already uses to hand a photo to exactly one worker
* (services/backgroundProcessor.js:110-116).
*
* heartbeat_at exists because a lock with no expiry is worse than no lock: a
* replica that is OOM-killed mid-run would leave is_running = true forever and
* no way to clear it short of editing the database. The runner touches it as
* it goes, and a claim is allowed to take over a run whose heartbeat has gone
* quiet. See services/maintenanceJobState.js for the read side, which reports
* a stale run as not-running so the button comes back on its own.
*
* Rows are seeded here rather than created on demand so the claim is a plain
* UPDATE with no insert race behind it.
*/
const JOBS = ['photo_dimension_repair', 'photo_capture_date_backfill'];
exports.up = async function (knex) {
const exists = await knex.schema.hasTable('maintenance_jobs');
if (!exists) {
await knex.schema.createTable('maintenance_jobs', (t) => {
// The job's identity, not a surrogate key: there is exactly one row per
// job and every access is by name, so the name is the primary key.
t.string('job_name', 64).primary();
t.boolean('is_running').notNullable().defaultTo(false);
t.timestamp('started_at').nullable();
t.timestamp('heartbeat_at').nullable();
t.timestamp('finished_at').nullable();
// JSON as text: the shape differs per job (the backfill reports a third
// counter the dimension repair has no equivalent for) and nothing
// queries into it, so a json column would buy nothing and cost engine
// differences between Postgres and SQLite.
t.text('last_result').nullable();
// Diagnostics only — which process is holding the claim.
t.string('owner', 128).nullable();
// The fencing token. Unique per claim, not per process: after a stale
// takeover the old runner may still be alive and mid-loop, and it can
// even be the same process that re-claimed. Every write it makes is
// scoped to the token it was handed, so a superseded runner can neither
// renew a claim it has lost nor release one it no longer owns.
t.string('claim_token', 64).nullable();
});
console.log('179: created maintenance_jobs');
}
// Idempotent on re-run and safe against a table that already carries rows.
for (const jobName of JOBS) {
const row = await knex('maintenance_jobs').where({ job_name: jobName }).first();
if (!row) {
await knex('maintenance_jobs').insert({ job_name: jobName, is_running: false });
console.log(`179: seeded job row ${jobName}`);
}
}
};
exports.down = async function (knex) {
await knex.schema.dropTableIfExists('maintenance_jobs');
};
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "picpeak-backend",
"version": "3.46.1",
"version": "3.46.5",
"description": "Backend for PicPeak event photo sharing platform",
"main": "server.js",
"engines": {
+135 -129
View File
@@ -1,141 +1,147 @@
#!/usr/bin/env node
/**
* Script to regenerate missing thumbnails for photos in the database
* Usage: node scripts/regenerate-thumbnails.js [eventId]
* Fill in missing thumbnails for photos already in the database.
*
* The CLI fallback for when the admin UI is not reachable. It is deliberately
* "missing only": ensureThumbnail short-circuits on a thumbnail that is
* already present and valid, so re-running this is cheap and safe. To REBUILD
* everything after a settings change, use POST /api/admin/thumbnails/regenerate
* — that path drops the existing renditions first, which this one must not do.
*
* Resolution goes through ensureThumbnail rather than a hand-built path
* (#1148, same defect as #1129). This script used to compute
* `storage/events/active/<photo.path>` and fs.access it, a location that does
* not exist for `external` or `reference` rows — their originals live under
* the mount in events.external_path. Every such photo failed the check and was
* counted as an error, so on an external-media install the script was inert
* while reporting one error per photo.
*
* ensureThumbnail already branches on source_origin, resolves both kinds via
* photoResolver, uses the per-photo `ext<id>_` output name so two events
* referencing one NAS basename cannot clobber each other, and writes
* thumbnail_path back itself. Sharing it is what stops the script and the
* route drifting apart again.
*
* Usage:
* node scripts/regenerate-thumbnails.js [eventId]
*/
const path = require('path');
const fs = require('fs').promises;
const sharp = require('sharp');
const { db } = require('../src/database/db');
// Configuration
const THUMBNAIL_SIZE = 300;
const STORAGE_PATH = process.env.STORAGE_PATH || path.join(__dirname, '../../storage');
const THUMBNAILS_DIR = path.join(STORAGE_PATH, 'thumbnails');
async function ensureDirectoryExists(dirPath) {
try {
await fs.access(dirPath);
} catch {
await fs.mkdir(dirPath, { recursive: true });
console.log(`Created directory: ${dirPath}`);
}
}
async function generateThumbnail(photoPath, thumbnailPath) {
try {
await sharp(photoPath)
.resize(THUMBNAIL_SIZE, THUMBNAIL_SIZE, {
fit: 'cover',
position: 'center'
})
.jpeg({ quality: 80 })
.toFile(thumbnailPath);
return true;
} catch (error) {
console.error(`Failed to generate thumbnail for ${photoPath}:`, error.message);
return false;
}
}
const { ensureThumbnail, isThumbnailValid } = require('../src/services/imageProcessor');
async function regenerateThumbnails(eventId = null) {
try {
console.log('Starting thumbnail regeneration...');
console.log(`Storage path: ${STORAGE_PATH}`);
console.log(`Thumbnails directory: ${THUMBNAILS_DIR}`);
// Ensure thumbnails directory exists
await ensureDirectoryExists(THUMBNAILS_DIR);
// Build query
let query = db('photos')
.join('events', 'photos.event_id', 'events.id')
.select(
'photos.id',
'photos.filename',
'photos.path',
'photos.thumbnail_path',
'events.slug as event_slug'
);
if (eventId) {
query = query.where('photos.event_id', eventId);
console.log(`Filtering for event ID: ${eventId}`);
}
const photos = await query;
console.log(`Found ${photos.length} photos to process`);
let successCount = 0;
let skipCount = 0;
let errorCount = 0;
for (const photo of photos) {
const photoPath = path.join(STORAGE_PATH, 'events/active', photo.path);
const thumbnailFilename = `thumb_${photo.filename}`;
const thumbnailPath = path.join(THUMBNAILS_DIR, thumbnailFilename);
try {
// Check if photo file exists
await fs.access(photoPath);
// Check if thumbnail already exists
try {
await fs.access(thumbnailPath);
console.log(`Thumbnail already exists for ${photo.filename}, skipping...`);
skipCount++;
continue;
} catch {
// Thumbnail doesn't exist, generate it
}
console.log(`Generating thumbnail for ${photo.filename}...`);
const success = await generateThumbnail(photoPath, thumbnailPath);
if (success) {
// Update database with thumbnail path
await db('photos')
.where('id', photo.id)
.update({
thumbnail_path: `thumbnails/${thumbnailFilename}`
});
successCount++;
console.log(`✓ Generated thumbnail for ${photo.filename}`);
} else {
errorCount++;
}
} catch (error) {
console.error(`✗ Photo file not found: ${photoPath}`);
errorCount++;
}
}
console.log('\nThumbnail regeneration complete!');
console.log(`- Successfully generated: ${successCount}`);
console.log(`- Skipped (already exist): ${skipCount}`);
console.log(`- Errors: ${errorCount}`);
console.log(`- Total processed: ${photos.length}`);
} catch (error) {
console.error('Error during thumbnail regeneration:', error);
process.exit(1);
} finally {
await db.destroy();
console.log('Starting thumbnail regeneration...');
// These columns are what ensureThumbnail branches on to resolve a source and
// name its output. Selecting a subset that misses
// source_origin/external_relpath is how the old path bug would come back —
// an external row would look managed and resolve under events/active.
let query = db('photos').select(
'id', 'event_id', 'path', 'filename', 'thumbnail_path',
'type', 'media_type', 'mime_type', 'source_origin', 'external_relpath'
);
if (eventId) {
query = query.where('event_id', eventId);
console.log(`Filtering for event ID: ${eventId}`);
}
// Skip videos. A video's thumbnail is a poster frame produced by
// videoProcessor, not a resize of the stored file, so handing the container
// to Sharp here only ever produced one error per row.
//
// Tested on every marker a video row can carry, not media_type alone:
// fileWatcher.processNewPhoto writes `type` and `mime_type` but never
// media_type, which defaults to 'image' — so an auto-imported video passes a
// media_type-only filter. Each clause is null-safe on its own so a row that
// simply has no mime_type is not swept up with them.
query = query
.where(function () {
this.whereNull('media_type').orWhere('media_type', '!=', 'video');
})
.where(function () {
this.whereNull('type').orWhere('type', '!=', 'video');
})
.where(function () {
this.whereNull('mime_type').orWhereNot('mime_type', 'like', 'video/%');
});
const photos = await query;
console.log(`Found ${photos.length} photos to process`);
let successCount = 0;
let skipCount = 0;
let errorCount = 0;
for (const photo of photos) {
const label = photo.filename || `photo ${photo.id}`;
try {
const existing = photo.thumbnail_path;
// Asked BEFORE the call, not inferred from the returned path afterwards.
// On local and external storage the key is deterministic, so repairing a
// missing or corrupt thumbnail hands back the identical string — and
// comparing paths would report that repair as "already valid", which is
// the one number an operator running this is actually reading.
const wasValid = existing ? await isThumbnailValid(existing) : false;
const thumbnailPath = await ensureThumbnail(photo);
if (!thumbnailPath) {
console.error(`✗ Could not generate thumbnail for ${label}`);
errorCount++;
continue;
}
if (wasValid && thumbnailPath === existing) {
skipCount++;
} else {
successCount++;
console.log(`✓ Generated thumbnail for ${label}`);
}
} catch (error) {
console.error(`✗ Failed for ${label}: ${error.message}`);
errorCount++;
}
}
console.log('\nThumbnail regeneration complete!');
console.log(`- Generated: ${successCount}`);
console.log(`- Skipped (already valid): ${skipCount}`);
console.log(`- Errors: ${errorCount}`);
console.log(`- Total processed: ${photos.length}`);
return { successCount, skipCount, errorCount };
}
// Parse command line arguments
const eventId = process.argv[2] ? parseInt(process.argv[2]) : null;
if (require.main === module) {
const args = process.argv.slice(2);
const eventArg = args.find((a) => !a.startsWith('--'));
const eventId = eventArg ? parseInt(eventArg, 10) : null;
// Run the script
regenerateThumbnails(eventId).then(() => {
console.log('Script completed successfully');
process.exit(0);
}).catch(error => {
console.error('Script failed:', error);
process.exit(1);
});
if (eventArg && !Number.isInteger(eventId)) {
console.error(`Not an event id: ${eventArg}`);
process.exit(1);
}
regenerateThumbnails(eventId)
.then(async (result) => {
await db.destroy();
// Exit status is the only thing a cron job reads. Resolving with a
// nonzero errorCount and still exiting 0 told automation the backfill
// was done when it had failed — which is how an unavailable mount stays
// unnoticed until someone opens a gallery.
if (result.errorCount) {
console.error(`Script completed with failures: ${result.errorCount} photo(s)`);
process.exit(1);
}
console.log('Script completed successfully');
process.exit(0);
})
.catch(async (error) => {
console.error('Script failed:', error);
await db.destroy().catch(() => {});
process.exit(1);
});
}
module.exports = { regenerateThumbnails };
+5
View File
@@ -240,6 +240,11 @@ router.post('/picpeak/import', adminAuth, requirePermission('backup.restore'), p
tables: result.tables,
filesRestored: result.filesRestored,
usesExternalMedia: result.usesExternalMedia,
// False when the pre-#1163 external-path conversion failed. The rows and
// files are in place, but no external original resolves until it is
// retried — the UI must say so rather than showing a plain success.
externalPathsConverted: result.externalPathsConverted !== false,
externalPathError: result.externalPathError || null,
crossEngine: result.crossEngine,
sessionInvalidated: true,
});
+38 -3
View File
@@ -7,6 +7,7 @@ const { formatBoolean } = require('../utils/dbCompat');
const { resolveAdapter } = require('../services/trackers');
const logger = require('../utils/logger');
const { errorResponse, getPagination } = require('../utils/routeHelpers');
const { measureLocalStorageUsage } = require('../services/localStorageUsage');
const router = express.Router();
/**
@@ -88,11 +89,33 @@ router.get('/stats', adminAuth, requirePermission('analytics.view'), async (req,
.count('id as count')
.first();
// Get storage usage (sum of all photo sizes)
const storageUsed = await applyEventScope(db('photos'), req.admin, 'event_id')
// The catalogued size of the ORIGINALS. Kept, and still worth showing —
// it answers "how much photography is in here" — but it is emphatically
// NOT storage used, which is what it was labelled for years (#1164).
const catalogedBytes = await applyEventScope(db('photos'), req.admin, 'event_id')
.sum('size_bytes as total')
.first();
// Storage used: what is actually on this machine. In reference mode the
// originals above live on a NAS and contribute nothing here; conversely
// this counts what the sum never did — thumbnails, previews, hero
// renditions, watermarks and the per-event download cache.
//
// Deliberately NOT event-scoped, unlike everything else on this endpoint:
// it is a disk measurement, and disk is not divisible by which admin owns
// which event.
//
// Skipped entirely on an S3 backend: the objects are in the bucket and a
// walk of STORAGE_PATH would report near-zero, which is worse than the
// catalogued figure those installs had before #1164.
const usesLocalBackend = (process.env.STORAGE_BACKEND || 'local').toLowerCase() !== 's3';
let localStorage = null;
try {
if (usesLocalBackend) localStorage = await measureLocalStorageUsage();
} catch (err) {
logger.warn(`Dashboard storage measurement failed: ${err.message}`);
}
// Get total views (last 30 days)
const thirtyDaysAgo = new Date();
thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
@@ -154,7 +177,19 @@ router.get('/stats', adminAuth, requirePermission('analytics.view'), async (req,
activeEvents: activeEvents.count || 0,
expiringEvents: expiringEvents.count || 0,
totalPhotos: totalPhotos.count || 0,
storageUsed: storageUsed.total || 0,
// Real bytes on this disk. Null when the measurement failed or was
// skipped, which the UI shows as "unavailable" rather than substituting
// a number that means something else.
storageUsed: localStorage ? localStorage.total : null,
// Three states, not two: 'catalog' means the backend is S3 and the
// objects are in the bucket, which is a fact about the install;
// 'unavailable' means the walk failed, which is a fault. Collapsing them
// made a failed local measurement claim the objects live in S3.
storageMeasurement: localStorage ? 'disk' : (usesLocalBackend ? 'unavailable' : 'catalog'),
storageBreakdown: localStorage ? localStorage.breakdown : null,
storagePartial: localStorage ? localStorage.partial : false,
// Catalogued original bytes — what `storageUsed` used to report (#1164).
catalogedBytes: Number(catalogedBytes.total) || 0,
totalViews: totalViews.count || 0,
totalDownloads: totalDownloads.count || 0,
viewsTrend: Math.round(viewsTrend * 10) / 10,
+107 -22
View File
@@ -8,10 +8,25 @@ const { list, resolveExternalPath, getExternalMediaRoot } = require('../services
const { db, logActivity } = require('../database/db');
const sharp = require('sharp');
const logger = require('../utils/logger');
const { generateThumbnail } = require('../services/imageProcessor');
const { generateThumbnail, extractCaptureDate } = require('../services/imageProcessor');
const { isUniqueViolation } = require('../utils/dbErrors');
const router = express.Router();
// Events with an import running in THIS process (#1162).
//
// The second line of defence, not the first: migration 176 puts a unique index
// on (event_id, external_relpath), and that is what actually makes a duplicate
// impossible — it holds across replicas, across restarts, and against anything
// that inserts external rows without going through this route.
//
// This set exists for the reason the duplicates got filed in the first place:
// a large tree takes long enough that the run LOOKS hung, so admins click
// again. Letting that second run walk the whole tree only to have every insert
// bounce off the index wastes minutes of CPU and reports a nonsense
// `skipped: 6012` back. Failing it immediately with 409 says what happened.
const importsInFlight = new Set();
// GET /api/admin/external-media/list?path=relative/dir
router.get('/list', adminAuth, requirePermission('photos.view'), async (req, res) => {
try {
@@ -50,8 +65,14 @@ async function walkDir(dir, baseDir) {
// POST /api/admin/events/:id/import-external
// Body: { external_path: string, recursive?: boolean, map?: { individual?: string, collages?: string } }
router.post('/events/:id/import-external', adminAuth, requirePermission('photos.upload'), requireEventOwnership, async (req, res) => {
const eventId = parseInt(req.params.id);
if (importsInFlight.has(eventId)) {
return res.status(409).json({
error: 'An import is already running for this event. Wait for it to finish before starting another.'
});
}
importsInFlight.add(eventId);
try {
const eventId = parseInt(req.params.id);
const { external_path, recursive = true, map = { individual: 'individual', collages: 'collages' } } = req.body || {};
if (!external_path) return res.status(400).json({ error: 'external_path is required' });
@@ -60,6 +81,14 @@ router.post('/events/:id/import-external', adminAuth, requirePermission('photos.
if (!event) return res.status(404).json({ error: 'Event not found' });
const baseAbs = resolveExternalPath({ external_path }, '');
// What gets STORED on the row (#1163). `f.rel` stays relative to the
// imported folder because the type inference below reads its first segment
// ('individual' / 'collages'); external_relpath is written relative to
// EXTERNAL_MEDIA_ROOT so the row does not depend on a column this very
// handler is about to overwrite.
const basePrefix = String(external_path).replace(/^\/+|\/+$/g, '');
const toRootRelative = (rel) => (basePrefix ? path.join(basePrefix, rel) : rel);
// Collect files
const files = recursive ? await walkDir(baseAbs, baseAbs) : (await fs.readdir(baseAbs, { withFileTypes: true }))
.filter(e => e.isFile())
@@ -106,10 +135,18 @@ router.post('/events/:id/import-external', adminAuth, requirePermission('photos.
if (segs[0] === map.collages) type = 'collage';
if (segs[0] === map.individual) type = 'individual';
const relFromRoot = toRootRelative(f.rel);
try {
// Check if already exists (by external_relpath)
// Fast path only. This SELECT settles the common case — a re-import of
// a folder already in the event — without paying for a stat and a
// Sharp metadata read per file. It is NOT the guard: those two calls
// sit between here and the INSERT below, which is exactly the window
// two overlapping imports both walked through (#1162). The unique
// index from migration 176 is the guard, and the catch below is how
// this loop converges when it fires.
const exists = await db('photos')
.where({ event_id: eventId, external_relpath: f.rel })
.where({ event_id: eventId, external_relpath: relFromRoot })
.first();
if (exists) { skipped++; continue; }
const stats = await fs.stat(f.full);
@@ -119,27 +156,65 @@ router.post('/events/:id/import-external', adminAuth, requirePermission('photos.
let height = null;
try {
const metadata = await sharp(f.full).metadata();
width = metadata.width || null;
height = metadata.height || null;
// Oriented, not raw — see imageProcessor.orientedDimensions (#1185).
({ width, height } = require('../services/imageProcessor').orientedDimensions(metadata));
} catch (dimErr) {
logger.warn(`Could not extract dimensions for ${f.rel}: ${dimErr.message}`);
}
const inserted = await db('photos')
.insert({
event_id: eventId,
filename: f.name,
// Keep path as a hint for legacy code but not used for resolution in external mode
path: path.join(event.slug, f.name),
thumbnail_path: null,
type,
size_bytes: stats.size,
width,
height,
source_origin: 'external',
external_relpath: f.rel
})
.returning('id');
// Capture date from EXIF (#1172). Managed uploads get this from
// photoProcessor, which external media never goes through — so
// captured_at stayed NULL for every externally imported photo, and the
// gallery's "Date Taken" sort silently degraded into import order via
// its COALESCE fallback. On a library imported in two batches that put
// the first days of a trip after the last ones.
//
// Read here because the file is already open a few lines above for the
// dimensions, so this costs one more read of the same source rather
// than a second pass over the mount.
//
// Best-effort, exactly like the dimensions: a source without EXIF, or
// one Sharp/exifr cannot parse, imports with captured_at NULL and
// falls back to uploaded_at as before.
let capturedAt = null;
try {
capturedAt = await extractCaptureDate(f.full);
} catch (dateErr) {
logger.warn(`Could not extract capture date for ${f.rel}: ${dateErr.message}`);
}
let inserted;
try {
inserted = await db('photos')
.insert({
event_id: eventId,
filename: f.name,
// Keep path as a hint for legacy code but not used for resolution in external mode
path: path.join(event.slug, f.name),
thumbnail_path: null,
type,
size_bytes: stats.size,
width,
height,
source_origin: 'external',
external_relpath: relFromRoot,
// .toISOString() rather than the Date: inside jest, Dates handed
// to the sqlite3 binding land as the literal string
// "[object Object]" (see CLAUDE.md). Strings round-trip on both
// engines.
captured_at: capturedAt ? capturedAt.toISOString() : null
})
.returning('id');
} catch (insertErr) {
// Another writer inserted this exact path while we were reading
// metadata. That is the outcome the index exists to produce, and it
// is a skip rather than a failure — the row is there, it just isn't
// ours. Counting it as `skipped` keeps the reported totals honest;
// before the index this landed in the outer catch as a nameless
// failure, or (more often) never fired at all and duplicated the row.
if (isUniqueViolation(insertErr)) { skipped++; continue; }
throw insertErr;
}
const photoId = Array.isArray(inserted) && inserted.length
? (typeof inserted[0] === 'object' ? inserted[0].id : inserted[0])
@@ -175,7 +250,12 @@ router.post('/events/:id/import-external', adminAuth, requirePermission('photos.
}
}
// Update event fields
// Safe for existing EXTERNAL rows as of #1163. It was not: relpaths were
// stored relative to external_path, so overwriting the column here rebased
// every row already in the event onto the new folder — quietly, because
// their thumbnails were already on local disk and the grid carried on
// rendering. Rows now carry a root-relative path and this write cannot
// reach them.
await db('events').where('id', eventId).update({ source_mode: 'reference', external_path });
await logActivity(
@@ -193,6 +273,11 @@ router.post('/events/:id/import-external', adminAuth, requirePermission('photos.
error: error.message
});
res.status(500).json({ error: 'Failed to import external media' });
} finally {
// In `finally` and not at the end of `try`: an import that throws must
// still release the event, or a single failure locks out every retry
// until the process restarts.
importsInFlight.delete(eventId);
}
});
+426 -66
View File
@@ -7,35 +7,106 @@ const fs = require('fs').promises;
const logger = require('../utils/logger');
const { resolvePhotoFilePath } = require('../services/photoResolver');
const maintenanceJobs = require('../services/maintenanceJobState');
// Module-level progress state
let repairProgress = {
isRunning: false,
lastResult: null
};
// Run state for both sweeps lives in the database, not in this process
// (#1181). It used to be a module-level object per job, which is correct on a
// single replica and wrong behind a load balancer: the status poll answers
// from whichever process it reaches, so an idle replica reports isRunning
// false while another is mid-run, the UI re-enables the button, and the next
// POST starts a duplicate pass over the entire library.
//
// Two separate rows, for the same reason the two objects were separate: the
// jobs walk the same photos but read different things out of them, and one
// running must not block or report for the other.
const { JOB_DIMENSION_REPAIR, JOB_CAPTURE_DATE_BACKFILL } = maintenanceJobs;
const { HEARTBEAT_INTERVAL_MS } = maintenanceJobs;
/**
* Renew the lease on a timer for as long as the run holds it.
*
* On a timer, not between photos: a single hung read on a stalled NAS mount or
* a slow S3 object can outlast the whole stale window inside one iteration, and
* a renewal that only fires between photos never gets to run. The lease would
* expire while the job was demonstrably alive, another replica would take it
* over, and the two would walk the same rows — precisely the case the lease
* exists to prevent. The timer also covers the candidate query, which on a
* large library is itself slow.
*
* `lost()` reports whether the claim has since been taken over. The loops check
* it between photos and stop: mid-photo interruption is not possible, so the
* worst case is one extra row written by the old runner, and its release is
* fenced on the token anyway.
*/
function startLeaseKeeper(jobName, token) {
let lost = false;
const timer = setInterval(async () => {
try {
if (!(await maintenanceJobs.heartbeat(jobName, token))) {
lost = true;
clearInterval(timer);
}
} catch (err) {
// heartbeat() already swallows query errors and reports the claim as
// held; this is belt-and-braces so an unexpected throw cannot kill the
// timer callback and silently stop all renewals.
logger.warn(`Lease renewal error for ${jobName}: ${err.message}`);
}
}, HEARTBEAT_INTERVAL_MS);
// Do not hold the event loop open on account of a maintenance sweep.
if (typeof timer.unref === 'function') timer.unref();
return {
lost: () => lost,
stop: () => clearInterval(timer),
};
}
// Repair photo dimensions (background job)
router.post('/repair-dimensions', adminAuth, requirePermission('photos.edit'), async (req, res) => {
try {
if (repairProgress.isRunning) {
// Claimed before the candidate query, not after: that query is an await,
// and two requests arriving inside it would both read "not running" and
// both start a pass. The claim is a conditional UPDATE, so it settles the
// race across replicas as well as within one.
const token = await maintenanceJobs.claim(JOB_DIMENSION_REPAIR);
if (!token) {
return res.status(409).json({ error: 'Repair is already running' });
}
// Started at the claim, not at the loop: on a large or loaded install the
// candidate SELECT below (plus the setImmediate hop) can itself outlast the
// stale window, and an unrenewed claim would be taken over before the sweep
// had read its first photo. Handed to the background section, which stops
// it; every early exit here stops it too.
const lease = startLeaseKeeper(JOB_DIMENSION_REPAIR, token);
const photos = await db('photos')
.join('events', 'photos.event_id', 'events.id')
.where(function () {
this.whereNull('photos.width').orWhereNull('photos.height');
})
.where(function () {
this.where('photos.media_type', '!=', 'video').orWhereNull('photos.media_type');
})
.select(
'photos.id', 'photos.path', 'photos.filename',
'photos.source_origin', 'photos.external_relpath', 'photos.event_id',
'events.source_mode', 'events.external_path', 'events.slug'
);
let photos;
try {
photos = await db('photos')
.join('events', 'photos.event_id', 'events.id')
.where(function () {
this.whereNull('photos.width').orWhereNull('photos.height');
})
.where(function () {
this.where('photos.media_type', '!=', 'video').orWhereNull('photos.media_type');
})
.select(
'photos.id', 'photos.path', 'photos.filename',
'photos.source_origin', 'photos.external_relpath', 'photos.event_id',
'events.source_mode', 'events.external_path', 'events.slug'
);
} catch (err) {
lease.stop();
await maintenanceJobs.release(JOB_DIMENSION_REPAIR, token);
throw err;
}
if (photos.length === 0) {
// Released with no result: nothing ran, so the numbers from the last
// real run stay on screen rather than being blanked by a no-op.
lease.stop();
await maintenanceJobs.release(JOB_DIMENSION_REPAIR, token);
return res.json({ message: 'No photos need dimension repair', count: 0 });
}
@@ -46,70 +117,94 @@ router.post('/repair-dimensions', adminAuth, requirePermission('photos.edit'), a
});
// Process in background
repairProgress.isRunning = true;
repairProgress.lastResult = null;
setImmediate(async () => {
let sharp;
try {
sharp = require('sharp');
} catch (err) {
logger.error('Sharp not available for dimension repair:', err.message);
repairProgress.isRunning = false;
repairProgress.lastResult = { success: 0, failed: 0, error: 'Sharp not available' };
lease.stop();
await maintenanceJobs.release(JOB_DIMENSION_REPAIR, token, { success: 0, failed: 0, error: 'Sharp not available' });
return;
}
let successCount = 0;
let errorCount = 0;
let lostClaim = false;
for (const photo of photos) {
try {
const event = { source_mode: photo.source_mode, external_path: photo.external_path, slug: photo.slug };
let fullPath;
try {
fullPath = resolvePhotoFilePath(event, photo);
} catch (err) {
logger.warn(`Photo ${photo.id} has no resolvable path, skipping dimension repair: ${err.message}`);
errorCount++;
continue;
}
// Everything below runs detached from the request, so an unexpected
// throw has nobody to report to. Without this the claim would sit held
// until it aged out of the staleness window, disabling the button for
// that whole time on every replica.
try {
for (const photo of photos) {
// The timer does the renewing; this only notices that it has
// already failed, so the loop stops instead of running on beside the
// replica that took the claim over.
if (lease.lost()) { lostClaim = true; break; }
try {
await fs.access(fullPath);
} catch (err) {
logger.warn(`File not found for photo ${photo.id}: ${fullPath}`);
errorCount++;
continue;
}
const metadata = await sharp(fullPath).metadata();
if (metadata.width && metadata.height) {
await db('photos')
.where({ id: photo.id })
.update({
width: metadata.width,
height: metadata.height
});
successCount++;
if (successCount % 50 === 0) {
logger.info(`Dimension repair progress: ${successCount} updated...`);
const event = { source_mode: photo.source_mode, external_path: photo.external_path, slug: photo.slug };
let fullPath;
try {
fullPath = resolvePhotoFilePath(event, photo);
} catch (err) {
logger.warn(`Photo ${photo.id} has no resolvable path, skipping dimension repair: ${err.message}`);
errorCount++;
continue;
}
} else {
logger.warn(`Could not extract dimensions for photo ${photo.id}`);
try {
await fs.access(fullPath);
} catch (err) {
logger.warn(`File not found for photo ${photo.id}: ${fullPath}`);
errorCount++;
continue;
}
const metadata = await sharp(fullPath).metadata();
// Oriented, not raw — see imageProcessor.orientedDimensions (#1185).
const dims = require('../services/imageProcessor').orientedDimensions(metadata);
if (dims.width && dims.height) {
await db('photos')
.where({ id: photo.id })
.update({
width: dims.width,
height: dims.height
});
successCount++;
if (successCount % 50 === 0) {
logger.info(`Dimension repair progress: ${successCount} updated...`);
}
} else {
logger.warn(`Could not extract dimensions for photo ${photo.id}`);
errorCount++;
}
} catch (error) {
logger.error(`Error repairing dimensions for photo ${photo.id}:`, error);
errorCount++;
}
} catch (error) {
logger.error(`Error repairing dimensions for photo ${photo.id}:`, error);
errorCount++;
}
}
repairProgress.isRunning = false;
repairProgress.lastResult = { success: successCount, failed: errorCount };
logger.info(`Dimension repair complete: ${successCount} success, ${errorCount} errors`);
if (lostClaim) {
// Another replica declared this run stale and took it over. It owns
// the row now, so releasing would clear ITS flag — release() refuses
// on the token, but there is nothing to report either way.
logger.warn(`Dimension repair stopped: claim taken over after ${successCount} updated, ${errorCount} errors`);
return;
}
await maintenanceJobs.release(JOB_DIMENSION_REPAIR, token, { success: successCount, failed: errorCount });
logger.info(`Dimension repair complete: ${successCount} success, ${errorCount} errors`);
} catch (err) {
logger.error('Dimension repair aborted:', err);
await maintenanceJobs
.release(JOB_DIMENSION_REPAIR, token, { success: successCount, failed: errorCount, error: err.message })
.catch(() => {});
} finally {
lease.stop();
}
});
} catch (error) {
logger.error('Error starting dimension repair:', error);
@@ -138,13 +233,15 @@ router.get('/repair-dimensions/status', adminAuth, requirePermission('photos.vie
const total = Number(totalPhotos.count);
const withDims = Number(withDimensions.count);
// Read from the shared row, so this answers the same on every replica.
const state = await maintenanceJobs.read(JOB_DIMENSION_REPAIR);
res.json({
total,
withDimensions: withDims,
withoutDimensions: total - withDims,
isRunning: repairProgress.isRunning,
lastResult: repairProgress.lastResult
isRunning: state.isRunning,
lastResult: state.lastResult
});
} catch (error) {
logger.error('Error fetching dimension repair status:', error);
@@ -152,4 +249,267 @@ router.get('/repair-dimensions/status', adminAuth, requirePermission('photos.vie
}
});
/**
* Backfill captured_at from EXIF (#1172).
*
* External imports never read EXIF before this release, so every
* externally-imported photo carries captured_at NULL — and the gallery's
* "Date Taken" sort falls back to uploaded_at, which on a bulk import is the
* import timestamp. A 5555-photo trip came back ordered by which folder was
* imported first.
*
* Deliberately an endpoint rather than a migration: the originals live on a
* mount that may be unavailable at upgrade time, reading 8000+ of them blocks
* the boot, and a run that found nothing needs to be repeatable once the mount
* is back. Same reasoning, and the same shape, as the dimension repair above —
* including resolvePhotoFilePath, which is what makes it work for external
* rows at all (the thumbnail regenerator resolves under
* storage/events/active/<path>, which never exists for them).
*/
// settings.edit, not photos.edit: this walks every event in the install and
// rewrites their metadata, which is a maintenance action rather than a photo
// edit. photos.edit is held by the `editor` role
// (056_add_role_permissions_table.js:73), which is scoped to contributing
// content, not to running an install-wide S3/NAS scan across other people's
// events. settings.edit is the restrictive one here — `admin` carries only
// settings.view (056:63).
//
// main gates the same endpoint on system.manage, which does not exist on this
// branch: it is one of the permissions settings.edit was later split into, and
// migration 175 there projects every settings.edit holder forward onto it. So
// this is the same gate under its older name, and the two branches let exactly
// the same people through.
router.post('/repair-capture-dates', adminAuth, requirePermission('settings.edit'), async (req, res) => {
try {
// Claimed here, not after the candidate query: that query is an await, and
// two POSTs arriving inside it would both read "not running" and both start
// a pass over the same rows. Being a conditional UPDATE, the claim settles
// that between replicas too. Every early exit below has to release it
// again, hence the try/catch around the query.
const token = await maintenanceJobs.claim(JOB_CAPTURE_DATE_BACKFILL);
if (!token) {
return res.status(409).json({ error: 'Capture date backfill is already running' });
}
// Started at the claim so the candidate SELECT below is covered too — see
// the dimension repair above.
const lease = startLeaseKeeper(JOB_CAPTURE_DATE_BACKFILL, token);
let photos;
try {
photos = await db('photos')
.join('events', 'photos.event_id', 'events.id')
.whereNull('photos.captured_at')
// Three markers, because no single one is reliable. fileWatcher's
// auto-import sets type='video' and a video/* mime but never
// media_type (fileWatcher.js:128-130), so those rows keep the 'image'
// default from migration 048 and a media_type-only filter queues them
// forever: extractCaptureDate returns null for a video, captured_at
// stays null, and every run picks it up again.
.where(function () {
this.where('photos.media_type', '!=', 'video').orWhereNull('photos.media_type');
})
.where(function () {
this.where('photos.type', '!=', 'video').orWhereNull('photos.type');
})
.where(function () {
this.whereNull('photos.mime_type').orWhere('photos.mime_type', 'not like', 'video/%');
})
// Archiving deletes the originals from storage but keeps the photos
// rows (archiveService.js:166,199). Those files are inside the zip and
// nothing here can read them, so including them would fail every row
// on every run and leave the button permanently lit.
.where(function () {
this.where('events.is_archived', false).orWhereNull('events.is_archived');
})
.select(
'photos.id', 'photos.path', 'photos.filename',
'photos.source_origin', 'photos.external_relpath', 'photos.event_id',
'events.source_mode', 'events.external_path', 'events.slug'
);
} catch (err) {
lease.stop();
await maintenanceJobs.release(JOB_CAPTURE_DATE_BACKFILL, token);
throw err;
}
if (photos.length === 0) {
// No result passed: nothing ran, so the last real run's numbers survive.
lease.stop();
await maintenanceJobs.release(JOB_CAPTURE_DATE_BACKFILL, token);
return res.json({ message: 'No photos need a capture date', count: 0 });
}
res.json({
message: `Started backfilling capture dates for ${photos.length} photos`,
count: photos.length
});
setImmediate(async () => {
const { extractCaptureDate, withLocalCopy } = require('../services/imageProcessor');
const { resolvePhotoStorageKey } = require('../services/photoResolver');
let successCount = 0;
let missingCount = 0;
let errorCount = 0;
let lostClaim = false;
// Same reasoning as the dimension repair: detached from the request, so
// an unexpected throw must not leave the claim held.
try {
for (const photo of photos) {
// The timer renews; this only notices it has already failed.
if (lease.lost()) { lostClaim = true; break; }
try {
const event = { source_mode: photo.source_mode, external_path: photo.external_path, slug: photo.slug };
const isExternal = photo.source_origin === 'external' || photo.source_origin === 'reference';
// Two source shapes, same split the thumbnail regenerator uses
// (imageProcessor.js:391-420). External rows live on a local mount
// and are read directly; managed rows live behind the storage
// backend, which on an S3 install is not a filesystem at all — going
// through resolvePhotoFilePath there would build a STORAGE_PATH that
// holds nothing and fail every managed photo.
let captured;
if (isExternal) {
let fullPath;
try {
fullPath = resolvePhotoFilePath(event, photo);
} catch (err) {
logger.warn(`Photo ${photo.id} has no resolvable path, skipping capture date: ${err.message}`);
errorCount++;
continue;
}
try {
await fs.access(fullPath);
} catch (err) {
logger.warn(`File not found for photo ${photo.id}: ${fullPath}`);
errorCount++;
continue;
}
captured = await extractCaptureDate(fullPath);
} else {
let sourceKey;
try {
sourceKey = resolvePhotoStorageKey(event, photo);
} catch (err) {
logger.warn(`Photo ${photo.id} has no resolvable storage key, skipping capture date: ${err.message}`);
errorCount++;
continue;
}
// In local-fs mode withLocalCopy hands back the resolved path
// without checking it exists, so the access probe stays. In S3
// mode a missing object throws out of getToFile and lands in the
// outer catch — both end up counted as failures, which is what a
// missing original is.
captured = await withLocalCopy(sourceKey, async (localPath) => {
await fs.access(localPath);
return extractCaptureDate(localPath);
});
}
if (!captured) {
// No date recovered. Usually genuine — plenty of sources carry no
// EXIF — but extractCaptureDate also returns null when the file is
// unreadable as an image, so this bucket is "nothing to write",
// not "definitely has no EXIF". The failure counter above is the
// one that means the storage is broken.
missingCount++;
continue;
}
// whereNull, not a blanket set: the job can run for a long time on a
// large library, and an import or a replacement finishing meanwhile
// has already written a date this pass would otherwise overwrite
// with the same-or-worse value.
const updated = await db('photos')
.where({ id: photo.id })
.whereNull('captured_at')
.update({ captured_at: captured.toISOString() });
if (updated) successCount++;
if (successCount % 50 === 0 && successCount > 0) {
logger.info(`Capture date backfill progress: ${successCount} updated...`);
}
} catch (error) {
logger.error(`Error backfilling capture date for photo ${photo.id}:`, error);
errorCount++;
}
}
if (lostClaim) {
logger.warn(`Capture date backfill stopped: claim taken over after ${successCount} updated, ${errorCount} errors`);
return;
}
await maintenanceJobs.release(JOB_CAPTURE_DATE_BACKFILL, token, { success: successCount, noExif: missingCount, failed: errorCount });
logger.info(`Capture date backfill complete: ${successCount} updated, ${missingCount} without EXIF, ${errorCount} errors`);
} catch (err) {
logger.error('Capture date backfill aborted:', err);
await maintenanceJobs
.release(JOB_CAPTURE_DATE_BACKFILL, token, { success: successCount, noExif: missingCount, failed: errorCount, error: err.message })
.catch(() => {});
} finally {
lease.stop();
}
});
} catch (error) {
logger.error('Error starting capture date backfill:', error);
res.status(500).json({ error: 'Failed to start capture date backfill' });
}
});
// The same permission as the POST, not the read-only settings.view. The built-in
// `admin` role holds settings.view but not settings.edit
// (056_add_role_permissions_table.js:63), and StatusTab has no permission gate
// of its own — a successful status payload is what renders the card and its
// enabled button. Gating on settings.view therefore showed every admin a live
// backfill button whose every click 403s with no error surfaced.
router.get('/repair-capture-dates/status', adminAuth, requirePermission('settings.edit'), async (req, res) => {
try {
// Same scope as the job itself — counting archived photos here would show
// a permanent backlog the button can never clear.
const scoped = () => db('photos')
.join('events', 'photos.event_id', 'events.id')
.where(function () {
this.where('photos.media_type', '!=', 'video').orWhereNull('photos.media_type');
})
.where(function () {
this.where('photos.type', '!=', 'video').orWhereNull('photos.type');
})
.where(function () {
this.whereNull('photos.mime_type').orWhere('photos.mime_type', 'not like', 'video/%');
})
.where(function () {
this.where('events.is_archived', false).orWhereNull('events.is_archived');
});
// One query, two aggregates. As two separate counts an import committing a
// dated photo between them could be counted by the second and not the
// first, so withCaptureDate came out larger than total and the card showed
// a negative backlog — with the button enabled to "fix" it.
const counts = await scoped()
.count('photos.id as total')
.count({ dated: db.raw('CASE WHEN photos.captured_at IS NOT NULL THEN 1 END') })
.first();
const total = Number(counts.total);
const withCaptureDate = Number(counts.dated);
// Read from the shared row, so this answers the same on every replica.
const state = await maintenanceJobs.read(JOB_CAPTURE_DATE_BACKFILL);
res.json({
total,
withCaptureDate,
withoutCaptureDate: total - withCaptureDate,
isRunning: state.isRunning,
lastResult: state.lastResult
});
} catch (error) {
logger.error('Error fetching capture date backfill status:', error);
res.status(500).json({ error: 'Failed to fetch capture date backfill status' });
}
});
module.exports = router;
+29 -1
View File
@@ -24,6 +24,7 @@ const { clearShareLinkSettingsCache } = require('../services/shareLinkService');
const { resetSecurityConfigCache } = require('../utils/authSecurity');
const { errorResponse } = require('../utils/routeHelpers');
const logger = require('../utils/logger');
const { measureLocalStorageUsage } = require('../services/localStorageUsage');
const router = express.Router();
const { clearMaxFilesPerUploadCache, MAX_ALLOWED_FILES_PER_UPLOAD } = require('../services/uploadSettings');
const watermarkService = require('../services/watermarkService');
@@ -1174,6 +1175,8 @@ router.put('/seo', adminAuth, requirePermission('settings.edit'), async (req, re
router.get('/storage/info', adminAuth, requirePermission('settings.view'), async (req, res) => {
try {
// Get total storage used
// Catalogued original bytes. Reported, but no longer as "used" (#1164) —
// in reference mode those files are on a NAS and none of them are here.
const totalStorage = await db('photos')
.sum('size_bytes as total')
.first();
@@ -1254,7 +1257,25 @@ router.get('/storage/info', adminAuth, requirePermission('settings.view'), async
}
}
const totalUsed = totalStorage?.total || 0;
// What is actually on this disk. This is what the soft limit is compared
// against and what the recommendation below is derived from, so getting it
// from the catalogued originals was the load-bearing half of #1164: a
// reference-mode install got a disk-capacity recommendation computed from
// bytes that are not on the disk.
//
// Gated BEFORE the walk: this endpoint is polled by the sidebar, and an S3
// install with a large local tree would otherwise pay a full traversal on
// every cold cache only to discard the result.
const catalogedBytes = Number(totalStorage?.total) || 0;
const usesLocalBackend = (process.env.STORAGE_BACKEND || 'local').toLowerCase() !== 's3';
let localUsage = null;
try {
if (usesLocalBackend) localUsage = await measureLocalStorageUsage();
} catch (err) {
logger.warn(`Storage measurement failed, falling back to catalogued bytes: ${err.message}`);
}
const measuredFromDisk = usesLocalBackend && !!localUsage;
const totalUsed = measuredFromDisk ? localUsage.total : catalogedBytes;
const parseBytesValue = (value) => {
const numeric = Number(value);
@@ -1376,6 +1397,13 @@ router.get('/storage/info', adminAuth, requirePermission('settings.view'), async
res.json({
total_used: totalUsed,
// What total_used used to be, kept so the UI can show both and the
// difference stops being invisible.
cataloged_bytes: catalogedBytes,
storage_measurement: measuredFromDisk ? 'disk' : (usesLocalBackend ? 'unavailable' : 'catalog'),
storage_breakdown: measuredFromDisk ? localUsage.breakdown : null,
storage_partial: measuredFromDisk ? localUsage.partial : false,
excluded_external_root: measuredFromDisk ? localUsage.excludedExternalRoot : null,
archive_storage: archiveStorage,
storage_by_event: storageByEvent,
storage_limit: effectiveSoftLimit,
+62 -28
View File
@@ -3,12 +3,27 @@ const router = express.Router();
const { db } = require('../database/db');
const { adminAuth } = require('../middleware/auth');
const { requirePermission } = require('../middleware/permissions');
const { generateThumbnail, ensurePreviewImage } = require('../services/imageProcessor');
const path = require('path');
const fs = require('fs').promises;
const { ensureThumbnail, ensurePreviewImage } = require('../services/imageProcessor');
const { getStorage } = require('../services/storage');
const logger = require('../utils/logger');
const getStoragePath = () => process.env.STORAGE_PATH || path.join(__dirname, '../../../storage');
/**
* Do these two stored paths address the same object?
*
* Compared the way the storage backends do, not as raw strings.
* LocalFsStorage._resolve and S3StorageBackend._key both fold `\` to `/` and
* strip a leading `./`, so a legacy thumbnail_path in any of those shapes is
* the SAME file as the freshly generated POSIX key while comparing unequal —
* and the "the key moved, delete the old one" branch below would then delete
* the thumbnail that had just been written.
*/
function sameStorageKey(a, b) {
const canonical = (key) => String(key)
.replace(/\\/g, '/')
.replace(/^\.?\/+/, '')
.replace(/\/+/g, '/');
return canonical(a) === canonical(b);
}
// Parse JSON-encoded setting values
function parseSettingValue(value) {
@@ -125,10 +140,21 @@ router.post('/regenerate', adminAuth, requirePermission('photos.edit'), async (r
try {
const { eventId } = req.body; // Optional: regenerate for specific event only
let query = db('photos').select('id', 'event_id', 'path');
// source_origin/external_relpath/filename are what ensureThumbnail branches
// on to resolve an external source off its mount instead of under
// events/active. thumbnail_path is selected so it can be nulled — see below.
let query = db('photos').select(
'id', 'event_id', 'path', 'media_type', 'mime_type', 'thumbnail_path',
'source_origin', 'external_relpath', 'filename'
);
if (eventId) {
query = query.where('event_id', eventId);
}
// Skip videos: their thumbnail is a poster frame from videoProcessor, so
// handing the container file to Sharp only ever produced an error per row.
query = query.where(function() {
this.whereNull('media_type').orWhere('media_type', '!=', 'video');
});
const photos = await query;
@@ -149,30 +175,38 @@ router.post('/regenerate', adminAuth, requirePermission('photos.edit'), async (r
for (const photo of photos) {
try {
const storagePath = getStoragePath();
const originalPath = path.join(storagePath, 'events/active', photo.path);
// Check if original file exists
try {
await fs.access(originalPath);
} catch (err) {
logger.warn(`Original file not found for photo ${photo.id}: ${originalPath}`);
errorCount++;
continue;
}
// Regenerate thumbnail
const thumbnailPath = await generateThumbnail(originalPath, { regenerate: true });
if (thumbnailPath) {
// Update database with new thumbnail path
await db('photos')
.where({ id: photo.id })
.update({
thumbnail_path: thumbnailPath,
updated_at: db.fn.now()
// Through ensureThumbnail, not a hand-rolled path (#1129). This route
// used to resolve every source as `storage/events/active/<path>` and
// fs.access it — a location that does not exist for external or
// reference rows, whose originals live under events.external_path. So
// every one of them failed the check and was counted as an error: on a
// reference install the endpoint rebuilt nothing while the UI reported
// success, because the response is sent before this loop starts.
//
// ensureThumbnail already resolves both source kinds, uses the
// per-photo ext<id>_ output name so two events referencing one NAS
// basename cannot clobber each other, and writes thumbnail_path back
// itself. Nulling thumbnail_path is what stops it short-circuiting on
// isThumbnailValid — necessary rather than cosmetic, because the old
// thumbnail is normally still readable at exactly the moment someone
// presses regenerate.
const newThumbnailPath = await ensureThumbnail({ ...photo, thumbnail_path: null });
if (newThumbnailPath) {
// Drop the superseded rendition when the key MOVED. On S3 the source
// is downloaded to a randomly-named temp file and, for non-RAW input,
// the key is derived from that name — so it differs every run, and
// nulling thumbnail_path hides the old key from everything that would
// otherwise clean it up. Guarded on the key actually changing: local
// storage is stable, and deleting the equal key would delete the file
// just written.
if (photo.thumbnail_path && !sameStorageKey(photo.thumbnail_path, newThumbnailPath)) {
await getStorage().delete(photo.thumbnail_path).catch((err) => {
logger.warn(
`Could not remove superseded thumbnail ${photo.thumbnail_path} for photo ${photo.id}: ${err.message}`
);
});
}
successCount++;
logger.info(`Regenerated thumbnail for photo ${photo.id}`);
} else {
+12 -1
View File
@@ -725,7 +725,18 @@ router.get('/session', async (req, res) => {
expiresIn: Math.floor(remainingTime),
user: decoded.username || decoded.eventSlug,
eventSlug: decoded.eventSlug,
adminUsername: decoded.username
adminUsername: decoded.username,
// What KIND of gallery session this cookie is (#1149). The frontend
// kept this in sessionStorage, which is per-tab: reopening a gallery
// in a second tab lost 'client' while the cookie — and therefore the
// backend — still treated it as one. Reported from the token so a
// restored session knows what it actually is.
//
// viaCustomer marks a portal-minted token, which opens the gallery
// without the password. Also a credential, and it does not look like
// one: it runs at accessLevel 'guest'.
accessLevel: decoded.type === 'gallery' ? (decoded.accessLevel || 'guest') : undefined,
viaCustomer: decoded.type === 'gallery' ? decoded.via === 'customer' : undefined
});
} catch (err) {
res.json({
+152 -32
View File
@@ -29,6 +29,7 @@ const { resolveGuest } = require('../middleware/guestAuth');
const { generateGuestIdentifier } = require('../middleware/feedbackRateLimit');
const secureImageService = require('../services/secureImageService');
const logger = require('../utils/logger');
const { pipeStreamToResponse } = require('../utils/streamResponse');
const { resolvePhotoFilePath } = require('../services/photoResolver');
const { getEventShareToken, resolveShareIdentifier, buildShareLinkVariants } = require('../services/shareLinkService');
const { handleAsync, errorResponse } = require('../utils/routeHelpers');
@@ -412,7 +413,10 @@ router.get('/:slug/show/:token/state', handleAsync(async (req, res) => {
router.get('/:slug/photos', verifyGalleryAccess, resolveGuest, async (req, res) => {
try {
// Get filter and sort parameters from query
const { filter, guest_id, sort = 'upload_date', order = 'desc' } = req.query;
// `guest_id` is deliberately NOT read from the query string: the viewer's
// own feedback is resolved from the request identity instead (see the
// filter block). The frontend still sends it; it is ignored.
const { filter, sort = 'upload_date', order = 'desc' } = req.query;
// Get watermark settings to generate cache-busting version for URLs
const watermarkSettings = await watermarkService.getWatermarkSettings();
@@ -443,20 +447,78 @@ router.get('/:slug/photos', verifyGalleryAccess, resolveGuest, async (req, res)
});
}
// Apply sort option
// Apply sort option.
//
// Every branch carries photos.id as a tiebreaker (#1172). Without one the
// order within a tie is whatever the engine happens to return, and ties are
// the normal case rather than the exception: a bulk import writes hundreds
// of rows inside the same second, so uploaded_at collapses — and with
// captured_at NULL the COALESCE below collapses onto it too. The visible
// symptom is a grid that reshuffles between page loads. id is insertion
// order, so it also makes the fallback ordering meaningful rather than
// arbitrary.
if (sort === 'capture_date') {
// Sort by capture date, falling back to uploaded_at if capture date is null
photosQuery = photosQuery.orderByRaw('COALESCE(photos.captured_at, photos.uploaded_at) ' + sortOrder);
// Sort by capture date, falling back to uploaded_at if capture date is null.
//
// On SQLite that fallback cannot be a plain COALESCE, because the two
// columns do not hold one type. photos.captured_at ends up carrying three
// different storage classes:
//
// integer managed uploads — photoProcessor.js:441 writes a Date, which
// the sqlite3 binding stores as epoch milliseconds
// text external imports and the backfill, which write ISO-8601
// ('2026-06-03T01:15:00.000Z') per the CLAUDE.md rule that
// Dates must not be handed to the binding in tests
// null no capture date, so the sort falls through to uploaded_at —
// usually text in knex's 'YYYY-MM-DD HH:MM:SS' default shape,
// but epoch milliseconds on rows a .picpeak restore carried in
// from an install that stored them that way, so that column
// needs the same two branches
//
// SQLite orders INTEGER before TEXT unconditionally, so every managed
// photo carrying EXIF sorted ahead of every photo that did not, whatever
// the actual dates — a 2027 capture landing before a 2020 one. Among the
// text values the 'T' separator (0x54) also outranks the space (0x20), so
// a same-day ISO 01:15 sorted after a fallback 23:00.
//
// Normalising in the ORDER BY rather than rewriting the column: the data
// fix would have to touch every existing row and every writer, which is a
// much heavier change than the sort it is meant to correct. The cost here
// is that this sort stops using idx_photos_captured_at on SQLite — an
// acceptable trade on the fallback engine, where the alternative is an
// index-assisted wrong answer.
//
// Postgres is untouched: captured_at is a real timestamp there, so
// COALESCE already compares correctly.
if (db.client.config.client === 'pg') {
photosQuery = photosQuery
.orderByRaw('COALESCE(photos.captured_at, photos.uploaded_at) ' + sortOrder);
} else {
photosQuery = photosQuery.orderByRaw(`CASE
WHEN typeof(photos.captured_at) IN ('integer', 'real') THEN datetime(photos.captured_at / 1000, 'unixepoch')
WHEN photos.captured_at IS NOT NULL THEN replace(replace(substr(photos.captured_at, 1, 19), 'T', ' '), 'Z', '')
WHEN typeof(photos.uploaded_at) IN ('integer', 'real') THEN datetime(photos.uploaded_at / 1000, 'unixepoch')
ELSE substr(photos.uploaded_at, 1, 19)
END ${sortOrder}`);
}
photosQuery = photosQuery.orderBy('photos.id', sortOrder);
} else if (sort === 'filename') {
photosQuery = photosQuery.orderBy('photos.filename', sortOrder);
photosQuery = photosQuery.orderBy('photos.filename', sortOrder).orderBy('photos.id', sortOrder);
} else {
// Default: sort by upload date
photosQuery = photosQuery.orderBy('photos.uploaded_at', sortOrder);
photosQuery = photosQuery.orderBy('photos.uploaded_at', sortOrder).orderBy('photos.id', sortOrder);
}
// Execute the query
let photos = await photosQuery;
// Check if feedback should be visible to guests. Read BEFORE the filter
// block, not after: the filters below consult it, because a filter that
// selects on other people's feedback is a way of reading that feedback.
const feedbackService = require('../services/feedbackService');
const feedbackSettings = await feedbackService.getEventFeedbackSettings(req.event.id);
const showFeedbackToGuests = isClient || parseBooleanInput(feedbackSettings.show_feedback_to_guests, true);
// Apply filtering if requested (supports global stats + per-guest interactions)
if (filter) {
const filterTokens = new Set(
@@ -486,10 +548,37 @@ router.get('/:slug/photos', verifyGalleryAccess, resolveGuest, async (req, res)
});
};
// Whose feedback counts as "mine" for these filters.
//
// Resolved from the REQUEST, the same either/or the per-viewer is_liked
// query below uses — never from the `guest_id` query parameter. Two
// reasons, and both matter now that this is the only half left when
// feedback is hidden:
//
// - It never matched. The frontend's `gallery_guest_id` is a
// localStorage string it invents (`guest_<ts>_<rand>`) and never
// sends when submitting feedback; submissions store
// generateGuestIdentifier(req). So this lookup found nothing, and
// the filters only ever worked through the aggregate half — which
// is exactly the half now gated.
// - It is caller-controlled. Accepting an identifier from the query
// string would let anyone holding someone else's read their hidden
// memberships one token at a time, straight back through the gate.
//
// Hidden rows are excluded, matching what the viewer can actually SEE:
// getPhotoFeedback drops is_hidden for the guest's own feedback too.
// Unapproved rows are NOT excluded — a comment still in the moderation
// queue is still the viewer's own, and that same read keeps it.
let guestFeedbackByType = null;
if (guest_id) {
const guestFeedbackRows = await db('photo_feedback')
.where({ event_id: req.event.id, guest_identifier: guest_id })
{
const viewerFeedback = db('photo_feedback')
.where({ event_id: req.event.id, is_hidden: false });
if (req.guest?.id) {
viewerFeedback.where('guest_id', req.guest.id);
} else {
viewerFeedback.where('guest_identifier', generateGuestIdentifier(req));
}
const guestFeedbackRows = await viewerFeedback
.select('photo_id', 'feedback_type');
guestFeedbackByType = guestFeedbackRows.reduce((acc, row) => {
@@ -508,39 +597,50 @@ router.get('/:slug/photos', verifyGalleryAccess, resolveGuest, async (req, res)
}
};
// Every token below is an OR of two halves: what THIS viewer marked,
// and what ANYONE marked. The second half is other people's feedback,
// so it is gated on show_feedback_to_guests exactly like the counts
// this endpoint returns.
//
// Without the gate the setting only hides the numbers. A guest could
// still send `?filter=liked` and get back precisely the set of photos
// other people liked — the membership, one token at a time, which is
// most of what the counts would have told them. The viewer's own half
// is always theirs to filter by.
const includeAggregate = (predicate) => {
if (showFeedbackToGuests) includeBy(predicate);
};
if (filterTokens.has('liked')) {
includeGuestMatches('like');
includeBy(photo => (photo.like_count || 0) > 0);
includeAggregate(photo => (photo.like_count || 0) > 0);
}
if (filterTokens.has('favorited')) {
includeGuestMatches('favorite');
includeBy(photo => (photo.favorite_count || 0) > 0);
includeAggregate(photo => (photo.favorite_count || 0) > 0);
}
if (filterTokens.has('rated')) {
includeGuestMatches('rating');
includeBy(photo => (photo.average_rating || 0) > 0);
includeAggregate(photo => (photo.average_rating || 0) > 0);
}
if (filterTokens.has('commented')) {
includeGuestMatches('comment');
const commentedRows = await db('photo_feedback')
.where({ event_id: req.event.id, feedback_type: 'comment', is_approved: true, is_hidden: false })
.groupBy('photo_id')
.select('photo_id');
commentedRows.forEach(row => include.add(row.photo_id));
if (showFeedbackToGuests) {
const commentedRows = await db('photo_feedback')
.where({ event_id: req.event.id, feedback_type: 'comment', is_approved: true, is_hidden: false })
.groupBy('photo_id')
.select('photo_id');
commentedRows.forEach(row => include.add(row.photo_id));
}
}
photos = photos.filter(photo => include.has(photo.id));
}
}
// Check if feedback should be visible to guests
const feedbackService = require('../services/feedbackService');
const feedbackSettings = await feedbackService.getEventFeedbackSettings(req.event.id);
const showFeedbackToGuests = isClient || parseBooleanInput(feedbackSettings.show_feedback_to_guests, true);
// Then get comment counts separately
const commentCounts = await db('photo_feedback')
.whereIn('photo_id', photos.map(p => p.id))
@@ -568,7 +668,12 @@ router.get('/:slug/photos', verifyGalleryAccess, resolveGuest, async (req, res)
const likedPhotoIds = new Set();
if (showFeedbackToGuests && photos.length > 0) {
const likeQuery = db('photo_feedback')
.where({ event_id: req.event.id, feedback_type: 'like' })
// Hidden rows are not there, for the viewer's OWN feedback as much as
// anyone's (#1150). getPhotoFeedback drops them and
// updatePhotoFeedbackStats does not count them — leaving the heart
// filled was the one place that disagreed, so a like the photographer
// had hidden still showed as liked on a photo whose like_count was 0.
.where({ event_id: req.event.id, feedback_type: 'like', is_hidden: false })
.whereIn('photo_id', photos.map(p => p.id));
if (req.guest?.id) {
likeQuery.where('guest_id', req.guest.id);
@@ -1044,7 +1149,7 @@ router.get('/:slug/download-all', verifyGalleryAccess, denySlideshowToken, async
res.setHeader('Content-Length', zipInfo.size);
res.setHeader('Content-Disposition', `attachment; filename="${req.event.slug}.zip"`);
const stream = await storage.get(zipInfo.key);
stream.pipe(res);
pipeStreamToResponse(stream, res, { context: `prepared zip for event ${req.event.id}`, missingStatus: 410 });
// Log bulk download
db('access_logs').insert({
@@ -1505,7 +1610,7 @@ router.get('/:slug/photo/:photoId',
const file = useStorageBackend
? await storage.getRange(storageKey, start, end)
: fs.createReadStream(filePath, { start, end });
file.pipe(res);
pipeStreamToResponse(file, res, { context: `video range for photo ${photo.id}` });
} else {
res.writeHead(200, {
'Content-Length': fileSize,
@@ -1517,7 +1622,7 @@ router.get('/:slug/photo/:photoId',
const file = useStorageBackend
? await storage.get(storageKey)
: fs.createReadStream(filePath);
file.pipe(res);
pipeStreamToResponse(file, res, { context: `video for photo ${photo.id}` });
}
return;
}
@@ -1551,7 +1656,7 @@ router.get('/:slug/photo/:photoId',
'X-Protection-Level': 'basic'
});
const wmStream = await storage.get(photo.watermark_path);
return wmStream.pipe(res);
return pipeStreamToResponse(wmStream, res, { context: `watermarked photo ${photo.id}` });
}
} else {
const watermarkFilePath = path.join(getStoragePath(), photo.watermark_path);
@@ -1600,7 +1705,7 @@ router.get('/:slug/photo/:photoId',
res.set('Content-Length', stat.size);
if (photo.mime_type) res.set('Content-Type', photo.mime_type);
const stream = await storage.get(storageKey);
stream.pipe(res);
pipeStreamToResponse(stream, res, { context: `photo ${photo.id}` });
} else {
const absolutePath = path.isAbsolute(filePath) ? filePath : path.resolve(filePath);
res.sendFile(absolutePath);
@@ -1695,7 +1800,7 @@ router.get('/:slug/thumbnail/:photoId',
} else {
res.setHeader('Content-Length', stat.size);
const stream = await storage.get(thumbnailPath);
stream.pipe(res);
pipeStreamToResponse(stream, res, { context: `thumbnail for photo ${photoId}` });
}
} catch (error) {
errorResponse(res, error, 500, 'Failed to serve thumbnail');
@@ -1781,7 +1886,7 @@ router.get('/:slug/hero/:photoId',
} else {
res.setHeader('Content-Length', stat.size);
const stream = await storage.get(heroPath);
stream.pipe(res);
pipeStreamToResponse(stream, res, { context: `hero for photo ${photoId}` });
}
} catch (error) {
logger.error('Error serving hero image:', {
@@ -1858,7 +1963,12 @@ router.get('/:slug/preview/:photoId',
}
res.set({
'Content-Type': 'image/jpeg',
// From the key, not hard-coded: a preview of a transparent or animated
// source is WebP, because JPEG carries neither. `nosniff` below means
// getting this wrong shows a broken image rather than being silently
// corrected by the browser. Pre-existing keys have no .webp suffix and
// are JPEG, so they keep their old header.
'Content-Type': previewPath.endsWith('.webp') ? 'image/webp' : 'image/jpeg',
// Cache aggressively — preview only changes on photo
// re-upload (which generates a new preview key) or settings
// regenerate (which writes a new mtime + ETag).
@@ -1870,6 +1980,16 @@ router.get('/:slug/preview/:photoId',
});
if (watermarkSettings && watermarkSettings.enabled) {
// No Content-Type override here. applyWatermark PRESERVES the source
// format (watermarkService.js: png -> png, webp -> webp, else jpeg),
// and its input is this preview — so the output format matches the key
// the header was already derived from. Forcing image/jpeg would
// mislabel a watermarked WebP preview, and `nosniff` means the browser
// will not correct it.
//
// What is still lost is the animation: the compositor flattens a
// multi-frame source to one frame while keeping the WebP container.
// That is a separate problem and a much larger one.
const watermarkedBuffer = await withLocalCopy(previewPath, (localPath) =>
watermarkService.applyWatermark(localPath, watermarkSettings)
);
@@ -1877,7 +1997,7 @@ router.get('/:slug/preview/:photoId',
} else {
res.setHeader('Content-Length', stat.size);
const stream = await storage.get(previewPath);
stream.pipe(res);
pipeStreamToResponse(stream, res, { context: `preview for photo ${photoId}` });
}
} catch (error) {
logger.error('Error serving preview image:', {
+8 -1
View File
@@ -367,7 +367,14 @@ router.get('/:slug/my-feedback',
const query = db('photo_feedback')
.join('photos', 'photo_feedback.photo_id', 'photos.id')
.where('photo_feedback.event_id', event.id);
.where('photo_feedback.event_id', event.id)
// Hidden rows are absent for the guest who left them too (#1150). In
// guest identity mode GalleryView builds its Liked/Favorited/Rated
// chips and their filters from THIS array rather than from is_liked,
// so without this a hidden like left an empty heart while the Liked
// chip still counted it and still surfaced the photo. Unapproved rows
// stay: a comment in the moderation queue is still the guest's own.
.where('photo_feedback.is_hidden', false);
// Prefer guest_id lookup when a verified guest token is present
// (per-person identity). Fall back to the device hash otherwise.
+2 -2
View File
@@ -609,8 +609,8 @@ router.post(
let height = null;
try {
const meta = await sharp(tempPath).metadata();
width = meta.width || null;
height = meta.height || null;
// Oriented, not raw — see imageProcessor.orientedDimensions (#1185).
({ width, height } = require('../../services/imageProcessor').orientedDimensions(meta));
} catch { /* non-fatal */ }
let thumbRel = null;
@@ -94,6 +94,13 @@ async function list(relativePath = '') {
return { path: relFromRoot, entries, canNavigateUp };
}
/**
* A path under an EVENT's configured base directory.
*
* Still the right resolver for anything that means "the folder this event was
* imported from" — the import walk in particular. It is NOT how a photo's
* original is found any more: see resolveExternalPhotoPath (#1163).
*/
function resolveExternalPath(event, relpath) {
const root = getExternalMediaRoot();
const base = event?.external_path ? path.join(event.external_path) : '';
@@ -101,9 +108,29 @@ function resolveExternalPath(event, relpath) {
return safePathJoin(root, combined);
}
/**
* A photo's original, from the root (#1163).
*
* photos.external_relpath used to be stored relative to events.external_path,
* which made a row's meaning depend on a column on another table that every
* import overwrites. Importing a second folder into an event therefore rebased
* every row already in it — silently, because thumbnails are written to local
* storage during the import and the grid keeps rendering. One reporter had
* 7547 of 8004 rows resolving to files that did not exist.
*
* Root-relative makes a row self-describing: nothing an admin does to the event
* afterwards can move an already-imported photo. Migration 177 rewrote the
* existing rows.
*/
function resolveExternalPhotoPath(photo) {
const root = getExternalMediaRoot();
return safePathJoin(root, photo?.external_relpath || '');
}
module.exports = {
getExternalMediaRoot,
isUnderRoot,
list,
resolveExternalPath,
resolveExternalPhotoPath,
};
+389
View File
@@ -0,0 +1,389 @@
/**
* One row per external file per event (#1162).
*
* The import route used to check for an existing external_relpath and then
* insert, with an fs.stat and a Sharp decode in between — wide enough that two
* overlapping imports both walked through it. A reporter's event held 8004 rows
* for 6012 distinct paths.
*
* This lives in a service rather than inside migration 176 because it has two
* callers. The migration is one. The other is a .picpeak restore: the archive
* carries the photos table verbatim, so a backup taken before this fix lands
* duplicate rows into a schema that now has a unique index on them — and
* neither Postgres' `session_replication_role = replica` nor SQLite's
* `defer_foreign_keys` disables a UNIQUE index, so batchInsert would abort the
* whole restore after every table had already been emptied.
*
* DELETING dependent rows explicitly, rather than trusting ON DELETE CASCADE,
* is the load-bearing part. Every FK into photos declares CASCADE, but PicPeak
* does not set `PRAGMA foreign_keys = ON` — the codebase says so in as many
* words where it deletes an event (adminEvents/helpers.js:245-249) — so on
* every SQLite install the cascade is inert and a bare delete would leave
* dangling face embeddings, feedback and marks behind. The same reason
* `hero_photo_id` is repointed by hand: its SET NULL is inert there too, so
* without it a SQLite install keeps a hero pointing at a row that is gone.
*
* Guest and admin state is MOVED to the survivor where it can be, not
* discarded. The duplicates were separate tiles in the grid, so a guest's
* comment or an admin's rating could legitimately be attached to either, and
* silently deleting it inside a fix for silent data loss would be its own bug.
* Where the target already holds an equivalent row — the same guest's like on
* the same photo, the same admin's mark, the same transfer's entry — the loser
* is dropped instead, because those tables mean "one per (photo, actor)" and
* moving would either violate a unique constraint or double-count.
*
* photo_faces is the deliberate exception: both rows were scanned
* independently, so the survivor already has its own embeddings and moving the
* duplicate's would fabricate a second copy of every face and split the
* person clusters built from them.
*/
const { isUniqueViolation } = require('../utils/dbErrors');
const CHUNK = 400; // SQLite caps a statement at 999 bound parameters.
// Joins the parts of an equivalence key. Escaped, not a literal: a raw NUL in
// the source makes git classify this whole file as binary and hide its diffs.
const KEY_SEP = '\u0000';
const INDEX_NAME = 'photos_event_external_relpath_uniq';
const chunked = (arr) => {
const out = [];
for (let i = 0; i < arr.length; i += CHUNK) out.push(arr.slice(i, i + CHUNK));
return out;
};
/** Pure log rows — nothing is lost by dropping them with the duplicate. */
const LOG_TABLES = [
['image_access_logs', 'photo_id'],
['transfer_downloads', 'photo_id'],
];
/**
* Tables holding one row per (photo, actor). `keys` is what makes two rows
* equivalent, so a move that would collide becomes a delete instead.
*/
const MOVE_TABLES = [
{
table: 'photo_feedback',
// Guest identity, the way feedbackService defines it: guest_id when the
// gallery uses per-person guests (migration 078), guest_identifier
// otherwise — the same COALESCE its own duplicate-check and stats
// aggregate use (feedbackService.js:208, :559). Keying on
// guest_identifier alone would treat two DIFFERENT people sharing a
// device as one and delete one of their ratings.
identity: (row) => (row.guest_id != null ? `id:${row.guest_id}` : `anon:${row.guest_identifier}`),
// is_hidden is part of the identity, not noise: feedbackService lets a
// moderator-hidden row coexist with the guest's visible replacement and
// excludes hidden rows from the counts. Without it the visible row is
// dropped as redundant against the hidden one.
keys: ['feedback_type', 'is_hidden'],
// A comment is distinct content, never a per-guest toggle: two comments
// from one guest are two comments, so they always move.
alwaysMove: (row) => row.feedback_type === 'comment',
},
{
table: 'photo_admin_marks',
keys: ['admin_id'],
// rating and color_label are independently writable, so the same admin can
// have rated one tile and colour-labelled the other. Dropping the loser
// outright would lose a half the survivor's row has no value for.
mergeFields: ['rating', 'color_label'],
},
{ table: 'transfer_files', keys: ['transfer_id'] },
];
const equivalenceKey = (spec, row) => [
spec.identity ? spec.identity(row) : '',
...spec.keys.map((k) => row[k]),
].join(KEY_SEP);
async function repointColumn(knex, table, column, doomedToSurvivor) {
if (!(await knex.schema.hasTable(table))) return;
if (!(await knex.schema.hasColumn(table, column))) return;
for (const [doomed, survivor] of doomedToSurvivor) {
await knex(table).where(column, doomed).update({ [column]: survivor });
}
}
async function moveOrDrop(knex, spec, doomedToSurvivor, touched) {
if (!(await knex.schema.hasTable(spec.table))) return;
for (const [doomed, survivor] of doomedToSurvivor) {
const rows = await knex(spec.table).where('photo_id', doomed);
if (!rows.length) continue;
if (touched) touched.add(survivor);
const existing = await knex(spec.table).where('photo_id', survivor);
const taken = new Set(existing.map((r) => equivalenceKey(spec, r)));
for (const row of rows) {
const key = equivalenceKey(spec, row);
const move = (spec.alwaysMove && spec.alwaysMove(row)) || !taken.has(key);
if (!move) {
// Before dropping the loser, hand over any field the winner has no
// value for — otherwise an independently-set half goes with it.
if (spec.mergeFields) {
const winner = existing.find((r) => equivalenceKey(spec, r) === key);
const fill = {};
for (const field of spec.mergeFields) {
if (winner && winner[field] == null && row[field] != null) fill[field] = row[field];
}
if (winner && Object.keys(fill).length) {
await knex(spec.table).where('id', winner.id).update(fill);
Object.assign(winner, fill);
}
}
await knex(spec.table).where('id', row.id).del();
continue;
}
try {
await knex(spec.table).where('id', row.id).update({ photo_id: survivor });
taken.add(key);
} catch (err) {
// A unique constraint we did not model. The row is redundant with one
// the survivor already has, so dropping it is correct — but anything
// else must surface rather than leave a dangling photo_id behind.
if (!isUniqueViolation(err)) throw err;
await knex(spec.table).where('id', row.id).del();
}
}
}
}
/**
* Remove every photo row in `doomedToSurvivor`, moving or dropping the state
* that hangs off it first. Safe on both engines and on schemas that predate
* any of the dependent tables.
*/
async function deleteDuplicatePhotos(knex, doomedToSurvivor) {
const doomed = [...doomedToSurvivor.keys()];
if (!doomed.length) return 0;
// SET NULL is as inert as CASCADE on SQLite, so an event whose hero happened
// to be the duplicate would silently lose its hero image.
await repointColumn(knex, 'events', 'hero_photo_id', doomedToSurvivor);
await repointColumn(knex, 'photo_categories', 'hero_photo_id', doomedToSurvivor);
const feedbackTouched = new Set();
for (const spec of MOVE_TABLES) {
await moveOrDrop(knex, spec, doomedToSurvivor, spec.table === 'photo_feedback' ? feedbackTouched : null);
}
// photos carries denormalized feedback totals (migration 033:
// feedback_count, like_count, average_rating, favorite_count, and later
// reaction/colour counts). Reparenting rows without recomputing leaves a
// survivor that now OWNS feedback still rendering zero.
if (feedbackTouched.size && await knex.schema.hasColumn('photos', 'feedback_count')) {
const feedbackService = require('./feedbackService');
for (const survivor of feedbackTouched) {
await feedbackService.updatePhotoFeedbackStats(survivor, knex);
}
}
for (const [table, column] of LOG_TABLES) {
if (!(await knex.schema.hasTable(table))) continue;
for (const ids of chunked(doomed)) await knex(table).whereIn(column, ids).del();
}
// Both rows were scanned, so the survivor has its own faces; moving the
// duplicate's would double every embedding and split the person clusters.
//
// Through purgePhotoFaces, not a raw delete: deleting the rows is only half
// of it. event_people counts and centroids are derived from the faces being
// removed, and #1132's separation snapshots hold a COPY of each side's
// centroid — so a bare delete leaves ghost or inflated people and vectors
// built from photos that no longer exist. faceProcessor says as much: it is
// "called from every photo-deletion path".
if (await knex.schema.hasTable('photo_faces')) {
// If the ONLY completed scan of this file belonged to the duplicate, the
// purge below takes the sole embeddings with it and nothing re-queues the
// survivor — it just silently stops having a face. Mark those for a
// rescan; the worker picks up 'pending' on its own.
const needsRescan = [];
for (const [doomedId, survivorId] of doomedToSurvivor) {
if (!(await knex('photo_faces').where('photo_id', doomedId).first())) continue;
if (!(await knex('photo_faces').where('photo_id', survivorId).first())) needsRescan.push(survivorId);
}
let purgePhotoFaces = null;
try {
({ purgePhotoFaces } = require('./faceProcessor'));
} catch (err) {
// Face detection is optional; an install without it still needs the rows
// gone so nothing dangles on SQLite.
purgePhotoFaces = null;
}
if (purgePhotoFaces) {
for (const id of doomed) await purgePhotoFaces(id, knex);
} else {
for (const ids of chunked(doomed)) await knex('photo_faces').whereIn('photo_id', ids).del();
}
if (needsRescan.length && await knex.schema.hasColumn('photos', 'face_status')) {
for (const ids of chunked(needsRescan)) {
await knex('photos').whereIn('id', ids).update({ face_status: 'pending' });
}
}
}
// Real interactions, recorded per row. Deleting the duplicate would quietly
// lower the engagement the admin grid shows for a photo people did view and
// download.
if (await knex.schema.hasColumn('photos', 'view_count')) {
for (const [doomedId, survivorId] of doomedToSurvivor) {
const from = await knex('photos').where('id', doomedId)
.select('view_count', 'download_count').first();
if (!from) continue;
const add = {};
if (from.view_count) add.view_count = knex.raw('COALESCE(view_count, 0) + ?', [from.view_count]);
if (from.download_count) add.download_count = knex.raw('COALESCE(download_count, 0) + ?', [from.download_count]);
if (Object.keys(add).length) await knex('photos').where('id', survivorId).update(add);
}
}
for (const ids of chunked(doomed)) await knex('photos').whereIn('id', ids).del();
// The pre-built "download everything" zip still contains the rows just
// removed. Every ordinary photo-deletion path calls
// downloadZipService.invalidate for this reason (adminPhotos.js:450 and
// friends) — but that service carries debounce timers and a regeneration
// queue, which is not something a migration should be starting. Clearing the
// columns is the durable half of what invalidate does: getZipInfo already
// treats a missing or absent record as a cache miss and rebuilds on the next
// request, so guests stop receiving an archive containing deleted duplicates.
//
// The stale object itself is left for the same reason the duplicates'
// thumbnails are — a migration is the wrong place to reach into storage,
// which may be S3.
if (await knex.schema.hasColumn('events', 'download_zip_path')) {
const affected = [...new Set([...doomedToSurvivor.values()])];
const eventIds = affected.length
? (await knex('photos').whereIn('id', affected).distinct('event_id')).map((r) => r.event_id)
: [];
for (const ids of chunked(eventIds)) {
await knex('events').whereIn('id', ids).update({
download_zip_path: null,
download_zip_generated_at: null,
});
}
}
return doomed.length;
}
/**
* Which rows are duplicates, and which one survives.
*
* Survivor: the lowest id that has a thumbnail_path, else the lowest id.
* Thumbnails are generated per row during import, so on a duplicated pair both
* usually have one and the tie-break never fires — but an import killed
* mid-flight leaves rows without, and dropping the one that HAS the thumbnail
* would blank a grid tile for no reason.
*/
async function planDedupe(knex) {
const dupKeys = await knex('photos')
.whereNotNull('external_relpath')
.select('event_id')
.count('* as c')
.groupBy('event_id', 'external_relpath')
.havingRaw('count(*) > 1');
const doomedToSurvivor = new Map();
for (const eventId of new Set(dupKeys.map((r) => r.event_id))) {
const rows = await knex('photos')
.where('event_id', eventId)
.whereNotNull('external_relpath')
.select('id', 'external_relpath', 'thumbnail_path')
.orderBy('id', 'asc');
const byPath = new Map();
for (const row of rows) {
const group = byPath.get(row.external_relpath);
if (group) group.push(row);
else byPath.set(row.external_relpath, [row]);
}
for (const group of byPath.values()) {
if (group.length < 2) continue;
const survivor = group.find((r) => r.thumbnail_path) || group[0];
for (const row of group) {
if (row.id !== survivor.id) doomedToSurvivor.set(row.id, survivor.id);
}
}
}
return doomedToSurvivor;
}
/** @returns {Promise<number>} how many duplicate rows were removed. */
async function dedupeExternalPhotos(knex) {
if (!(await knex.schema.hasTable('photos'))) return 0;
if (!(await knex.schema.hasColumn('photos', 'external_relpath'))) return 0;
return deleteDuplicatePhotos(knex, await planDedupe(knex));
}
/** Is the index actually there? Asked of the catalog, not inferred. */
async function externalRelpathIndexExists(knex) {
const isPg = knex.client && knex.client.config && knex.client.config.client === 'pg';
const row = isPg
? await knex('pg_indexes').where('indexname', INDEX_NAME).first()
: await knex('sqlite_master').where({ type: 'index', name: INDEX_NAME }).first();
return !!row;
}
/**
* The error a failed index MUST raise.
*
* Deliberately carries no `code`. run-migrations-safe.js treats 23505, 42P07,
* 42701 and 42710 as "schema already exists" and marks the migration applied
* (run-migrations-safe.js:138) — and a CREATE UNIQUE INDEX that finds
* duplicate rows raises exactly 23505 on Postgres. Letting the driver's error
* through would therefore record 176 as done on an install that never got the
* index, with nothing to trigger a retry: the precise outcome the throw
* exists to prevent.
*/
function indexFailure(detail) {
return new Error(
`Could not create ${INDEX_NAME}: ${detail}. The photos table still holds `
+ 'duplicate (event_id, external_relpath) rows — most likely inserted by a '
+ 'concurrent import while this migration ran. Stop other writers and re-run.'
);
}
/**
* Partial, so the managed rows — which all carry NULL — are not indexed at
* all. Both engines treat NULLs as distinct in a unique index, so a plain one
* would also be correct, but it would carry every managed photo for no query
* that ever uses it.
*/
async function createExternalRelpathIndex(knex) {
try {
await knex.raw(
`CREATE UNIQUE INDEX IF NOT EXISTS ${INDEX_NAME} `
+ 'ON photos (event_id, external_relpath) WHERE external_relpath IS NOT NULL'
);
} catch (err) {
throw indexFailure(err.message);
}
// IF NOT EXISTS makes the statement itself a poor witness, and a replica
// inserting a duplicate between the dedupe and this lock is a real rolling-
// deploy shape. Ask the catalog.
if (!(await externalRelpathIndexExists(knex))) {
throw indexFailure('the index is absent afterwards');
}
}
async function dropExternalRelpathIndex(knex) {
await knex.raw(`DROP INDEX IF EXISTS ${INDEX_NAME}`);
}
module.exports = {
dedupeExternalPhotos,
externalRelpathIndexExists,
deleteDuplicatePhotos,
planDedupe,
createExternalRelpathIndex,
dropExternalRelpathIndex,
INDEX_NAME,
};
+304
View File
@@ -0,0 +1,304 @@
/**
* Fold each event's base path into its external photo rows (#1163).
*
* photos.external_relpath used to be stored relative to events.external_path —
* a column every import overwrites — so importing a second folder into an
* event rebased every photo already in it. Root-relative paths make a row
* self-describing.
*
* This lives in a service rather than inside migration 177 because it has two
* callers. The migration is one. The other is a .picpeak restore: knex_migrations
* is excluded from the archive, so restoring a pre-#1163 backup onto an
* already-migrated instance drops base-relative rows into a schema that no
* longer folds them, and every original in the restored library becomes
* unreachable with nothing logged.
*
* REPAIR, and its limits. For a healthy event the correct new value is just
* `external_path + relpath` — that is what the app resolves today, so folding
* it in changes nothing and can break nothing. For an event that has ALREADY
* been rebased, that same rule would bake the broken path in permanently, so
* where the current resolution does not exist on disk this walks up the base
* path looking for an ancestor under which the file IS there (the shape the
* bug produces: a parent imported first, a child second). A row it cannot
* place is left resolving exactly where it resolves today — preserving current
* behaviour is the floor, never guess below it.
*
* Existence alone is NOT enough to accept an ancestor. A row whose file an
* admin simply deleted would otherwise adopt any same-named file further up —
* base `Trip/Sub`, relpath `photo.jpg`, an unrelated `Trip/photo.jpg` — and
* downloads would then serve the WRONG original, which is worse than a broken
* link. So an ancestor candidate must also match photos.size_bytes, recorded
* by the import from the very file the row describes. Rows carrying no size
* are never repaired from an ancestor.
*
* ATOMICITY. Probing is read-only and runs first; every rewrite and the marker
* are then committed in ONE transaction. Split across commits, a process
* killed mid-fold would leave converted and unconverted rows behind with no
* marker, and the next run would fold the converted ones a second time —
* putting every original one directory deeper, permanently.
*
* The probe is skipped entirely when the media root is unreachable or empty:
* an unmounted share makes every file look missing, and "repairing" off that
* signal would move every original on a healthy install. When it does run it
* is one access() per photo, base path first, so a healthy install pays one
* stat per row and then a single UPDATE per event.
*
* Idempotency is recorded explicitly in app_settings rather than inferred from
* the data. The tempting inference — "does the relpath already start with the
* base path?" — is wrong for any event with a subfolder named after its parent
* (base 'Trip', row 'Trip/x.jpg'), and being wrong there corrupts a path in an
* operation that has no undo.
*/
const path = require('path');
const fsp = require('fs').promises;
const { deleteDuplicatePhotos } = require('./externalPhotoDedupe');
const MARKER = 'external_relpath_root_relative';
// Per-row parking value for the two-pass rewrite below.
//
// NOT a NUL-prefixed string, which is what this was first written as: Postgres
// rejects U+0000 in a `text` column outright ("invalid byte sequence for
// encoding UTF8"), so the rewrite would abort on exactly the installs that
// need the two-pass repair — and only on Postgres, which SQLite-only tests
// cannot see. The prefix below is ordinary text, cannot collide with a real
// relative path (no import writes a leading dot-segment like this), and stays
// obviously wrong if a crash ever leaves one behind.
const STAGING_PREFIX = '.picpeak-fold-staging/';
const CHUNK = 400; // SQLite caps a statement at 999 bound parameters.
const chunk = (arr) => {
const out = [];
for (let i = 0; i < arr.length; i += CHUNK) out.push(arr.slice(i, i + CHUNK));
return out;
};
function normalizeBase(externalPath) {
return String(externalPath || '').replace(/\\/g, '/').replace(/^\/+|\/+$/g, '');
}
/** Every prefix of `base`, longest first, then '' (the root itself). */
function ancestorPrefixes(base) {
const segs = base.split('/').filter(Boolean);
const out = [];
for (let i = segs.length; i > 0; i--) out.push(segs.slice(0, i).join('/'));
out.push('');
return out;
}
async function exists(p) {
try { await fsp.access(p); return true; } catch { return false; }
}
/**
* Is `p` plausibly the file this row was imported from?
*
* Size is the provenance signal available without re-reading every original:
* photos.size_bytes was written by the import from the file the row describes.
* Returns false when it cannot be verified, so an unverifiable candidate is
* never adopted from somewhere the row did not previously point.
*/
async function fileMatchesSize(p, expectedSize) {
if (expectedSize == null || Number(expectedSize) <= 0) return false;
try {
const stats = await fsp.stat(p);
return stats.isFile() && stats.size === Number(expectedSize);
} catch {
return false;
}
}
/**
* Joined without the safePathJoin the app serves through: this is reading, and
* a stored path that escapes the root is damage worth detecting rather than
* throwing on.
*/
const under = (root, ...parts) => path.join(root, ...parts.filter(Boolean));
async function rootUsable(root) {
if (!root) return false;
try {
// An unmounted NFS/SMB share usually leaves the mountpoint behind as an
// ordinary empty directory, so readdir succeeds on storage that is gone.
return (await fsp.readdir(root)).length > 0;
} catch {
return false;
}
}
/**
* @param {import('knex')} knex a knex instance, or a transaction from a caller
* that is already inside one (the restore).
* @param {(msg: string) => void} [log]
* @returns {Promise<{skipped?: string, folded?: number, repaired?: number, stranded?: number, collided?: number}>}
*/
async function foldExternalRelpaths(knex, log = () => {}) {
if (!(await knex.schema.hasTable('photos'))) return { skipped: 'no photos table' };
if (!(await knex.schema.hasColumn('photos', 'external_relpath'))) return { skipped: 'no external_relpath column' };
if (!(await knex.schema.hasTable('events'))) return { skipped: 'no events table' };
if (!(await knex.schema.hasTable('app_settings'))) return { skipped: 'no app_settings table' };
if (await knex('app_settings').where('setting_key', MARKER).first()) {
return { skipped: 'already folded' };
}
const events = await knex('events').select('id', 'external_path');
const byId = new Map(events.map((e) => [e.id, normalizeBase(e.external_path)]));
const eventRows = await knex('photos').whereNotNull('external_relpath').distinct('event_id');
let root = null;
try {
root = require('./externalMediaService').getExternalMediaRoot();
} catch (e) {
log(`media root unavailable (${e.message}) — folding without on-disk repair`);
}
const canProbe = await rootUsable(root);
if (!canProbe) log('media root unreachable or empty — folding base paths in without on-disk repair');
// ---- Phase 1: decide, writing nothing. -------------------------------
// Read-only, so the transaction below stays short. Probing a cold NAS can
// take minutes and holding a write transaction open for that would block the
// app for the duration.
let folded = 0; let repaired = 0; let stranded = 0; let collided = 0;
const plan = [];
for (const { event_id: eventId } of eventRows) {
// No base path means the rows are already relative to the root.
const base = byId.get(eventId);
if (!base) continue;
const rows = await knex('photos')
.where('event_id', eventId)
.whereNotNull('external_relpath')
.select('id', 'external_relpath', 'size_bytes');
// Deciding health from a SAMPLE was the tempting shortcut and it is not
// safe: a rebased event whose first few rows happen to come from the most
// recent import reads as healthy, and every older row is baked in wrong.
const prefixes = ancestorPrefixes(base);
const placements = [];
let allUnderBase = true;
for (const row of rows) {
if (!canProbe) { placements.push([row, base]); continue; }
let chosen = null;
// The current base first, on existence alone — nothing is inferred
// there, it is where the row already resolves.
if (await exists(under(root, base, row.external_relpath))) {
chosen = base;
} else {
// Anywhere else has to prove itself: the name AND the size the import
// recorded. Without that a row whose file an admin deleted would adopt
// an unrelated same-named file one directory up, and downloads would
// serve the wrong original.
for (const prefix of prefixes) {
if (prefix === base) continue;
if (await fileMatchesSize(under(root, prefix, row.external_relpath), row.size_bytes)) {
chosen = prefix;
break;
}
}
}
if (chosen === null) { chosen = base; stranded++; }
if (chosen !== base) allUnderBase = false;
placements.push([row, chosen]);
}
if (allUnderBase) {
folded += rows.length;
plan.push({ eventId, base, bulk: true, rows: [], ids: rows.map((r) => r.id) });
continue;
}
// Two rows can now target the same path — the same file imported under two
// different bases really is one file. Resolved HERE rather than by letting
// the write fail: a caught write error cannot tell a genuine duplicate from
// a lock or I/O fault, and continuing past one would certify a partial
// conversion by writing the marker anyway.
//
// The loser is DELETED, not skipped. Skipping leaves it holding a
// base-relative path that the root-only resolver then reads as
// `<root>/<relpath>` — permanently pointing at the wrong place, or
// nowhere, with the marker saying the conversion is done. And it is a
// duplicate by construction: two rows that resolve to one file is exactly
// what migration 176 removes, so it goes through the same helper, which
// reparents the feedback and marks and reconciles the face clusters.
const claimed = new Map();
const resolved = [];
const losers = new Map();
for (const [row, chosen] of placements) {
const next = chosen ? `${chosen}/${row.external_relpath}` : row.external_relpath;
const winner = claimed.get(next);
if (winner != null) { losers.set(row.id, winner); collided++; continue; }
claimed.set(next, row.id);
if (chosen === base) folded++; else repaired++;
resolved.push([row.id, next]);
}
plan.push({ eventId, base, bulk: false, rows: resolved, losers });
}
// ---- Phase 2: write, all or nothing. ---------------------------------
// The marker rides in the same transaction as the rewrites, so there is no
// window where some rows are folded, the marker is absent, and a second run
// folds them again — which would put every original one directory deeper,
// permanently.
const apply = async (trx) => {
for (const step of plan) {
if (step.bulk) {
// BY ID, not by event. Phase 1 runs outside the transaction and can
// take minutes probing a cold mount; an import completing in that
// window inserts an already root-relative row, and `where event_id`
// would prefix it a second time with the stale base.
for (const ids of chunk(step.ids)) {
await trx('photos')
.whereIn('id', ids)
.whereNotNull('external_relpath')
.update({ external_relpath: trx.raw('? || external_relpath', [`${step.base}/`]) });
}
continue;
}
// Losers first: while they still hold their old path, the survivor has
// not taken the value they would collide with.
if (step.losers && step.losers.size) {
await deleteDuplicatePhotos(trx, step.losers);
}
// Two passes, through a per-row temporary value. The FINAL values are
// all distinct, but a final value can equal another row's CURRENT one —
// `photo.jpg` repairing to `Trip/photo.jpg` while the existing
// `Trip/photo.jpg` is still waiting to fold — so a single pass violates
// migration 176's unique index halfway through. And on Postgres that
// surfaces as 23505, which run-migrations-safe.js mistakes for "schema
// already exists" and records the migration as applied after the
// rollback, leaving every path unconverted with no retry.
for (const [id] of step.rows) {
await trx('photos').where('id', id).update({ external_relpath: `${STAGING_PREFIX}${id}` });
}
for (const [id, next] of step.rows) {
// No catch: collisions were resolved above, so anything failing here is
// a real fault and must roll the whole fold back rather than leave a
// half-converted table certified by the marker.
await trx('photos').where('id', id).update({ external_relpath: next });
}
}
await trx('app_settings').insert({
setting_key: MARKER,
setting_value: JSON.stringify(true),
setting_type: 'system',
updated_at: new Date().toISOString(),
});
};
// A caller already inside a transaction (the restore) passes its trx in as
// `knex`; opening a nested one would deadlock SQLite.
if (knex.isTransaction) await apply(knex);
else await knex.transaction(apply);
log(`${folded} folded, ${repaired} repaired, ${stranded} left unresolved, ${collided} skipped as duplicates`);
return { folded, repaired, stranded, collided };
}
module.exports = { foldExternalRelpaths, MARKER };
+59 -11
View File
@@ -124,7 +124,12 @@ class FeedbackService {
*/
async countGuestFeedback(eventId, feedbackType, guestId, guestIdentifier) {
const query = db('photo_feedback')
.where({ event_id: eventId, feedback_type: feedbackType });
// Hidden rows do not count against the guest's cap (#1150). They are
// absent everywhere else — the heart is empty, the tallies skip them,
// and submitFeedback now treats one as room for a fresh row. Counting
// them here would meet that fresh row with limit_reached and leave the
// control dead until the guest un-likes something they can still see.
.where({ event_id: eventId, feedback_type: feedbackType, is_hidden: false });
if (guestId) {
query.where('guest_id', guestId);
} else {
@@ -152,6 +157,13 @@ class FeedbackService {
photo_id: photoId,
event_id: eventId,
feedback_type,
// A hidden row is not there (#1150). Without this the guest saw an
// empty heart — every read surface treats hidden as absent — and
// clicking it found the hidden row and TOGGLED IT OFF, so the
// click appeared to do nothing and it took two more to get back to
// a filled heart. Skipping it makes the click create a fresh,
// visible row, which is what the guest is asking for.
is_hidden: false,
});
if (guest_id) {
duplicateQuery.where('guest_id', guest_id);
@@ -297,6 +309,11 @@ class FeedbackService {
const totalStats = await db('photo_feedback')
.where('event_id', eventId)
// Hidden rows do not count, the same rule the photo counters above
// already apply — without this the two halves of THIS response
// disagreed, and a hidden row preserved beside its replacement (#1150)
// is counted twice.
.where('is_hidden', false)
.select(
db.raw('COUNT(DISTINCT CASE WHEN feedback_type = ? THEN guest_identifier END) as unique_raters', ['rating']),
db.raw('COUNT(CASE WHEN feedback_type = ? THEN 1 END) as total_ratings', ['rating']),
@@ -317,25 +334,30 @@ class FeedbackService {
}
/**
* Update photo feedback statistics
* Update photo feedback statistics.
*
* `trx` so a caller running outside the request path — the duplicate-photo
* dedupe (#1162), which reparents feedback rows and must leave the
* survivor's denormalized totals correct — can recompute on its own
* connection.
*/
async updatePhotoFeedbackStats(photoId) {
async updatePhotoFeedbackStats(photoId, trx = db) {
try {
// Get aggregated stats
const stats = await db('photo_feedback')
const stats = await trx('photo_feedback')
.where('photo_id', photoId)
.where('is_hidden', false)
.select(
db.raw('COUNT(CASE WHEN feedback_type = ? AND is_approved = ? THEN 1 END) as comment_count', ['comment', formatBoolean(true)]),
db.raw('COUNT(CASE WHEN feedback_type = ? THEN 1 END) as like_count', ['like']),
db.raw('COUNT(CASE WHEN feedback_type = ? THEN 1 END) as favorite_count', ['favorite']),
db.raw('AVG(CASE WHEN feedback_type = ? THEN rating END) as average_rating', ['rating']),
db.raw('COUNT(DISTINCT COALESCE(CAST(guest_id AS VARCHAR), guest_identifier)) as feedback_count')
trx.raw('COUNT(CASE WHEN feedback_type = ? AND is_approved = ? THEN 1 END) as comment_count', ['comment', formatBoolean(true)]),
trx.raw('COUNT(CASE WHEN feedback_type = ? THEN 1 END) as like_count', ['like']),
trx.raw('COUNT(CASE WHEN feedback_type = ? THEN 1 END) as favorite_count', ['favorite']),
trx.raw('AVG(CASE WHEN feedback_type = ? THEN rating END) as average_rating', ['rating']),
trx.raw('COUNT(DISTINCT COALESCE(CAST(guest_id AS VARCHAR), guest_identifier)) as feedback_count')
)
.first();
// Update photo table
await db('photos')
await trx('photos')
.where('id', photoId)
.update({
feedback_count: stats.feedback_count || 0,
@@ -379,7 +401,33 @@ class FeedbackService {
await db('photo_feedback')
.where('id', feedbackId)
.update(updates);
// Unhiding can collide with a replacement (#1150). A hidden row reads as
// absent, so the guest may well have re-added the same feedback in the
// meantime; making the original visible again would leave TWO visible
// rows for one guest on one photo — double-counted in the tallies, and
// needing two toggles to clear because each one deletes a single row.
//
// Needs a stable identity to scope by. With neither id nor identifier
// the fallback degrades to `guest_identifier IS NULL`, which is every
// identifier-less row on the photo — other people's, deleted. Nothing to
// converge in that case, so leave it alone. Comments are exempt: several
// from one guest on one photo is normal.
const collapseIdentity = feedback.guest_id || feedback.guest_identifier;
if (updates.is_hidden === false && feedback.feedback_type !== 'comment' && collapseIdentity) {
const superseded = db('photo_feedback')
.where({
photo_id: feedback.photo_id,
event_id: feedback.event_id,
feedback_type: feedback.feedback_type,
is_hidden: false,
})
.whereNot('id', feedbackId);
if (feedback.guest_id) superseded.where('guest_id', feedback.guest_id);
else superseded.where('guest_identifier', feedback.guest_identifier);
await superseded.delete();
}
// Update photo stats if visibility changed
await this.updatePhotoFeedbackStats(feedback.photo_id);
+4 -2
View File
@@ -101,8 +101,10 @@ async function processNewPhoto(filePath) {
if (!isVideo) {
try {
const metadata = await sharp(filePath).metadata();
if (metadata.width && metadata.height) {
dimensions = { width: metadata.width, height: metadata.height };
// Oriented, not raw — see imageProcessor.orientedDimensions (#1185).
const dims = require('./imageProcessor').orientedDimensions(metadata);
if (dims.width && dims.height) {
dimensions = { width: dims.width, height: dims.height };
}
} catch (err) {
logger.debug(`Could not read image dimensions for ${filename}: ${err.message}`);
+174 -25
View File
@@ -123,6 +123,31 @@ const contentTypeFor = (format) => {
* import path passes a per-photo unique basename so two events both
* referencing `IMG_0001.jpg` don't clobber each other's thumbnail.
*/
/**
* The dimensions a viewer actually sees, given EXIF orientation (#1185).
*
* sharp reports `metadata.width`/`height` as the pixels are stored, not as
* they are displayed. Orientation values 5-8 carry a 90° rotation, so for
* those the two are swapped — which is why a portrait photo from a body that
* tags rather than rotates was landing in the database as landscape, and why
* masonry and justified layouts sized its tile with the wrong aspect ratio on
* top of the image itself being unrotated.
*
* Everything that renders these photos now applies `.rotate()`, so the stored
* numbers have to describe the rotated result to match.
*
* @param {Object} metadata - a sharp metadata object
* @returns {{ width: number|null, height: number|null }}
*/
function orientedDimensions(metadata) {
if (!metadata || !metadata.width || !metadata.height) return { width: null, height: null };
const swap = metadata.orientation >= 5 && metadata.orientation <= 8;
return {
width: swap ? metadata.height : metadata.width,
height: swap ? metadata.width : metadata.height,
};
}
async function generateThumbnail(imagePath, options = {}) {
const sourceBasename = path.basename(imagePath);
const outputBasename = options.outputBasename || sourceBasename;
@@ -133,10 +158,18 @@ async function generateThumbnail(imagePath, options = {}) {
// Get thumbnail settings
const settings = await getThumbnailSettings();
// Force regeneration: drop the existing object before writing the new one
if (options.regenerate) {
await storage.delete(thumbnailRelKey).catch(() => {});
}
// `options.regenerate` deliberately does NOT delete the existing object first
// (#1129).
//
// It used to, and the delete ran BEFORE sharp had even opened the source — so
// a source that could not be read (a NAS mount that blipped, a corrupt file)
// left the old thumbnail already gone and returned null, with the database
// still pointing at it. One bulk regeneration during a mount outage could
// therefore strip every canonical thumbnail in a reference gallery.
//
// Nothing is lost by dropping it: LocalFsStorage.put stages to a temp file and
// renames over the target, which replaces atomically, and an S3 put overwrites
// by key. The delete only added a window with no thumbnail at all.
try {
// First, verify the source image is complete and valid
@@ -152,6 +185,18 @@ async function generateThumbnail(imagePath, options = {}) {
failOn: 'none'
});
// Apply EXIF orientation before resizing (#1185). Without this a photo
// whose Orientation tag is not 1 — routine for portrait shots on bodies
// that tag rather than rotate the sensor data — is resized from the raw
// pixels and comes out sideways. `.withMetadata(false)` below then strips
// the tag, so the browser has no hint left to correct it either.
//
// Unconditional: this pipeline never passes `animated: true`, so it
// already flattens a multi-frame source. Guarding on `pages` would protect
// an animation that was being discarded anyway while leaving the output in
// raw orientation against corrected dimensions.
sharpInstance = sharpInstance.rotate();
// Strip EXIF/metadata from thumbnails (privacy: prevent GPS leak etc.)
sharpInstance = sharpInstance.withMetadata(false);
@@ -192,9 +237,12 @@ async function generateThumbnail(imagePath, options = {}) {
const msg = (error && error.message) ? error.message : String(error);
logger.error(`Failed to generate thumbnail for ${sourceBasename}: ${msg}`);
// Clean up any partially uploaded object
await storage.delete(thumbnailRelKey).catch(() => {});
// No cleanup delete here either, for the same reason (#1129). This was
// "clean up any partially uploaded object", but there cannot be one:
// storage.put is the LAST statement in the try, every throw above it
// happens before anything is written, and put unlinks its own temp file on
// failure. The only object this could remove is the PREVIOUS, valid
// rendition — exactly the thumbnail a failed regeneration must leave alone.
return null;
}
}
@@ -366,7 +414,10 @@ async function generateVideoPlaceholder(originalFilename, options = {}) {
* Outputs a 1920x1080 image suitable for full-width hero sections
*/
async function generateHeroImage(imagePath, options = {}) {
const filename = path.basename(imagePath);
// outputBasename lets callers disambiguate sources that share a basename —
// two events referencing the same NAS filename would otherwise clobber each
// other's hero. Same contract as generateThumbnail and generatePreviewImage.
const filename = options.outputBasename || path.basename(imagePath);
const heroFilename = `hero_${filename}`;
const heroRelKey = path.posix.join('heroes', heroFilename);
const storage = getStorage();
@@ -392,6 +443,10 @@ async function generateHeroImage(imagePath, options = {}) {
failOn: 'none'
});
// EXIF orientation, same reasoning as generateThumbnail (#1185) — and
// unconditional for the same reason: no `animated: true` on the input.
sharpInstance = sharpInstance.rotate();
// Strip EXIF/metadata from hero images (privacy: prevent GPS leak etc.)
sharpInstance = sharpInstance.withMetadata(false);
@@ -448,16 +503,13 @@ async function isHeroValid(heroPath) {
* Ensure a hero image exists for a photo, regenerate if needed
*/
async function ensureHeroImage(photo) {
const { resolvePhotoStorageKey } = require('./photoResolver');
const { resolvePhotoStorageKey, resolvePhotoFilePath } = require('./photoResolver');
let sourceKey;
let event;
try {
const event = await db('events').where('id', photo.event_id).first();
sourceKey = resolvePhotoStorageKey(event, photo);
logger.info(`Ensuring hero image for photo ${photo.id} from key: ${sourceKey}`);
event = await db('events').where('id', photo.event_id).first();
} catch (e) {
const msg = (e && e.message) ? e.message : String(e);
logger.error(`Failed to resolve original key for hero image (photo ${photo.id}): ${msg}`);
logger.error(`Failed to load event for hero image (photo ${photo.id}): ${e.message}`);
return null;
}
@@ -469,7 +521,56 @@ async function ensureHeroImage(photo) {
logger.warn(`Invalid hero image detected for photo ${photo.id}, regenerating...`);
}
const newHeroPath = await withLocalCopy(sourceKey, (localPath) =>
// External sources never reach the managed backend, so resolvePhotoStorageKey
// returns null for them by design — and this function used to feed that null
// straight to withLocalCopy, which throws, so the hero route fell back to
// redirecting at the full original. #1078 fixed exactly this for
// ensurePreviewImage and nobody carried it across; it only became visible
// when the Story hero started asking for hero_url instead of the original
// (#1166), which on a reference-mode gallery quietly changed nothing.
const heroIsExternal = photo.source_origin === 'external' || photo.source_origin === 'reference';
let newHeroPath;
if (heroIsExternal) {
// Mirrors the external branch in ensurePreviewImage: a direct fs read off
// the mount, so no withLocalCopy, and a per-photo outputBasename so two
// events referencing the same NAS basename cannot clobber each other.
let localPath;
try {
localPath = resolvePhotoFilePath(event, photo);
} catch (e) {
logger.error(`Failed to resolve external file for hero image (photo ${photo.id}): ${e.message}`);
return null;
}
const sourceBasename = path.basename(photo.external_relpath || photo.filename || `photo-${photo.id}`);
newHeroPath = await generateHeroImage(localPath, {
regenerate: true,
outputBasename: `ext${photo.id}_${sourceBasename}`,
});
if (newHeroPath) {
await db('photos').where({ id: photo.id }).update({ hero_path: newHeroPath });
}
return newHeroPath;
}
let sourceKey;
try {
sourceKey = resolvePhotoStorageKey(event, photo);
logger.info(`Ensuring hero image for photo ${photo.id} from key: ${sourceKey}`);
} catch (e) {
const msg = (e && e.message) ? e.message : String(e);
logger.error(`Failed to resolve original key for hero image (photo ${photo.id}): ${msg}`);
return null;
}
if (!sourceKey) {
// Reference-mode event holding a row with no source_origin: the mode falls
// back to the event's and resolvePhotoStorageKey returns null. Honour the
// null-on-failure contract rather than feeding it to withLocalCopy.
logger.warn(`No managed storage key for hero image (photo ${photo.id}); skipping generation`);
return null;
}
newHeroPath = await withLocalCopy(sourceKey, (localPath) =>
generateHeroImage(localPath, { regenerate: true })
);
@@ -496,22 +597,50 @@ async function ensureHeroImage(photo) {
* Output to `previews/preview_<filename>` so an admin who flips the
* setting back off can wipe the folder cleanly without touching
* thumbnails or heroes.
*
* ENCODING follows the source, it is not always JPEG. JPEG has no alpha
* channel and no second frame, so encoding everything as JPEG flattened a
* transparent PNG onto a solid background and reduced an animated GIF to its
* first frame — for every consumer of this tier, not just the lightbox.
* Sources with alpha or more than one page are encoded as WebP instead, which
* carries both and is still far smaller than the original.
*
* The output extension is rewritten to match what was actually written.
* Previously the source basename was kept verbatim, so a PNG source produced
* `preview_foo.png` holding JPEG bytes — harmless while the route hard-coded
* image/jpeg, and actively wrong now that the encoding varies. Old keys keep
* working: they are still JPEG and still served as such.
*/
async function generatePreviewImage(imagePath, options = {}) {
// outputBasename lets callers disambiguate sources that share a basename
// (external mounts, see ensurePreviewImage) — same contract as
// generateThumbnail.
const filename = options.outputBasename || path.basename(imagePath);
const previewFilename = `preview_${filename}`;
const previewRelKey = path.posix.join('previews', previewFilename);
const storage = getStorage();
// Probed BEFORE the key is built: the extension has to match the encoding,
// and the encoding depends on what the source turns out to be.
let probe;
try {
probe = await sharp(imagePath).metadata();
} catch (error) {
const msg = (error && error.message) ? error.message : String(error);
logger.error(`Failed to read metadata for preview of ${filename}: ${msg}`);
return null;
}
const isAnimated = (probe.pages || 1) > 1;
const needsWebp = isAnimated || probe.hasAlpha === true;
const base = filename.replace(/\.[^./\\]+$/, '');
const previewFilename = `preview_${base}.${needsWebp ? 'webp' : 'jpg'}`;
const previewRelKey = path.posix.join('previews', previewFilename);
if (options.regenerate) {
await storage.delete(previewRelKey).catch(() => {});
}
try {
const metadata = await sharp(imagePath).metadata();
const metadata = probe;
if (!metadata.width || !metadata.height) {
throw new Error('Invalid image metadata - file may be incomplete');
}
@@ -523,8 +652,27 @@ async function generatePreviewImage(imagePath, options = {}) {
limitInputPixels: 268402689, // ~16k x 16k max
sequentialRead: true,
failOn: 'none',
// Without this an animated source is opened as its first frame only, and
// every later frame is discarded before the resize ever sees it.
// limitInputPixels still applies, and sharp counts an animated input as
// width x (height x pages) — so a pathological GIF is rejected rather
// than decoded, and the caller falls back to the original.
animated: isAnimated,
});
// EXIF orientation (#1185). Guarded here and not in the thumbnail/hero
// generators because this one DOES open multi-frame sources with
// `animated: true` above, and `.rotate()` would flatten them to a single
// frame — trading an animation for an orientation.
//
// Which leaves one corner unsolved: a multi-frame source that also carries
// an orientation tag keeps its raw orientation here while the thumbnail
// and the stored dimensions describe the rotated one. GIF has no EXIF at
// all and animated WebP effectively never sets it.
if (!isAnimated) {
sharpInstance = sharpInstance.rotate();
}
// Strip EXIF — same privacy reasoning as thumbnails/heroes.
sharpInstance = sharpInstance.withMetadata(false);
@@ -536,18 +684,18 @@ async function generatePreviewImage(imagePath, options = {}) {
fit: 'inside',
});
sharpInstance = sharpInstance.jpeg({
quality,
progressive: true,
mozjpeg: true,
});
sharpInstance = needsWebp
? sharpInstance.webp({ quality })
: sharpInstance.jpeg({ quality, progressive: true, mozjpeg: true });
const buffer = await sharpInstance.toBuffer();
if (!buffer || buffer.length === 0) {
throw new Error('Generated preview image is empty');
}
await storage.put(previewRelKey, buffer, { contentType: 'image/jpeg' });
await storage.put(previewRelKey, buffer, {
contentType: needsWebp ? 'image/webp' : 'image/jpeg',
});
logger.info(`Generated preview image for ${filename}${previewRelKey}`);
return previewRelKey;
@@ -703,6 +851,7 @@ async function extractCaptureDate(imagePath) {
}
module.exports = {
orientedDimensions,
generateThumbnail,
isThumbnailValid,
ensureThumbnail,
+216
View File
@@ -0,0 +1,216 @@
/**
* What PicPeak actually occupies on this machine (#1164).
*
* The dashboard's "Storage used" tile summed photos.size_bytes, which is the
* catalogued size of the ORIGINALS — a number with no relationship to the disk
* PicPeak runs on:
*
* - in reference mode the originals are never copied. Those bytes are on the
* NAS. The reporter's tile read ~80 GB against 21 GB of real local usage.
* - duplicate rows counted the same file twice (#1162).
* - it ignored everything PicPeak genuinely does write: thumbnails, previews,
* hero renditions, and the per-event download cache — an 11.8 GB
* `.download-cache/all.zip` sat outside the figure entirely.
*
* So the one number an admin reaches for when asking "am I running out of
* disk" pointed away from the answer and omitted exactly the things filling
* the disk. This walks the storage root instead and reports what is there.
*
* Walking rather than summing DB columns is deliberate: thumbnail/preview/hero
* rows record a key, never a byte count, and orphans (a deleted event's
* leftovers, an interrupted import's thumbnails) are real bytes on a real
* disk. A `du` is the only honest answer, and the only one that notices what
* PicPeak has forgotten about.
*
* The external media root is EXCLUDED, and that is the whole point rather than
* a detail. Its compose default is `<storage>/external-media`, where the NAS is
* bind-mounted — a plain directory, not a symlink — so walking it would add
* every referenced original back into a figure that exists to leave them out,
* and compare NAS bytes against statfs() of the local disk. That is the
* over-count this replaces, reintroduced by the fix for it.
*
* Cached, because it is one stat per file. On a large install that is seconds,
* and the dashboard is polled — and concurrent misses share one walk rather
* than each starting their own.
*/
const path = require('path');
const fsp = require('fs').promises;
const logger = require('../utils/logger');
const { getStoragePath } = require('../config/storage');
const TTL_MS = 5 * 60 * 1000;
let cache = null;
// The walk in flight, if any. Two admins loading the dashboard, or the sidebar
// and the storage tab on one page, hit the same cold cache and would otherwise
// each stat every file on the disk.
let inFlight = null;
/**
* The external media root, resolved, when it lies inside the storage root.
* Returns null when it is elsewhere (the usual production case) or cannot be
* resolved — nothing to exclude then.
*/
function nestedExternalRoot(storageRoot) {
let externalRoot;
try {
externalRoot = require('./externalMediaService').getExternalMediaRoot();
} catch (err) {
return null;
}
if (!externalRoot) return null;
const resolvedExternal = path.resolve(externalRoot);
const resolvedStorage = path.resolve(storageRoot);
if (resolvedExternal === resolvedStorage) return null;
return resolvedExternal.startsWith(resolvedStorage + path.sep) ? resolvedExternal : null;
}
/**
* Which line of the breakdown a path belongs to.
*
* The names are the ones the writers actually use — `heroes` from
* imageProcessor, `watermarks` from watermarkService, and so on — rather than
* the ones the layout docs imply. Getting one wrong is not a crash, it is a
* silent 30 MB in "other", which is the least useful place for it to land.
*
* `.download-cache` is the case that needs the explicit check: it lives INSIDE
* an event directory, so the naive rule files an 11.8 GB zip as photography —
* and it is the one bucket that is pure disposable cache, which makes it the
* one an admin most wants to see on its own.
*
* There is no external-media bucket: that subtree is not walked at all (see
* nestedExternalRoot). Those bytes live on the media share, and counting them
* is the exact over-count this measurement exists to end.
*/
function categorize(relPath) {
const segments = relPath.split(path.sep);
if (segments.includes('.download-cache')) return 'downloadCache';
switch (segments[0]) {
case 'thumbnails': return 'thumbnails';
case 'previews': return 'previews';
case 'heroes': return 'heroes';
case 'watermarks': return 'watermarks';
case 'uploads': return 'uploads';
case 'temp': return 'temp';
case 'business-docs': return 'businessDocs';
case 'events':
return segments[1] === 'archived' ? 'archives' : 'originals';
default:
return 'other';
}
}
const EMPTY_BREAKDOWN = () => ({
originals: 0,
archives: 0,
thumbnails: 0,
previews: 0,
heroes: 0,
watermarks: 0,
uploads: 0,
businessDocs: 0,
downloadCache: 0,
temp: 0,
other: 0,
});
async function walk(absDir, relDir, acc) {
// The media share, bind-mounted under the storage root. Walking it would put
// every referenced original back into a local-usage figure, and on a real
// NAS the traversal alone would take far longer than the measurement is
// worth.
if (acc.excludeRoot && path.resolve(absDir) === acc.excludeRoot) {
acc.excludedExternalRoot = acc.excludeRoot;
return;
}
let entries;
try {
entries = await fsp.readdir(absDir, { withFileTypes: true });
} catch (err) {
// A directory that is not there yet (a fresh install has no /previews) is
// not an error. Anything else is worth knowing about but must not abort
// the measurement — a partial number beats no number, and `partial` says
// so to the caller.
if (err.code !== 'ENOENT') {
acc.partial = true;
logger.debug?.(`localStorageUsage: skipped ${absDir}: ${err.message}`);
}
return;
}
for (const entry of entries) {
const abs = path.join(absDir, entry.name);
const rel = relDir ? path.join(relDir, entry.name) : entry.name;
// Symlinks are not followed: a link into the external media mount would
// otherwise add the NAS to the local total, which is the exact confusion
// this replaces.
if (entry.isDirectory()) {
await walk(abs, rel, acc);
} else if (entry.isFile()) {
try {
const stats = await fsp.stat(abs);
acc.total += stats.size;
acc.files += 1;
acc.breakdown[categorize(rel)] += stats.size;
} catch (err) {
// Raced with a delete, most likely. Nothing to add.
if (err.code !== 'ENOENT') acc.partial = true;
}
}
}
}
/**
* @param {{ force?: boolean }} [opts] force skips the TTL cache.
* @returns {Promise<{total:number, files:number, breakdown:object, partial:boolean, measuredAt:string, root:string}>}
*/
async function measureLocalStorageUsage(opts = {}) {
const now = Date.now();
if (!opts.force && cache && now - cache.at < TTL_MS) return cache.value;
// Share a walk already underway rather than starting a second one.
if (!opts.force && inFlight) return inFlight;
inFlight = runMeasurement()
.then((value) => { cache = { at: Date.now(), value }; return value; })
.finally(() => { inFlight = null; });
return inFlight;
}
async function runMeasurement() {
const root = getStoragePath();
const acc = {
total: 0,
files: 0,
breakdown: EMPTY_BREAKDOWN(),
partial: false,
excludeRoot: nestedExternalRoot(root),
excludedExternalRoot: null,
};
await walk(root, '', acc);
return {
total: acc.total,
files: acc.files,
breakdown: acc.breakdown,
partial: acc.partial,
// Set when the media share sits inside the storage root and was skipped,
// so the UI can say why the figure is smaller than `du` would report.
excludedExternalRoot: acc.excludedExternalRoot,
measuredAt: new Date().toISOString(),
root,
};
}
/** Test seam — the TTL cache would otherwise outlive a temp storage root. */
function resetLocalStorageUsageCache() {
cache = null;
inFlight = null;
}
module.exports = {
measureLocalStorageUsage,
resetLocalStorageUsageCache,
};
+178
View File
@@ -0,0 +1,178 @@
/**
* Shared run state for the photo maintenance sweeps (#1181).
*
* These jobs used to keep `{ isRunning, lastResult }` in a module-level
* variable. That is invisible to every other replica, so on a multi-replica
* install the status endpoint answers from whichever process the poll happens
* to reach and a second POST can start a duplicate pass over the whole
* library. Moving the state into the database makes both the claim and the
* reporting shared.
*
* The claim is a conditional UPDATE whose affected-row count is the answer —
* the same shape backgroundProcessor uses to hand a photo to exactly one
* worker (backgroundProcessor.js:110-116). Two replicas issuing it
* concurrently cannot both match: the row is locked for the duration of each
* UPDATE, so the loser sees is_running already true and gets 0 rows back.
*
* A lease that can be taken over needs fencing, which is what claim_token is
* for. Taking over a stale claim does not stop the old runner — it is a
* process nobody can signal, quite possibly still walking the library. So
* every write it attempts carries the token it was issued:
*
* - heartbeat() reports whether the renewal landed. It returns false once
* the claim has moved on, and the run loops treat that as "stop".
* - release() only clears the row if the token still matches, so a
* superseded runner finishing late cannot clear the new owner's flag or
* overwrite its result.
*
* Without both of those, a takeover produces two live runners and the loser
* ends up stomping the winner's state on its way out.
*
* Timestamps are written as ISO strings rather than Date objects. Production
* stores Dates fine, but inside jest the sqlite3 binding turns them into the
* literal string "[object Object]" (see CLAUDE.md), which would silently break
* every staleness comparison in the tests. ISO-8601 also compares correctly
* under SQLite's lexicographic text ordering, so the `<` below means the same
* thing on both engines.
*/
const os = require('os');
const crypto = require('crypto');
const { db } = require('../database/db');
const logger = require('../utils/logger');
const JOB_DIMENSION_REPAIR = 'photo_dimension_repair';
const JOB_CAPTURE_DATE_BACKFILL = 'photo_capture_date_backfill';
// How long a run may go without renewing its lease before another replica is
// allowed to take it over. Generous on purpose: these jobs walk the whole
// library and a single slow original on a stalled NAS mount can block the loop
// for a while. The cost of being too eager is a duplicate pass; the cost of
// being too patient is a button that stays disabled after a crash.
const DEFAULT_STALE_MS = 15 * 60 * 1000;
// How often a running job renews. Time-based, and comfortably inside the stale
// window: tying renewal to a photo counter meant a job whose photos were slow
// — a stalled mount, a handful of very large originals — could be declared
// abandoned while it was still working.
const HEARTBEAT_INTERVAL_MS = 60 * 1000;
const OWNER = `${os.hostname()}:${process.pid}`;
const nowIso = () => new Date().toISOString();
const cutoffIso = (staleAfterMs) => new Date(Date.now() - staleAfterMs).toISOString();
/**
* Try to become the one runner of `jobName`.
*
* Returns a claim token on success, or null when another replica holds it and
* is still renewing — the caller should answer 409. The token must be passed
* to every subsequent heartbeat/release for this run.
*/
async function claim(jobName, { staleAfterMs = DEFAULT_STALE_MS } = {}) {
const stamp = nowIso();
const cutoff = cutoffIso(staleAfterMs);
const token = crypto.randomBytes(16).toString('hex');
const claimed = await db('maintenance_jobs')
.where({ job_name: jobName })
.where(function () {
// Free, or held by a run that has stopped renewing. heartbeat_at is
// always written by the claim below, so a running job cannot have a null
// heartbeat — no third case to handle here.
this.where('is_running', false).orWhere('heartbeat_at', '<', cutoff);
})
.update({
is_running: true,
started_at: stamp,
heartbeat_at: stamp,
finished_at: null,
owner: OWNER,
claim_token: token,
});
return claimed > 0 ? token : null;
}
/**
* Renew the lease.
*
* Returns false when this run no longer owns the claim — it was declared stale
* and taken over. The caller must stop working at that point: the new owner is
* already walking the same rows, and two runners writing is exactly what the
* lock exists to prevent.
*/
async function heartbeat(jobName, token) {
try {
const renewed = await db('maintenance_jobs')
.where({ job_name: jobName, is_running: true, claim_token: token })
.update({ heartbeat_at: nowIso() });
return renewed > 0;
} catch (err) {
// A failed renewal query is not proof the claim is gone, and aborting a
// long sweep over one transient database blip is the worse trade. Say the
// claim still holds; if it really has moved on, the next renewal says so.
logger.warn(`maintenanceJobState: heartbeat failed for ${jobName}: ${err.message}`);
return true;
}
}
/**
* Give up the claim.
*
* Scoped to the token, so a runner that was superseded while it was working
* cannot clear the new owner's flag or overwrite its result on the way out.
* Returns false when the claim had already moved on.
*
* `result` is stored as the job's last outcome. Pass null (the "nothing to do"
* and error paths) to release without overwriting what the previous real run
* reported.
*/
async function release(jobName, token, result = null) {
const update = { is_running: false, finished_at: nowIso() };
if (result !== null && result !== undefined) {
update.last_result = JSON.stringify(result);
}
const released = await db('maintenance_jobs')
.where({ job_name: jobName, claim_token: token })
.update(update);
return released > 0;
}
/**
* Current state, in the shape the status endpoints hand to the frontend.
*
* A run whose lease has gone stale is reported as not running: the owning
* replica is gone, nothing is going to release the claim, and the operator
* needs the button back. The next claim() takes the row over on the same
* condition, so the two agree.
*/
async function read(jobName, { staleAfterMs = DEFAULT_STALE_MS } = {}) {
const row = await db('maintenance_jobs').where({ job_name: jobName }).first();
if (!row) return { isRunning: false, lastResult: null };
const alive = row.heartbeat_at && new Date(row.heartbeat_at).getTime() > Date.now() - staleAfterMs;
let lastResult = null;
if (row.last_result) {
try {
lastResult = JSON.parse(row.last_result);
} catch (err) {
// Never let a malformed row take the status endpoint down with it.
logger.warn(`maintenanceJobState: unreadable last_result for ${jobName}: ${err.message}`);
}
}
return { isRunning: Boolean(row.is_running) && Boolean(alive), lastResult };
}
module.exports = {
claim,
heartbeat,
release,
read,
JOB_DIMENSION_REPAIR,
JOB_CAPTURE_DATE_BACKFILL,
DEFAULT_STALE_MS,
HEARTBEAT_INTERVAL_MS,
};
+9 -8
View File
@@ -149,11 +149,10 @@ async function processUploadedPhotos(files, eventId, uploadedBy = 'admin', categ
try {
const sharp = require('sharp');
const metadata = await sharp(tempPath).metadata();
if (metadata.width && metadata.height) {
imageMetadata = {
width: metadata.width,
height: metadata.height
};
// Oriented, not raw — see imageProcessor.orientedDimensions (#1185).
const dims = require('./imageProcessor').orientedDimensions(metadata);
if (dims.width && dims.height) {
imageMetadata = { width: dims.width, height: dims.height };
}
} catch (metadataError) {
logger.warn(`Could not extract image dimensions for ${file.originalname}:`, metadataError.message);
@@ -468,9 +467,11 @@ async function processPhoto(photoId) {
try {
const sharp = require('sharp');
const metadata = await sharp(localPath).metadata();
if (metadata.width && metadata.height) {
updateData.width = metadata.width;
updateData.height = metadata.height;
// Oriented, not raw — see imageProcessor.orientedDimensions (#1185).
const dims = require('./imageProcessor').orientedDimensions(metadata);
if (dims.width && dims.height) {
updateData.width = dims.width;
updateData.height = dims.height;
}
} catch (e) {
logger.warn(`processPhoto: dimensions extraction failed for ${photoId}`, { error: e.message });
@@ -65,8 +65,8 @@ async function replacePhoto(existingPhoto, newFileTempPath, { originalFilename,
let height = null;
try {
const metadata = await sharp(newFileTempPath).metadata();
width = metadata.width || null;
height = metadata.height || null;
// Oriented, not raw — see imageProcessor.orientedDimensions (#1185).
({ width, height } = require('./imageProcessor').orientedDimensions(metadata));
} catch {
// Non-image or corrupt
}
+14 -16
View File
@@ -1,5 +1,5 @@
const path = require('path');
const { resolveExternalPath } = require('./externalMediaService');
const { resolveExternalPhotoPath } = require('./externalMediaService');
const { safePathJoin } = require('../utils/fileSecurityUtils');
const getStoragePath = () => process.env.STORAGE_PATH || path.join(__dirname, '../../../storage');
@@ -40,7 +40,7 @@ function resolvePhotoStorageKey(event, photo) {
/**
* Resolve absolute photo file path based on event + photo origin
* Managed: storage/events/active + photo.path (legacy variants supported)
* External reference: EXTERNAL_MEDIA_ROOT + event.external_path + photo.external_relpath
* External reference: EXTERNAL_MEDIA_ROOT + photo.external_relpath
*/
function resolvePhotoFilePath(event, photo) {
if (!event || !photo) throw new Error('resolvePhotoFilePath requires event and photo');
@@ -61,20 +61,18 @@ function resolvePhotoFilePath(event, photo) {
}
throw new Error('Missing external_relpath for external photo');
}
// Normalize duplicate leaf segments (e.g., event.external_path ends with 'individual'
// and external_relpath starts with 'individual/') to avoid double segment like
// '/external-media/.../individual/individual/file.jpg'
let rel = photo.external_relpath;
try {
const lastSeg = path.basename(event.external_path || '');
const firstSeg = rel.split(path.sep)[0];
if (lastSeg && firstSeg && lastSeg === firstSeg) {
rel = rel.split(path.sep).slice(1).join(path.sep) || '';
}
} catch (_) {
// ignore normalization errors
}
return resolveExternalPath(event, rel);
// external_relpath is relative to EXTERNAL_MEDIA_ROOT, so the event is not
// consulted at all (#1163). It used to be relative to event.external_path,
// which meant importing a second folder into an event silently moved every
// photo already in it.
//
// The duplicate-leaf-segment normalisation that used to live here went with
// it. It stripped the first segment of the relpath when it matched the last
// segment of event.external_path — a guess that papered over the
// double-prefixing this class of bug produced, and one that actively
// corrupts a root-relative path whose first segment legitimately repeats
// (external_path 'Trip', relpath 'Trip/x.jpg').
return resolveExternalPhotoPath(photo);
}
const storagePath = getStoragePath();
+11 -1
View File
@@ -29,7 +29,17 @@ const packageJson = require('../../package.json');
const PICPEAK_FORMAT_VERSION = 1;
// Never exported as data — the target owns these (its own migrations set them).
const EXCLUDED_TABLES = new Set(['knex_migrations', 'knex_migrations_lock']);
const EXCLUDED_TABLES = new Set([
'knex_migrations',
'knex_migrations_lock',
// Live lease state for the maintenance sweeps (#1181), not data. An archive
// taken while a sweep was running would otherwise carry is_running = true and
// a claim token belonging to a process on the source install. Restored within
// the staleness window, the target reports the job as running and refuses new
// POSTs, with no runner anywhere that could release it. The table is seeded
// by its migration, so the target already has the rows it needs.
'maintenance_jobs',
]);
// Storage subdirs holding non-recalculable blobs — always included.
const DOC_DIRS = ['business-docs', 'uploads'];
+69 -1
View File
@@ -26,6 +26,11 @@ const { getStoragePath } = require('../config/storage');
const { hasColumnCached } = require('../utils/schemaCache');
const logger = require('../utils/logger');
const { PICPEAK_FORMAT_VERSION, EXCLUDED_TABLES, listDataTables } = require('./picpeakExportService');
const {
dedupeExternalPhotos,
createExternalRelpathIndex,
dropExternalRelpathIndex,
} = require('./externalPhotoDedupe');
const isPostgres = () => knexConfig.client === 'pg';
@@ -288,6 +293,19 @@ async function replaceAllTables(tables, dataDir, currentAdmin, { crossEngine = f
await trx.raw('PRAGMA defer_foreign_keys = ON');
}
// Suspending FK enforcement does not suspend UNIQUE indexes on either
// engine (#1162). A backup taken before migration 176 carries the
// duplicate photo rows that migration exists to remove, so batchInsert
// below would hit photos_event_external_relpath_uniq and roll the whole
// restore back — after every table had already been emptied. Drop it for
// the load and rebuild it once the rows are deduped, which is the same
// repair the migration performs.
let hadRelpathIndex = false;
if (await trx.schema.hasColumn('photos', 'external_relpath')) {
hadRelpathIndex = true;
await dropExternalRelpathIndex(trx);
}
for (const table of tables) {
await trx(table).del();
}
@@ -309,6 +327,18 @@ async function replaceAllTables(tables, dataDir, currentAdmin, { crossEngine = f
await trx.batchInsert(table, prepared, 100);
}
// Restore the constraint the load ran without. Deduping first because the
// incoming rows may be exactly the duplicates migration 176 removes; the
// index creation then also proves the repair worked, inside the same
// transaction that would otherwise leave the target unprotected.
if (hadRelpathIndex) {
const removed = await dedupeExternalPhotos(trx);
if (removed) {
logger.info(`picpeakImport: removed ${removed} duplicate external photo row(s) from the archive (#1162)`);
}
await createExternalRelpathIndex(trx);
}
await reinjectCurrentAdmin(trx, currentAdmin);
// Reset the pg session flag BEFORE the connection returns to the pool.
@@ -427,12 +457,50 @@ async function importFromPicpeak({ picpeakPath, currentAdminId }) {
await resyncSequences(tables);
const filesRestored = await restoreFiles(staging);
// External media paths (#1163). knex_migrations is excluded from the
// archive, so migration 177 does not re-run after a restore — a pre-#1163
// backup would otherwise drop base-relative rows onto an instance that
// resolves them from the media root, and every original in the restored
// library would be unreachable with nothing logged. The fold is a no-op
// when the restored app_settings already carries the marker.
let externalPathsConverted = true;
let externalPathError = null;
try {
const { foldExternalRelpaths } = require('./externalRelpathFold');
const result = await foldExternalRelpaths(db, (msg) => logger.info(`picpeakImport: external paths — ${msg}`));
if (result.folded || result.repaired) {
logger.info(`picpeakImport: folded ${result.folded} external path(s), repaired ${result.repaired}`);
}
} catch (err) {
// NOT swallowed as a footnote. The fold is transactional, so a failure
// leaves every external path in the pre-#1163 format while the running
// resolver reads from the media root — meaning every original in the
// restored library is unreachable. Reporting that as a clean restore
// sends the admin away believing it worked.
externalPathsConverted = false;
externalPathError = err.message;
logger.error(`picpeakImport: external path conversion FAILED — originals will not resolve until this is retried: ${err.message}`);
}
const usesExternalMedia = await detectExternalMedia();
logger.info(
`[picpeak-import] restored ${tables.length} tables, ${filesRestored} files (externalMedia=${usesExternalMedia}, crossEngine=${crossEngine})`
);
return { restored: true, tables: tables.length, filesRestored, usesExternalMedia, crossEngine, manifest };
return {
restored: true,
tables: tables.length,
filesRestored,
usesExternalMedia,
crossEngine,
manifest,
// Surfaced so the caller can warn rather than report an unqualified
// success: the rows and files are in place, but the external originals
// do not resolve until the conversion is retried (#1163).
externalPathsConverted,
externalPathError,
};
} finally {
await fsp.rm(staging, { recursive: true, force: true }).catch(() => {});
}
+4 -2
View File
@@ -110,8 +110,10 @@ async function processEvent(event, storage) {
try {
dimensions = await withLocalCopy(entry.key, async (localPath) => {
const metadata = await sharp(localPath).metadata();
if (metadata.width && metadata.height) {
return { width: metadata.width, height: metadata.height };
// Oriented, not raw — see imageProcessor.orientedDimensions (#1185).
const dims = require('./imageProcessor').orientedDimensions(metadata);
if (dims.width && dims.height) {
return { width: dims.width, height: dims.height };
}
return null;
});
+23 -4
View File
@@ -1,4 +1,5 @@
const sharp = require('sharp');
const { orientedDimensions } = require('./imageProcessor');
const path = require('path');
const fs = require('fs').promises;
const { db } = require('../database/db');
@@ -105,8 +106,21 @@ class WatermarkService {
}
// Load the main image
const image = sharp(imagePath);
const metadata = await image.metadata();
// .rotate() for the same reason as the other generators (#1185): sharp
// decodes pixels as stored, so an orientation-tagged photo would be
// composited and re-encoded sideways — and gallery.js serves
// watermark_path ahead of the original, so this is exactly what a guest
// sees on a watermarked gallery.
const image = sharp(imagePath).rotate();
// Deliberately NOT `await image.metadata()`: .rotate() does not change
// what metadata() reports — a 400x200 source tagged orientation 6 still
// reads 400x200 there, even though the pipeline now emits 200x400. Every
// use below is positioning, so it has to be the DISPLAYED size or the
// mark lands against the wrong axis.
const rawMetadata = await sharp(imagePath).metadata();
const oriented = orientedDimensions(rawMetadata);
const metadata = { ...rawMetadata, width: oriented.width, height: oriented.height };
let watermarkBuffer;
let watermarkMetadata;
@@ -180,10 +194,15 @@ class WatermarkService {
);
// Apply watermark with high quality output to preserve original image quality
// Floored: getPositionCoordinates derives from the SVG's estimated text
// extent, which is fractional, and sharp rejects a non-integer offset
// outright — applyWatermark then catches its own error and silently
// returns the unwatermarked original. Whether it landed on a whole pixel
// was previously luck.
let watermarkedImage = image.composite([{
input: watermarkBuffer,
top: position.top,
left: position.left
top: Math.max(0, Math.floor(position.top)),
left: Math.max(0, Math.floor(position.left))
}]);
// Preserve original format with high quality settings
+81
View File
@@ -0,0 +1,81 @@
/**
* Pipe a file/storage stream to an Express response without betting the
* process on the source still being there (#1128).
*
* `fs.createReadStream` — what LocalFsStorage.get() returns — is LAZY. It
* resolves immediately and only opens the file on a later tick, so an ENOENT
* arrives AFTER the `await` returned and outside the route's try/catch. An
* EventEmitter that emits 'error' with no listener throws, and an uncaught
* throw from an I/O callback is not something Express can catch: Node exits.
*
* That is how one missing thumbnail tier took down every gallery on the
* install — the process died on the first grid load and only came back
* because Docker restarted it.
*
* The window is real and cannot be closed by a stat() beforehand: between the
* stat and the open, another request regenerating the same derivative can
* unlink it. So the handler is the fix, not the preflight.
*/
const logger = require('./logger');
/**
* @param {import('stream').Readable} stream source, already opened or lazy
* @param {import('express').Response} res
* @param {object} [options]
* @param {string} [options.context] what was being served, for the log line
* @param {number} [options.missingStatus=404] status when the source is gone
*/
function pipeStreamToResponse(stream, res, options = {}) {
const { context = 'file', missingStatus = 404 } = options;
stream.on('error', (err) => {
const gone = err && (err.code === 'ENOENT' || err.code === 'EISDIR');
// Once bytes are on the wire the status line is spent — there is no way to
// turn this into a 404. Destroy the response so the client sees a broken
// connection rather than a silently truncated image it would cache.
if (res.headersSent) {
logger.warn(`Stream failed mid-response for ${context}: ${err.message}`);
res.destroy(err);
return;
}
// Every header staged for the FILE now describes a body that will never
// be sent. They are cleared rather than left to Express, which does not
// overwrite a Content-Type that is already set — so without this the JSON
// error goes out as `image/jpeg`, or as an `application/zip` attachment
// that saves to disk as a corrupt download.
//
// Cache-Control matters most. The image routes stage `max-age=1800` (the
// hero route 3600), so a 404 from the regeneration race — the transient
// case this whole helper exists for — would be cached as a broken tile for
// up to an hour after the tier finished generating.
res.removeHeader('Content-Length');
res.removeHeader('ETag');
res.removeHeader('Content-Type');
res.removeHeader('Content-Disposition');
res.setHeader('Cache-Control', 'no-store');
if (gone) {
// Expected under the regeneration race — the tier existed at stat time
// and was replaced before the open. One broken tile, not an outage.
logger.warn(`Source vanished while serving ${context}: ${err.message}`);
res.status(missingStatus).json({ error: 'File not found' });
return;
}
logger.error(`Failed to stream ${context}`, { error: err.message, code: err.code });
res.status(500).json({ error: 'Failed to serve file' });
});
// A client that navigates away mid-download leaves the source handle open
// otherwise; on a gallery grid that is one leaked fd per abandoned tile.
res.on('close', () => {
if (!res.writableEnded) stream.destroy();
});
stream.pipe(res);
}
module.exports = { pipeStreamToResponse };
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "picpeak-frontend",
"private": true,
"version": "3.46.1",
"version": "3.46.5",
"type": "module",
"scripts": {
"dev": "vite",
@@ -361,7 +361,9 @@ const StorageInfo: React.FC = () => {
<div className="flex items-center justify-between text-sm">
<span className="text-neutral-700 dark:text-neutral-300">{t('admin.storageUsed')}</span>
<span className="font-medium text-neutral-900 dark:text-neutral-100">
{settingsService.formatBytes(storageInfo.total_used)}
{/* `+` marks a floor: part of the storage root was unreadable, so
the real figure — and the percentage below — is higher (#1164). */}
{settingsService.formatBytes(storageInfo.total_used)}{storageInfo.storage_partial ? '+' : ''}
</span>
</div>
<div className="mt-2 w-full bg-neutral-200 dark:bg-neutral-700 rounded-full h-2">
@@ -16,6 +16,11 @@ interface RestoreResult {
tables: number;
filesRestored: number;
usesExternalMedia: boolean;
// False when the pre-#1163 external-path conversion failed. Rows and files
// are in place, but no external original resolves until it is retried — so
// this must not be presented as a plain success.
externalPathsConverted?: boolean;
externalPathError?: string | null;
crossEngine?: boolean;
sessionInvalidated?: boolean;
}
@@ -115,7 +120,12 @@ export const PicpeakRestoreCard: React.FC = () => {
const res = await api.post<RestoreResult>('/admin/backup/picpeak/import', fd);
setResult(res.data);
setPendingFile(null);
toast.success(t('backup.picpeak.restoreDone', 'Backup restored.'));
if (res.data?.externalPathsConverted === false) {
toast.error(t('backup.picpeak.externalPathsFailed',
'Backup restored, but external photo paths could not be converted — those originals will not load until this is retried.'));
} else {
toast.success(t('backup.picpeak.restoreDone', 'Backup restored.'));
}
// The restore rewrote admin_users and the backend revoked our session
// (ids may have shifted). Send the operator to a fresh login rather than
// letting the now-stale token resolve to a different restored account.
@@ -169,6 +179,16 @@ export const PicpeakRestoreCard: React.FC = () => {
{t('backup.picpeak.crossEngineNote', 'Cross-engine restore: a SQLite backup was converted onto this PostgreSQL instance.')}
</p>
)}
{result.externalPathsConverted === false && (
<p className="mt-2 flex items-start gap-1 text-xs text-red-800 dark:text-red-300">
<AlertTriangle className="mt-0.5 h-4 w-4 flex-shrink-0" />
<span>
{t('backup.picpeak.externalPathsFailedDetail',
'External photo paths were not converted, so every referenced original is currently unreachable. Re-run the restore or the pending migrations once the cause is resolved.')}
{result.externalPathError ? ` (${result.externalPathError})` : ''}
</span>
</p>
)}
{result.usesExternalMedia && (
<p className="mt-2 flex items-start gap-1 text-xs text-amber-800 dark:text-amber-300">
<AlertTriangle className="mt-0.5 h-4 w-4 flex-shrink-0" />
@@ -33,6 +33,20 @@ import { useQueryClient } from '@tanstack/react-query';
interface GalleryViewProps {
slug: string;
/**
* Whether this gallery is password-protected (#1149).
*
* Drives the Logout button. Logging out of a gallery that asks for nothing
* is meaningless — there is no credential to drop and nothing to return to
* — and it used to strand the visitor: GalleryPage's auto-login is a
* one-shot latch, so clearing the session left the page rendering its
* skeleton until a manual reload.
*
* A client (PIN) session still gets the button on a public gallery: that
* one IS a credential, and it is the only way back to the guest view. So is
* a customer-portal session.
*/
requiresPassword?: boolean;
event: {
id: number;
event_name: string;
@@ -67,9 +81,9 @@ const parseDefaultPhotoSort = (defaultSort?: string): { sortBy: 'date' | 'name'
}
};
export const GalleryView: React.FC<GalleryViewProps> = ({ slug, event }) => {
export const GalleryView: React.FC<GalleryViewProps> = ({ slug, event, requiresPassword = true }) => {
const { t } = useTranslation();
const { logout, isClient } = useGalleryAuth();
const { logout, isClient, viaCustomer } = useGalleryAuth();
const { setTheme, theme } = useTheme();
const queryClient = useQueryClient();
const [selectedCategoryId, setSelectedCategoryId] = useState<number | string | null>(null);
@@ -705,6 +719,18 @@ export const GalleryView: React.FC<GalleryViewProps> = ({ slug, event }) => {
// Skip all wrapper elements (header, footer, sidebar, filters) for these layouts
const isFullPageLayout = theme.galleryLayout === 'gallery-premium' || theme.galleryLayout === 'gallery-story';
// Does this session hold something worth dropping? A password gallery and a
// PIN client obviously do, and so does a customer-portal session — its token
// opens the gallery without the password and lives for 24h in a cookie the
// customer logout does not clear.
//
// Read from the auth context, which resolves it from /auth/session on mount.
// accessLevel used to come from sessionStorage alone, which is per-TAB while
// the cookie is per-browser: a gallery reopened in a second tab lost
// 'client' while the backend went on serving it as one, and the gate would
// then hide the only control that clears the privileged cookie (#1149).
const showLogoutControl = requiresPassword || isClient || viaCustomer;
// For full-page layouts, render just the PhotoGridWithLayouts without any wrappers
if (isFullPageLayout) {
return (
@@ -745,7 +771,10 @@ export const GalleryView: React.FC<GalleryViewProps> = ({ slug, event }) => {
heroDividerStyle={data?.event?.hero_divider_style || theme.heroDividerStyle || 'wave'}
heroImageAnchor={data?.event?.hero_image_anchor || 'center'}
welcomeMessage={event.welcome_message}
onLogout={logout}
// Same gate as the standard layout below (#1149). These layouts
// render the button on the callback being present rather than on a
// showLogout flag, so withholding it is how the gate reaches them.
onLogout={showLogoutControl ? logout : undefined}
showOriginalFilename={showOriginalFilename}
/>
@@ -823,7 +852,7 @@ export const GalleryView: React.FC<GalleryViewProps> = ({ slug, event }) => {
heroLogoVisible={data?.event?.hero_logo_visible !== false}
heroLogoSize={data?.event?.hero_logo_size || undefined}
headerStyle={data?.event?.header_style || theme.headerStyle}
showLogout={true}
showLogout={showLogoutControl}
onLogout={logout}
// Old Download All header button is replaced by the new
// showHeaderDownload below — accent-coloured, always visible when
@@ -11,6 +11,7 @@ import { FeedbackIdentityModal } from './FeedbackIdentityModal';
import { VideoPlayer } from './VideoPlayer';
import { useGuestIdentityOptional } from '../../contexts/GuestIdentityContext';
import { useFeedbackLimitModal } from '../../hooks/useFeedbackLimitModal';
import { lightboxImageUrl } from './imageTiers';
interface PhotoLightboxProps {
photos: Photo[];
@@ -838,12 +839,10 @@ export const PhotoLightbox: React.FC<PhotoLightboxProps> = ({
/>
) : (
<AuthenticatedImage
// Prefer the lightbox preview tier when the admin
// opted in (#492). Falls back to `url` (the
// original) when preview_url is null — happens
// when the toggle is off, when the photo is a
// video, or briefly while lazy generation runs.
src={photo.preview_url || photo.url}
// The preview tier, falling back to slideshow_url when the
// admin never flipped lightbox_preview_enabled (#1166) —
// otherwise a stock install renders the untouched original.
src={lightboxImageUrl(photo)}
alt={photo.filename}
fallbackSrc={photo.thumbnail_url || undefined}
className="max-w-full max-h-full object-contain select-none pointer-events-none"
@@ -867,9 +866,8 @@ export const PhotoLightbox: React.FC<PhotoLightboxProps> = ({
onClick={handleImageClick}
>
<AuthenticatedImage
// Same preview-prefer-with-fallback logic as the
// off-screen tile above (#492).
src={photo.preview_url || photo.url}
// Same source selection as the off-screen tile above (#1166).
src={lightboxImageUrl(photo)}
alt={photo.filename}
fallbackSrc={photo.thumbnail_url || undefined}
className="max-w-full max-h-full object-contain select-none"
@@ -0,0 +1,88 @@
/**
* The lightbox must not display a photo by downloading the original (#1166).
*
* `preview_url` is only emitted when the admin has flipped
* lightbox_preview_enabled, which is off by default — so a stock install fell
* through to `url`. A reporter measured 16.5 MB for a photo whose preview is
* 345 KB, and the lightbox renders its neighbours too, so one open pulled
* three originals.
*
* `slideshow_url` is the same /preview/:id URL and has been emitted
* unconditionally for images since #1015. Preferring it is what fixes existing
* installs.
*
* No viewport-tier cases here: the responsive `?w=` machinery (#1095) is
* main-only, so this branch uses the URLs exactly as the server emits them.
*/
import { describe, it, expect } from 'vitest';
import { lightboxImageUrl } from '../imageTiers';
const PHOTO = {
url: '/api/gallery/g/photo/47',
preview_url: null as string | null,
slideshow_url: '/api/gallery/g/preview/47' as string | null,
};
describe('lightboxImageUrl (#1166)', () => {
it('uses the preview tier when the admin opted in', () => {
expect(lightboxImageUrl({ ...PHOTO, preview_url: '/api/gallery/g/preview/47' }))
.toBe('/api/gallery/g/preview/47');
});
it('uses the preview tier when they did NOT — the reported install', () => {
// The regression, exactly as filed: preview_url null, slideshow_url set.
expect(lightboxImageUrl(PHOTO)).toBe('/api/gallery/g/preview/47');
});
it('never serves the original while a derivative exists', () => {
for (const preview_url of [null, undefined, '', '/api/gallery/g/preview/47']) {
expect(lightboxImageUrl({ ...PHOTO, preview_url })).not.toContain('/photo/');
}
});
it('falls back to the original when neither derivative exists', () => {
// Videos: the server emits null for both, and the player needs the real
// source.
expect(lightboxImageUrl({ ...PHOTO, preview_url: null, slideshow_url: null }))
.toBe('/api/gallery/g/photo/47');
});
it('carries the watermark query through', () => {
// preview_url and slideshow_url are built from the same string server-side,
// so the wm parameter is on whichever one is used — losing it would serve
// an unwatermarked frame to a gallery that asked for one.
expect(lightboxImageUrl({
url: '/api/gallery/g/photo/47?wm=3',
preview_url: null,
slideshow_url: '/api/gallery/g/preview/47?wm=3',
})).toBe('/api/gallery/g/preview/47?wm=3');
});
it.each(['image/gif', 'image/apng', 'image/png', 'image/webp', 'image/jpeg'])(
'uses the preview tier for %s — the backend preserves alpha and frames now',
(mime_type) => {
// The bypass list this replaces existed because generatePreviewImage
// always encoded JPEG. Previews of alpha or multi-page sources are WebP
// now, so there is nothing left for the frontend to guess at.
expect(lightboxImageUrl({ ...PHOTO, mime_type } as Parameters<typeof lightboxImageUrl>[0]))
.toBe('/api/gallery/g/preview/47');
},
);
it.each(['image/gif', 'image/apng', 'image/png', 'image/webp', 'image/jpeg'])(
'uses the preview tier for %s — the backend preserves alpha and frames now',
(mime_type) => {
// The bypass list this replaces existed because generatePreviewImage
// always encoded JPEG. Previews of alpha or multi-page sources are WebP
// now, so there is nothing left for the frontend to guess at — including
// the filename check that worked around migration 039's mislabelling.
expect(lightboxImageUrl({ ...PHOTO, mime_type } as Parameters<typeof lightboxImageUrl>[0]))
.toBe('/api/gallery/g/preview/47');
},
);
it('ignores a filename that used to force the original', () => {
expect(lightboxImageUrl({ ...PHOTO, filename: 'legacy.png' } as Parameters<typeof lightboxImageUrl>[0]))
.toBe('/api/gallery/g/preview/47');
});
});
@@ -0,0 +1,45 @@
/**
* Which rendition a surface should display.
*
* On `main` this file also carries the responsive tier machinery (#1095) —
* `previewUrlForViewport`, `thumbnailUrlForTile`, the width tables. None of
* that is on this branch, so URLs here are used as the server emits them. The
* filename matches main deliberately, so that when #1095 is backported it
* merges into this file rather than landing beside it.
*/
/**
* What the lightbox actually puts in an <img> (#1166).
*
* `preview_url` is only emitted when the admin has flipped
* lightbox_preview_enabled, which is off by default — so a stock install fell
* straight through to `url`, the untouched original. A reporter measured
* 16.5 MB per photo where the preview is 345 KB, and the lightbox renders its
* neighbours too, so opening one photo pulled three originals.
*
* `slideshow_url` is the same /preview/:id URL, watermark query and all, but
* emitted unconditionally for images (#1015) — the slideshow has never had a
* fallback worth taking. Preferring it here fixes every existing install
* without an admin touching a setting.
*
* `url` stays as the last resort, which is where videos land (both derivative
* URLs are null for them) and where an image goes if the server ever stops
* emitting either. The preview route generates lazily and redirects to the
* original on any failure, so nothing here can show less than it does today.
*/
export function lightboxImageUrl(photo: {
url: string;
preview_url?: string | null;
slideshow_url?: string | null;
}): string {
// No format is excluded any more. This used to bypass the preview tier for
// GIF, APNG and PNG because generatePreviewImage always encoded JPEG, which
// has neither an alpha channel nor a second frame — so a transparent source
// came back flattened and an animated one came back as a still. That is
// fixed at the source: previews of alpha or multi-page images are now WebP,
// which carries both, and the guess-by-MIME this file could never make
// correctly (a still and an animated WebP declare the same type) is gone
// with it — including the filename fallback the previous commit needed
// because migration 039 made mime_type untrustworthy.
return photo.preview_url || photo.slideshow_url || photo.url;
}
@@ -27,6 +27,7 @@ import { useDownloadPhoto } from '../../../hooks/useGallery';
import { toast } from 'react-toastify';
import './GalleryPremiumLayout.css';
import { lightboxImageUrl } from '../imageTiers';
interface PhotoCardProps {
photo: Photo;
@@ -54,7 +55,7 @@ interface PhotoCardProps {
const PhotoCard: React.FC<PhotoCardProps> = ({
photo,
width,
height: _height,
height,
onClick,
onLike,
onSelect,
@@ -70,8 +71,13 @@ const PhotoCard: React.FC<PhotoCardProps> = ({
allowLikes = false,
index
}) => {
// Note: height is passed but not used as we maintain aspect ratio via width
void _height;
// The height MasonryPhotoAlbum computed from photos.width/height is used, not
// discarded (#1130). Letting the tile size itself from the image meant the
// rendered shape came from whatever rendition was served — and with
// thumbnail_fit seeded to 'cover' (migration 040) every rendition is square,
// so the masonry laid out identical squares and was indistinguishable from
// the fixed grid. The photo's real aspect ratio is in the DB and is what the
// album already laid out against.
const { ref, inView } = useInView({
triggerOnce: true,
threshold: 0.1,
@@ -85,7 +91,7 @@ const PhotoCard: React.FC<PhotoCardProps> = ({
<motion.div
ref={ref}
className={`gallery-premium-photo-card group ${isSelected ? 'selected' : ''}`}
style={{ width: '100%', height: 'auto', display: 'block' }}
style={{ width: '100%', height, display: 'block' }}
initial={{ opacity: 0, y: 20 }}
animate={inView ? { opacity: 1, y: 0 } : { opacity: 0, y: 20 }}
transition={{ duration: 0.4, delay: Math.min(index * 0.05, 0.3) }}
@@ -95,8 +101,11 @@ const PhotoCard: React.FC<PhotoCardProps> = ({
<AuthenticatedImage
src={photo.thumbnail_url || photo.url}
alt={photo.filename}
style={{ width, height: 'auto' }}
className="w-full h-auto object-cover"
// No inline height: the card now has a definite one, so the
// stylesheet's `.gallery-premium-photo-card img { height: 100% }` can
// finally apply and object-fit: cover crops a square rendition INTO the
// correctly-shaped tile, rather than the rendition dictating the shape.
className="w-full h-full object-cover"
loading="lazy"
isGallery={true}
slug={slug}
@@ -248,7 +257,17 @@ export const GalleryPremiumLayout: React.FC<GalleryPremiumLayoutProps> = ({
// when the admin has flipped the original-filenames toggle (#508).
const slides = useMemo(() => {
return filteredPhotos.map(photo => ({
src: photo.url,
// Display source, not the original (#1166). This layout returns early
// from PhotoGridWithLayouts and never renders PhotoLightbox, so it needs
// its own call — without it a premium gallery keeps pulling
// multi-megabyte originals to show a photo on screen. `download` below
// deliberately stays on photo.url: what a guest saves must be the full
// original.
src: lightboxImageUrl(photo),
// The download handler recovers the photo by id, because matching
// slide.src against photo.url stops working the moment src is a
// derivative — Download would silently do nothing.
photoId: photo.id,
alt: photo.filename,
width: photo.width || 1200,
height: photo.height || 800,
@@ -363,10 +382,15 @@ export const GalleryPremiumLayout: React.FC<GalleryPremiumLayoutProps> = ({
}
}, [selectedPhotos, slug, t]);
const handleDownloadFromLightbox = useCallback((slide: { src?: string }) => {
const handleDownloadFromLightbox = useCallback((slide: { src?: string; photoId?: number }) => {
if (!allowDownloads || !slide.src) return;
const photo = filteredPhotos.find(p => p.url === slide.src);
// By id, carried on the slide. Matching on src broke the moment the slide
// stopped being the original — and what Download hands over must stay the
// original regardless of what is rendered.
const photo = slide.photoId != null
? filteredPhotos.find(p => p.id === slide.photoId)
: filteredPhotos.find(p => p.url === slide.src);
if (photo) {
analyticsService.trackDownload(photo.id, slug, false);
downloadPhotoMutation.mutate({
@@ -39,9 +39,14 @@ export const StoryHero: React.FC<StoryHeroProps> = ({
<div className="story-hero">
{/* Background */}
<div className="story-hero-bg">
{photo && (photo.url || photo.thumbnail_url) ? (
{photo && (photo.hero_url || photo.url || photo.thumbnail_url) ? (
<AuthenticatedImage
src={photo.url || photo.thumbnail_url || ''}
// hero_url, which is what it is for (#1166): a 1920x1080 cover crop,
// and this is a full-bleed object-cover background. It rendered
// photo.url — a full original on the critical path for first paint
// of every Story gallery. Emitted unconditionally for every photo,
// so the fallbacks below are belt-and-braces.
src={photo.hero_url || photo.url || photo.thumbnail_url || ''}
alt="Hero"
className="w-full h-full object-cover"
isGallery={true}
@@ -1,8 +1,9 @@
import React, { useState } from 'react';
import { motion } from 'framer-motion';
import React, { useRef, useState } from 'react';
import { motion, useInView } from 'framer-motion';
import { Heart } from 'lucide-react';
import { AuthenticatedImage } from '../../../common';
import type { Photo } from '../../../../types';
import { lightboxImageUrl } from '../../imageTiers';
interface StoryPhotoCardProps {
photo: Photo;
@@ -37,8 +38,22 @@ export const StoryPhotoCard: React.FC<StoryPhotoCardProps> = ({
void _galleryId;
const [isLoaded, setIsLoaded] = useState(false);
// Don't fetch until the card is near the viewport (#1166).
//
// Every card in a Story gallery mounts at page load — `whileInView` gates the
// ANIMATION, not the render — and AuthenticatedImage fetches from an effect
// on mount, so all of them requested at once. That was tolerable while they
// pointed at `photo.url`, because nothing was generated; pointing them at
// the preview tier means a gallery with cold previews would Sharp-decode
// every original in one burst.
//
// `once` so a card that has loaded never unloads on scroll-away.
const cardRef = useRef<HTMLDivElement>(null);
const isNearViewport = useInView(cardRef, { once: true, margin: '200px' });
return (
<motion.div
ref={cardRef}
initial={{ opacity: 0, y: 20 }}
whileInView={{ opacity: 1, y: 0 }}
viewport={{ once: true, margin: '-50px' }}
@@ -47,7 +62,10 @@ export const StoryPhotoCard: React.FC<StoryPhotoCardProps> = ({
>
<a
href={photo.url}
data-pswp-src={photo.url}
// PhotoSwipe's full-size source (#1166). The preview tier, like every
// other lightbox surface — the original is what Download hands out,
// not what gets rendered on screen.
data-pswp-src={lightboxImageUrl(photo)}
data-pswp-width={photo.width || 1200}
data-pswp-height={photo.height || 800}
data-photo-id={photo.id}
@@ -59,8 +77,22 @@ export const StoryPhotoCard: React.FC<StoryPhotoCardProps> = ({
}}
className="block w-full h-full"
>
{/* The placeholder keeps the card's box while the image is still
out of range, so nothing reflows when it arrives. */}
{!isNearViewport ? (
<div className="w-full h-full bg-neutral-200 dark:bg-neutral-800" aria-hidden="true" />
) : (
<AuthenticatedImage
src={photo.url}
// A card tile, and it used to render the full ORIGINAL at
// object-cover — the one place where the reporter's "hundreds of
// megabytes for a gallery" was literally true (#1166).
//
// The preview tier rather than the thumbnail, deliberately.
// thumbnail_fit is seeded to 'cover' on every install, so thumbnails
// are square centre-crops; these cards are not square, so a
// thumbnail would be cropped a second time by object-cover and
// reframe every photo. Previews are the whole frame.
src={lightboxImageUrl(photo)}
alt={photo.filename}
onLoad={() => setIsLoaded(true)}
className={`w-full h-full object-cover transition-all duration-700 ease-out will-change-transform ${
@@ -76,6 +108,7 @@ export const StoryPhotoCard: React.FC<StoryPhotoCardProps> = ({
useEnhancedProtection={useEnhancedProtection}
useCanvasRendering={useCanvasRendering || protectionLevel === 'maximum'}
/>
)}
</a>
{/* Overlay */}
+18 -1
View File
@@ -39,6 +39,8 @@ interface GalleryAuthContextType {
isAuthenticated: boolean;
event: GalleryEvent | null;
accessLevel: GalleryAccessLevel;
/** Session was minted by the customer portal — credentialed, not a plain guest. */
viaCustomer: boolean;
isClient: boolean;
login: (slug: string, password?: string, recaptchaToken?: string | null) => Promise<void>;
clientLogin: (slug: string, password: string) => Promise<void>;
@@ -65,6 +67,7 @@ export const GalleryAuthProvider: React.FC<GalleryAuthProviderProps> = ({ childr
const [isAuthenticated, setIsAuthenticated] = useState(false);
const [event, setEvent] = useState<GalleryEvent | null>(null);
const [accessLevel, setAccessLevel] = useState<GalleryAccessLevel>('guest');
const [viaCustomer, setViaCustomer] = useState(false);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [routeError, setRouteError] = useState<string | null>(null);
@@ -204,13 +207,25 @@ export const GalleryAuthProvider: React.FC<GalleryAuthProviderProps> = ({ childr
const initialise = async () => {
try {
setIsLoading(true);
const sessionResponse = await api.get<{ valid: boolean; type: string; eventSlug?: string }>(
const sessionResponse = await api.get<{
valid: boolean; type: string; eventSlug?: string;
accessLevel?: GalleryAccessLevel; viaCustomer?: boolean;
}>(
'/auth/session',
{ params: { slug: currentSlug } }
);
if (sessionResponse.data?.valid && sessionResponse.data.type === 'gallery' && sessionResponse.data.eventSlug === currentSlug) {
setIsAuthenticated(true);
// The SERVER's view of this session, not the per-tab sessionStorage
// guess above (#1149). A second tab has no sessionStorage but the
// same cookie, so the stored value silently downgraded a client
// session to 'guest' while the backend kept serving it as a client.
if (sessionResponse.data.accessLevel === 'client') {
setAccessLevel('client');
sessionStorage.setItem(`gallery_access_level_${currentSlug}`, 'client');
}
setViaCustomer(Boolean(sessionResponse.data.viaCustomer));
// Always refresh from the server — the stored event from sessionStorage
// is shown above as an instant placeholder for perceived perf, but it
@@ -340,6 +355,7 @@ export const GalleryAuthProvider: React.FC<GalleryAuthProviderProps> = ({ childr
setIsAuthenticated(false);
setEvent(null);
setAccessLevel('guest');
setViaCustomer(false);
clearActiveGallerySlug();
};
@@ -350,6 +366,7 @@ export const GalleryAuthProvider: React.FC<GalleryAuthProviderProps> = ({ childr
event,
accessLevel,
isClient: accessLevel === 'client',
viaCustomer,
login,
clientLogin: clientLoginFn,
logout,
@@ -8,6 +8,7 @@ import {
HardDrive,
Activity,
Ruler,
CalendarClock,
} from 'lucide-react';
import { Button, Card, Input } from '../../../components/common';
import { useTranslation } from 'react-i18next';
@@ -17,6 +18,7 @@ import { settingsService } from '../../../services/settings.service';
import { useStatusTab } from '../hooks/useStatusTab';
import { UpdateNotificationSettings } from '../components/UpdateNotificationSettings';
import { useLocalizedDate } from '../../../hooks/useLocalizedDate';
import { usePermission } from '../../../hooks/usePermission';
const BYTES_PER_GB = 1024 * 1024 * 1024;
@@ -80,6 +82,36 @@ export const StatusTab: React.FC<StatusTabProps> = ({
},
});
// Capture dates (#1172). Same shape as the dimension repair above — a
// background pass over originals that resolves external rows properly — so
// it gets the same status/poll/mutation treatment.
// Gated on the same permission the endpoint requires, so a role without it
// never starts the poll. Without this the card would poll a 403 every ten
// seconds for anyone who can open the Status tab but cannot run the job —
// which on this branch is every built-in admin, since they hold settings.view
// but not settings.edit.
const canEditSettings = usePermission('settings.edit');
const { data: captureDateStatus } = useQuery({
queryKey: ['photo-capture-date-status'],
queryFn: async () => {
const res = await api.get('/admin/photos/repair-capture-dates/status');
return res.data;
},
enabled: isActive && canEditSettings,
refetchInterval: 10000,
});
const captureDateMutation = useMutation({
mutationFn: async () => {
const res = await api.post('/admin/photos/repair-capture-dates');
return res.data;
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['photo-capture-date-status'] });
},
});
// Sync soft limit from storage info
useEffect(() => {
if (!storageInfo || softLimitDirty) return;
@@ -197,7 +229,10 @@ export const StatusTab: React.FC<StatusTabProps> = ({
<div className="bg-neutral-50 dark:bg-neutral-800 rounded-lg p-4">
<p className="text-sm text-neutral-600 dark:text-neutral-400">{t('settings.storage.totalUsed')}</p>
<p className="text-2xl font-bold text-neutral-900 dark:text-neutral-100">
{settingsService.formatBytes(storageInfo.total_used)}
{/* `+` marks a floor: part of the storage root was
unreadable, so the real figure — and the limit
percentage derived from it — is higher (#1164). */}
{settingsService.formatBytes(storageInfo.total_used)}{storageInfo.storage_partial ? '+' : ''}
</p>
</div>
<div className="bg-neutral-50 dark:bg-neutral-800 rounded-lg p-4">
@@ -609,6 +644,73 @@ export const StatusTab: React.FC<StatusTabProps> = ({
</Card>
)}
{/* Capture Dates (#1172) */}
{/* canEditSettings as well as the payload: TanStack keeps the cached
status after `enabled` flips false, so without it a built-in admin
logging in behind a settings.edit user inside the cache lifetime would
still be shown the card and a button whose POST 403s. */}
{captureDateStatus && canEditSettings && (
<Card padding="md">
<h2 className="text-lg font-semibold text-neutral-900 dark:text-neutral-100 mb-4 flex items-center gap-2">
<CalendarClock className="w-5 h-5" />
{t('settings.captureDates.title', 'Capture Dates')}
</h2>
<p className="text-sm text-neutral-600 dark:text-neutral-400 mb-4">
{t('settings.captureDates.description', 'Backfill "Date Taken" from EXIF for photos imported before capture dates were read. External/reference imports never recorded one, so their galleries sort by import order instead of when the photos were taken.')}
</p>
<div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-4">
<div className="bg-neutral-50 dark:bg-neutral-800 rounded-lg p-3 text-center">
<p className="text-2xl font-bold text-neutral-900 dark:text-neutral-100">{captureDateStatus.total}</p>
<p className="text-xs text-neutral-600 dark:text-neutral-400">{t('settings.captureDates.totalPhotos', 'Total Photos')}</p>
</div>
<div className="bg-neutral-50 dark:bg-neutral-800 rounded-lg p-3 text-center">
<p className="text-2xl font-bold text-green-600 dark:text-green-400">{captureDateStatus.withCaptureDate}</p>
<p className="text-xs text-neutral-600 dark:text-neutral-400">{t('settings.captureDates.withDates', 'With Capture Date')}</p>
</div>
<div className={`rounded-lg p-3 text-center ${Number(captureDateStatus.withoutCaptureDate) > 0 ? 'bg-amber-50 dark:bg-amber-900/30' : 'bg-neutral-50 dark:bg-neutral-800'}`}>
<p className={`text-2xl font-bold ${Number(captureDateStatus.withoutCaptureDate) > 0 ? 'text-amber-600 dark:text-amber-400' : 'text-neutral-900 dark:text-neutral-100'}`}>{captureDateStatus.withoutCaptureDate}</p>
<p className="text-xs text-neutral-600 dark:text-neutral-400">{t('settings.captureDates.missingDates', 'Missing Capture Date')}</p>
</div>
</div>
{captureDateStatus.lastResult && (
<p className="text-sm text-neutral-600 dark:text-neutral-400 mb-4">
{/* Two buckets on purpose: "the mount is gone" and "these files
carry no date" need different reactions. The middle number is
worded as "no date found" rather than "without EXIF" because
it also absorbs files whose metadata could not be parsed —
extractCaptureDate returns null for those too. The last number
is the one that means the storage could not be reached. */}
{t('settings.captureDates.resultSuccess', {
success: captureDateStatus.lastResult.success,
noExif: captureDateStatus.lastResult.noExif,
failed: captureDateStatus.lastResult.failed,
defaultValue: 'Last run: {{success}} updated, {{noExif}} with no date found, {{failed}} unreachable',
})}
</p>
)}
<div className="flex justify-end">
<Button
variant="secondary"
size="sm"
onClick={() => captureDateMutation.mutate()}
isLoading={captureDateMutation.isPending || captureDateStatus.isRunning}
disabled={Number(captureDateStatus.withoutCaptureDate) === 0 || captureDateStatus.isRunning}
leftIcon={<CalendarClock className="w-4 h-4" />}
>
{captureDateStatus.isRunning
? t('settings.captureDates.running', 'Backfilling...')
: Number(captureDateStatus.withoutCaptureDate) === 0
? t('settings.captureDates.noneToFill', 'All photos already have a capture date')
: t('settings.captureDates.button', 'Backfill Capture Dates')}
</Button>
</div>
</Card>
)}
{/* Update Notification Settings */}
<UpdateNotificationSettings />
@@ -299,7 +299,7 @@ export const ThumbnailsTab: React.FC = () => {
{t('settings.thumbnails.lightboxTitle', 'Lightbox Preview Tier')}
</h2>
<p className="text-sm text-neutral-600 dark:text-neutral-400 mb-4">
{t('settings.thumbnails.lightboxHelp', 'When enabled, the lightbox loads an aspect-preserved ~1920px JPEG (typically 200500 KB) instead of the full original (often 512 MB). Originals are still served when guests click Download. Costs roughly one extra preview file per photo on disk; previews are generated lazily on first open and stored in /previews.')}
{t('settings.thumbnails.lightboxHelp', 'The lightbox shows an aspect-preserved ~1920px JPEG (typically 200500 KB) rather than the full original (often 512 MB). Originals are still served when guests click Download. Previews cost roughly one extra file per photo on disk and are stored in /previews.')}
</p>
<label className="flex items-start gap-3 cursor-pointer mb-4">
@@ -311,10 +311,10 @@ export const ThumbnailsTab: React.FC = () => {
/>
<span className="text-sm">
<span className="font-medium text-neutral-900 dark:text-neutral-100">
{t('settings.thumbnails.lightboxToggle', 'Use medium-resolution previews in the lightbox')}
{t('settings.thumbnails.lightboxToggle', 'Enable eager preview generation')}
</span>
<span className="block text-xs text-neutral-600 dark:text-neutral-400 mt-0.5">
{t('settings.thumbnails.lightboxToggleHelp', 'Off by default. Flip on after deciding the perceived-perf win is worth the extra disk usage.')}
{t('settings.thumbnails.lightboxToggleHelp', 'Off by default: each preview is built the first time a guest opens that photo. Turning this on unlocks the button below, which builds them all up front.')}
</span>
</span>
</label>
+22 -5
View File
@@ -1544,9 +1544,9 @@
"regenerateStarted": "Neugenerierung der Vorschaubilder gestartet",
"regenerateError": "Neugenerierung der Vorschaubilder konnte nicht gestartet werden",
"lightboxTitle": "Lightbox-Vorschau-Stufe",
"lightboxHelp": "Wenn aktiviert, lädt die Lightbox ein seitenverhältnis-erhaltendes JPEG mit ~1920 px (typischerweise 200500 KB) statt des vollen Originals (oft 512 MB). Beim Download durch Gäste wird weiterhin das Original ausgeliefert. Kostet pro Foto eine zusätzliche Vorschaudatei auf der Festplatte; Vorschauen werden beim ersten Öffnen erzeugt und unter /previews gespeichert.",
"lightboxToggle": "Mittelauflösende Vorschauen in der Lightbox verwenden",
"lightboxToggleHelp": "Standardmäßig deaktiviert. Aktivieren, sobald der gefühlte Geschwindigkeitsgewinn den zusätzlichen Speicherbedarf rechtfertigt.",
"lightboxHelp": "Die Lightbox zeigt ein seitenverhältnis-erhaltendes JPEG mit ~1920 px (typischerweise 200500 KB) statt des vollen Originals (oft 512 MB). Beim Download durch Gäste wird weiterhin das Original ausgeliefert. Vorschauen kosten pro Foto etwa eine zusätzliche Datei auf der Festplatte und liegen unter /previews.",
"lightboxToggle": "Lightbox-Vorschauen vorab erzeugen",
"lightboxToggleHelp": "Standardmäßig deaktiviert: Eine Vorschau entsteht, sobald ein Gast das Foto zum ersten Mal öffnet. Aktivieren schaltet die Schaltfläche unten frei, die alle im Voraus erzeugt.",
"regeneratePreviewsButton": "Alle Vorschauen neu generieren",
"previewsRegenerateStarted": "Neugenerierung der Lightbox-Vorschauen gestartet",
"previewsRegenerateError": "Neugenerierung der Vorschauen konnte nicht gestartet werden",
@@ -2067,6 +2067,17 @@
"enableFailed": "Zwei-Faktor-Authentifizierung konnte nicht aktiviert werden. Prüfe den Code und versuche es erneut.",
"disableFailed": "Zwei-Faktor-Authentifizierung konnte nicht deaktiviert werden. Prüfe den Code und versuche es erneut.",
"regenerateFailed": "Wiederherstellungscodes konnten nicht neu erzeugt werden. Prüfe den Code und versuche es erneut."
},
"captureDates": {
"title": "Aufnahmedaten",
"totalPhotos": "Fotos gesamt",
"withDates": "Mit Aufnahmedatum",
"missingDates": "Ohne Aufnahmedatum",
"button": "Aufnahmedaten nachtragen",
"running": "Wird nachgetragen...",
"noneToFill": "Alle Fotos haben bereits ein Aufnahmedatum",
"resultSuccess": "Letzter Lauf: {{success}} aktualisiert, {{noExif}} ohne gefundenes Datum, {{failed}} nicht erreichbar",
"description": "Trägt „Aufnahmedatum\" aus den EXIF-Daten nach, für Fotos die vor dieser Auswertung importiert wurden. Externe Importe haben nie eines gespeichert, dadurch sortieren diese Galerien nach Importreihenfolge statt nach Aufnahmezeit."
}
},
"branding": {
@@ -2823,7 +2834,10 @@
"email_template_created": "E-Mail-Vorlage erstellt: {{template_key}}",
"event_duplicated": "Event dupliziert aus {{source_event_name}}",
"whatsapp_config_updated": "WhatsApp-Konfiguration aktualisiert"
}
},
"catalogedMedia": "{{size}} katalogisiert",
"catalogedMediaOnly": "katalogisiert — Objekte liegen in S3",
"storageUnavailable": "nicht verfügbar"
},
"acceptInvitation": {
"title": "Einladung annehmen",
@@ -2944,7 +2958,10 @@
"totalPhotos": "Gesamte Fotos",
"activeEvents": "Aktive Veranstaltungen",
"notConfigured": "Umami Analytics nicht konfiguriert",
"configureInstructions": "Um echte Analysedaten zu sehen, konfigurieren Sie Umami in Ihren Umgebungsvariablen und Admin-Panel-Einstellungen."
"configureInstructions": "Um echte Analysedaten zu sehen, konfigurieren Sie Umami in Ihren Umgebungsvariablen und Admin-Panel-Einstellungen.",
"catalogedMedia": "Katalogisierte Medien",
"storageUnavailable": "nicht verfügbar",
"storageNoMeasurement": "keine Messung verfügbar"
},
"email": {
"title": "E-Mail-Konfiguration",
+22 -5
View File
@@ -1152,9 +1152,9 @@
"regenerateStarted": "Thumbnail regeneration started",
"regenerateError": "Failed to start thumbnail regeneration",
"lightboxTitle": "Lightbox Preview Tier",
"lightboxHelp": "When enabled, the lightbox loads an aspect-preserved ~1920px JPEG (typically 200500 KB) instead of the full original (often 512 MB). Originals are still served when guests click Download. Costs roughly one extra preview file per photo on disk; previews are generated lazily on first open and stored in /previews.",
"lightboxToggle": "Use medium-resolution previews in the lightbox",
"lightboxToggleHelp": "Off by default. Flip on after deciding the perceived-perf win is worth the extra disk usage.",
"lightboxHelp": "The lightbox shows an aspect-preserved ~1920px JPEG (typically 200500 KB) rather than the full original (often 512 MB). Originals are still served when guests click Download. Previews cost roughly one extra file per photo on disk and are stored in /previews.",
"lightboxToggle": "Enable eager preview generation",
"lightboxToggleHelp": "Off by default: each preview is built the first time a guest opens that photo. Turning this on unlocks the button below, which builds them all up front.",
"regeneratePreviewsButton": "Regenerate All Previews",
"previewsRegenerateStarted": "Lightbox preview regeneration started",
"previewsRegenerateError": "Failed to start preview regeneration",
@@ -1608,6 +1608,17 @@
"enableFailed": "Could not enable two-factor authentication. Check the code and try again.",
"disableFailed": "Could not disable two-factor authentication. Check the code and try again.",
"regenerateFailed": "Could not regenerate recovery codes. Check the code and try again."
},
"captureDates": {
"title": "Capture Dates",
"totalPhotos": "Total Photos",
"withDates": "With Capture Date",
"missingDates": "Missing Capture Date",
"button": "Backfill Capture Dates",
"running": "Backfilling...",
"noneToFill": "All photos already have a capture date",
"resultSuccess": "Last run: {{success}} updated, {{noExif}} with no date found, {{failed}} unreachable",
"description": "Backfill \"Date Taken\" from EXIF for photos imported before capture dates were read. External/reference imports never recorded one, so their galleries sort by import order instead of when the photos were taken."
}
},
"analytics": {
@@ -1639,7 +1650,10 @@
"totalPhotos": "Total Photos",
"activeEvents": "Active Events",
"notConfigured": "Umami Analytics Not Configured",
"configureInstructions": "To see real analytics data, configure Umami in your environment variables and admin panel settings."
"configureInstructions": "To see real analytics data, configure Umami in your environment variables and admin panel settings.",
"catalogedMedia": "Catalogued media",
"storageUnavailable": "unavailable",
"storageNoMeasurement": "no measurement available"
},
"branding": {
"title": "Branding & Themes",
@@ -2395,7 +2409,10 @@
"email_template_created": "Email template created: {{template_key}}",
"event_duplicated": "Event duplicated from {{source_event_name}}",
"whatsapp_config_updated": "WhatsApp configuration updated"
}
},
"catalogedMedia": "{{size}} catalogued",
"catalogedMediaOnly": "catalogued — objects live in S3",
"storageUnavailable": "unavailable"
},
"acceptInvitation": {
"title": "Accept Invitation",
+22 -5
View File
@@ -953,9 +953,9 @@
"regenerateStarted": "Régénération des miniatures démarrée",
"regenerateError": "Échec du démarrage de la régénération des miniatures",
"lightboxTitle": "Niveau d'aperçu de la visionneuse",
"lightboxHelp": "Lorsqu'il est activé, la visionneuse charge un JPEG de ~1920px préservant les proportions (généralement 200500 Ko) au lieu de l'original complet (souvent 512 Mo). Les originaux sont toujours servis lorsque les invités cliquent sur Télécharger. Coûte environ un fichier d'aperçu supplémentaire par photo sur le disque ; les aperçus sont générés paresseusement lors de la première ouverture et stockés dans /previews.",
"lightboxToggle": "Utiliser des aperçus de résolution moyenne dans la visionneuse",
"lightboxToggleHelp": "Désactivé par défaut. Activez après avoir décidé que le gain de performance perçu vaut l'utilisation supplémentaire de disque.",
"lightboxHelp": "La visionneuse affiche un JPEG d'environ 1920 px préservant les proportions (généralement 200500 Ko) plutôt que l'original complet (souvent 512 Mo). Les originaux sont toujours servis lorsque les invités cliquent sur Télécharger. Les aperçus coûtent environ un fichier supplémentaire par photo sur le disque et sont stockés dans /previews.",
"lightboxToggle": "Activer la génération anticipée des aperçus",
"lightboxToggleHelp": "Désactivé par défaut : chaque aperçu est créé la première fois qu'un invité ouvre la photo. L'activer débloque le bouton ci-dessous, qui les crée tous à l'avance.",
"regeneratePreviewsButton": "Régénérer tous les aperçus",
"previewsRegenerateStarted": "Régénération des aperçus de la visionneuse démarrée",
"previewsRegenerateError": "Échec du démarrage de la régénération des aperçus",
@@ -1171,6 +1171,17 @@
"save": "Enregistrer les modifications",
"saved": "Marque du tableau de bord client enregistrée",
"error": "Impossible d'enregistrer les paramètres"
},
"captureDates": {
"title": "Dates de prise de vue",
"totalPhotos": "Photos au total",
"withDates": "Avec date de prise de vue",
"missingDates": "Sans date de prise de vue",
"button": "Compléter les dates",
"running": "Traitement...",
"noneToFill": "Toutes les photos ont déjà une date de prise de vue",
"resultSuccess": "Dernier passage : {{success}} mises à jour, {{noExif}} sans date trouvée, {{failed}} inaccessibles",
"description": "Complète la « date de prise de vue » depuis les EXIF pour les photos importées avant sa lecture. Les imports externes n'en enregistraient aucune, si bien que ces galeries se trient par ordre d'import plutôt que par date de prise de vue."
}
},
"analytics": {
@@ -1202,7 +1213,10 @@
"totalPhotos": "Photos totales",
"activeEvents": "Événements actifs",
"notConfigured": "Umami Analytics non configuré",
"configureInstructions": "Pour voir les données analytiques réelles, configurez Umami dans vos variables d'environnement et les paramètres du panneau d'administration."
"configureInstructions": "Pour voir les données analytiques réelles, configurez Umami dans vos variables d'environnement et les paramètres du panneau d'administration.",
"catalogedMedia": "Médias catalogués",
"storageUnavailable": "indisponible",
"storageNoMeasurement": "aucune mesure disponible"
},
"branding": {
"title": "Marque & Thèmes",
@@ -1806,7 +1820,10 @@
"category_hero_updated": "Photo de couverture de catégorie mise à jour",
"public_site_reset_to_default": "Site public réinitialisé aux valeurs par défaut",
"cms_page_logo_uploaded": "Logo de la page CMS téléversé : {{slug}}"
}
},
"catalogedMedia": "{{size}} catalogués",
"catalogedMediaOnly": "catalogué — les objets sont dans S3",
"storageUnavailable": "indisponible"
},
"acceptInvitation": {
"title": "Accepter l'invitation",
+22 -5
View File
@@ -953,9 +953,9 @@
"regenerateStarted": "Ponovno ustvarjanje sličic se je začelo",
"regenerateError": "Ponovnega ustvarjanja sličic ni bilo mogoče zagnati",
"lightboxTitle": "Raven predogleda v lightboxu",
"lightboxHelp": "Ko je omogočeno, lightbox namesto polnega originala (pogosto 512 MB) naloži JPEG predogled z ohranjenim razmerjem okoli 1920 px (običajno 200500 KB). Originali so še vedno uporabljeni, ko gost klikne Prenesi. Na disku to pomeni približno eno dodatno predogledno datoteko na fotografijo; predogledi se ustvarijo po potrebi ob prvem odpiranju in shranijo v /previews.",
"lightboxToggle": "Uporabi predoglede srednje ločljivosti v lightboxu",
"lightboxToggleHelp": "Privzeto izklopljeno. Vklopite, ko presodite, da je boljša zaznana hitrost vredna dodatne porabe diska.",
"lightboxHelp": "Lightbox prikaže JPEG z ohranjenim razmerjem okoli 1920 px (običajno 200500 KB) namesto polnega originala (pogosto 512 MB). Originali so še vedno uporabljeni, ko gost klikne Prenesi. Predogledi na disku pomenijo približno eno dodatno datoteko na fotografijo in so shranjeni v /previews.",
"lightboxToggle": "Omogoči vnaprejšnje ustvarjanje predogledov",
"lightboxToggleHelp": "Privzeto izklopljeno: vsak predogled nastane, ko gost fotografijo prvič odpre. Vklop odklene spodnji gumb, ki jih ustvari vse vnaprej.",
"regeneratePreviewsButton": "Ponovno ustvari vse predoglede",
"previewsRegenerateStarted": "Ponovno ustvarjanje predogledov lightbox se je začelo",
"previewsRegenerateError": "Ponovnega ustvarjanja predogledov ni bilo mogoče zagnati",
@@ -1171,6 +1171,17 @@
"save": "Shrani spremembe",
"saved": "Blagovna znamka nadzorne plošče stranke je shranjena",
"error": "Nastavitev ni bilo mogoče shraniti"
},
"captureDates": {
"title": "Datumi zajema",
"totalPhotos": "Skupaj fotografij",
"withDates": "Z datumom zajema",
"missingDates": "Brez datuma zajema",
"button": "Dopolni datume zajema",
"running": "Dopolnjevanje...",
"noneToFill": "Vse fotografije že imajo datum zajema",
"resultSuccess": "Zadnji zagon: {{success}} posodobljenih, {{noExif}} brez najdenega datuma, {{failed}} nedosegljivih",
"description": "Dopolni »datum zajema« iz EXIF za fotografije, uvožene pred njegovim branjem. Zunanji uvozi ga niso zabeležili, zato se te galerije razvrščajo po vrstnem redu uvoza namesto po času zajema."
}
},
"analytics": {
@@ -1202,7 +1213,10 @@
"totalPhotos": "Skupaj fotografij",
"activeEvents": "Aktivni dogodki",
"notConfigured": "Umami Analytics ni nastavljen",
"configureInstructions": "Za prikaz resničnih analitičnih podatkov nastavite Umami v okoljskih spremenljivkah in nastavitvah administratorske plošče."
"configureInstructions": "Za prikaz resničnih analitičnih podatkov nastavite Umami v okoljskih spremenljivkah in nastavitvah administratorske plošče.",
"catalogedMedia": "Katalogizirani mediji",
"storageUnavailable": "ni na voljo",
"storageNoMeasurement": "meritev ni na voljo"
},
"branding": {
"title": "Blagovna znamka in teme",
@@ -1795,7 +1809,10 @@
"category_hero_updated": "Hero fotografija kategorije posodobljena",
"public_site_reset_to_default": "Javna stran ponastavljena na privzeto",
"cms_page_logo_uploaded": "Logotip CMS strani naložen: {{slug}}"
}
},
"catalogedMedia": "{{size}} katalogizirano",
"catalogedMediaOnly": "katalogizirano — objekti so v S3",
"storageUnavailable": "ni na voljo"
},
"acceptInvitation": {
"title": "Sprejmi povabilo",
+53
View File
@@ -716,3 +716,56 @@
margin-top: 0;
}
}
/*
* iOS Safari zooms the whole page in when a focused form control computes to
* less than 16px, and it does not zoom back out (#1105). Unlocking a gallery
* is a client-side transition rather than a document navigation, so the zoom
* the password field triggered carries straight into the gallery: the layout
* pans horizontally and the header actions sit off-screen until the visitor
* pinch-zooms out by hand.
*
* The lever is the font size, not the viewport meta — adding maximum-scale=1
* would suppress the zoom by disabling pinch-to-zoom for everyone, which is an
* accessibility regression, so index.html deliberately omits it.
*
* Keyed to the POINTER, not a width. The zoom depends on the computed font
* size and a touch device, never on how wide the viewport is — and a phone in
* landscape is 667956 CSS px, above any width you could call "phone". A
* max-width query fixes portrait and leaves every landscape phone (and iPad)
* still zooming. `pointer: coarse` is the population that actually has the
* behaviour; a mouse-driven desktop reports `fine` and keeps its 14px density.
*
* Deliberately NOT inside @layer, and deliberately more specific than a single
* utility class: `.input` is 14px and ~440 raw controls carry their own
* `text-sm`, so a rule that loses to a utility fixes almost nothing. The
* `:not()` on each selector is what buys that specificity — without it,
* `select`/`textarea` (0,0,1) lose to `.text-sm` (0,1,0) and keep zooming,
* while `input` alone happens to win. Excluding checkbox and radio keeps
* font-size off controls that size their box from it.
*
* max(16px, 1em, 1rem) is a FLOOR, not a size. Writing a flat 16px would make
* controls that are already larger smaller: Typography -> Large sets
* --font-size-base to 18px on body, so anything inheriting it would be clamped
* down and the setting quietly ignored. Each term covers a case the others
* miss - 1em follows the theme's body size, 1rem follows a browser default the
* visitor raised themselves, 16px catches Small themes and .text-sm controls:
*
* normal (body 16) 16px Large theme (body 18) 18px
* Small theme (body 14) 16px browser default 20px 20px
*
* The specificity that beats a utility class also beats a gallery's custom CSS
* (Theme -> Custom CSS), so `.input-themed { font-size: 20px }` lands at 16px
* on touch. That is unavoidable here rather than an oversight: nothing in CSS
* distinguishes a class that sets 14px from one that sets 20px, so a rule that
* loses to the second also loses to the first and fixes nothing. Overriding
* DOWNWARD is the point; upward is the cost. `font-size: 20px !important`
* still wins for anyone who wants it.
*/
@media (pointer: coarse) {
input:not([type="checkbox"]):not([type="radio"]),
select:not([hidden]),
textarea:not([hidden]) {
font-size: max(16px, 1em, 1rem);
}
}
+39 -2
View File
@@ -345,14 +345,51 @@ export const GalleryPage: React.FC = () => {
// Show gallery view if authenticated
if (isAuthenticated && event) {
return <GalleryView slug={gallerySlugForView} event={event} />;
return <GalleryView slug={gallerySlugForView} event={event} requiresPassword={requiresPassword} />;
}
// Public gallery: auto-login is in flight (or about to fire). Show the
// skeleton instead of the "publicly accessible — loading photos" card so
// visitors see one continuous skeleton until real photos appear (#321).
if (!requiresPassword) {
return <GallerySkeleton />;
if (!autoLoginAttempted || isLoggingIn) {
return <GallerySkeleton />;
}
// Auto-login has run and we are still not authenticated (#1149).
//
// Returning the skeleton here meant it never stopped: the effect above is
// latched on autoLoginAttempted and will not fire again, so the visitor
// sat on a loading gallery until they reloaded by hand. It also swallowed
// loginError completely — a public gallery that failed to open showed no
// reason, because this branch returns before the form that renders it.
//
// Reachable two ways: a failed or expired auto-login, and clearing the
// session from inside the gallery (the Logout button that should not have
// been there, or GalleryView's 401 handler). Retry re-arms the latch; it
// is a button rather than an automatic re-fire so a genuinely failing
// gallery cannot spin.
return (
<div className="min-h-screen flex items-center justify-center p-4"
style={{ backgroundColor: 'var(--color-background, #fafafa)' }}>
<Card className="w-full max-w-md">
<CardContent className="p-6 text-center">
<AlertCircle className="w-10 h-10 mx-auto mb-3 text-muted-theme" />
<p className="text-base mb-4">
{loginError || t('gallery.failedToLoad', 'Failed to load gallery')}
</p>
<Button
onClick={() => {
setLoginError(null);
setAutoLoginAttempted(false);
}}
>
{t('gallery.tryAgain', 'Try again')}
</Button>
</CardContent>
</Card>
</div>
);
}
// Show login form
+14 -1
View File
@@ -169,8 +169,21 @@ export const AdminDashboard: React.FC = () => {
color: 'text-blue-600',
},
{
// Real bytes under the storage root (#1164). This used to be the summed
// size of the catalogued originals, which on a reference-mode install is
// the size of a NAS. `== null` rather than `||`: an absent measurement
// must read as unavailable, not as 0 Bytes.
title: t('admin.storageUsed'),
value: adminService.formatBytes(dashboardStats?.storageUsed || 0),
value: dashboardStats?.storageUsed == null
? (dashboardStats?.storageMeasurement === 'catalog'
? adminService.formatBytes(dashboardStats.catalogedBytes)
: t('admin.storageUnavailable', 'unavailable'))
: `${adminService.formatBytes(dashboardStats.storageUsed)}${dashboardStats.storagePartial ? '+' : ''}`,
change: dashboardStats
? (dashboardStats.storageMeasurement === 'catalog'
? t('admin.catalogedMediaOnly', 'catalogued — objects live in S3')
: t('admin.catalogedMedia', { size: adminService.formatBytes(dashboardStats.catalogedBytes) }))
: undefined,
icon: HardDrive,
color: 'text-purple-600',
},
+33 -8
View File
@@ -438,15 +438,30 @@ export const AnalyticsPage: React.FC = () => {
{/* Storage Information */}
{dashboardStats && (() => {
// On S3 there is no disk to walk and the catalogued figure IS the
// available answer; a failed local walk has none at all.
const measured = dashboardStats.storageUsed ?? (
dashboardStats.storageMeasurement === 'catalog' ? dashboardStats.catalogedBytes : null);
const softLimitBytes = storageInfo?.storage_soft_limit ?? storageInfo?.storage_limit ?? storageInfo?.recommended_soft_limit ?? null;
// `measured`, not storageUsed. An editor or viewer holds
// analytics.view but not settings.view, so /storage/info 403s and
// storageInfo is undefined — and on S3 storageUsed is null, which
// made this denominator 1 and rendered percentages in the billions.
const safeSoftLimit = Math.max(
softLimitBytes ?? storageInfo?.recommended_soft_limit ?? (dashboardStats.storageUsed || 1),
softLimitBytes ?? storageInfo?.recommended_soft_limit ?? (measured || 1),
1
);
const usageRatio = dashboardStats.storageUsed / safeSoftLimit;
const usagePercent = Math.round(usageRatio * 100);
const usageWidth = Math.min(usageRatio * 100, 100);
const overSoftLimit = softLimitBytes != null && dashboardStats.storageUsed >= softLimitBytes;
// Without a real limit there is no percentage worth showing: the
// denominator would be the usage itself, which always reads 100%.
const hasLimit = softLimitBytes != null || storageInfo?.recommended_soft_limit != null;
// No measurement, or no limit, means no percentage. Coercing null
// to 0 drew an empty bar at "0% of limit" and suppressed the
// over-limit state — reading as plenty of room precisely when
// nothing is known (#1164).
const usageRatio = (measured == null || !hasLimit) ? null : measured / safeSoftLimit;
const usagePercent = usageRatio == null ? null : Math.round(usageRatio * 100);
const usageWidth = usageRatio == null ? 0 : Math.min(usageRatio * 100, 100);
const overSoftLimit = softLimitBytes != null && measured != null && measured >= softLimitBytes;
const limitDisplay = softLimitBytes != null
? adminService.formatBytes(softLimitBytes)
: storageInfo?.recommended_soft_limit != null
@@ -454,7 +469,7 @@ export const AnalyticsPage: React.FC = () => {
: t('settings.storage.unlimited');
const progressColor = overSoftLimit
? 'bg-red-600'
: usagePercent >= 90
: (usagePercent != null && usagePercent >= 90)
? 'bg-amber-500'
: 'bg-accent-dark';
const limitDescriptor = storageInfo
@@ -470,7 +485,11 @@ export const AnalyticsPage: React.FC = () => {
<div>
<div className="flex justify-between text-sm mb-1">
<span className="text-neutral-600 dark:text-neutral-400">{t('analytics.used')}</span>
<span className="font-medium text-neutral-900 dark:text-neutral-100">{adminService.formatBytes(dashboardStats.storageUsed)}</span>
<span className="font-medium text-neutral-900 dark:text-neutral-100">
{measured == null
? t('analytics.storageUnavailable', 'unavailable')
: `${adminService.formatBytes(measured)}${dashboardStats.storagePartial ? '+' : ''}`}
</span>
</div>
<div className="w-full bg-neutral-200 dark:bg-neutral-700 rounded-full h-2">
<div
@@ -479,7 +498,9 @@ export const AnalyticsPage: React.FC = () => {
/>
</div>
<p className="text-xs text-neutral-500 dark:text-neutral-400 mt-1">
{usagePercent}% {t('analytics.of')} {limitDisplay}
{usagePercent == null
? t('analytics.storageNoMeasurement', 'no measurement available')
: `${usagePercent}% ${t('analytics.of')} ${limitDisplay}`}
</p>
<p className={`text-xs mt-1 ${overSoftLimit ? 'text-red-600 dark:text-red-400 font-semibold' : 'text-red-500 dark:text-red-400 font-medium'}`}>
{limitDescriptor}
@@ -487,6 +508,10 @@ export const AnalyticsPage: React.FC = () => {
</div>
<div className="pt-2 border-t border-neutral-200 dark:border-neutral-700">
<div className="flex justify-between text-sm">
<span className="text-neutral-600 dark:text-neutral-400">{t('analytics.catalogedMedia', 'Catalogued media')}</span>
<span className="font-medium text-neutral-900 dark:text-neutral-100">{adminService.formatBytes(dashboardStats.catalogedBytes)}</span>
</div>
<div className="flex justify-between text-sm mt-2">
<span className="text-neutral-600 dark:text-neutral-400">{t('analytics.totalPhotos')}</span>
<span className="font-medium text-neutral-900 dark:text-neutral-100">{dashboardStats.totalPhotos.toLocaleString()}</span>
</div>
+18 -1
View File
@@ -61,7 +61,24 @@ export interface DashboardStats {
activeEvents: number;
expiringEvents: number;
totalPhotos: number;
storageUsed: number;
// Real bytes under the storage root — thumbnails, previews, hero
// renditions, watermarks, download caches and any managed originals
// (#1164). Null when the measurement failed, or when the backend is S3 and
// the objects live in the bucket. The UI must show that as unavailable
// rather than substituting `catalogedBytes`: they are different quantities
// and on a reference-mode install they are wildly different.
storageUsed: number | null;
// 'catalog' when the backend is S3 — the objects are in the bucket, so no
// disk walk was made. 'unavailable' when a local walk was attempted and
// failed. Distinct because the first is a fact about the install and the
// second is a fault, and the UI must not claim S3 for a broken measurement.
storageMeasurement?: 'disk' | 'catalog' | 'unavailable';
storageBreakdown: Record<string, number> | null;
// The total is a floor: part of the storage root could not be read.
storagePartial?: boolean;
// Summed photos.size_bytes — what this endpoint used to label "storage
// used". In reference mode those files are on external storage.
catalogedBytes: number;
totalViews: number;
totalDownloads: number;
viewsTrend: number;
@@ -81,7 +81,15 @@ export interface PasswordComplexitySettings {
}
export interface StorageInfo {
// Real bytes under the storage root (#1164), excluding the external media
// share. Was the summed size of the catalogued originals, which on a
// reference-mode install is the size of a NAS.
total_used: number;
cataloged_bytes?: number;
// True when part of the storage root could not be read, so total_used is a
// floor. Anything comparing it against a limit has to say so.
storage_partial?: boolean;
storage_measurement?: 'disk' | 'catalog' | 'unavailable';
archive_storage: number;
storage_by_event: Array<{
event_name: string;