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;
}