TheRare Visuals

Folders, print shops and wedding days

Four studio requests in one week: nested gallery folders with private per-folder links, view counts that ignore reloads, page JPEGs for the album printer, and weddings tracked event by event, plus the race and the token gap that testing caught.

TheRare Engineering24 November 20269 min readIntermediate

Four requests, one week

A wedding delivery is not one shoot. It is a Haldi on a Saturday morning, a Muhurtha the following Friday at dawn, a Reception that Sunday night, and somewhere between three hundred and a thousand edited photos at the end of it. This week four requests from the studio all came back to that shape:

  1. "The gallery needs subfolders, and I want to share one subfolder privately."
  2. "How many times was it watched?"
  3. "The album printer wants a JPEG of every page, not the PDF."
  4. "A wedding has Haldi, Reception and Muhurtha on different days. I want to see that Haldi is shot and in editing while Reception is still to come."

None of them is hard on its own. Each one hides a small trap, though, and this post is about those traps.

Subfolders: a folder is a view, not a place

Booking galleries already had folders, introduced as a flat row of chips: Ceremony, Reception, Portraits. One decision from that first version shapes everything here. A file is not stored in a folder. Membership lives in its own table, so one photo can sit in "Ceremony" and "Best shots" at once, and deleting a folder never deletes a photo.

Nesting adds one column, parent_id, and one question: does "Haldi" show the photos filed under "Haldi > Bride's side"? It has to. When the client taps the parent they expect everything under it. So a file's folder list now includes every ancestor of every folder it is in:

Java
for (MediaFolder folder : folderRepository.findAllById(folderIds)) {
    List<Long> chain = new ArrayList<>();
    for (MediaFolder f = folder; f != null; f = f.getParent()) {
        chain.add(f.getId());
    }
    lineage.put(folder.getId(), chain);
}

The walk is short because nesting is capped at three levels, and it runs once per folder, not once per photo. Counts work the other way round: a parent's number is the set of distinct files across its whole subtree, so a photo filed in two subfolders is still counted once.

The admin gallery is paged, so filtering by folder has to happen in SQL rather than in the browser. The query takes the folder plus all its subfolders as a list. One small JPQL gotcha: an empty IN () list is invalid, so the query carries a separate boolean saying whether to filter at all.

The studio's Media Library (files waiting for a booking that doesn't exist yet) got subfolders too, but there a folder is a location: each file lives in exactly one. Same feature name, different meaning, so the parent page lists its own files and shows subfolders as cards instead of merging them. Deleting a library folder now has to delete the stored files of the whole subtree first. The database cascade only removes rows, and rows were the only thing pointing at those objects.

Clients could already make share links to hand-picked photos, public or private. Private links let in anyone on the booking's guest list, after an email code or Google sign-in. That model breaks with folders. A couple wants the bride's family to see "Haldi" and their college friends to see "Sangeet", and nobody to see the other one.

So a private link now carries its own email list. A folder link is also live: it doesn't freeze the files present when it was made, so photos added to the folder later show up on the link without anyone making a new one.

The trap was in the token. After the email check, the guest receives a token that says "this email, this booking". That was fine when every private link on a booking had the same audience. With per-link lists, a friend verified for the Sangeet link holds a token that is valid for the booking, so on its own it would also open the Haldi link. The fix is to check the email against this link's list on every read:

Java
// Checked per link, not per booking: the token is booking-bound,
// so without this a guest verified for one folder link could open
// every other private link on the same booking.
String guestEmail = galleryShareJwtService.extractGuestEmail(guestToken);
if (!isAllowedGuestEmail(link, guestEmail)) {
    throw new AccessDeniedException("Your access to this link has been removed.");
}

Library links have no booking at all, so their tokens carry a different type claim and the link id itself. A token minted for one thing can't be replayed against another, because every check starts by asking what kind of token it is.

"How many times was it watched?"

Counting views sounds like count++. It isn't, for three reasons.

Reloads are not views. Someone opening a link, scrolling, and refreshing twice has visited once. We already had a rule for whole-gallery shares: opens within 30 minutes of the viewer's last activity are one visit. The same rule, as one atomic upsert:

SQL
INSERT INTO share_link_views (link_ref, viewer_key, view_count, first_viewed_at, last_viewed_at)
VALUES (:ref, :key, 1, :now, :now)
ON CONFLICT (link_ref, viewer_key) DO UPDATE SET
    view_count = share_link_views.view_count
        + CASE WHEN share_link_views.last_viewed_at < :windowStart THEN 1 ELSE 0 END,
    last_viewed_at = GREATEST(share_link_views.last_viewed_at, EXCLUDED.last_viewed_at)

ON CONFLICT rather than "find, then insert or update", because two tabs opening at once would otherwise both miss the row and the second insert would hit the unique constraint.

Public links have no names. A private link knows the viewer's verified email. A public one knows nothing, so the page keeps a random id in the browser's local storage and sends it along. That is enough to say "Visitor 1, Visitor 2" without knowing who they are. If storage is blocked, the view is still counted, just not told apart.

A counter must never break the page. The gallery endpoints run in read-only transactions, and Postgres refuses writes inside one. The counter therefore runs in its own REQUIRES_NEW transaction inside a try/catch. A lost count is fine. A guest seeing an error instead of the photos because the counter failed is not.

Opening a photo or video full size is counted separately, with a five-minute window so paging back and forth in the viewer doesn't inflate it. The share popup shows "12 views · 3 people", and the details list the most-watched files.

Album prints: JPEGs, in order, for the print shop

The print shop asked for one JPEG per page instead of the album PDF. That became a new admin section: upload the pages, send the printer a private link, and they get a carousel, a "download all" button, and a note box on every page.

Page order is the whole product. Exports are named Page-1.jpg ... Page-24.jpg. Plain string sorting puts Page-10 before Page-2, so pages sort the way a person reads them, comparing runs of digits as numbers. Until someone drags a page by hand, that order is reapplied as uploads land. After a manual move it stops, and "Sort by file name" turns it back on.

Testing found a race. Three pages uploaded at once came back as page 1, page 1 and page 1. Each upload's "add page" request read the page list before the others had saved, and each concluded it was first. The fix is to lock the album's row for the rest of the transaction, so additions queue up instead of racing:

Java
@Lock(LockModeType.PESSIMISTIC_WRITE)
@Query("select s from AlbumPrintSet s where s.id = :id")
Optional<AlbumPrintSet> findByIdForUpdate(@Param("id") Long id);

The same test turned up a second bug, older than this feature. The shared upload tray started jobs from inside a React state updater. React's development mode deliberately runs updaters twice to surface exactly this kind of side effect, so a job could start twice. Other upload types hid it because the server treats a repeated file name as a replacement. Album pages keep a version history, so here it showed up as a page "replaced" by itself. One line fixed it: never start a job that is already running.

"Download all" can't send a header. The printer's access token travels in a request header, but a download is a plain link the browser follows, and links can't carry headers. The page asks for a five-minute ticket, a separate token type that only opens the zip, and puts that in the URL. Files inside the zip are prefixed with their page number (01-Page-1.jpg), so the zip sorts correctly whatever the originals were called.

Changes keep history. When the printer leaves a note on page 12, the studio uploads a fix for that page. The old file becomes a previous version instead of being deleted, so both sides can see what changed. The printer sees "updated (v2)" and their note marked done.

A printer who works with the studio regularly also gets a home page at /print: they confirm their email once and see every album sent to it, each opening without a second check.

Events within a booking

The last request changed the data model. A booking had one date range, event_date to event_end_date. For a wedding with Haldi on the 12th and Reception on the 20th, both ways of entering it were wrong. Enter 12 to 20, and the photographer looked busy for nine days, including the six with nothing on. Enter just the 12th, and the 20th didn't exist as far as reminders and availability were concerned.

A booking can now hold events, each with a day, optional times and venue, and its own status: scheduled, shoot done, editing, preview ready, delivered. Every change is stored with when and who, which is what "Haldi was shot on the 12th and has been in editing since the 13th" needs.

Two decisions kept this from touching half the codebase:

Events are optional. A portrait shoot has no events and behaves exactly as before. Nothing had to be converted.

The old range stays true. Once a booking has events, its range is rewritten to the first and last event day. Lists, reminders and the crew's "mark my work complete" gate all read the range, and all of them keep working without knowing events exist.

Only availability needed to know. The check "is this photographer free on the 15th?" became "the booking overlaps the 15th, and it either has no events or has one on that day":

SQL
AND b.eventDate <= :end AND b.eventEndDate >= :start
AND (NOT EXISTS (SELECT 1 FROM BookingEvent e WHERE e.booking.id = b.id
                 AND e.status <> CANCELLED)
     OR EXISTS (SELECT 1 FROM BookingEvent e WHERE e.booking.id = b.id
                 AND e.status <> CANCELLED
                 AND e.eventDate BETWEEN :start AND :end))

With Haldi on the 12th and Reception on the 20th, the 15th now comes back free and the 20th busy. The studio adds the events, the assigned crew move each one's status along from their own booking page, and the client follows each event's progress on their dashboard.

What we'd tell ourselves next time

  • Decide what a folder means before adding nesting. "Membership" and "location" folders behave differently for counts, deletes and display. We had one of each, and the subfolder code is different for both on purpose.
  • A token answers "who", not "what". When access rules get finer than the token, re-check the finer rule on every request.
  • Counters belong in their own transaction. Analytics should never be able to fail the request it is measuring.
  • Test uploads in bulk. One file at a time hid both a race and a double start. Three at once found them in seconds.
  • Keep the old field true. Making the booking range follow its events meant one new feature instead of a migration of every query that reads dates.

Found this useful?

Built something with what you learned here, or spotted a better way? Tell us. We work with freelance developers on Shootlo.