From 494fbe36c7652c03a10a9b26622a9b207fb383dd Mon Sep 17 00:00:00 2001
From: Alan Grainger <16197738+alangrainger@users.noreply.github.com>
Date: Mon, 22 Jun 2026 06:21:51 +1200
Subject: [PATCH] Prepping for v3.0 release Fetch album assets from timeline
endpoint is the major change
---
app/package.json | 2 +-
app/src/client/init.ts | 1 +
app/src/client/lightbox-ui.ts | 5 +
app/src/client/lightbox.ts | 19 ++-
app/src/client/metadata.ts | 90 +++++++++++
app/src/client/sidebar.ts | 2 +
app/src/client/state.ts | 10 +-
app/src/gallery/builder.ts | 25 ++-
app/src/gallery/metadata.ts | 40 +++++
app/src/immich.ts | 229 ++++++++++++++++++++++-----
app/src/index.ts | 138 +++++++++++-----
app/src/shared/types.ts | 27 +++-
app/src/stream/download.ts | 45 +++++-
app/src/types.ts | 37 +++--
app/src/view/gallery.tsx | 4 +-
app/tests/albumTimeline.test.ts | 146 +++++++++++++++++
app/tests/assetMetadata.test.ts | 80 ++++++++++
app/tests/contentDisposition.test.ts | 25 +++
18 files changed, 808 insertions(+), 117 deletions(-)
create mode 100644 app/src/client/metadata.ts
create mode 100644 app/src/gallery/metadata.ts
create mode 100644 app/tests/albumTimeline.test.ts
create mode 100644 app/tests/assetMetadata.test.ts
create mode 100644 app/tests/contentDisposition.test.ts
diff --git a/app/package.json b/app/package.json
index 64ece5b..48abea1 100644
--- a/app/package.json
+++ b/app/package.json
@@ -1,6 +1,6 @@
{
"name": "immich-public-proxy",
- "version": "2.5.0",
+ "version": "3.0.0",
"scripts": {
"dev": "concurrently -n server,client -c blue,green \"tsx watch src/index.ts\" \"tsc -w -p tsconfig.client.json\"",
"build": "tsc && tsc -p tsconfig.client.json",
diff --git a/app/src/client/init.ts b/app/src/client/init.ts
index 2950eea..9eb651e 100644
--- a/app/src/client/init.ts
+++ b/app/src/client/init.ts
@@ -25,6 +25,7 @@ function init () {
state.lightboxConfig = params.lightboxConfig || {}
if (params.metadataConfig) state.metadataConfig = params.metadataConfig
state.groupByDate = !!params.groupByDate
+ state.metaBase = params.metaBase || ''
state.container = document.getElementById('gallery')
if (!state.container) return
diff --git a/app/src/client/lightbox-ui.ts b/app/src/client/lightbox-ui.ts
index 34966a5..e4e0861 100644
--- a/app/src/client/lightbox-ui.ts
+++ b/app/src/client/lightbox-ui.ts
@@ -80,6 +80,8 @@ export function registerCaption (lightbox: LightboxInstance) {
}
render()
pswp.on('change', render)
+ // Re-render when a lazy album item's description arrives after open.
+ state.slideRefreshers.push(render)
}
})
})
@@ -113,6 +115,9 @@ export function registerDownloadButton (lightbox: LightboxInstance) {
}
update()
pswp.on('change', update)
+ // Refresh the href/filename when a lazy album item's real download
+ // filename arrives after open.
+ state.slideRefreshers.push(update)
}
})
})
diff --git a/app/src/client/lightbox.ts b/app/src/client/lightbox.ts
index a780d3d..ec54e23 100644
--- a/app/src/client/lightbox.ts
+++ b/app/src/client/lightbox.ts
@@ -16,6 +16,7 @@ import {
registerFullscreenButton
} from './lightbox-ui.js'
import { registerSidebar } from './sidebar.js'
+import { registerLazyDetail } from './metadata.js'
/**
* Replace the current history entry with the same URL minus any hash.
@@ -33,9 +34,12 @@ function parseVideoData (item: GalleryItem): { src: string, type: string } {
try {
const data = JSON.parse(item.videoData || '{}')
const source = (data.source && data.source[0]) || {}
- return { src: source.src || '', type: source.type || 'video/mp4' }
+ // type may be empty for lazy album videos (the content-type probe is
+ // deferred); an empty type attribute is omitted below so the browser
+ // falls back to the proxy's response Content-Type.
+ return { src: source.src || '', type: source.type || '' }
} catch (e) {
- return { src: '', type: 'video/mp4' }
+ return { src: '', type: '' }
}
}
@@ -52,11 +56,12 @@ function buildDataSource () {
return state.items.map(item => {
if (item.type === 'VIDEO') {
const v = parseVideoData(item)
+ const typeAttr = v.type ? ' type="' + escapeAttr(v.type) + '"' : ''
return {
html:
'
' +
'' +
'
'
}
@@ -127,11 +132,19 @@ export function initLightbox () {
state.lightbox = new PhotoSwipeLightbox(lightboxOptions)
+ // PhotoSwipe recreates its pswp instance (and re-fires uiRegister) on every
+ // open, so the UI elements below re-register their slide refreshers each
+ // time. Clear the list before each open so it can't grow unbounded.
+ state.lightbox.on('beforeOpen', () => { state.slideRefreshers = [] })
+
registerBackButton(state.lightbox)
if (state.lightboxConfig.showDownload) registerDownloadButton(state.lightbox)
registerFullscreenButton(state.lightbox)
if (state.metadataConfig.descriptionInCaption) registerCaption(state.lightbox)
if (state.metadataConfig.sidebarHasContent) registerSidebar(state.lightbox)
+ // Lazy album items load their exif / description / filename on open; this
+ // refreshes the UI elements above once detail arrives.
+ registerLazyDetail(state.lightbox)
// Hash navigation + back-button handling: push a history entry on open so
// the mobile back gesture closes the lightbox; sync the hash with the
diff --git a/app/src/client/metadata.ts b/app/src/client/metadata.ts
new file mode 100644
index 0000000..26d2388
--- /dev/null
+++ b/app/src/client/metadata.ts
@@ -0,0 +1,90 @@
+/*
+Lazy per-asset metadata loading for album shares. Album items arrive as
+grid-only data (id, type, thumbhash, dimensions); their exif / description /
+real download filename are fetched from the `/meta/` route the first time
+the item opens in the lightbox - mirroring how Immich's own web client loads
+shared-album detail on demand. Individual shares bake everything in and
+never reach this module (no `metaBase`).
+*/
+
+import { state } from './state.js'
+import type { GalleryItem, AssetMetadata } from '../shared/types.js'
+
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+type LightboxInstance = any
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+type PswpInstance = any
+
+// One in-flight (then resolved) request per asset id, so paging back and
+// forth - or prefetching a neighbour we then navigate to - reuses the fetch.
+const detailCache = new Map>()
+
+function fetchDetail (id: string): Promise {
+ const cached = detailCache.get(id)
+ if (cached) return cached
+ const promise = fetch(state.metaBase + '/' + encodeURIComponent(id))
+ .then(res => (res.ok ? res.json() as Promise : null))
+ .catch(() => null)
+ detailCache.set(id, promise)
+ return promise
+}
+
+/**
+ * Copy fetched detail onto the grid item in place and clear `needsDetail`.
+ * Only fills fields the server sent (all are config/share gated), so a share
+ * with metadata disabled simply leaves them unset.
+ */
+function applyMeta (item: GalleryItem, meta: AssetMetadata): void {
+ if (meta.exif) item.exif = meta.exif
+ if (meta.description) item.description = meta.description
+ if (meta.downloadFilename) item.downloadFilename = meta.downloadFilename
+ item.needsDetail = false
+}
+
+/**
+ * Ensure `item`'s detail is loaded. Resolves true when this call is the one
+ * that applied the detail (so the caller can refresh the view), false if the
+ * item needs no detail, the fetch failed, or another call already applied it.
+ */
+function ensureDetail (item: GalleryItem | undefined): Promise {
+ if (!item || !item.needsDetail) return Promise.resolve(false)
+ return fetchDetail(item.id).then(meta => {
+ if (!meta || !item.needsDetail) return false
+ applyMeta(item, meta)
+ return true
+ })
+}
+
+/**
+ * Warm the cache for a neighbouring slide without touching the view, so
+ * paging next/prev shows detail instantly (matches Immich's prefetch).
+ */
+function prefetch (item: GalleryItem | undefined): void {
+ if (item && item.needsDetail) fetchDetail(item.id)
+}
+
+function loadCurrent (pswp: PswpInstance): void {
+ const index = pswp.currIndex
+ ensureDetail(state.items[index]).then(applied => {
+ // Only refresh if the user is still on the slide we loaded for.
+ if (applied && pswp.currIndex === index) {
+ state.slideRefreshers.forEach(fn => fn())
+ }
+ })
+ prefetch(state.items[index + 1])
+ prefetch(state.items[index - 1])
+}
+
+/**
+ * Hook lazy detail loading into the lightbox. Loads the opened slide's detail
+ * (and prefetches its neighbours) on open and on every slide change. No-op
+ * unless the share exposed a `metaBase` (album shares only).
+ */
+export function registerLazyDetail (lightbox: LightboxInstance): void {
+ if (!state.metaBase) return
+ lightbox.on('uiRegister', () => {
+ const pswp = lightbox.pswp
+ loadCurrent(pswp)
+ pswp.on('change', () => loadCurrent(pswp))
+ })
+}
diff --git a/app/src/client/sidebar.ts b/app/src/client/sidebar.ts
index dfe691d..7e146fc 100644
--- a/app/src/client/sidebar.ts
+++ b/app/src/client/sidebar.ts
@@ -41,6 +41,8 @@ export function registerSidebar (lightbox: LightboxInstance) {
const renderSidebar = () => renderContents(el, state.items[pswp.currIndex])
renderSidebar()
pswp.on('change', renderSidebar)
+ // Re-render when a lazy album item's detail arrives after open.
+ state.slideRefreshers.push(renderSidebar)
pswp.on('destroy', () => {
document.documentElement.classList.remove('ipp-sidebar-open')
})
diff --git a/app/src/client/state.ts b/app/src/client/state.ts
index b0abda3..69dcd30 100644
--- a/app/src/client/state.ts
+++ b/app/src/client/state.ts
@@ -49,8 +49,6 @@ export interface GroupSpec {
}
// PhotoSwipeLightbox is an external module with no TS types in this project.
-// Typing it as `unknown` would push casts to every call site; `any` is the
-// pragmatic choice and stays scoped to this single state slot.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type PhotoSwipeLightboxInstance = any
@@ -85,5 +83,11 @@ export const state = {
downloadBtn: null as HTMLButtonElement | null,
// Info sidebar open/closed. Persisted to localStorage so the choice
// survives navigation between slides and gallery reloads.
- sidebarOpen: false
+ sidebarOpen: false,
+ // Base URL (`/share/meta/`) for the on-demand per-asset metadata route.
+ metaBase: '',
+ // Re-render callbacks registered by lightbox UI elements (sidebar, caption,
+ // download button). Each re-renders for the current slide. Invoked after a
+ // lazy item's detail arrives so the just-opened slide reflects it.
+ slideRefreshers: [] as Array<() => void>
}
diff --git a/app/src/gallery/builder.ts b/app/src/gallery/builder.ts
index dff6b48..23bad65 100644
--- a/app/src/gallery/builder.ts
+++ b/app/src/gallery/builder.ts
@@ -49,13 +49,13 @@ export async function gallery (res: Response, share: SharedLink, openItem?: numb
const items: GalleryItem[] = await Promise.all(share.assets.map(async (asset): Promise => {
let videoData: string | undefined
if (asset.type === AssetType.video) {
+ const source: { src: string, type?: string } = { src: videoUrl(share.key, asset.id) }
+ // Album "grid" videos defer the content-type probe (one upstream call
+ // per video) - a with no type lets the browser fall back to
+ // the proxy's response Content-Type, keeping grid render O(buckets).
+ if (!asset.needsDetail) source.type = await getVideoContentType(asset)
videoData = JSON.stringify({
- source: [
- {
- src: videoUrl(share.key, asset.id),
- type: await getVideoContentType(asset)
- }
- ],
+ source: [source],
attributes: {
playsinline: 'playsinline',
controls: 'controls'
@@ -105,10 +105,18 @@ export async function gallery (res: Response, share: SharedLink, openItem?: numb
height,
thumbhash: asset.thumbhash,
fileCreatedAt: asset.fileCreatedAt,
- exif: shareMetadataAllowed ? pickExif(asset) : undefined
+ exif: shareMetadataAllowed ? pickExif(asset) : undefined,
+ // Album grid items carry no exif / description / real filename yet; the
+ // client fetches them from `metaBase` the first time the item opens.
+ needsDetail: asset.needsDetail || undefined
}
}))
+ // Album shares contain lazy items; expose the on-demand metadata route so
+ // the client can fetch per-asset detail on lightbox open. Individual shares
+ // bake everything in, so no metaBase is needed there.
+ const metaBase = items.some(item => item.needsDetail) ? '/share/meta/' + share.key : undefined
+
const downloadAllowed = canDownload(share)
// Prefer the album's owner-chosen cover for og:image; fall back to first
// item if the cover asset has been filtered out (e.g. trashed).
@@ -144,7 +152,8 @@ export async function gallery (res: Response, share: SharedLink, openItem?: numb
sidebarHasContent,
locationWebLink: !!getConfigOption('ipp.showMetadata.location.webLink', true)
},
- groupByDate
+ groupByDate,
+ metaBase
}
res.send(renderPage(h(Gallery, props)))
diff --git a/app/src/gallery/metadata.ts b/app/src/gallery/metadata.ts
new file mode 100644
index 0000000..464977d
--- /dev/null
+++ b/app/src/gallery/metadata.ts
@@ -0,0 +1,40 @@
+import { Asset, ImageSize, SharedLink } from '../types'
+import { AssetMetadata } from '../shared/types'
+import { getConfigOption } from '../config/access'
+import { requiresOriginal } from '../immich'
+import { pickExif } from './exif'
+import { getFilename } from './filename'
+
+/**
+ * Build the on-demand metadata payload for a single asset, served by the
+ * `/meta/` route when a lazy album item opens in the lightbox.
+ *
+ * This is the lazy-flow counterpart to the per-item baking the gallery
+ * builder does eagerly for individual shares: it applies the same
+ * `showMetadata` kill-switch and `ipp.showMetadata.*` gating, so the client
+ * never receives anything the operator hasn't opted into.
+ */
+export function buildAssetMetadata (asset: Asset, share: SharedLink): AssetMetadata {
+ // The share owner's "Show metadata" toggle is a kill-switch over the
+ // operator's own config - mirrors gallery/builder.ts.
+ const shareMetadataAllowed = share.showMetadata !== false
+ const descriptionInCaption = shareMetadataAllowed && !!getConfigOption('ipp.showMetadata.description.caption', false)
+ const descriptionInSidebar = shareMetadataAllowed && !!getConfigOption('ipp.showMetadata.description.sidebar', false)
+ const descriptionEnabled = descriptionInCaption || descriptionInSidebar
+
+ const description = descriptionEnabled && typeof asset?.exifInfo?.description === 'string'
+ ? asset.exifInfo.description
+ : undefined
+
+ // Match the gallery builder's download-size resolution so the filename's
+ // extension reflects the bytes the user will actually receive.
+ const downloadServedSize = (getConfigOption('ipp.downloadOriginalPhoto', true) || requiresOriginal(asset))
+ ? ImageSize.original
+ : ImageSize.preview
+
+ return {
+ exif: shareMetadataAllowed ? pickExif(asset) : undefined,
+ description,
+ downloadFilename: getFilename(asset, downloadServedSize)
+ }
+}
diff --git a/app/src/immich.ts b/app/src/immich.ts
index f52d47c..9178bf5 100644
--- a/app/src/immich.ts
+++ b/app/src/immich.ts
@@ -1,5 +1,4 @@
import {
- Album,
AlbumType,
Asset,
AssetType,
@@ -7,7 +6,9 @@ import {
IncomingShareRequest,
KeyType,
SharedLink,
- SharedLinkResult
+ SharedLinkResult,
+ TimelineBucket,
+ TimelineBucketAssets
} from './types'
import dayjs from 'dayjs'
import { getConfigOption } from './config/access'
@@ -28,12 +29,12 @@ import { TtlLruCache } from './utils/ttlLruCache'
/*
In-process cache for share-link lookups. Each direct-asset request (e.g.
`/share/photo/:key/:id/thumbnail`) re-validates the share by calling
- getShareByKey, which for album shares also pulls the entire album asset
- list from Immich. Without this cache, a gallery view of N tiles fans out
- into N concurrent full-album fetches against Immich and serializes there,
- pushing per-thumbnail latency into seconds. The cache holds Promises
- (not resolved values) so concurrent cold misses coalesce into one upstream
- call instead of stampeding.
+ getShareByKey, which for album shares also enumerates the album's assets
+ from Immich's timeline API (1 + N_buckets requests). Without this cache, a
+ gallery view of N tiles fans out into N concurrent enumerations against
+ Immich and serializes there, pushing per-thumbnail latency into seconds.
+ The cache holds Promises (not resolved values) so concurrent cold misses
+ coalesce into one upstream call instead of stampeding.
CAUTION: a cache hit returns the SAME SharedLinkResult reference across
requests. Callers MUST treat the result (and its `link.assets`) as
@@ -56,6 +57,45 @@ const shareCache = new TtlLruCache>({ ttlMs: 120_000,
*/
const tokenCache = new TtlLruCache>({ ttlMs: 120_000, max: 100 })
+/*
+ Per-asset detail cache for the lazy album flow. When a `needsDetail` album
+ item opens in the lightbox, the `/meta/` route fetches the full asset from
+ `GET /assets/:id` for its exif / filename. Paging quickly through a gallery
+ (or prefetching neighbours) would otherwise re-fetch the same asset; this
+ coalesces repeats. Keyed by (keyType, key, id); holds Promises so concurrent
+ opens of the same asset share one upstream call.
+*/
+const assetDetailCache = new TtlLruCache>({ ttlMs: 120_000, max: 500 })
+
+/**
+ * Memoise an in-flight Promise in `cache`, coalescing concurrent callers onto
+ * a single upstream call. The entry is evicted as soon as it resolves to an
+ * invalid value (per `isValid`, default "falsy is invalid") or rejects, so a
+ * transient Immich blip never poisons the cache with a negative result.
+ *
+ * This is the shared form of the "should this stay cached?" policy that
+ * TtlLruCache deliberately leaves to its callers (see its doc-comment): the
+ * cache stays storage-only; the eviction rule lives here, once, instead of
+ * being hand-copied at each call site.
+ */
+function cachedPromise (
+ cache: TtlLruCache>,
+ key: string,
+ factory: () => Promise,
+ isValid: (value: T) => boolean = (value) => !!value
+): Promise {
+ const cached = cache.get(key)
+ if (cached) return cached
+
+ const promise = factory()
+ cache.set(key, promise)
+ promise.then(
+ (value) => { if (!isValid(value)) cache.delete(key) },
+ () => { cache.delete(key) }
+ )
+ return promise
+}
+
/**
* Make a request to Immich API. We're not using the SDK to limit
* the possible attack surface of this app.
@@ -181,23 +221,16 @@ export async function handleShareRequest (req: IncomingShareRequest, res: Respon
* in-process cache + in-flight de-duplication. See the cache notes at the
* top of this file for the why.
*
- * The cache holds the full post-album-population SharedLinkResult, so warm
- * hits skip both the `/shared-links/me` and `/albums/:id` round trips.
+ * The cache holds the full post-album-enumeration SharedLinkResult, so warm
+ * hits skip both the `/shared-links/me` and the timeline round trips.
* Negative results (`valid: false`) and rejections are dropped from the
* cache immediately so a transient Immich blip doesn't poison the cache.
*/
-export async function getShareByKey (key: string, password?: string, keyType: KeyType = KeyType.key): Promise {
+export function getShareByKey (key: string, password?: string, keyType: KeyType = KeyType.key): Promise {
const cacheKey = `${keyType}:${key}:${password ?? ''}`
- const cached = shareCache.get(cacheKey)
- if (cached) return cached
-
- const promise = fetchShareByKey(key, password, keyType)
- shareCache.set(cacheKey, promise)
- promise.then(
- (result) => { if (!result?.valid) shareCache.delete(cacheKey) },
- () => { shareCache.delete(cacheKey) }
- )
- return promise
+ // A `{ valid: false }` result is a truthy object, so the default eviction
+ // rule wouldn't drop it - key off `.valid` explicitly.
+ return cachedPromise(shareCache, cacheKey, () => fetchShareByKey(key, password, keyType), (result) => !!result?.valid)
}
/**
@@ -221,22 +254,30 @@ async function fetchShareByKey (key: string, password?: string, keyType: KeyType
link = jsonBody as SharedLink
link.keyType = keyType
- // For an album, we need to make a second request to Immich to populate
- // the array of assets
+ // For an album, `/shared-links/me` returns an empty `assets` array
+ // (Immich 3.0 dropped album assets from both that response and
+ // `AlbumResponseDto`). We enumerate the album's assets from the
+ // timeline API instead - the same approach Immich's own web client
+ // uses for shared albums. This yields grid-only assets; their full
+ // detail (exif, filename) is fetched lazily on lightbox open. The
+ // album cover id we need for og:image is already on `link.album`
+ // (mapAlbum still returns albumThumbnailAssetId).
if (link.type === AlbumType.album) {
- const albumRes = await fetch(buildUrl(apiUrl() + '/albums/' + link?.album?.id, {
- [keyType]: key
- }), { headers })
- const album = await albumRes.json() as Album
- if (!album?.id) {
- log('Invalid album ID - ' + link?.album?.id)
+ if (!link.album?.id) {
+ log('Album share missing album id for key ' + key)
return {
valid: false
}
}
- // Replace the empty link.assets array with the array of assets from the album
- link.assets = album.assets
- if (link.album) link.album.albumThumbnailAssetId = album.albumThumbnailAssetId
+ const albumAssets = await fetchAlbumAssets(link.album.id, keyType, key, headers)
+ if (albumAssets === null) {
+ // Enumeration failed upstream. Return invalid (not cached) rather
+ // than caching an empty album for the next 120s on a transient blip.
+ return {
+ valid: false
+ }
+ }
+ link.assets = albumAssets
}
link.password = password
@@ -298,6 +339,115 @@ async function fetchShareByKey (key: string, password?: string, keyType: KeyType
}
}
+// Base resolution used to turn an Immich `ratio` (width/height) into concrete
+// width/height for layout + lightbox sizing. The justified-rows layout only
+// needs the ratio; PhotoSwipe also uses these for its fit/zoom maths, so we
+// scale to a realistic preview-sized longest edge rather than `ratio`x1.
+const TIMELINE_BASE_EDGE = 1600
+
+/**
+ * Turn an Immich timeline `ratio` (width / height, already orientation-aware)
+ * into concrete pixel dimensions whose longest edge is TIMELINE_BASE_EDGE.
+ */
+function ratioToDimensions (ratio: number): { width: number, height: number } {
+ if (!ratio || ratio <= 0 || !isFinite(ratio)) {
+ return { width: TIMELINE_BASE_EDGE, height: TIMELINE_BASE_EDGE }
+ }
+ return ratio >= 1
+ ? { width: TIMELINE_BASE_EDGE, height: Math.round(TIMELINE_BASE_EDGE / ratio) }
+ : { width: Math.round(TIMELINE_BASE_EDGE * ratio), height: TIMELINE_BASE_EDGE }
+}
+
+/**
+ * Map a columnar `GET /timeline/bucket` response into grid-only `Asset`s.
+ * Only the fields needed to render the gallery grid are populated; exif /
+ * filename / mime are filled in lazily on lightbox open (`needsDetail`).
+ * `key` / `keyType` / `password` are stamped by the caller.
+ */
+function timelineBucketToAssets (bucket: TimelineBucketAssets): Asset[] {
+ const assets: Asset[] = []
+ const count = bucket?.id?.length || 0
+ for (let i = 0; i < count; i++) {
+ const { width, height } = ratioToDimensions(bucket.ratio?.[i])
+ assets.push({
+ id: bucket.id[i],
+ key: '',
+ keyType: KeyType.key,
+ type: bucket.isImage?.[i] ? AssetType.image : AssetType.video,
+ isTrashed: !!bucket.isTrashed?.[i],
+ fileCreatedAt: bucket.fileCreatedAt?.[i],
+ thumbhash: bucket.thumbhash?.[i] || undefined,
+ width,
+ height,
+ needsDetail: true
+ })
+ }
+ return assets
+}
+
+/**
+ * Enumerate an album's assets via Immich's timeline API, scoped by album id +
+ * shared-link key. `GET /timeline/buckets` lists the time buckets (months),
+ * then one `GET /timeline/bucket` per bucket returns that bucket's assets in
+ * a columnar shape. Request volume is `1 + N_buckets`, not `N_assets`, so it
+ * scales flat with album size (a 5000-image album is ~a dozen calls).
+ *
+ * All-or-nothing: returns `null` if the bucket list or any bucket fetch fails
+ * (so the caller can treat it as an invalid, uncached result rather than a
+ * partial/empty album). Returns an empty array only for a genuinely empty
+ * album. Never throws - a rejection here would surface as an unhandled
+ * rejection and take the process down.
+ */
+async function fetchAlbumAssets (albumId: string, keyType: KeyType, key: string, headers: Record): Promise {
+ try {
+ const bucketsRes = await fetch(buildUrl(apiUrl() + '/timeline/buckets', {
+ albumId,
+ [keyType]: key
+ }), { headers })
+ if (!bucketsRes.ok) {
+ log('Failed to list timeline buckets for album ' + albumId + ' (status ' + bucketsRes.status + ')')
+ return null
+ }
+ const buckets = await bucketsRes.json() as TimelineBucket[]
+ const perBucket = await Promise.all((buckets || []).map(async (bucket) => {
+ const res = await fetch(buildUrl(apiUrl() + '/timeline/bucket', {
+ albumId,
+ timeBucket: bucket.timeBucket,
+ [keyType]: key
+ }), { headers })
+ if (!res.ok) {
+ log('Failed to fetch timeline bucket ' + bucket.timeBucket + ' for album ' + albumId + ' (status ' + res.status + ')')
+ return null
+ }
+ return timelineBucketToAssets(await res.json() as TimelineBucketAssets)
+ }))
+ // If any bucket failed, treat the whole enumeration as failed.
+ if (perBucket.some(b => b === null)) return null
+ return (perBucket as Asset[][]).flat()
+ } catch (e) {
+ log('Error enumerating album ' + albumId + ' via timeline: ' + (e instanceof Error ? e.message : String(e)))
+ return null
+ }
+}
+
+/**
+ * Fetch a single asset's full detail (`GET /assets/:id`) for the lazy album
+ * flow, cached + de-duplicated per (keyType, key, id). The `asset` argument
+ * supplies the id and the already-stamped key/keyType/password. Returns
+ * undefined on any failure.
+ */
+export function fetchAssetDetail (asset: Asset): Promise {
+ const cacheKey = `${asset.keyType}:${asset.key}:${asset.id}`
+ return cachedPromise(assetDetailCache, cacheKey, async () => {
+ const headers = await authHeaders(asset.keyType, asset.key, asset.password)
+ const res = await fetch(buildUrl(apiUrl() + '/assets/' + encodeURIComponent(asset.id), {
+ [asset.keyType]: asset.key
+ }), { headers })
+ if (!res.ok) return undefined
+ return await res.json() as Asset
+ })
+}
+
/**
* Get the content-type of a video, for the lightbox