fix(journey): keep an iPhone photo's capture time and place through the HEIC conversion

The browser converts a HEIC to a JPEG before it uploads it, and that
JPEG carries no EXIF, so iPhone photos arrived without their capture
time and GPS. A small lazily loaded reader now takes DateTimeOriginal
with its offset and the GPS pair from the HEIC's Exif item before the
conversion, and journey photo uploads (gallery, entry, Studio) send them
as optional taken_at, lat and lng fields.

The server reads those fields leniently (an ISO instant between 1900
and tomorrow, a pair inside the globe that is not 0,0) and hands them to
the capture backfill only when the request carried one file. They fill
in only what the file's own EXIF lacks and go through the existing
COALESCE write, so a stored value is never replaced. Covers and place
images keep the plain conversion and never carry a location.
This commit is contained in:
Maurice
2026-11-30 14:38:56 +01:00
parent 555027f10f
commit 78c0f65de4
23 changed files with 931 additions and 33 deletions
@@ -0,0 +1,56 @@
import type { CaptureHint } from '../memories/photo-capture-backfill.service';
import type { JourneyPhotoCaptureFields } from '@trek/shared';
/** The earliest capture time taken at its word; a phone clock reset to 1970 is no capture time. */
const EARLIEST_CAPTURE_MS = Date.UTC(1900, 0, 1);
/** A day of slack for a camera clock a little ahead of the server's. */
const FUTURE_SLACK_MS = 24 * 60 * 60 * 1000;
const ISO_INSTANT = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d{1,3})?(?:Z|[+-]\d{2}:\d{2})$/;
const DECIMAL = /^-?\d{1,3}(?:\.\d{1,12})?$/;
/** Whether the date and time an ISO stamp spells exist: Date.parse rolls 30 February over into March. */
function realWallClock(parts: number[]): boolean {
const [year, month, day, hour, minute, second] = parts;
const wall = new Date(Date.UTC(year, month - 1, day, hour, minute, second));
return (
wall.getUTCMonth() === month - 1 &&
wall.getUTCDate() === day &&
wall.getUTCHours() === hour &&
wall.getUTCMinutes() === minute &&
wall.getUTCSeconds() === second
);
}
function instant(value: string | undefined, now: number): string | null {
const m = value ? ISO_INSTANT.exec(value) : null;
if (!value || !m || !realWallClock(m.slice(1, 7).map(Number))) return null;
const ms = Date.parse(value);
if (!Number.isFinite(ms) || ms < EARLIEST_CAPTURE_MS || ms > now + FUTURE_SLACK_MS) return null;
return new Date(ms).toISOString();
}
function degrees(value: string | undefined, limit: number): number | null {
if (!value || !DECIMAL.test(value)) return null;
const n = Number(value);
return Math.abs(n) <= limit ? n : null;
}
/**
* The capture time and place a client sent beside one uploaded photo (#3120),
* read as the backfill reads a file's own EXIF: an ISO instant between 1900 and
* tomorrow, and a pair of coordinates inside the globe that is not 0,0. A field
* that is anything else is dropped rather than refused, so a bad hint never
* costs the photo its upload. Null when nothing usable is left.
*/
export function captureHintFrom(
fields: JourneyPhotoCaptureFields | undefined,
now: number = Date.now(),
): CaptureHint | null {
if (!fields) return null;
const takenAt = instant(fields.taken_at, now);
const lat = degrees(fields.lat, 90);
const lng = degrees(fields.lng, 180);
const place = lat !== null && lng !== null && !(lat === 0 && lng === 0);
if (!takenAt && !place) return null;
return { takenAt, lat: place ? lat : null, lng: place ? lng : null };
}
@@ -1,7 +1,7 @@
import { withRequestContext } from '../database/request-context';
import { UnitOfWork } from '../database/unit-of-work';
import { MapsService } from '../maps/maps.service';
import { PhotoCaptureBackfillService } from '../memories/photo-capture-backfill.service';
import { PhotoCaptureBackfillService, type CaptureHint } from '../memories/photo-capture-backfill.service';
import { JourneyDomainService } from './journey-domain.service';
import { MikroORM } from '@mikro-orm/core';
import { Injectable } from '@nestjs/common';
@@ -134,15 +134,21 @@ export class JourneyPhotoCaptureService {
* 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.
*
* A capture hint (#3120) is what the client read from the file before it
* converted it; it belongs to one file, so it is kept only when the upload
* added exactly one photo, and only fills in what that file lacks.
*
* @txStandalone a detached refresh after the upload has committed.
*/
scheduleUpload(photos: readonly unknown[], userId: number): void {
scheduleUpload(photos: readonly unknown[], userId: number, hint?: CaptureHint | null): void {
const ids = trekPhotoIdsOf(photos);
if (!ids.length) return;
const hints = hint && ids.length === 1 ? new Map([[ids[0], hint]]) : undefined;
// The placing is chained inside the fork, not after it, so it runs in the
// same context as the backfill rather than in whatever the caller had.
void withRequestContext(this.orm, () => this.backfill.run(ids, userId).then(() => this.placeEntries(ids))).catch(
(err) => console.error('[Journey] capture for uploads failed:', err instanceof Error ? err.message : err),
const capture = () => this.backfill.run(ids, userId, hints).then(() => this.placeEntries(ids));
void withRequestContext(this.orm, capture).catch((err) =>
console.error('[Journey] capture for uploads failed:', err instanceof Error ? err.message : err),
);
}
@@ -26,6 +26,7 @@ import { RuntimeEnvService } from '../app-config/runtime-env.service';
import { isDemoWriteBlocked, DEMO_WRITE_ERROR } from '../common/demo-write';
import { StorageService } from '../storage/storage.service';
import { JourneyGalleryService } from './journey-gallery.service';
import { captureHintFrom } from './journey-capture-hint';
import { JourneyService } from './journey.service';
import { JourneyBookService } from './journey-book.service';
import { JourneyPhotoCaptureService, type ProviderPhotoBatch, type ProviderPhotoTarget } from './journey-photo-capture.service';
@@ -37,7 +38,7 @@ import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
import { CurrentUser } from '../auth-core/current-user.decorator';
import {
JourneyAddTripDto, JourneyContributorAddDto, JourneyContributorUpdateDto, JourneyCreateDto,
JourneyEntryCreateDto, JourneyEntryPhotoUploadDto, JourneyEntryUpdateDto, JourneyGalleryVideoDto,
JourneyEntryCreateDto, JourneyEntryPhotoUploadDto, JourneyEntryUpdateDto, JourneyGalleryPhotoUploadDto, JourneyGalleryVideoDto,
JourneyLinkPhotoDto, JourneyPhotosMoveDto, JourneyPhotoUpdateDto, JourneyPreferencesDto, JourneyProviderPhotosDto,
JourneyReorderEntriesDto,
JourneyReorderEntryPhotosDto, JourneyShareLinkDto, JourneyUpdateDto,
@@ -336,8 +337,9 @@ export class JourneyController {
// 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);
// request and reloads once after the last. What the client read from a
// HEIC before converting it fills in what the file lost (#3120).
this.photoCapture.scheduleUpload(results, user.id, files.length === 1 ? captureHintFrom(body) : null);
return { photos: results };
}
@@ -474,7 +476,7 @@ export class JourneyController {
// ── Gallery (prefix /:id/gallery — before /:id) ─────────────────────────
@Post(':id/gallery/photos')
@UseInterceptors(FilesInterceptor('photos'))
async uploadGalleryPhotos(@CurrentUser() user: User, @Param('id') id: string, @UploadedFiles() files: Express.Multer.File[] | undefined) {
async uploadGalleryPhotos(@CurrentUser() user: User, @Param('id') id: string, @UploadedFiles() files: Express.Multer.File[] | undefined, @Body() body: JourneyGalleryPhotoUploadDto) {
this.refuseDemoUpload(user, files ?? []);
if (!files?.length) {
throw new HttpException({ error: 'No files uploaded' }, 400);
@@ -489,7 +491,8 @@ export class JourneyController {
// An uploaded file carries its own EXIF; reading it is what puts the photo on
// 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);
// A HEIC's capture, read by the client before converting it, goes along (#3120).
this.photoCapture.scheduleUpload(photos, user.id, files.length === 1 ? captureHintFrom(body) : null);
return { photos };
}
+2
View File
@@ -6,6 +6,7 @@ import {
journeyEntryCreateRequestSchema,
journeyEntryPhotoUploadRequestSchema,
journeyEntryUpdateRequestSchema,
journeyGalleryPhotoUploadRequestSchema,
journeyGalleryVideoRequestSchema,
journeyLinkPhotoRequestSchema,
journeyPhotoUpdateRequestSchema,
@@ -55,6 +56,7 @@ export class JourneyPhotoUpdateDto extends createZodDto(journeyPhotoUpdateReques
/** Photos of an entry moved to another entry: strict, a new route with nothing older to keep answering. */
export class JourneyPhotosMoveDto extends createZodDto(journeyPhotosMoveRequestSchema) {}
export class JourneyEntryPhotoUploadDto extends createZodDto(journeyEntryPhotoUploadRequestSchema) {}
export class JourneyGalleryPhotoUploadDto extends createZodDto(journeyGalleryPhotoUploadRequestSchema) {}
export class JourneyGalleryVideoDto extends createZodDto(journeyGalleryVideoRequestSchema) {}
/** A Studio book save — the whole document, plus the version it was made against. */
@@ -29,6 +29,25 @@ const CAPTURE_TAGS = [
/** When and where an uploaded file says it was taken. */
type LocalCapture = { takenAt: string | null; lat: number | null; lng: number | null };
/**
* The capture time and place a client read from a photo before converting it
* (#3120): an iPhone HEIC becomes a JPEG in the browser, without its EXIF.
* Used only where the uploaded file has none of its own.
*/
export type CaptureHint = LocalCapture;
/** The file's own capture data, with the hint filling in only what the file lacks. */
function withHint(own: LocalCapture | null, hint: CaptureHint | undefined): LocalCapture | null {
if (!hint) return own;
if (!own) return hint;
const ownPlace = own.lat !== null && own.lng !== null;
return {
takenAt: own.takenAt ?? hint.takenAt,
lat: ownPlace ? own.lat : hint.lat,
lng: ownPlace ? own.lng : hint.lng,
};
}
type Exif = Partial<Record<(typeof CAPTURE_TAGS)[number] | 'latitude' | 'longitude', unknown>>;
function coordinate(value: unknown, limit: number): number | null {
@@ -127,13 +146,13 @@ export class PhotoCaptureBackfillService {
* 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> {
async run(trekPhotoIds: number[], userId: number, hints?: ReadonlyMap<number, CaptureHint>): 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;
if (await this.fillOne(id, userId, hints?.get(id))) changed = true;
}
};
const workers = Math.min(BACKFILL_CONCURRENCY, trekPhotoIds.length);
@@ -187,7 +206,7 @@ export class PhotoCaptureBackfillService {
}
/** One photo; answers whether its row changed. */
private async fillOne(id: number, userId: number): Promise<boolean> {
private async fillOne(id: number, userId: number, hint?: CaptureHint): Promise<boolean> {
try {
const photo = await this.photos.resolve(id);
// A row that already knows both has nothing to gain, and a provider call
@@ -198,8 +217,10 @@ export class PhotoCaptureBackfillService {
// 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.
// A hint the client read before converting the file fills in what the
// file itself no longer says (#3120); the file's own EXIF always wins.
if (photo.provider === 'local') {
const meta = await this.readLocalExif(photo.file_path);
const meta = withHint(await this.readLocalExif(photo.file_path), hint);
return meta ? await this.photos.recordCaptureMetadata(id, meta) : false;
}
+65
View File
@@ -1358,5 +1358,70 @@ describe('Journey upload parity', () => {
const row = await captureOf(res.body.photos[0].file_path);
expect(row).toEqual({ taken_at: '2026-05-30T13:52:19.000Z', lat: null, lng: null });
});
it('JOURNEY-P13: a converted HEIC without EXIF keeps the capture the client read from it (#3120)', async () => {
const { user } = await makeUser(orm);
const journey = await makeJourney(orm, user.id);
const res = await request(app)
.post(`/api/journeys/${journey.id}/gallery/photos`)
.set('Cookie', authCookie(user.id))
.field('taken_at', '2026-05-30T13:52:19.000Z')
.field('lat', '64.1466000')
.field('lng', '-21.9426000')
.attach('photos', jpegWithExif({}), { filename: 'IMG_0042.jpg', contentType: 'image/jpeg' });
expect(res.status).toBe(201);
const row = await captureOf(res.body.photos[0].file_path);
expect(row.taken_at).toBe('2026-05-30T13:52:19.000Z');
expect(row.lat).toBeCloseTo(64.1466, 5);
expect(row.lng).toBeCloseTo(-21.9426, 5);
});
it("JOURNEY-P14: an entry photo's own EXIF time wins over the hint, which only adds the place it lacks", async () => {
const { user } = await makeUser(orm);
const journey = await makeJourney(orm, user.id);
const entry = await makeJourneyEntry(orm, journey.id, user.id, { entry_date: '2026-05-30' });
const res = await request(app)
.post(`/api/journeys/entries/${entry.id}/photos`)
.set('Cookie', authCookie(user.id))
.field('taken_at', '2020-01-01T00:00:00.000Z')
.field('lat', '64.1466000')
.field('lng', '-21.9426000')
.attach('photos', jpegWithExif({ DateTimeOriginal: '2026:05:30 15:52:19', OffsetTimeOriginal: '+02:00' }), {
filename: 'IMG_0043.jpg',
contentType: 'image/jpeg',
});
expect(res.status).toBe(201);
const row = await captureOf(res.body.photos[0].file_path);
expect(row.taken_at).toBe('2026-05-30T13:52:19.000Z');
expect(row.lat).toBeCloseTo(64.1466, 5);
expect(row.lng).toBeCloseTo(-21.9426, 5);
});
it('JOURNEY-P15: a hint that is no real time or place is dropped, and the upload still goes through', async () => {
const { user } = await makeUser(orm);
const journey = await makeJourney(orm, user.id);
const res = await request(app)
.post(`/api/journeys/${journey.id}/gallery/photos`)
.set('Cookie', authCookie(user.id))
.field('taken_at', 'yesterday')
.field('lat', '0')
.field('lng', '0')
.attach('photos', jpegWithExif({}), { filename: 'IMG_0044.jpg', contentType: 'image/jpeg' });
expect(res.status).toBe(201);
// The backfill runs detached; give it the time it took the cases above.
await new Promise((resolve) => setTimeout(resolve, 200));
const photo = await findRow(orm, TrekPhotos, { file_path: res.body.photos[0].file_path });
expect({ taken_at: photo?.taken_at ?? null, lat: photo?.lat ?? null, lng: photo?.lng ?? null }).toEqual({
taken_at: null,
lat: null,
lng: null,
});
});
});
});
@@ -0,0 +1,52 @@
/**
* captureHintFrom: the capture time and place a client read from a HEIC before
* converting it (#3120), held to the rules the backfill holds a file's own EXIF
* to. Anything that is not a real time or place is dropped, never refused.
*/
import { captureHintFrom } from '../../../src/nest/journey/journey-capture-hint';
import { describe, expect, it } from 'vitest';
const NOW = Date.UTC(2026, 10, 30, 12, 0, 0);
describe('captureHintFrom', () => {
it('CHINT-001: reads an ISO instant and a pair of coordinates', () => {
const fields = { taken_at: '2026-05-30T15:52:19+02:00', lat: '64.1466000', lng: '-21.9426000' };
expect(captureHintFrom(fields, NOW)).toEqual({
takenAt: '2026-05-30T13:52:19.000Z',
lat: 64.1466,
lng: -21.9426,
});
});
it('CHINT-002: no fields, or nothing usable in them, is no hint', () => {
expect(captureHintFrom(undefined, NOW)).toBeNull();
expect(captureHintFrom({}, NOW)).toBeNull();
expect(captureHintFrom({ taken_at: 'yesterday', lat: 'north', lng: '2' }, NOW)).toBeNull();
});
it('CHINT-003: a time before 1900 or more than a day ahead is dropped, the place kept', () => {
for (const taken_at of ['1899-12-31T23:59:59Z', '2026-12-02T12:00:00Z', '2026-02-30T10:00:00Z']) {
expect(captureHintFrom({ taken_at, lat: '48.8584', lng: '2.2945' }, NOW)).toEqual({
takenAt: null,
lat: 48.8584,
lng: 2.2945,
});
}
expect(captureHintFrom({ taken_at: '2026-12-01T11:00:00Z' }, NOW)?.takenAt).toBe('2026-12-01T11:00:00.000Z');
});
it('CHINT-004: half a pair, a pair outside the globe, 0,0 or an exponent is no place, the time kept', () => {
const taken_at = '2026-05-30T13:52:19.000Z';
for (const [lat, lng] of [
['48.8584', undefined],
['91', '2.2945'],
['48.8584', '-180.5'],
['0', '0'],
['1e-7', '2'],
[' 48.8', '2'],
] as Array<[string | undefined, string | undefined]>) {
expect(captureHintFrom({ taken_at, lat, lng }, NOW)).toEqual({ takenAt: taken_at, lat: null, lng: null });
}
});
});
@@ -204,7 +204,7 @@ describe('JourneyPhotoCaptureService', () => {
svc.scheduleUpload([{ id: 1, photo_id: 11 }, null, { id: 2 }], 3);
await vi.waitFor(() => expect(placeEntriesFromPhotos).toHaveBeenCalledWith([11]));
expect(run).toHaveBeenCalledWith([11], 3);
expect(run).toHaveBeenCalledWith([11], 3, undefined);
expect(journeyIdOfEntry).not.toHaveBeenCalled();
expect(broadcastJourneyEvent).not.toHaveBeenCalled();
@@ -214,6 +214,19 @@ describe('JourneyPhotoCaptureService', () => {
expect(run).not.toHaveBeenCalled();
});
it('JPCAP-009: a capture hint goes to the backfill for the one photo it was read from (#3120)', async () => {
const { svc, run, placeEntriesFromPhotos } = build(true);
const hint = { takenAt: '2026-05-30T13:52:19.000Z', lat: 64.1466, lng: -21.9426 };
svc.scheduleUpload([{ id: 1, photo_id: 11 }], 3, hint);
await vi.waitFor(() => expect(placeEntriesFromPhotos).toHaveBeenCalledWith([11]));
expect(run).toHaveBeenLastCalledWith([11], 3, new Map([[11, hint]]));
// Two photos from one request: the hint names neither, so it is dropped.
svc.scheduleUpload([{ photo_id: 12 }, { photo_id: 13 }], 3, hint);
await vi.waitFor(() => expect(run).toHaveBeenLastCalledWith([12, 13], 3, undefined));
});
it('JPCAP-1003: an entry placed from its photo gets a name and the journey hears about it', async () => {
const { svc, placeEntriesFromPhotos, nameEntryLocation, reverseGeocode, broadcastJourneyEvent } = build(false);
placeEntriesFromPhotos.mockReturnValueOnce([
@@ -433,6 +433,51 @@ describe('PhotoCaptureBackfillService — local files', () => {
expect(recordCaptureMetadata).not.toHaveBeenCalled();
});
it('CAPTURE-026: a converted HEIC without EXIF takes the capture the client read before converting it (#3120)', async () => {
vi.mocked(exifr.parse).mockResolvedValue(undefined as never);
const { svc, recordCaptureMetadata } = localBuild([{ id: 7, provider: 'local', file_path: 'journey/a.jpg' }]);
const hint = { takenAt: '2026-05-30T13:52:19.000Z', lat: 64.1466, lng: -21.9426 };
await svc.run([7], 1, new Map([[7, hint]]));
expect(recordCaptureMetadata).toHaveBeenCalledWith(7, hint);
});
it("CAPTURE-027: the file's own EXIF wins, and the hint only fills in what the file lacks", async () => {
vi.mocked(exifr.parse).mockResolvedValue({ DateTimeOriginal: '2026:03:15 11:20:00', OffsetTimeOriginal: '+01:00' });
const { svc, recordCaptureMetadata } = localBuild([
{ id: 7, provider: 'local', file_path: 'journey/a.jpg' },
{ id: 8, provider: 'local', file_path: 'journey/b.jpg' },
]);
const hint = { takenAt: '2026-05-30T13:52:19.000Z', lat: 64.1466, lng: -21.9426 };
await svc.run([7], 1, new Map([[7, hint]]));
expect(recordCaptureMetadata).toHaveBeenLastCalledWith(7, {
takenAt: '2026-03-15T10:20:00.000Z',
lat: 64.1466,
lng: -21.9426,
});
vi.mocked(exifr.parse).mockResolvedValue({ latitude: 48.8584, longitude: 2.2945 });
await svc.run([8], 1, new Map([[8, { takenAt: null, lat: 1, lng: 2 }]]));
expect(recordCaptureMetadata).toHaveBeenLastCalledWith(8, { takenAt: null, lat: 48.8584, lng: 2.2945 });
});
it('CAPTURE-028: a hint names one photo; the others of the batch read their file alone', async () => {
vi.mocked(exifr.parse).mockResolvedValue({});
const { svc, recordCaptureMetadata } = localBuild([
{ id: 7, provider: 'local', file_path: 'journey/a.jpg' },
{ id: 8, provider: 'local', file_path: 'journey/b.jpg' },
]);
const hint = { takenAt: '2026-05-30T13:52:19.000Z', lat: null, lng: null };
await svc.run([7, 8], 1, new Map([[7, hint]]));
expect(recordCaptureMetadata).toHaveBeenCalledTimes(1);
expect(recordCaptureMetadata).toHaveBeenCalledWith(7, hint);
});
it('CAPTURE-009: a file with nothing readable is left alone', async () => {
vi.mocked(exifr.parse).mockResolvedValue({});
const { svc, recordCaptureMetadata } = localBuild([{ id: 7, provider: 'local', file_path: 'journey/a.jpg' }]);