cd52a2f82f
Browser-based photo catalog with an optional team server (SQLite + LibRaw). Local database, uploaded photos, build output and dependencies are gitignored. 🤖 Generated with Codebuff Co-Authored-By: Codebuff <noreply@codebuff.com>
268 lines
8.7 KiB
TypeScript
268 lines
8.7 KiB
TypeScript
import exifr from 'exifr';
|
|
import type { UploadResult } from './api';
|
|
import type { PhotoMeta, PhotoRecord } from '../types';
|
|
import { putAsset, putPhoto } from './db';
|
|
import { defaultEdits, normalizePhoto } from './edits';
|
|
import { defaultForMeta, loadCameraLensDefaults, type CameraLensDefault } from './lensDefaults';
|
|
import { isRawFile, RAW_EXTENSIONS } from './raw';
|
|
|
|
export interface ImportProgress {
|
|
done: number;
|
|
total: number;
|
|
current: string;
|
|
}
|
|
|
|
export interface ImportResult {
|
|
photos: PhotoRecord[];
|
|
failed: { name: string; reason: string }[];
|
|
cancelled?: boolean;
|
|
}
|
|
|
|
/** Provided by the app when a Luminary server is connected. */
|
|
export interface CloudImport {
|
|
uploadOriginal: (id: string, file: File, name: string) => Promise<UploadResult>;
|
|
push: (photo: PhotoRecord) => Promise<PhotoRecord>;
|
|
}
|
|
|
|
/** Files imported at once; the server bounds how many raws decode in parallel. */
|
|
const IMPORT_CONCURRENCY = 4;
|
|
|
|
export function uid(): string {
|
|
if (typeof crypto !== 'undefined' && 'randomUUID' in crypto) return crypto.randomUUID();
|
|
return `p_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
|
|
}
|
|
|
|
function mapLimit<T>(items: T[], limit: number, fn: (item: T, index: number) => Promise<void>): Promise<void[]> {
|
|
let cursor = 0;
|
|
const runners = Array.from({ length: Math.min(Math.max(1, limit), items.length) }, async () => {
|
|
for (;;) {
|
|
const index = cursor++;
|
|
if (index >= items.length) return;
|
|
await fn(items[index], index);
|
|
}
|
|
});
|
|
return Promise.all(runners);
|
|
}
|
|
|
|
function formatShutter(time: unknown): string | undefined {
|
|
if (typeof time !== 'number' || !Number.isFinite(time) || time <= 0) return undefined;
|
|
if (time >= 1) return `${Math.round(time * 10) / 10}s`;
|
|
return `1/${Math.round(1 / time)}s`;
|
|
}
|
|
|
|
async function readMeta(file: File): Promise<{ meta: PhotoMeta; takenAt?: number }> {
|
|
try {
|
|
const data = (await exifr.parse(file, {
|
|
tiff: true,
|
|
exif: true,
|
|
gps: false,
|
|
interop: false,
|
|
translateValues: false,
|
|
reviveValues: true,
|
|
})) as Record<string, unknown> | undefined;
|
|
if (!data) return { meta: {} };
|
|
const make = typeof data.Make === 'string' ? data.Make.trim() : '';
|
|
const model = typeof data.Model === 'string' ? data.Model.trim() : '';
|
|
const meta: PhotoMeta = {
|
|
camera: [make, model].filter(Boolean).join(' ').replace(/\s+/g, ' ') || undefined,
|
|
lens: typeof data.LensModel === 'string' ? data.LensModel.trim() : undefined,
|
|
iso: typeof data.ISO === 'number' ? data.ISO : undefined,
|
|
aperture: typeof data.FNumber === 'number' ? data.FNumber : undefined,
|
|
shutter: formatShutter(data.ExposureTime),
|
|
focal: typeof data.FocalLength === 'number' ? Math.round(data.FocalLength) : undefined,
|
|
};
|
|
const taken = data.DateTimeOriginal ?? data.CreateDate ?? data.ModifyDate;
|
|
const takenAt = taken instanceof Date && !Number.isNaN(taken.getTime()) ? taken.getTime() : undefined;
|
|
return { meta, takenAt };
|
|
} catch {
|
|
return { meta: {} };
|
|
}
|
|
}
|
|
|
|
function editsForImport(meta: PhotoMeta, defaults: CameraLensDefault[]) {
|
|
const edits = defaultEdits();
|
|
const match = defaultForMeta(defaults, meta);
|
|
if (match) {
|
|
edits.lens = {
|
|
...match.profile,
|
|
corrections: { ...match.profile.corrections },
|
|
};
|
|
}
|
|
return edits;
|
|
}
|
|
|
|
async function makeThumb(bitmap: ImageBitmap): Promise<string> {
|
|
const max = 560;
|
|
const scale = Math.min(1, max / Math.max(bitmap.width, bitmap.height));
|
|
const w = Math.max(1, Math.round(bitmap.width * scale));
|
|
const h = Math.max(1, Math.round(bitmap.height * scale));
|
|
const canvas = document.createElement('canvas');
|
|
canvas.width = w;
|
|
canvas.height = h;
|
|
const ctx = canvas.getContext('2d');
|
|
if (!ctx) throw new Error('Canvas 2D is unavailable');
|
|
ctx.imageSmoothingQuality = 'high';
|
|
ctx.drawImage(bitmap, 0, 0, w, h);
|
|
return canvas.toDataURL('image/jpeg', 0.82);
|
|
}
|
|
|
|
export function isSupportedFile(file: File): boolean {
|
|
if (file.type.startsWith('image/')) return true;
|
|
const ext = file.name.split('.').pop()?.toLowerCase() ?? '';
|
|
return RAW_EXTENSIONS.has(ext) || /^(jpe?g|png|webp|avif|gif|bmp|tiff?)$/.test(ext);
|
|
}
|
|
|
|
/**
|
|
* Raw files cannot be decoded by the browser, so they are sent to the server,
|
|
* demosaiced there, and represented locally by the returned editable proxy.
|
|
*/
|
|
async function importRaw(
|
|
file: File,
|
|
eventId: string,
|
|
keywords: string[],
|
|
cloud: CloudImport,
|
|
defaults: CameraLensDefault[],
|
|
): Promise<PhotoRecord> {
|
|
const id = uid();
|
|
const upload = await cloud.uploadOriginal(id, file, file.name);
|
|
const previewUrl = upload.previewUrl ?? `/api/photos/${id}/preview`;
|
|
const res = await fetch(previewUrl, { credentials: 'same-origin' });
|
|
if (!res.ok) throw new Error('The server could not produce a preview for this raw file');
|
|
const blob = await res.blob();
|
|
const bitmap = await createImageBitmap(blob, { imageOrientation: 'from-image' });
|
|
const thumb = await makeThumb(bitmap);
|
|
const { meta, takenAt } = await readMeta(file);
|
|
const width = upload.width ?? bitmap.width;
|
|
const height = upload.height ?? bitmap.height;
|
|
const edits = editsForImport(meta, defaults);
|
|
bitmap.close();
|
|
|
|
const record = normalizePhoto({
|
|
id,
|
|
eventId,
|
|
name: file.name,
|
|
width,
|
|
height,
|
|
size: file.size,
|
|
mime: 'image/jpeg',
|
|
addedAt: Date.now(),
|
|
takenAt: takenAt ?? file.lastModified,
|
|
meta,
|
|
thumb,
|
|
rating: 0,
|
|
flag: 'none',
|
|
color: '',
|
|
keywords,
|
|
edits,
|
|
history: [{ label: 'Import', ts: Date.now(), edits }],
|
|
raw: true,
|
|
decode: upload.engine,
|
|
previewUrl,
|
|
});
|
|
|
|
await putPhoto(record);
|
|
// No local blob: the multi-megabyte raw stays on the server.
|
|
const saved = await cloud.push(record);
|
|
const merged = normalizePhoto({ ...record, ...saved });
|
|
await putPhoto(merged);
|
|
return merged;
|
|
}
|
|
|
|
async function importStandard(
|
|
file: File,
|
|
eventId: string,
|
|
keywords: string[],
|
|
cloud: CloudImport | null | undefined,
|
|
defaults: CameraLensDefault[],
|
|
): Promise<PhotoRecord> {
|
|
// Camera JPEGs carry their orientation in EXIF; ask for it to be applied so
|
|
// the thumbnail and the edited proxy agree with what the camera shot.
|
|
const bitmap = await createImageBitmap(file, { imageOrientation: 'from-image' });
|
|
const thumb = await makeThumb(bitmap);
|
|
const { meta, takenAt } = await readMeta(file);
|
|
const id = uid();
|
|
const edits = editsForImport(meta, defaults);
|
|
let record = normalizePhoto({
|
|
id,
|
|
eventId,
|
|
name: file.name,
|
|
width: bitmap.width,
|
|
height: bitmap.height,
|
|
size: file.size,
|
|
mime: file.type || 'image/jpeg',
|
|
addedAt: Date.now(),
|
|
takenAt: takenAt ?? file.lastModified,
|
|
meta,
|
|
thumb,
|
|
rating: 0,
|
|
flag: 'none',
|
|
color: '',
|
|
keywords,
|
|
edits,
|
|
history: [{ label: 'Import', ts: Date.now(), edits }],
|
|
});
|
|
await putAsset(id, file);
|
|
bitmap.close();
|
|
|
|
if (cloud) {
|
|
// Originals are mirrored to the server; failures fall back to a local-only import.
|
|
try {
|
|
await cloud.uploadOriginal(id, file, file.name);
|
|
const saved = await cloud.push(record);
|
|
record = normalizePhoto({ ...record, ...saved });
|
|
} catch (err) {
|
|
console.warn('Could not copy the original to the server', file.name, err);
|
|
}
|
|
}
|
|
|
|
await putPhoto(record);
|
|
return record;
|
|
}
|
|
|
|
export async function importFiles(
|
|
files: File[],
|
|
eventId: string,
|
|
keywords: string[] = [],
|
|
onProgress?: (p: ImportProgress) => void,
|
|
cloud?: CloudImport | null,
|
|
signal?: AbortSignal,
|
|
): Promise<ImportResult> {
|
|
const result: ImportResult = { photos: [], failed: [] };
|
|
const images = files.filter(isSupportedFile);
|
|
const total = images.length;
|
|
if (!total) return result;
|
|
|
|
const collected: { index: number; photo: PhotoRecord }[] = [];
|
|
const defaults = await loadCameraLensDefaults().catch(() => []);
|
|
let done = 0;
|
|
|
|
await mapLimit(images, cloud ? IMPORT_CONCURRENCY : 2, async (file, index) => {
|
|
if (signal?.aborted) return;
|
|
try {
|
|
const photo = isRawFile(file)
|
|
? cloud
|
|
? await importRaw(file, eventId, keywords, cloud, defaults)
|
|
: (() => {
|
|
throw new Error('Raw files need the Luminary server. Sign in, then import again.');
|
|
})()
|
|
: await importStandard(file, eventId, keywords, cloud, defaults);
|
|
collected.push({ index, photo });
|
|
} catch (err) {
|
|
result.failed.push({
|
|
name: file.name,
|
|
reason: err instanceof Error ? err.message : 'Unsupported image format',
|
|
});
|
|
} finally {
|
|
done += 1;
|
|
onProgress?.({ done, total, current: file.name });
|
|
}
|
|
});
|
|
|
|
// Keep the shoot in capture/selection order regardless of which finished first.
|
|
collected.sort((a, b) => a.index - b.index);
|
|
result.photos = collected.map((c) => c.photo);
|
|
result.cancelled = Boolean(signal?.aborted);
|
|
onProgress?.({ done: total, total, current: '' });
|
|
return result;
|
|
}
|