All files / lib exif.ts

81.48% Statements 88/108
70.73% Branches 58/82
94.11% Functions 16/17
86.36% Lines 76/88

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274                                            2x 2x       2x 2x     2x 6x     2x                             2x   2x   2x 2x 3x                                   5x   5x 5x   5x                   4x 2x   2x                               9x   9x             2x   5x     15x       15x                         23x   6x           8x 8x 1x 7x 6x     1x     2x 1x       6x                     19x   15x 10x 9x 8x 7x 1x 4x     6x               2x               2x   6x 6x 4x 6x   4x             2x 2x 2x           2x 2x 2x         2x       2x       2x   2x 2x     2x   2x 10x     10x           10x   10x 10x 10x 8x 8x     2x   2x 2x            
import type * as DB from './database.js';
import type { ExifFieldKey } from './exiffields.js';
 
import { match, type } from 'arktype';
import * as dates from 'date-fns';
import * as exifParser from 'exif-parser';
import piexif from 'piexifjs';
 
import { Schemas } from './database.js';
import { EXIF_FIELDS } from './exiffields.js';
import { errorMessage } from './i18n.js';
import * as db from './idb.svelte.js';
import { resolveMetadataImport, storeMetadataValue } from './metadata/index.js';
import { toasts } from './toasts.svelte.js';
import { byteString, byteStringToArray } from './utils.js';
 
export async function processExifData(
	sessionId: string,
	imageFileId: string,
	imageBytes: ArrayBuffer | Buffer,
	file: { type: string; name: string }
) {
	const session = await db.tables.Session.get(sessionId);
	Iif (!session) {
		throw new Error(`Session ${sessionId} introuvable`);
	}
 
	const protocol = await db.tables.Protocol.get(session.protocol);
	Iif (!protocol) {
		throw new Error(`Protocole ${session.protocol} introuvable`);
	}
	const metadataOfProtocol = await db.tables.Metadata.getMany(
		protocol.metadata.map((key) => resolveMetadataImport(protocol, key))
	);
 
	const metadataFromExif = await extractMetadata(
		// 2^16 + 100 of margin
		// see https://www.npmjs.com/package/exif-parser#creating-a-parser
		imageBytes.slice(0, 2 ** 16 + 100),
		metadataOfProtocol ?? []
	).catch((e) => {
		console.warn(e);
		if (file.type === 'image/jpeg') {
			toasts.warn(
				`Impossible d'extraire les métadonnées EXIF de ${file.name}: ${e?.toString() ?? 'Erreur inattendue'}`
			);
		}
		return {};
	});
 
	const images = await db
		.listByIndex('Image', 'sessionId', sessionId)
		.then((imgs) => imgs.filter((img) => img.fileId === imageFileId));
 
	for (const { id: subjectId } of images) {
		for (const [key, { value, confidence }] of Object.entries(metadataFromExif)) {
			await storeMetadataValue({
				db: db.databaseHandle(),
				subjectId,
				sessionId: session.id,
				metadataId: key,
				value,
				confidence,
			});
		}
	}
}
 
type ExifExtractionPlanItem = Pick<DB.Metadata, 'id' | 'infer' | 'type'>;
 
export async function extractMetadata(
	buffer: ArrayBuffer | Buffer,
	extractionPlan: ExifExtractionPlanItem[]
): Promise<Record<string, { value: unknown; confidence: number; alternatives: unknown[] }>> {
	const exif = exifParser.create(buffer).enableImageSize(false).parse();
 
	Iif (!exif) return {};
	console.debug('Starting EXIF Extraction', { extractionPlan, exif });
 
	const extract = match
		.case(
			{
				type: '"location"',
				infer: {
					latitude: { exif: 'string' },
					longitude: { exif: 'string' },
				},
			},
			({ infer }) => {
				if (!(infer.longitude.exif in exif.tags)) return undefined;
				Iif (!(infer.latitude.exif in exif.tags)) return undefined;
 
				return {
					confidence: 1,
					alternatives: [],
					value: {
						longitude: coerceExifValue(exif.tags[infer.longitude.exif], 'float'),
						latitude: coerceExifValue(exif.tags[infer.latitude.exif], 'float'),
					},
				};
			}
		)
		.case(
			{
				type: Schemas.MetadataTypeSchema,
				infer: { exif: 'string' },
			},
			({ infer, type }) => {
				Iif (!(infer.exif in exif.tags)) return undefined;
 
				return {
					confidence: 1,
					alternatives: [],
					value: coerceExifValue(exif.tags[infer.exif], type),
				};
			}
		)
		.default(() => undefined);
 
	return Object.fromEntries(
		extractionPlan
			.map(({ id, ...option }) => {
				return /** @type {const} */ [id, extract(option)];
			})
			.filter(
				([, extracted]) =>
					extracted !== undefined &&
					!type({ latitude: 'number.NaN', longitude: 'number.NaN' }).allows(
						extracted.value
					) &&
					!Number.isNaN(extracted.value)
			)
	);
}
 
export function coerceExifValue<T extends DB.MetadataType>(
	value: unknown,
	coerceTo: T
): import('./schemas/metadata.js').RuntimeValue<T> {
	switch (coerceTo) {
		case 'string':
			return value?.toString() ?? '';
 
		case 'boolean':
			return Boolean(value);
 
		case 'date':
			Iif (value instanceof Date) return value;
			if (typeof value !== 'number')
				throw new Error(`Date value must be a number, was ${typeof value}`);
			if (Number.isNaN(value)) throw new Error('Date value is invalid');
			return new Date(value * 1e3);
 
		case 'boundingbox':
			throw new Error('Bounding box not supported in EXIF');
 
		case 'enum':
			if (typeof value !== 'string') throw new Error('Enum value must be a string');
			return value;
 
		case 'integer':
		case 'float':
			return Number(value);
 
		default:
			throw new Error(`Unknown type ${coerceTo}`);
	}
}
 
/**
 * Serialize a value to a string for EXIF writing
 */
export function serializeExifValue(value: unknown): string | unknown[] {
	if (value instanceof Date) return dates.format(value, 'yyyy:MM:dd HH:mm:ss');
	// Let multivalued exif entries through
	if (Array.isArray(value)) return value;
	if (typeof value === 'number') return [value];
	if (value === undefined) return 'undefined';
	if (value === null) return 'null';
	if (typeof value === 'object' && value !== null) {
		return Object.entries(value)
			.map(([key, val]) => `${key}=${val}`)
			.join(';');
	}
	return value?.toString() ?? '';
}
 
export function addExifMetadata(
	bytes: ArrayBuffer | Buffer,
	metadataDefs: DB.Metadata[],
	metadataValues: DB.MetadataValues
): Uint8Array {
	const ExifMetadata = Schemas.Metadata.and({
		infer: [
			{ exif: 'string' },
			'|',
			{ latitude: { exif: 'string' }, longitude: { exif: 'string' } },
		],
	});
 
	const changes: Partial<Record<ExifFieldKey, unknown>> = {};
 
	for (const def of metadataDefs.map((m) => ExifMetadata(m))) {
		if (def instanceof type.errors) continue;
		const value = metadataValues[def.id]?.value;
		Iif (value === undefined) continue;
 
		if (
			type({ latitude: { exif: 'string' }, longitude: { exif: 'string' } }).allows(
				def.infer
			) &&
			type({ latitude: 'number', longitude: 'number' }).allows(value)
		) {
			// XXX harcoded BS :/
			if (def.infer.latitude.exif === 'GPSLatitude') {
				changes['GPSLatitudeRef'] = value.latitude >= 0 ? 'N' : 'S';
				changes['GPSLatitude'] = piexif.GPSHelper.degToDmsRational(value.latitude);
			} else E{
				changes[def.infer.latitude.exif] = value.latitude;
			}
 
			// XXX harcoded BS :/
			if (def.infer.longitude.exif === 'GPSLongitude') {
				changes['GPSLongitudeRef'] = value.longitude >= 0 ? 'E' : 'W';
				changes['GPSLongitude'] = piexif.GPSHelper.degToDmsRational(value.longitude);
			} else E{
				changes[def.infer.longitude.exif] = value.longitude;
			}
		} else {
			changes[def.infer.exif] = value;
		}
	}
 
	return setExifFields(bytes, changes);
}
 
export function setExifFields(bytes: ArrayBuffer, changes: Partial<Record<ExifFieldKey, unknown>>) {
	const bytestring = byteString(new Uint8Array(bytes));
 
	try {
		const exifDict = piexif.load(bytestring);
 
		// Prevent any write if no exif data changed
		let dirty = false;
 
		for (const [key, value] of Object.entries(changes)) {
			const field = EXIF_FIELDS[key];
 
			const [category] =
				Object.entries(exifDict).find(([, tags]) => tags && field in tags) ??
				Object.entries(piexif.TAGS).find(
					([cat, tags]) => cat !== 'Image' && field in tags
				) ??
				[];
 
			Iif (!category) continue;
 
			const serialized = serializeExifValue(value);
			Iif (serialized === undefined) continue;
			if (serialized === exifDict[category][field]) continue;
			exifDict[category][field] = serialized;
			dirty = true;
		}
 
		Iif (!dirty) return new Uint8Array(bytes);
 
		const outputstr = piexif.insert(piexif.dump(exifDict), bytestring);
		return byteStringToArray(outputstr);
	} catch (error) {
		toasts.warn(errorMessage(error, 'Impossible de modifier les données EXIF'));
		return new Uint8Array(buffer);
	}
}