mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-30 16:33:16 +00:00
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:
@@ -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<NonNullable<Window['__addToast']>>;
|
||||
|
||||
@@ -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, {
|
||||
|
||||
@@ -20,7 +20,7 @@ vi.mock('../../hooks/useGeolocation', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('../../hooks/useGeolocation')>()),
|
||||
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() }),
|
||||
}));
|
||||
|
||||
@@ -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]);
|
||||
};
|
||||
|
||||
|
||||
@@ -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 })
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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<JourneyState>((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<JourneyState>((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 || []
|
||||
|
||||
@@ -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<unknown> => 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([])
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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<File> {
|
||||
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<File | null> {
|
||||
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<File[]> {
|
||||
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<File> {
|
||||
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<CapturedFile> {
|
||||
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<CapturedFile[]> {
|
||||
return Promise.all(Array.from(files).map(normalizeJourneyPhoto))
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -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<number, number> {
|
||||
const tags = new Map<number, number>();
|
||||
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<number, number>, 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<number, number>() : 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<number, number>() : 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<PhotoCapture | null> {
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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' })
|
||||
|
||||
Reference in New Issue
Block a user