diff --git a/client/src/components/Journey/useGalleryUpload.test.ts b/client/src/components/Journey/useGalleryUpload.test.ts index bb9bcf6f9..5403caa3c 100644 --- a/client/src/components/Journey/useGalleryUpload.test.ts +++ b/client/src/components/Journey/useGalleryUpload.test.ts @@ -13,7 +13,7 @@ vi.mock('../../i18n', () => ({ }), })); vi.mock('../../utils/convertHeic', () => ({ - normalizeImageFiles: (files: File[]) => Promise.resolve(files.map((f) => new File([f], `${f.name}.jpg`))), + normalizeJourneyPhotos: (files: File[]) => Promise.resolve(files.map((f) => new File([f], `${f.name}.jpg`))), })); let addToast: Mock>; diff --git a/client/src/components/Journey/useGalleryUpload.ts b/client/src/components/Journey/useGalleryUpload.ts index 1048ea4b9..379142b2e 100644 --- a/client/src/components/Journey/useGalleryUpload.ts +++ b/client/src/components/Journey/useGalleryUpload.ts @@ -4,7 +4,7 @@ import { useState } from 'react'; import { useTranslation } from '../../i18n'; import { useJourneyStore } from '../../store/journeyStore'; import { getApiErrorMessage } from '../../types'; -import { normalizeImageFiles } from '../../utils/convertHeic'; +import { normalizeJourneyPhotos } from '../../utils/convertHeic'; import { isVideoFile } from '../../utils/videoPoster'; import { useToast } from '../shared/Toast'; @@ -54,7 +54,7 @@ export function useGalleryUpload({ const all = Array.from(files); const videos = all.filter(isVideoFile); const images = all.filter((f) => !isVideoFile(f)); - const normalized = [...(images.length ? await normalizeImageFiles(images) : []), ...videos]; + const normalized = [...(images.length ? await normalizeJourneyPhotos(images) : []), ...videos]; const store = useJourneyStore.getState(); const { failed } = trackProgress ? await store.uploadGalleryPhotos(journeyId, normalized, { diff --git a/client/src/components/Journey/useJourneyEntryForm.test.ts b/client/src/components/Journey/useJourneyEntryForm.test.ts index 8ce860c73..9777a610b 100644 --- a/client/src/components/Journey/useJourneyEntryForm.test.ts +++ b/client/src/components/Journey/useJourneyEntryForm.test.ts @@ -20,7 +20,7 @@ vi.mock('../../hooks/useGeolocation', async (importOriginal) => ({ ...(await importOriginal()), getCurrentPositionOnce: vi.fn(), })); -vi.mock('../../utils/convertHeic', () => ({ normalizeImageFiles: (files: File[]) => Promise.resolve([...files]) })); +vi.mock('../../utils/convertHeic', () => ({ normalizeJourneyPhotos: (files: File[]) => Promise.resolve([...files]) })); vi.mock('./useJourneyTripSuggestion', () => ({ useJourneyTripSuggestion: () => ({ trip: null, link: vi.fn(), linking: false, dismiss: vi.fn() }), })); diff --git a/client/src/components/Journey/useJourneyEntryForm.ts b/client/src/components/Journey/useJourneyEntryForm.ts index ee78cd82d..a9ceb8684 100644 --- a/client/src/components/Journey/useJourneyEntryForm.ts +++ b/client/src/components/Journey/useJourneyEntryForm.ts @@ -9,7 +9,7 @@ import { usePlaceSuggestions } from '../../hooks/usePlaceSuggestions'; import { useTranslation } from '../../i18n'; import type { GalleryPhoto, JourneyEntry, JourneyPhoto, JourneyTrip } from '../../store/journeyStore'; import { getApiErrorMessage } from '../../types'; -import { normalizeImageFiles } from '../../utils/convertHeic'; +import { normalizeJourneyPhotos } from '../../utils/convertHeic'; import { localIsoDate } from '../../utils/localDate'; import { PlacesSession } from '../../utils/placesSession'; import type { ResilientResult, UploadProgress } from '../../utils/uploadQueue'; @@ -441,7 +441,7 @@ export function useJourneyEntryForm({ const files = e.target.files; if (!files?.length) return; // Queue files locally until Save so cancel and close actually discard. - const normalized = await normalizeImageFiles(files); + const normalized = await normalizeJourneyPhotos(files); setPendingFiles((prev) => [...prev, ...normalized]); }; diff --git a/client/src/components/Studio/studioUpload.ts b/client/src/components/Studio/studioUpload.ts index 471751603..de37aa8c8 100644 --- a/client/src/components/Studio/studioUpload.ts +++ b/client/src/components/Studio/studioUpload.ts @@ -1,5 +1,5 @@ import { useJourneyStore } from '../../store/journeyStore' -import { normalizeImageFiles } from '../../utils/convertHeic' +import { normalizeJourneyPhotos } from '../../utils/convertHeic' import { isVideoFile } from '../../utils/videoPoster' import type { UploadProgress } from '../../utils/uploadQueue' @@ -40,7 +40,7 @@ export async function uploadStudioPhotos( const skippedVideos = files.length - images.length if (!images.length) return { photoIds: [], failed: 0, skippedVideos } - const normalized = await normalizeImageFiles(images) + const normalized = await normalizeJourneyPhotos(images) const store = useJourneyStore.getState() const sent = entryId != null ? await store.uploadPhotos(entryId, normalized, { onProgress }) diff --git a/client/src/store/journeyStore.test.ts b/client/src/store/journeyStore.test.ts index ba8823c88..f8e5d2f91 100644 --- a/client/src/store/journeyStore.test.ts +++ b/client/src/store/journeyStore.test.ts @@ -310,6 +310,32 @@ describe('journeyStore', () => { spy.mockRestore(); }); + it('FE-STORE-JOURNEY-013c: a converted HEIC sends the capture it held beside the file, a plain JPEG nothing (#3120)', async () => { + useJourneyStore.setState({ current: buildJourneyDetail({ id: 50, entries: [buildEntry({ id: 100, photos: [] })] }) }); + const entrySpy = vi.spyOn(journeyApi, 'uploadPhotos').mockResolvedValue({ photos: [] } as never); + const gallerySpy = vi.spyOn(journeyApi, 'uploadGalleryPhotos').mockResolvedValue({ photos: [] } as never); + const converted = Object.assign(new File(['x'], 'IMG_1.jpg', { type: 'image/jpeg' }), { + capture: { takenAt: '2026-05-30T13:52:19.000Z', lat: 64.1466, lng: -21.9426 }, + }); + const plain = new File(['x'], 'p.jpg', { type: 'image/jpeg' }); + + await useJourneyStore.getState().uploadPhotos(100, [converted]); + await useJourneyStore.getState().uploadGalleryPhotos(50, [converted, plain]); + + const sent = [entrySpy.mock.calls[0][1], ...gallerySpy.mock.calls.map(call => call[1])] as FormData[]; + const nameOf = (fd: FormData) => (fd.get('photos') as File).name; + for (const fd of sent.filter(fd => nameOf(fd) === 'IMG_1.jpg')) { + expect(fd.get('taken_at')).toBe('2026-05-30T13:52:19.000Z'); + expect(fd.get('lat')).toBe('64.1466000'); + expect(fd.get('lng')).toBe('-21.9426000'); + } + expect(sent.filter(fd => nameOf(fd) === 'IMG_1.jpg')).toHaveLength(2); + const plainSent = sent.find(fd => nameOf(fd) === 'p.jpg'); + expect(plainSent && [...plainSent.keys()]).toEqual(['photos']); + entrySpy.mockRestore(); + gallerySpy.mockRestore(); + }); + /* * A picture uploaded onto an entry is a gallery row as well: the entry only * holds a link to it. Studio's content browser reads the gallery, so without diff --git a/client/src/store/journeyStore.ts b/client/src/store/journeyStore.ts index b5b13430f..5adbce73d 100644 --- a/client/src/store/journeyStore.ts +++ b/client/src/store/journeyStore.ts @@ -2,6 +2,7 @@ import { create } from 'zustand' import { journeyApi } from '../api/client' import type { ProviderPhotosAdded } from '../api/providerPhotoBatches' import { uploadFilesResilient, type ResilientResult, type UploadProgress } from '../utils/uploadQueue' +import { captureFields } from '../utils/photoCapture' import { captureVideoPoster, isVideoFile } from '../utils/videoPoster' export interface Journey { @@ -380,6 +381,8 @@ export const useJourneyStore = create((set, get) => ({ data = await journeyApi.uploadEntryVideo(entryId, fd, opts) } else { fd.append('photos', file) + // A converted HEIC's capture time and place, which its JPEG lost (#3120). + for (const [name, value] of captureFields(file)) fd.append(name, value) data = await journeyApi.uploadPhotos(entryId, fd, opts) } const photos: JourneyPhoto[] = data.photos || [] @@ -418,6 +421,7 @@ export const useJourneyStore = create((set, get) => ({ data = await journeyApi.uploadGalleryVideo(journeyId, fd, opts) } else { fd.append('photos', file) + for (const [name, value] of captureFields(file)) fd.append(name, value) data = await journeyApi.uploadGalleryPhotos(journeyId, fd, opts) } const photos: GalleryPhoto[] = data.photos || [] diff --git a/client/src/utils/convertHeic.test.ts b/client/src/utils/convertHeic.test.ts index e16bd7e8b..761f878f4 100644 --- a/client/src/utils/convertHeic.test.ts +++ b/client/src/utils/convertHeic.test.ts @@ -1,19 +1,24 @@ -// FE-W4HEIC-001 to FE-W4HEIC-007 +// FE-W4HEIC-001 to FE-W4HEIC-010 import { describe, it, expect, vi, beforeEach } from 'vitest' const isHeic = vi.fn(async (_f: File) => true) const heicTo = vi.fn(async (_opts: unknown) => new Blob(['jpeg'], { type: 'image/jpeg' })) +const readHeicCapture = vi.fn(async (_f: Blob): Promise => null) vi.mock('heic-to', () => ({ isHeic: (f: File) => isHeic(f), heicTo: (opts: unknown) => heicTo(opts), })) -import { normalizeImageFile, normalizeImageFiles } from './convertHeic' +vi.mock('./heicCapture', () => ({ readHeicCapture: (f: Blob) => readHeicCapture(f) })) + +import { normalizeImageFile, normalizeJourneyPhotos } from './convertHeic' +import { captureFields, type CapturedFile } from './photoCapture' beforeEach(() => { isHeic.mockClear() heicTo.mockClear() + readHeicCapture.mockReset().mockResolvedValue(null) isHeic.mockResolvedValue(true) }) @@ -58,12 +63,14 @@ describe('normalizeImageFile', () => { }) }) -describe('normalizeImageFiles', () => { +describe('normalizeJourneyPhotos', () => { + const capture = { takenAt: '2026-05-30T13:52:19.000Z', lat: 64.1466, lng: -21.9426 } + it('FE-W4HEIC-006: normalizes a mixed list and keeps the order', async () => { const jpg = new File(['x'], 'a.jpg', { type: 'image/jpeg' }) const heic = new File(['x'], 'b.heic') - const out = await normalizeImageFiles([jpg, heic]) + const out = await normalizeJourneyPhotos([jpg, heic]) expect(out).toHaveLength(2) expect(out[0]).toBe(jpg) @@ -74,6 +81,40 @@ describe('normalizeImageFiles', () => { const jpg = new File(['x'], 'a.jpg', { type: 'image/jpeg' }) const fakeList = { 0: jpg, length: 1 } as unknown as FileList - await expect(normalizeImageFiles(fakeList)).resolves.toEqual([jpg]) + await expect(normalizeJourneyPhotos(fakeList)).resolves.toEqual([jpg]) + }) + + it('FE-W4HEIC-008: a HEIC keeps its capture time and place on the converted file (#3120)', async () => { + readHeicCapture.mockResolvedValue(capture) + const heic = new File(['x'], 'IMG_1.HEIC') + + const [out] = await normalizeJourneyPhotos([heic]) + + expect(readHeicCapture).toHaveBeenCalledWith(heic) + expect((out as CapturedFile).capture).toEqual(capture) + expect(captureFields(out)).toEqual([ + ['taken_at', '2026-05-30T13:52:19.000Z'], + ['lat', '64.1466000'], + ['lng', '-21.9426000'], + ]) + }) + + it('FE-W4HEIC-009: a JPEG is never read, and a HEIC without capture data carries none', async () => { + const jpg = new File(['x'], 'a.jpg', { type: 'image/jpeg' }) + const [plain] = await normalizeJourneyPhotos([jpg]) + expect(readHeicCapture).not.toHaveBeenCalled() + expect(captureFields(plain)).toEqual([]) + + const [heic] = await normalizeJourneyPhotos([new File(['x'], 'b.heic')]) + expect((heic as CapturedFile).capture).toBeUndefined() + }) + + it('FE-W4HEIC-010: a cover or place image never carries a capture, a location least of all', async () => { + readHeicCapture.mockResolvedValue(capture) + + const out = await normalizeImageFile(new File(['x'], 'cover.heic')) + + expect(readHeicCapture).not.toHaveBeenCalled() + expect(captureFields(out)).toEqual([]) }) }) diff --git a/client/src/utils/convertHeic.ts b/client/src/utils/convertHeic.ts index 6f757792e..52577cfb0 100644 --- a/client/src/utils/convertHeic.ts +++ b/client/src/utils/convertHeic.ts @@ -1,17 +1,45 @@ +import type { CapturedFile } from './photoCapture' + function looksLikeHeic(file: File): boolean { const ext = file.name.split('.').pop()?.toLowerCase() ?? '' return ext === 'heic' || ext === 'heif' || file.type === 'image/heic' || file.type === 'image/heif' } -export async function normalizeImageFile(file: File): Promise { - if (!looksLikeHeic(file)) return file +/** The HEIC as a JPEG, or null when the bytes are not a HEIC after all. */ +async function convertHeic(file: File): Promise { const { isHeic, heicTo } = await import('heic-to') - if (!(await isHeic(file))) return file + if (!(await isHeic(file))) return null const blob = await heicTo({ blob: file, type: 'image/jpeg', quality: 0.92 }) const jpegName = file.name.replace(/\.(heic|heif)$/i, '.jpg') return new File([blob], jpegName, { type: 'image/jpeg' }) } -export async function normalizeImageFiles(files: FileList | File[]): Promise { - return Promise.all(Array.from(files).map(normalizeImageFile)) +/** + * A HEIC turned into a JPEG, anything else as it is. The JPEG carries no EXIF, so + * covers and place images, which go through here, never take a location along. + */ +export async function normalizeImageFile(file: File): Promise { + if (!looksLikeHeic(file)) return file + return (await convertHeic(file)) ?? file +} + +/** + * A journey photo made ready to upload. A HEIC is converted like any other image, + * but its capture time and place are read first and travel on the converted file + * (`capture`), since the conversion drops them; the upload hands them to the server, + * which keeps them where the file itself has none. Only journey photos do this: + * their place is what the journey map shows. + */ +async function normalizeJourneyPhoto(file: File): Promise { + if (!looksLikeHeic(file)) return file + const { readHeicCapture } = await import('./heicCapture') + const capture = await readHeicCapture(file) + const converted: CapturedFile | null = await convertHeic(file) + if (!converted) return file + if (capture) converted.capture = capture + return converted +} + +export async function normalizeJourneyPhotos(files: FileList | File[]): Promise { + return Promise.all(Array.from(files).map(normalizeJourneyPhoto)) } diff --git a/client/src/utils/heicCapture.test.ts b/client/src/utils/heicCapture.test.ts new file mode 100644 index 000000000..d3fddc2e6 --- /dev/null +++ b/client/src/utils/heicCapture.test.ts @@ -0,0 +1,181 @@ +// FE-HEICCAP-001 to FE-HEICCAP-007 +import { describe, expect, it } from 'vitest'; +import { captureInstant, readHeicCapture } from './heicCapture'; + +type Dms = [number, number, number]; + +interface TiffFields { + stamp?: string; + zone?: string; + lat?: Dms; + latRef?: string; + lng?: Dms; + lngRef?: string; +} + +/** An EXIF TIFF block with an EXIF and a GPS directory, in either byte order. */ +function buildTiff(little: boolean, fields: TiffFields): Uint8Array { + const buffer = new ArrayBuffer(512); + const view = new DataView(buffer); + const u16 = (at: number, value: number) => view.setUint16(at, value, little); + const u32 = (at: number, value: number) => view.setUint32(at, value, little); + let data = 300; + const text = (value: string) => { + const at = data; + [...value].forEach((c, i) => view.setUint8(at + i, c.charCodeAt(0))); + view.setUint8(at + value.length, 0); + data += value.length + 1; + return at; + }; + const rational = (dms: Dms) => { + const at = data; + dms.forEach((part, i) => { + u32(at + i * 8, Math.round(part * 1000)); + u32(at + i * 8 + 4, 1000); + }); + data += 24; + return at; + }; + const entry = (at: number, tag: number, type: number, count: number, value: number) => { + u16(at, tag); + u16(at + 2, type); + u32(at + 4, count); + u32(at + 8, value); + }; + view.setUint16(0, little ? 0x4949 : 0x4d4d); + u16(2, 42); + u32(4, 8); + // IFD0: the pointers to the EXIF (at 40) and GPS (at 120) directories. + u16(8, 2); + entry(10, 0x8769, 4, 1, 40); + entry(22, 0x8825, 4, 1, 120); + const exif: Array<[number, string]> = []; + if (fields.stamp) exif.push([0x9003, fields.stamp]); + if (fields.zone) exif.push([0x9011, fields.zone]); + u16(40, exif.length); + exif.forEach(([tag, value], i) => entry(42 + i * 12, tag, 2, value.length + 1, text(value))); + const inlineRef = (at: number, tag: number, ref: string) => { + entry(at, tag, 2, 2, 0); + view.setUint8(at + 8, ref.charCodeAt(0)); + }; + u16(120, fields.lat && fields.lng ? 4 : 0); + if (fields.lat && fields.lng) { + inlineRef(122, 0x0001, fields.latRef ?? 'N'); + entry(134, 0x0002, 5, 3, rational(fields.lat)); + inlineRef(146, 0x0003, fields.lngRef ?? 'E'); + entry(158, 0x0004, 5, 3, rational(fields.lng)); + } + return new Uint8Array(buffer); +} + +function concat(...parts: Uint8Array[]): Uint8Array { + const out = new Uint8Array(parts.reduce((sum, part) => sum + part.length, 0)); + let at = 0; + for (const part of parts) { + out.set(part, at); + at += part.length; + } + return out; +} + +function bytes(...values: Array<[number, number]>): Uint8Array { + const out = new Uint8Array(values.reduce((sum, [, size]) => sum + size, 0)); + const view = new DataView(out.buffer); + let at = 0; + for (const [value, size] of values) { + if (size === 1) view.setUint8(at, value); + else if (size === 2) view.setUint16(at, value); + else view.setUint32(at, value); + at += size; + } + return out; +} + +const ascii = (value: string) => new Uint8Array([...value].map((c) => c.charCodeAt(0))); + +function box(type: string, ...parts: Uint8Array[]): Uint8Array { + const body = concat(...parts); + return concat(bytes([body.length + 8, 4]), ascii(type), body); +} + +/** A HEIC whose meta box names one Exif item and places it in the mdat. */ +function buildHeic(tiff: Uint8Array, itemType = 'Exif'): Blob { + const item = concat(bytes([6, 4]), ascii('Exif\0\0'), tiff); + const ftyp = box('ftyp', ascii('heic'), bytes([0, 4]), ascii('mif1heic')); + // infe version 2: item 1, no protection, of the given type, with an empty name. + const infe = box('infe', bytes([2 << 24, 4], [1, 2], [0, 2]), ascii(itemType), ascii('\0')); + // iloc version 0: four-byte offsets and lengths, no base offset, one item in one extent. + const iloc = (offset: number) => + box('iloc', bytes([0, 4], [0x44, 1], [0, 1], [1, 2], [1, 2], [0, 2], [1, 2], [offset, 4], [item.length, 4])); + const hdlr = box('hdlr', bytes([0, 4], [0, 4]), ascii('pict'), new Uint8Array(13)); + const iinf = box('iinf', bytes([0, 4], [1, 2]), infe); + const meta = (offset: number) => box('meta', bytes([0, 4]), hdlr, iinf, iloc(offset)); + const at = ftyp.length + meta(0).length + 8; + return new Blob([concat(ftyp, meta(at), box('mdat', item))]); +} + +describe('readHeicCapture', () => { + it('FE-HEICCAP-001: reads the capture time with its zone and the place, south and west signed', async () => { + const tiff = buildTiff(false, { + stamp: '2026:05:30 15:52:19', + zone: '+02:00', + lat: [64, 8, 47.76], + latRef: 'S', + lng: [21, 56, 33.36], + lngRef: 'W', + }); + + const capture = await readHeicCapture(buildHeic(tiff)); + + expect(capture?.takenAt).toBe('2026-05-30T13:52:19.000Z'); + expect(capture?.lat).toBeCloseTo(-64.1466, 4); + expect(capture?.lng).toBeCloseTo(-21.9426, 4); + }); + + it('FE-HEICCAP-002: reads a little-endian block, and a stamp without a zone as this device local time', async () => { + const tiff = buildTiff(true, { stamp: '2026:01:02 03:04:05', lat: [48, 51, 30], lng: [2, 17, 40] }); + + const capture = await readHeicCapture(buildHeic(tiff)); + + expect(capture?.takenAt).toBe(new Date(2026, 0, 2, 3, 4, 5).toISOString()); + expect(capture?.lat).toBeCloseTo(48.858333, 5); + expect(capture?.lng).toBeCloseTo(2.294444, 5); + }); + + it('FE-HEICCAP-003: the 0,0 of a receiver without a fix is no place, the time still counts', async () => { + const tiff = buildTiff(false, { stamp: '2026:05:30 15:52:19', zone: '+00:00', lat: [0, 0, 0], lng: [0, 0, 0] }); + + expect(await readHeicCapture(buildHeic(tiff))).toEqual({ + takenAt: '2026-05-30T15:52:19.000Z', + lat: null, + lng: null, + }); + }); + + it('FE-HEICCAP-004: a HEIC with neither time nor place, or without an Exif item, reads as nothing', async () => { + expect(await readHeicCapture(buildHeic(buildTiff(false, {})))).toBeNull(); + const tiff = buildTiff(false, { stamp: '2026:05:30 15:52:19' }); + expect(await readHeicCapture(buildHeic(tiff, 'mime'))).toBeNull(); + }); + + it('FE-HEICCAP-005: a file that is no HEIC, or is cut short, reads as nothing rather than failing', async () => { + expect(await readHeicCapture(new Blob(['not a heic at all']))).toBeNull(); + const whole = buildHeic(buildTiff(false, { stamp: '2026:05:30 15:52:19' })); + const cut = whole.slice(0, whole.size - 200); + expect(await readHeicCapture(cut)).toBeNull(); + }); +}); + +describe('captureInstant', () => { + it('FE-HEICCAP-006: applies a negative zone, and refuses a zone that is out of range', () => { + expect(captureInstant('2026:05:30 15:52:19', '-05:30')).toBe('2026-05-30T21:22:19.000Z'); + expect(captureInstant('2026:05:30 15:52:19', '+15:00')).toBe(new Date(2026, 4, 30, 15, 52, 19).toISOString()); + }); + + it('FE-HEICCAP-007: a stamp that is not a real moment is null', () => { + expect(captureInstant('2026:02:30 10:00:00', null)).toBeNull(); + expect(captureInstant('0000:00:00 00:00:00', null)).toBeNull(); + expect(captureInstant('yesterday', null)).toBeNull(); + expect(captureInstant(null, '+02:00')).toBeNull(); + }); +}); diff --git a/client/src/utils/heicCapture.ts b/client/src/utils/heicCapture.ts new file mode 100644 index 000000000..9f8e3c19f --- /dev/null +++ b/client/src/utils/heicCapture.ts @@ -0,0 +1,313 @@ +/** + * When and where an iPhone photo was taken, read from the HEIC itself. + * + * The browser has to turn a HEIC into a JPEG before it can go up (convertHeic.ts), + * and the JPEG that comes out carries no EXIF, so the capture time and the place + * were lost on the way (#3120). This reads them from the HEIC first, so the upload + * can hand them to the server beside the converted file. + * + * A tiny reader rather than a library: it needs three tags, and the EXIF parsers + * that read HEIC weigh tens of kilobytes. It only ever reads what it is asked for: + * the boxes at the head of the file that say where the EXIF item lies, then that + * item. Anything it does not understand reads as "nothing found", never an error, + * so a photo always uploads. + * + * The orientation is not carried over: the conversion applies the HEIC's own + * rotation, so the JPEG already stands upright. + */ + +export interface PhotoCapture { + /** The capture instant as an ISO string. */ + takenAt: string | null; + lat: number | null; + lng: number | null; +} + +/** The boxes that say where the EXIF lies sit at the front; this is far more than they take. */ +const HEAD_BYTES = 1024 * 1024; +/** An EXIF block is a few kilobytes; one larger than this is not what it claims. */ +const EXIF_MAX_BYTES = 256 * 1024; + +const TAG_EXIF_IFD = 0x8769; +const TAG_GPS_IFD = 0x8825; +const TAG_DATE_TIME_ORIGINAL = 0x9003; +const TAG_OFFSET_TIME_ORIGINAL = 0x9011; +const TAG_GPS_LAT_REF = 0x0001; +const TAG_GPS_LAT = 0x0002; +const TAG_GPS_LNG_REF = 0x0003; +const TAG_GPS_LNG = 0x0004; + +interface Box { + type: string; + /** Where the box's content starts, past its header. */ + body: number; + end: number; +} + +function fourcc(view: DataView, at: number): string { + return String.fromCharCode(view.getUint8(at), view.getUint8(at + 1), view.getUint8(at + 2), view.getUint8(at + 3)); +} + +/** The boxes laid one after the other between two offsets; a box cut off by the end closes the list. */ +function boxesIn(view: DataView, from: number, to: number): Box[] { + const boxes: Box[] = []; + let at = from; + while (at + 8 <= to) { + let size = view.getUint32(at); + let header = 8; + if (size === 1) { + if (at + 16 > to) break; + size = view.getUint32(at + 8) * 2 ** 32 + view.getUint32(at + 12); + header = 16; + } else if (size === 0) { + size = to - at; + } + if (size < header) break; + boxes.push({ type: fourcc(view, at + 4), body: at + header, end: Math.min(at + size, to) }); + at += size; + } + return boxes; +} + +/** An unsigned number of 0, 2, 4 or 8 bytes, as the iloc box sizes them. */ +function uint(view: DataView, at: number, bytes: number): number | null { + if (bytes === 0) return 0; + if (bytes === 2) return view.getUint16(at); + if (bytes === 4) return view.getUint32(at); + if (bytes === 8) return view.getUint32(at) * 2 ** 32 + view.getUint32(at + 4); + return null; +} + +/** The item id of the EXIF block, from the item info box. */ +function exifItemId(view: DataView, iinf: Box): number | null { + const version = view.getUint8(iinf.body); + const first = iinf.body + 4 + (version === 0 ? 2 : 4); + for (const infe of boxesIn(view, first, iinf.end)) { + if (infe.type !== 'infe') continue; + const infeVersion = view.getUint8(infe.body); + if (infeVersion < 2) continue; + const wide = infeVersion >= 3; + const id = wide ? view.getUint32(infe.body + 4) : view.getUint16(infe.body + 4); + const typeAt = infe.body + 4 + (wide ? 4 : 2) + 2; + if (fourcc(view, typeAt) === 'Exif') return id; + } + return null; +} + +/** How the item location box sizes its fields, which depends on its version. */ +interface IlocLayout { + offsetSize: number; + lengthSize: number; + baseOffsetSize: number; + indexSize: number; + /** Version 2 writes item ids in four bytes, the older ones in two. */ + wideIds: boolean; + /** Versions 1 and 2 say how each item is stored. */ + hasMethod: boolean; +} + +interface IlocItem { + id: number; + /** The item's bytes when they lie in the file in one piece (method 0, one extent), else null. */ + extent: { offset: number; length: number } | null; + /** Where the next item starts. */ + next: number; +} + +function readIlocItem(view: DataView, start: number, layout: IlocLayout): IlocItem { + let at = start; + const id = layout.wideIds ? view.getUint32(at) : view.getUint16(at); + at += layout.wideIds ? 4 : 2; + const method = layout.hasMethod ? view.getUint16(at) & 15 : 0; + at += (layout.hasMethod ? 2 : 0) + 2; // construction_method, data_reference_index + const base = uint(view, at, layout.baseOffsetSize); + at += layout.baseOffsetSize; + const extents = view.getUint16(at); + at += 2; + let extent: IlocItem['extent'] = null; + for (let i = 0; i < extents; i++) { + at += layout.indexSize; + const offset = uint(view, at, layout.offsetSize); + const length = uint(view, at + layout.offsetSize, layout.lengthSize); + at += layout.offsetSize + layout.lengthSize; + const whole = method === 0 && extents === 1 && base !== null && offset !== null && length !== null; + if (whole) extent = { offset: base + offset, length }; + } + return { id, extent, next: at }; +} + +/** Where in the file an item's bytes lie, from the item location box; null unless they lie there in one piece. */ +function itemExtent(view: DataView, iloc: Box, itemId: number): { offset: number; length: number } | null { + const version = view.getUint8(iloc.body); + const sizes = view.getUint8(iloc.body + 4); + const more = view.getUint8(iloc.body + 5); + const hasMethod = version === 1 || version === 2; + const layout: IlocLayout = { + offsetSize: sizes >> 4, + lengthSize: sizes & 15, + baseOffsetSize: more >> 4, + indexSize: hasMethod ? more & 15 : 0, + wideIds: version >= 2, + hasMethod, + }; + const countAt = iloc.body + 6; + const count = layout.wideIds ? view.getUint32(countAt) : view.getUint16(countAt); + let at = countAt + (layout.wideIds ? 4 : 2); + for (let i = 0; i < count; i++) { + const item = readIlocItem(view, at, layout); + if (item.id === itemId) return item.extent; + at = item.next; + } + return null; +} + +/** Reads the TIFF structure of an EXIF block: its byte order, its offsets and its values. */ +class Tiff { + private readonly little: boolean; + + constructor( + private readonly view: DataView, + private readonly start: number + ) { + this.little = view.getUint16(start) === 0x4949; + } + + u16(at: number): number { + return this.view.getUint16(this.start + at, this.little); + } + + u32(at: number): number { + return this.view.getUint32(this.start + at, this.little); + } + + /** The tags of one directory, by tag number, each as the offset of its 12-byte entry. */ + entries(ifd: number): Map { + const tags = new Map(); + const count = this.u16(ifd); + for (let i = 0; i < count; i++) { + const entry = ifd + 2 + i * 12; + tags.set(this.u16(entry), entry); + } + return tags; + } + + ascii(entry: number | undefined): string | null { + if (entry === undefined || this.u16(entry + 2) !== 2) return null; + const count = this.u32(entry + 4); + if (count > 64) return null; + const at = count <= 4 ? entry + 8 : this.u32(entry + 8); + let text = ''; + for (let i = 0; i < count; i++) { + const code = this.view.getUint8(this.start + at + i); + if (code === 0) break; + text += String.fromCharCode(code); + } + return text; + } + + /** Degrees, minutes and seconds as three RATIONALs, in decimal degrees. */ + degrees(entry: number | undefined): number | null { + if (entry === undefined || this.u16(entry + 2) !== 5 || this.u32(entry + 4) !== 3) return null; + const at = this.u32(entry + 8); + const parts = [0, 1, 2].map((i) => { + const denominator = this.u32(at + i * 8 + 4); + return denominator === 0 ? Number.NaN : this.u32(at + i * 8) / denominator; + }); + const value = parts[0] + parts[1] / 60 + parts[2] / 3600; + return Number.isFinite(value) ? value : null; + } + + pointer(tags: Map, tag: number): number | null { + const entry = tags.get(tag); + return entry === undefined ? null : this.u32(entry + 8); + } +} + +const EXIF_STAMP = /^(\d{4}):(\d{2}):(\d{2}) (\d{2}):(\d{2}):(\d{2})$/; +const EXIF_ZONE = /^([+-])(\d{2}):(\d{2})$/; + +/** + * The instant an EXIF wall-clock stamp names, with the zone the camera wrote + * beside it, or in this device's zone without one (the phone the photo comes + * from is the best guess there is). Null for a stamp that is not a real moment. + */ +export function captureInstant(stamp: string | null, zone: string | null): string | null { + const m = stamp ? EXIF_STAMP.exec(stamp.trim()) : null; + if (!m) return null; + const [year, month, day, hour, minute, second] = m.slice(1, 7).map(Number); + const wall = new Date(Date.UTC(year, month - 1, day, hour, minute, second)); + const real = + wall.getUTCFullYear() === year && + wall.getUTCMonth() === month - 1 && + wall.getUTCDate() === day && + wall.getUTCHours() === hour && + wall.getUTCMinutes() === minute && + wall.getUTCSeconds() === second; + if (!real || year < 1900) return null; + const z = zone ? EXIF_ZONE.exec(zone.trim()) : null; + if (z && Number(z[2]) <= 14 && Number(z[3]) <= 59) { + const minutes = (z[1] === '-' ? -1 : 1) * (Number(z[2]) * 60 + Number(z[3])); + return new Date(wall.getTime() - minutes * 60000).toISOString(); + } + return new Date(year, month - 1, day, hour, minute, second).toISOString(); +} + +/** The capture time and place in an EXIF block that starts with its TIFF header at `start`. */ +function readTiff(view: DataView, start: number): PhotoCapture { + const tiff = new Tiff(view, start); + const ifd0 = tiff.entries(tiff.u32(4)); + const exifIfd = tiff.pointer(ifd0, TAG_EXIF_IFD); + const exif = exifIfd === null ? new Map() : tiff.entries(exifIfd); + const takenAt = captureInstant( + tiff.ascii(exif.get(TAG_DATE_TIME_ORIGINAL)), + tiff.ascii(exif.get(TAG_OFFSET_TIME_ORIGINAL)) + ); + const gpsIfd = tiff.pointer(ifd0, TAG_GPS_IFD); + const gps = gpsIfd === null ? new Map() : tiff.entries(gpsIfd); + const latitude = tiff.degrees(gps.get(TAG_GPS_LAT)); + const longitude = tiff.degrees(gps.get(TAG_GPS_LNG)); + const lat = latitude === null ? null : tiff.ascii(gps.get(TAG_GPS_LAT_REF)) === 'S' ? -latitude : latitude; + const lng = longitude === null ? null : tiff.ascii(gps.get(TAG_GPS_LNG_REF)) === 'W' ? -longitude : longitude; + // A pair or nothing, inside the globe, and not the 0,0 a receiver without a fix writes. + const place = lat !== null && lng !== null && Math.abs(lat) <= 90 && Math.abs(lng) <= 180 && (lat !== 0 || lng !== 0); + return { takenAt, lat: place ? lat : null, lng: place ? lng : null }; +} + +/** Where the TIFF header starts in an EXIF item: after the offset its first four bytes name. */ +function tiffStart(view: DataView): number | null { + const named = 4 + view.getUint32(0); + const isHeader = (at: number) => + at + 8 <= view.byteLength && (view.getUint32(at) === 0x49492a00 || view.getUint32(at) === 0x4d4d002a); + if (isHeader(named)) return named; + // Some writers leave the offset at 0 and put "Exif\0\0" before the header anyway. + return isHeader(10) ? 10 : null; +} + +/** + * When and where a HEIC photo was taken, or null when the file holds neither, + * or is not a HEIC this reader understands. + */ +export async function readHeicCapture(file: Blob): Promise { + try { + const head = new DataView(await file.slice(0, HEAD_BYTES).arrayBuffer()); + const meta = boxesIn(head, 0, head.byteLength).find((box) => box.type === 'meta'); + if (!meta) return null; + const children = boxesIn(head, meta.body + 4, meta.end); + const iinf = children.find((box) => box.type === 'iinf'); + const iloc = children.find((box) => box.type === 'iloc'); + if (!iinf || !iloc) return null; + const id = exifItemId(head, iinf); + const extent = id === null ? null : itemExtent(head, iloc, id); + if (!extent || extent.length < 12 || extent.length > EXIF_MAX_BYTES || extent.offset + extent.length > file.size) { + return null; + } + const exif = new DataView(await file.slice(extent.offset, extent.offset + extent.length).arrayBuffer()); + const start = tiffStart(exif); + if (start === null) return null; + const capture = readTiff(exif, start); + return capture.takenAt || capture.lat !== null ? capture : null; + } catch { + // A truncated or foreign file reads past its end: nothing to carry over. + return null; + } +} diff --git a/client/src/utils/photoCapture.ts b/client/src/utils/photoCapture.ts new file mode 100644 index 000000000..2491dbe71 --- /dev/null +++ b/client/src/utils/photoCapture.ts @@ -0,0 +1,21 @@ +import type { PhotoCapture } from './heicCapture'; + +/** A converted journey photo, carrying the capture time and place its HEIC held (#3120). */ +export type CapturedFile = File & { capture?: PhotoCapture }; + +/** + * The capture fields a journey photo upload sends beside the file: `taken_at` as + * an ISO instant, `lat` and `lng` as a pair. Nothing for a file that brought none, + * which is every file but a converted HEIC: a JPEG keeps its own EXIF. + */ +export function captureFields(file: File): Array<[string, string]> { + const capture = (file as CapturedFile).capture; + if (!capture) return []; + const fields: Array<[string, string]> = []; + if (capture.takenAt) fields.push(['taken_at', capture.takenAt]); + if (capture.lat !== null && capture.lng !== null) { + // Seven decimals are a centimetre: plenty for a photo, and never an exponent. + fields.push(['lat', capture.lat.toFixed(7)], ['lng', capture.lng.toFixed(7)]); + } + return fields; +} diff --git a/client/tests/unit/studio/studioUpload.test.ts b/client/tests/unit/studio/studioUpload.test.ts index c025ebb20..bd8db7c79 100644 --- a/client/tests/unit/studio/studioUpload.test.ts +++ b/client/tests/unit/studio/studioUpload.test.ts @@ -17,7 +17,7 @@ import { uploadStudioPhotos } from '../../../src/components/Studio/studioUpload' vi.mock('../../../src/utils/convertHeic', () => ({ // The real one decodes HEIC through a worker. What matters here is that the // files reach the store, not how they were converted on the way. - normalizeImageFiles: vi.fn(async (files: File[]) => files), + normalizeJourneyPhotos: vi.fn(async (files: File[]) => files), })) const jpeg = (name = 'shrine.jpg') => new File(['x'], name, { type: 'image/jpeg' }) diff --git a/server/src/nest/journey/journey-capture-hint.ts b/server/src/nest/journey/journey-capture-hint.ts new file mode 100644 index 000000000..7f3c4fcac --- /dev/null +++ b/server/src/nest/journey/journey-capture-hint.ts @@ -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 }; +} diff --git a/server/src/nest/journey/journey-photo-capture.service.ts b/server/src/nest/journey/journey-photo-capture.service.ts index 87701d1ca..ad522e8c0 100644 --- a/server/src/nest/journey/journey-photo-capture.service.ts +++ b/server/src/nest/journey/journey-photo-capture.service.ts @@ -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), ); } diff --git a/server/src/nest/journey/journey.controller.ts b/server/src/nest/journey/journey.controller.ts index e0852f851..df4d75288 100644 --- a/server/src/nest/journey/journey.controller.ts +++ b/server/src/nest/journey/journey.controller.ts @@ -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 }; } diff --git a/server/src/nest/journey/journey.dto.ts b/server/src/nest/journey/journey.dto.ts index 47bcea8e4..be45466f0 100644 --- a/server/src/nest/journey/journey.dto.ts +++ b/server/src/nest/journey/journey.dto.ts @@ -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. */ diff --git a/server/src/nest/memories/photo-capture-backfill.service.ts b/server/src/nest/memories/photo-capture-backfill.service.ts index 08fec55c9..0a2f3989a 100644 --- a/server/src/nest/memories/photo-capture-backfill.service.ts +++ b/server/src/nest/memories/photo-capture-backfill.service.ts @@ -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>; 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 { + async run(trekPhotoIds: number[], userId: number, hints?: ReadonlyMap): Promise { let next = 0; let changed = false; const worker = async (): Promise => { 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 { + private async fillOne(id: number, userId: number, hint?: CaptureHint): Promise { 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; } diff --git a/server/tests/integration/journey.test.ts b/server/tests/integration/journey.test.ts index 14c2d505a..db8711ba5 100644 --- a/server/tests/integration/journey.test.ts +++ b/server/tests/integration/journey.test.ts @@ -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, + }); + }); }); }); diff --git a/server/tests/unit/nest/journey-capture-hint.test.ts b/server/tests/unit/nest/journey-capture-hint.test.ts new file mode 100644 index 000000000..dffa06944 --- /dev/null +++ b/server/tests/unit/nest/journey-capture-hint.test.ts @@ -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 }); + } + }); +}); diff --git a/server/tests/unit/nest/journey-photo-capture.service.test.ts b/server/tests/unit/nest/journey-photo-capture.service.test.ts index 218277f82..e5e6c61b1 100644 --- a/server/tests/unit/nest/journey-photo-capture.service.test.ts +++ b/server/tests/unit/nest/journey-photo-capture.service.test.ts @@ -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([ diff --git a/server/tests/unit/nest/photo-capture-backfill.service.test.ts b/server/tests/unit/nest/photo-capture-backfill.service.test.ts index bebb4bffd..353ae154a 100644 --- a/server/tests/unit/nest/photo-capture-backfill.service.test.ts +++ b/server/tests/unit/nest/photo-capture-backfill.service.test.ts @@ -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' }]); diff --git a/shared/src/journey/journey.schema.ts b/shared/src/journey/journey.schema.ts index 5cd9c7cb1..4f7b3899d 100644 --- a/shared/src/journey/journey.schema.ts +++ b/shared/src/journey/journey.schema.ts @@ -374,13 +374,34 @@ export type JourneyEntryUpdateRequest = z.infer; + export const journeyEntryPhotoUploadRequestSchema = z .looseObject({ caption: z.unknown().optional(), + ...journeyPhotoCaptureFieldsSchema.shape, }) .optional(); export type JourneyEntryPhotoUploadRequest = z.infer; +/** The text fields beside a gallery photo upload: only its capture hint. Absent body, as above. */ +export const journeyGalleryPhotoUploadRequestSchema = journeyPhotoCaptureFieldsSchema.optional(); +export type JourneyGalleryPhotoUploadRequest = z.infer; + /** Multipart field alongside the uploaded video — absent body for the same reason. */ export const journeyGalleryVideoRequestSchema = z .looseObject({