fix(journey): select all takes every photo in the range and imports keep their order

The photo picker's Select all took only the pages already loaded, 50 at a
time, and replaced whatever had been picked on another tab. It now loads
the rest of a day, trip or date-range search before selecting (cancelled
by closing the picker or switching tab), adds to earlier picks, and
Deselect all only clears what is in view. Add stays disabled until that
loading is done. The whole-library tab keeps selecting what is loaded and
shows the count as "N+".

A date-filtered Immich search stopped at 1,000 photos without a word,
because its page budget was absolute; it is now relative to the page
asked for, with an absolute ceiling of 270 raw pages sized so the
picker's deepest page still gets a full answer. Adds go out in batches of
500 ids, under the JSON body limit, and each batch is sent oldest first,
so photos land in an entry in the order they were taken. When a later
batch fails, the photos already saved are counted and the journey
reloads while the error still shows, through one hook for desktop and
phone.

After a provider add, the capture-time lookup runs at most four at a time
per user, shared by all of that user's batches. When it fills a row, a
journey:photos:updated event reloads open journeys once per batch, from
the REST routes and the MCP add tool alike. Device uploads, which arrive
one file per request, get the same lookup without the event.

Addresses discussion #1587.
This commit is contained in:
Maurice
2026-09-24 23:33:11 +00:00
parent 650451bdf7
commit c7c9ba24a3
50 changed files with 2440 additions and 246 deletions
@@ -1,9 +1,9 @@
import { Module } from '@nestjs/common';
import { AllowedFileTypesModule } from '../files/allowed-file-types.module';
import { MemoriesModule } from '../memories/memories.module';
import { PluginGuardsModule } from '../plugins/host/plugin-guards.module';
import { StorageModule } from '../storage/storage.module';
import { JourneyDomainModule } from './journey-domain.module';
import { JourneyPhotoCaptureModule } from './journey-photo-capture.module';
import { JournalRpc } from './journal.rpc';
/**
@@ -11,17 +11,17 @@ import { JournalRpc } from './journal.rpc';
*
* JournalRpc used to sit in JourneyDomainModule, and it cannot stay there now
* that it writes photo bytes: that needs StorageService and, for the EXIF
* backfill, PhotoCaptureBackfillService out of MemoriesModule. JourneyDomainModule
* exists precisely so places, assignments and the plugin host can reach a few
* journey functions WITHOUT dragging MemoriesModule and both photo providers into
* their graphs (see the comment there), so the dependency goes here instead and
* only the plugin host pays for it.
* backfill, JourneyPhotoCaptureModule, which brings MemoriesModule with it.
* JourneyDomainModule exists precisely so places, assignments and the plugin
* host can reach a few journey functions WITHOUT dragging MemoriesModule and
* both photo providers into their graphs (see the comment there), so the
* dependency goes here instead and only the plugin host pays for it.
*
* JourneyDomainModule is re-exported so importing this one is a superset of
* importing that one, and nothing that already depended on it has to change.
*/
@Module({
imports: [JourneyDomainModule, StorageModule, AllowedFileTypesModule, MemoriesModule, PluginGuardsModule],
imports: [JourneyDomainModule, StorageModule, AllowedFileTypesModule, JourneyPhotoCaptureModule, PluginGuardsModule],
providers: [JournalRpc],
exports: [JourneyDomainModule],
})
+6 -5
View File
@@ -11,10 +11,10 @@ import { ADDON_IDS } from '../../addons';
import { readEnv } from '../../app-config';
import { isDemoEmail } from '../common/demo';
import { AllowedFileTypesService } from '../files/allowed-file-types.service';
import { PhotoCaptureBackfillService } from '../memories/photo-capture-backfill.service';
import { DatabaseService } from '../database/database.service';
import { StorageService } from '../storage/storage.service';
import { JourneyDomainService } from './journey-domain.service';
import { JourneyPhotoCaptureService } from './journey-photo-capture.service';
/** 10MB decoded, the same cap the file surface applies to plugin uploads. */
const PHOTO_CONTENT_MAX = 10 * 1024 * 1024;
@@ -45,7 +45,7 @@ export class JournalRpc {
private readonly guards: PluginGuards,
private readonly storage: StorageService,
private readonly allowedTypes: AllowedFileTypesService,
private readonly captureBackfill: PhotoCaptureBackfillService,
private readonly photoCapture: JourneyPhotoCaptureService,
private readonly db: DatabaseService,
) {}
@@ -181,9 +181,10 @@ export class JournalRpc {
await this.storage.delete('journey', filename).catch(() => {});
throw new ForbiddenResource(`no editable journal entry ${entryId} for this user`);
}
// Best-effort, exactly as the REST route does it: reads EXIF so the photo
// carries its capture date.
this.captureBackfill.schedule([photo.photo_id].filter((id): id is number => typeof id === 'number'), userId);
// Best-effort, exactly as the REST upload does it: reads EXIF so the photo
// carries its capture date. One photo per call, so no journey refresh, or a
// plugin importing a folder would reload every open client once per photo.
this.photoCapture.scheduleUpload([photo], userId);
return photo;
}
@@ -1500,6 +1500,19 @@ export class JourneyDomainService {
// ── Photos ───────────────────────────────────────────────────────────────
/**
* The journey an entry belongs to, or null when there is no such entry.
*
* No access check: it answers for a caller that has already added photos to
* the entry, and only decides which journey hears about their capture times.
*/
journeyIdOfEntry(entryId: number): number | null {
const row = this.db.prepare('SELECT journey_id FROM journey_entries WHERE id = ?').get(entryId) as
| { journey_id: number }
| undefined;
return row?.journey_id ?? null;
}
// Promote a skeleton suggestion to a concrete entry. Called whenever the user
// adds content (photo upload, provider photo, gallery link) — a suggestion
// with photos is no longer just a suggestion.
@@ -0,0 +1,21 @@
import { Module } from '@nestjs/common';
import { MemoriesModule } from '../memories/memories.module';
import { JourneyDomainModule } from './journey-domain.module';
import { JourneyPhotoCaptureService } from './journey-photo-capture.service';
/**
* The capture-time backfill as the journey surfaces use it: fill taken_at, then,
* for a batch of provider photos, tell the journey (#1587).
*
* Its own module because two containers need the same instance of the rule:
* JourneyModule (REST routes and the MCP tool) and JournalRpcModule (the plugin
* RPC). Neither JourneyDomainModule nor MemoriesModule can own it, the first
* because it stays free of the photo providers on purpose and the second
* because the memories domain knows nothing about journeys.
*/
@Module({
imports: [JourneyDomainModule, MemoriesModule],
providers: [JourneyPhotoCaptureService],
exports: [JourneyPhotoCaptureService],
})
export class JourneyPhotoCaptureModule {}
@@ -0,0 +1,85 @@
import { Injectable } from '@nestjs/common';
import { PhotoCaptureBackfillService } from '../memories/photo-capture-backfill.service';
import { JourneyDomainService } from './journey-domain.service';
/** The trek_photos ids of freshly added journey photo rows, whatever shape the add answered with. */
function trekPhotoIdsOf(photos: readonly unknown[]): number[] {
return photos
.map(p => (p as { photo_id?: unknown } | null)?.photo_id)
.filter((id): id is number => typeof id === 'number');
}
/**
* Capture times for photos that just landed on a journey, and the refresh that
* has to follow them (#1587).
*
* The add answers before anyone has asked the provider when each photo was
* taken (#1614 keeps that on the server rather than trusting the client). So
* the reload a client does straight after the add still sees the new photos
* without taken_at, and the gallery files them at the end by import time. Once
* the backfill has written something, everyone on the journey is told, the
* importer included: its own reload came too early, which is why the event
* excludes no socket.
*
* One place for the REST routes, the MCP tool and the plugin RPC, so no surface
* can add provider photos that stay out of order until somebody reloads.
*
* Uploads from a device fill their capture times here too, but tell nobody (see
* scheduleUpload): one upload request carries one file, so a refresh per request
* would reload every open client once per photo of a bulk upload.
*/
@Injectable()
export class JourneyPhotoCaptureService {
constructor(
private readonly backfill: PhotoCaptureBackfillService,
private readonly journey: JourneyDomainService,
) {}
/** Provider photos just added to a journey, to its gallery or to one of its entries. Detached. */
scheduleForJourney(journeyId: number, photos: readonly unknown[], userId: number): void {
const ids = trekPhotoIdsOf(photos);
if (!ids.length) return;
void this.fill(journeyId, ids, userId);
}
/** Provider photos just added to an entry, for a caller that only knows the entry. Detached. */
scheduleForEntry(entryId: number, photos: readonly unknown[], userId: number): void {
const ids = trekPhotoIdsOf(photos);
if (!ids.length) return;
void this.fill(this.journey.journeyIdOfEntry(entryId), ids, userId);
}
/**
* Photos uploaded from a device: read their capture times, and nothing more.
* Detached.
*
* No refresh on purpose. The client sends one file per upload request and
* reloads the journey itself once the last one is in, so an event per request
* would only make every other open client reload once per uploaded photo. The
* refresh belongs to the provider adds, where one request carries the batch.
*/
scheduleUpload(photos: readonly unknown[], userId: number): void {
const ids = trekPhotoIdsOf(photos);
if (!ids.length) return;
this.backfill.schedule(ids, userId);
}
/**
* Awaitable form, so tests do not have to chase a floating promise. Answers
* whether the batch changed anything. Never rejects: it runs detached, and a
* refresh that could not be sent is a gallery that sorts right on the next
* reload, not a failed add.
*/
async fill(journeyId: number | null, trekPhotoIds: number[], userId: number): Promise<boolean> {
let changed = false;
try {
changed = await this.backfill.run(trekPhotoIds, userId);
if (changed && journeyId != null) {
this.journey.broadcastJourneyEvent(journeyId, 'journey:photos:updated', {});
}
} catch (err) {
console.error(`[Journey] capture refresh failed for journey ${journeyId}:`, err instanceof Error ? err.message : err);
}
return changed;
}
}
+14 -19
View File
@@ -26,7 +26,7 @@ import { StorageService } from '../storage/storage.service';
import { journeyThumbName } from '../memories/thumbnail.service';
import { JourneyService } from './journey.service';
import { JourneyBookService } from './journey-book.service';
import { PhotoCaptureBackfillService } from '../memories/photo-capture-backfill.service';
import { JourneyPhotoCaptureService } from './journey-photo-capture.service';
import { AddonGuard } from '../addons/addon.guard';
import { RequireAddon } from '../addons/require-addon.decorator';
import { ADDON_IDS } from '../../addons';
@@ -130,7 +130,7 @@ export class JourneyController {
private readonly journey: JourneyService,
private readonly storage: StorageService,
private readonly books: JourneyBookService,
private readonly captureBackfill: PhotoCaptureBackfillService,
private readonly photoCapture: JourneyPhotoCaptureService,
) {}
/**
@@ -166,16 +166,6 @@ export class JourneyController {
}
}
// The add call carries only an asset id, so when and where the picture was taken
// are fetched from the provider afterwards rather than trusted from the client
// (#1614). Detached: a slow or unreachable provider must not hold up the add.
private backfillCapture(photos: unknown[], userId: number): void {
const ids = photos
.map(p => (p as { photo_id?: number } | null)?.photo_id)
.filter((id): id is number => typeof id === 'number');
this.captureBackfill.schedule(ids, userId);
}
// ── Static prefix routes (before /:id) ──────────────────────────────────
@Get()
list(@CurrentUser() user: User) {
@@ -263,7 +253,11 @@ export class JourneyController {
if (!results.length) {
throw new HttpException({ error: 'Not allowed' }, 403);
}
this.backfillCapture(results, user.id);
// When and where the picture was taken is read from the file afterwards
// (#1614). Detached, so the add never waits for it, and without the journey
// refresh the provider adds send (#1587): the client uploads one file per
// request and reloads once after the last.
this.photoCapture.scheduleUpload(results, user.id);
return { photos: results };
}
@@ -327,7 +321,7 @@ export class JourneyController {
const photo = this.journey.addProviderPhoto(Number(entryId), user.id, String(body.provider), String(id), body.caption as string | undefined, pp, mt);
if (photo) added.push(photo);
});
this.backfillCapture(added, user.id);
this.photoCapture.scheduleForEntry(Number(entryId), added, user.id);
return { photos: added, added: added.length };
}
if (!body.provider || !body.asset_id) {
@@ -337,7 +331,7 @@ export class JourneyController {
if (!photo) {
throw new HttpException({ error: 'Not allowed or duplicate' }, 403);
}
this.backfillCapture([photo], user.id);
this.photoCapture.scheduleForEntry(Number(entryId), [photo], user.id);
return photo;
}
@@ -424,8 +418,9 @@ export class JourneyController {
throw new HttpException({ error: 'Not allowed' }, 403);
}
// An uploaded file carries its own EXIF; reading it is what puts the photo on
// the map later. Detached, like the provider branch.
this.backfillCapture(photos, user.id);
// the map later. Detached, like the provider branch, but without its journey
// refresh: one file per request would mean one reload per photo (#1587).
this.photoCapture.scheduleUpload(photos, user.id);
return { photos };
}
@@ -484,7 +479,7 @@ export class JourneyController {
const photo = this.journey.addProviderPhotoToGallery(Number(id), user.id, String(body.provider), String(aid), undefined, pp, mt);
if (photo) added.push(photo);
});
this.backfillCapture(added, user.id);
this.photoCapture.scheduleForJourney(Number(id), added, user.id);
return { photos: added, added: added.length };
}
if (!body.provider || !body.asset_id) {
@@ -494,7 +489,7 @@ export class JourneyController {
if (!photo) {
throw new HttpException({ error: 'Not allowed or duplicate' }, 403);
}
this.backfillCapture([photo], user.id);
this.photoCapture.scheduleForJourney(Number(id), [photo], user.id);
return photo;
}
+5 -7
View File
@@ -12,7 +12,7 @@ import type { JourneyContributor } from '../../types';
import { addonGate } from '../addons/addon-gate';
import { AddonsService } from '../addons/addons.service';
import { AuthService } from '../auth/auth.service';
import { PhotoCaptureBackfillService } from '../memories/photo-capture-backfill.service';
import { JourneyPhotoCaptureService } from './journey-photo-capture.service';
/** Legacy registrar gate: the whole journey surface rode the journey addon. */
const journeyAddonOn = addonGate(ADDON_IDS.JOURNEY);
@@ -110,7 +110,7 @@ export class JourneyMcp {
private readonly share: JourneyShareService,
readonly addons: AddonsService,
private readonly auth: AuthService,
private readonly captureBackfill: PhotoCaptureBackfillService,
private readonly photoCapture: JourneyPhotoCaptureService,
) {}
// ── Read ────────────────────────────────────────────────────────────────
@@ -572,11 +572,9 @@ export class JourneyMcp {
// Detached, exactly as the REST routes schedule it: the provider is asked
// when and where each photo was taken, and without that answer an attached
// photo can never appear on the journey map (#1614).
this.captureBackfill.schedule(
photos.map(p => (p as { photo_id?: number }).photo_id).filter((id): id is number => typeof id === 'number'),
ctx.userId,
);
// photo can never appear on the journey map (#1614). Open clients are told
// once it lands, so the gallery re-sorts without a reload (#1587).
this.photoCapture.scheduleForJourney(journeyId, photos, ctx.userId);
// `skipped` is what tells a caller that a shortfall was duplicates rather
// than a failure; the REST body carries only photos and added.
return ok({ photos, added: photos.length, skipped: asset_ids.length - photos.length });
+2 -1
View File
@@ -6,6 +6,7 @@ import { JourneyBookService } from './journey-book.service';
import { AddonsModule } from '../addons/addons.module';
import { MemoriesModule } from '../memories/memories.module';
import { JourneyDomainModule } from './journey-domain.module';
import { JourneyPhotoCaptureModule } from './journey-photo-capture.module';
import { JourneyMcp } from './journey.mcp';
import { AuthModule } from '../auth/auth.module';
import { MulterModule } from '@nestjs/platform-express';
@@ -33,7 +34,7 @@ import { journeyImageFileFilter, journeyUploadFilename } from './journey.control
}),
}),
StorageModule,
AuthModule, AddonsModule, MemoriesModule, JourneyDomainModule],
AuthModule, AddonsModule, MemoriesModule, JourneyDomainModule, JourneyPhotoCaptureModule],
controllers: [JourneyController, JourneyPublicController],
providers: [JourneyService, JourneyBookService, JourneyMcp],
})
+27 -2
View File
@@ -1,4 +1,5 @@
import { Injectable } from '@nestjs/common';
import { PROVIDER_SELECT_ALL_MAX_PAGES } from '@trek/shared';
import type { Response } from 'express';
import { maybe_encrypt_api_key, decrypt_api_key } from '../common/crypto/apiKeyCrypto';
import { checkSsrf, safeFetch, type SafeFetchOptions } from '../../utils/ssrfGuard';
@@ -13,7 +14,7 @@ import { describeFetchFailure, fail, handleServiceResult, isWithinLocalDayRange,
const ALBUM_PAGE_SIZE = 1000;
const ALBUM_MAX_PAGES = 20;
/**
* How many upstream pages one search may read while filling one answered page.
* How many upstream pages one search may spend on rows the day filter drops.
*
* The day filter runs after the fetch, so the number of raw pages an answered
* page costs depends on how much of the padding days sits in front of it. This
@@ -21,8 +22,29 @@ const ALBUM_MAX_PAGES = 20;
* would otherwise keep a single request fetching, so the scan stops here and
* answers `hasMore: false` rather than spinning or handing back the same
* partial page for every page the caller asks for.
*
* It is an allowance on top of the pages the answered ones need, not a ceiling
* on the scan. Every call restarts at raw page 1, so page N reads at least N-1
* raw pages before it reaches its own, and a flat budget of 20 ended every
* date-filtered search at 20 answered pages: 1,000 photos at the picker's old
* page size, with no word to the user (#1587).
*/
const SEARCH_MAX_RAW_PAGES = 20;
/**
* The hard stop behind that allowance: no single search reads more raw pages
* than this, whatever page it asks for. `page` comes from the caller unbounded,
* and a purely relative budget would walk 100,000 raw pages to answer page
* 100,000.
*
* Sized for the journey picker, which never asks a date-bounded search for a
* page past PROVIDER_SELECT_ALL_MAX_PAGES + 1 (251), whether "Select all" loads
* it, a second press does, or it is scrolled into view: photos 50,001 to 50,200
* at its 200 a page. Page N may read N - 1 + SEARCH_MAX_RAW_PAGES raw pages, so
* page 251 needs 250 + 20 = 270, and that is the ceiling. A deeper page, which
* only another caller such as the MCP tool asks for, gets a smaller allowance,
* and one past the ceiling can only come back empty with `hasMore: false`.
*/
const SEARCH_ABSOLUTE_MAX_RAW_PAGES = PROVIDER_SELECT_ALL_MAX_PAGES + SEARCH_MAX_RAW_PAGES;
/** A mirrored journey upload is one photo; a server that sits on it this long is not coming back. */
const UPLOAD_TIMEOUT_MS = 60_000;
@@ -331,7 +353,10 @@ export class ImmichService {
const narrowed = Boolean(from || to);
const skip = narrowed ? (page - 1) * size : 0;
const wanted = skip + size;
const maxRawPages = narrowed ? SEARCH_MAX_RAW_PAGES : 1;
// The pages before this one, read even when every row on them is kept, plus
// the allowance for rows the filter drops. Page 1 keeps its budget of 20, and
// no page reads past the absolute ceiling.
const maxRawPages = narrowed ? Math.min(page - 1 + SEARCH_MAX_RAW_PAGES, SEARCH_ABSOLUTE_MAX_RAW_PAGES) : 1;
const kept: any[] = [];
let rawPage = narrowed ? 1 : page;
@@ -4,6 +4,26 @@ import { PhotoResolverService } from './photo-resolver.service';
import { StorageService } from '../storage/storage.service';
import { TrekPhotosRepository } from '../photos/trek-photos.repository';
/**
* Provider lookups one user keeps in flight at once, across every run of theirs.
*
* Per user rather than per run: the picker sends a large import in batches of
* 500, every batch starts its own detached run, and a per-run cap let those runs
* add up to several times this against the same NAS. Per user rather than for
* the whole server: each lookup goes to the importer's own Immich or Synology,
* so a NAS that has stopped answering must not hold up the capture times of
* everybody else on the instance. The service is a singleton of MemoriesModule,
* so a user's imports queue for the same slots whichever surface sent them.
*/
const BACKFILL_CONCURRENCY = 4;
/** One user's lookup slots: how many are open, and who waits for the next. */
interface LookupSlots {
active: number;
/** First come first served. */
waiting: Array<() => void>;
}
/**
* Ask the provider when and where a photo was taken, and record it (#1614).
*
@@ -19,6 +39,13 @@ import { TrekPhotosRepository } from '../photos/trek-photos.repository';
*/
@Injectable()
export class PhotoCaptureBackfillService {
/**
* Open lookups per user, never above BACKFILL_CONCURRENCY for any of them. An
* entry lives only while its user has a lookup open or waiting, so the map
* does not grow with every user who ever imported a photo.
*/
private readonly slots = new Map<number, LookupSlots>();
constructor(
private readonly resolver: PhotoResolverService,
private readonly photos: TrekPhotosRepository,
@@ -31,34 +58,104 @@ export class PhotoCaptureBackfillService {
void this.run(trekPhotoIds, userId);
}
/** Awaitable form, so tests do not have to chase a floating promise. */
async run(trekPhotoIds: number[], userId: number): Promise<void> {
for (const id of trekPhotoIds) {
try {
const photo = this.photos.resolve(id);
// A row that already knows both has nothing to gain, and a provider call
// per photo is the expensive part of an album import.
if (!photo || (photo.taken_at && photo.lat != null && photo.lng != null)) continue;
// A local file has no provider to ask — the answer is in its own EXIF, and
// getPhotoInfo would only hand back what the DB row already says.
if (photo.provider === 'local') {
const meta = await this.readLocalExif(photo.file_path);
if (meta) this.photos.recordCaptureMetadata(id, meta);
continue;
}
const info = await this.resolver.getPhotoInfo(userId, id);
if (!info.success) continue;
this.photos.recordCaptureMetadata(id, {
takenAt: info.data.takenAt ?? null,
lat: info.data.lat ?? null,
lng: info.data.lng ?? null,
});
} catch (err) {
console.error(`[Photos] capture backfill failed for ${id}:`, err instanceof Error ? err.message : err);
/**
* Awaitable form: resolves once every photo of the batch has been tried, with
* whether any of them learned something. The journey refresh hangs off that
* answer (#1587).
*
* A few photos at a time rather than one after the other: every provider call
* can take seconds, and a strictly sequential walk kept a large import out of
* order for minutes. The cap is shared by every run of the same user, so a
* thousand-photo import, however many batches it arrives in, never has more
* than BACKFILL_CONCURRENCY lookups open against that user's NAS.
*/
async run(trekPhotoIds: number[], userId: number): Promise<boolean> {
let next = 0;
let changed = false;
const worker = async (): Promise<void> => {
while (next < trekPhotoIds.length) {
const id = trekPhotoIds[next++];
if (await this.fillOne(id, userId)) changed = true;
}
};
const workers = Math.min(BACKFILL_CONCURRENCY, trekPhotoIds.length);
await Promise.all(Array.from({ length: workers }, worker));
return changed;
}
/**
* One provider lookup inside the user's cap. The slot is given back whatever
* the lookup does: a slot lost to a throw would stay lost, and four of them
* would stall every later import of that user for good.
*/
private async withLookupSlot<T>(userId: number, lookup: () => Promise<T>): Promise<T> {
const slots = await this.acquireSlot(userId);
try {
return await lookup();
} finally {
this.releaseSlot(userId, slots);
}
}
/** Wait for one of the user's lookup slots, and answer the entry it came from. */
private async acquireSlot(userId: number): Promise<LookupSlots> {
let slots = this.slots.get(userId);
if (!slots) {
slots = { active: 0, waiting: [] };
this.slots.set(userId, slots);
}
if (slots.active < BACKFILL_CONCURRENCY) {
slots.active++;
return slots;
}
// releaseSlot hands its slot straight to the first waiter, so the count
// stays where it is and nobody can slip in between.
const { waiting } = slots;
await new Promise<void>(resolve => {
waiting.push(resolve);
});
return slots;
}
/** Give a slot back: to the user's longest waiter, or, once nobody holds one, drop the entry. */
private releaseSlot(userId: number, slots: LookupSlots): void {
const next = slots.waiting.shift();
if (next) {
next();
return;
}
slots.active--;
if (slots.active === 0) this.slots.delete(userId);
}
/** One photo; answers whether its row changed. */
private async fillOne(id: number, userId: number): Promise<boolean> {
try {
const photo = this.photos.resolve(id);
// A row that already knows both has nothing to gain, and a provider call
// per photo is the expensive part of an album import.
if (!photo || (photo.taken_at && photo.lat != null && photo.lng != null)) return false;
// A local file has no provider to ask: the answer is in its own EXIF, and
// getPhotoInfo would only hand back what the DB row already says. Nor does
// it take a lookup slot, which exists to spare a NAS: a device upload must
// not wait behind the same user's provider import.
if (photo.provider === 'local') {
const meta = await this.readLocalExif(photo.file_path);
return meta ? this.photos.recordCaptureMetadata(id, meta) : false;
}
const info = await this.withLookupSlot(userId, () => this.resolver.getPhotoInfo(userId, id));
if (!info.success) return false;
return this.photos.recordCaptureMetadata(id, {
takenAt: info.data.takenAt ?? null,
lat: info.data.lat ?? null,
lng: info.data.lng ?? null,
});
} catch (err) {
console.error(`[Photos] capture backfill failed for ${id}:`, err instanceof Error ? err.message : err);
return false;
}
}
@@ -99,24 +99,35 @@ export class TrekPhotosRepository {
* and a later, emptier answer must not blank what is already there.
*
* A photo with neither is the normal case, not a failure.
*
* Answers whether the row learned anything. The guard in the WHERE clause is
* what makes that answer mean something: SQLite counts a matched row as changed
* even when every COALESCE kept the old value, and the caller broadcasts a
* journey refresh on it (#1587).
*/
recordCaptureMetadata(
photoId: number,
meta: { takenAt?: string | null; lat?: number | null; lng?: number | null },
): void {
): boolean {
const { takenAt = null, lat = null, lng = null } = meta;
if (takenAt == null && lat == null && lng == null) return;
if (takenAt == null && lat == null && lng == null) return false;
// Coordinates are stored as a pair or not at all — a lone latitude is not a
// place, and half a pair would put the photo on the null island.
const hasPair = Number.isFinite(lat) && Number.isFinite(lng);
this.db.run(
const pairLat = hasPair ? lat : null;
const pairLng = hasPair ? lng : null;
const result = this.db.run(
`UPDATE trek_photos
SET taken_at = COALESCE(taken_at, ?),
lat = COALESCE(lat, ?),
lng = COALESCE(lng, ?)
WHERE id = ?`,
takenAt, hasPair ? lat : null, hasPair ? lng : null, photoId,
WHERE id = ?
AND ((taken_at IS NULL AND ? IS NOT NULL)
OR (lat IS NULL AND ? IS NOT NULL)
OR (lng IS NULL AND ? IS NOT NULL))`,
takenAt, pairLat, pairLng, photoId, takenAt, pairLat, pairLng,
);
return result.changes > 0;
}
/**