diff --git a/src/lib/db.ts b/src/lib/db.ts index cf79023..64e1396 100644 --- a/src/lib/db.ts +++ b/src/lib/db.ts @@ -64,6 +64,11 @@ export async function getAsset(id: string): Promise { return wrap((await store('assets')).get(id) as IDBRequest); } +/** Drop one cached file without touching its photo record. */ +export async function deleteAsset(id: string): Promise { + await wrap((await store('assets', 'readwrite')).delete(id)); +} + export async function getAllEvents(): Promise { return wrap((await store('events')).getAll() as IDBRequest); } diff --git a/src/lib/images.ts b/src/lib/images.ts index f6a7775..78c59f0 100644 --- a/src/lib/images.ts +++ b/src/lib/images.ts @@ -1,5 +1,5 @@ import type { PhotoRecord } from '../types'; -import { getAsset, putAsset } from './db'; +import { deleteAsset, getAsset, putAsset } from './db'; import { parsePreview16, type Preview16 } from './preview16'; const CACHE_LIMIT = 6; @@ -56,6 +56,18 @@ async function fetchRemote(photo: PhotoRecord): Promise { } } +/** + * Decode upright, falling back for decoders that refuse the orientation option + * (a plain decode is better than no frame at all). + */ +async function decodeBitmap(blob: Blob): Promise { + try { + return await createImageBitmap(blob, { imageOrientation: 'from-image' }); + } catch { + return await createImageBitmap(blob); + } +} + export async function getBitmap(photo: PhotoRecord): Promise { const hit = cache.get(photo.id); if (hit) { @@ -75,7 +87,18 @@ export async function getBitmap(photo: PhotoRecord): Promise { } // Apply EXIF orientation so the pixels the editor works on are upright. - const bitmap = await createImageBitmap(blob, { imageOrientation: 'from-image' }); + // A cached copy can be stale — truncated by an interrupted download, or + // written when the server produced a different proxy — and then it decodes + // to nothing forever, so one failure drops it and refetches the current bytes. + let bitmap: ImageBitmap; + try { + bitmap = await decodeBitmap(blob); + } catch (err) { + await deleteAsset(photo.id).catch(() => undefined); + const fresh = (await fetchRemoteCopy(photo)) ?? undefined; + if (!fresh) throw err; + bitmap = await decodeBitmap(fresh); + } cache.set(photo.id, bitmap); while (cache.size > CACHE_LIMIT) { const first = cache.keys().next();