Prepping for v3.0 release
Fetch album assets from timeline endpoint is the major change
This commit is contained in:
+1
-1
@@ -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",
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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:
|
||||
'<div class="pswp__video-wrap">' +
|
||||
'<video controls playsinline poster="' + escapeAttr(item.thumbnailUrl) + '">' +
|
||||
'<source src="' + escapeAttr(v.src) + '" type="' + escapeAttr(v.type) + '">' +
|
||||
'<source src="' + escapeAttr(v.src) + '"' + typeAttr + '>' +
|
||||
'</video>' +
|
||||
'</div>'
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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<string, Promise<AssetMetadata | null>>()
|
||||
|
||||
function fetchDetail (id: string): Promise<AssetMetadata | null> {
|
||||
const cached = detailCache.get(id)
|
||||
if (cached) return cached
|
||||
const promise = fetch(state.metaBase + '/' + encodeURIComponent(id))
|
||||
.then(res => (res.ok ? res.json() as Promise<AssetMetadata> : 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<boolean> {
|
||||
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))
|
||||
})
|
||||
}
|
||||
@@ -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')
|
||||
})
|
||||
|
||||
@@ -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/<key>`) 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>
|
||||
}
|
||||
|
||||
@@ -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<GalleryItem> => {
|
||||
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 <source> 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)))
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
+186
-43
@@ -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<Promise<SharedLinkResult>>({ ttlMs: 120_000,
|
||||
*/
|
||||
const tokenCache = new TtlLruCache<Promise<string | null>>({ 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<Promise<Asset | undefined>>({ 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<T> (
|
||||
cache: TtlLruCache<Promise<T>>,
|
||||
key: string,
|
||||
factory: () => Promise<T>,
|
||||
isValid: (value: T) => boolean = (value) => !!value
|
||||
): Promise<T> {
|
||||
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<SharedLinkResult> {
|
||||
export function getShareByKey (key: string, password?: string, keyType: KeyType = KeyType.key): Promise<SharedLinkResult> {
|
||||
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<string, string>): Promise<Asset[] | null> {
|
||||
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<Asset | undefined> {
|
||||
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 <video> element
|
||||
*/
|
||||
@@ -328,18 +478,11 @@ export async function authHeaders (keyType: KeyType, key: string, password?: str
|
||||
* authenticated session. See `tokenCache` doc-comment for the security
|
||||
* argument.
|
||||
*/
|
||||
async function getSharedLinkToken (key: string, password: string, keyType: KeyType): Promise<string | null> {
|
||||
function getSharedLinkToken (key: string, password: string, keyType: KeyType): Promise<string | null> {
|
||||
const cacheKey = `${keyType}:${key}:${password}`
|
||||
const cached = tokenCache.get(cacheKey)
|
||||
if (cached) return cached
|
||||
|
||||
const promise = sharedLinkLogin(key, password, keyType)
|
||||
tokenCache.set(cacheKey, promise)
|
||||
promise.then(
|
||||
(token) => { if (!token) tokenCache.delete(cacheKey) },
|
||||
() => { tokenCache.delete(cacheKey) }
|
||||
)
|
||||
return promise
|
||||
// Default eviction (falsy is invalid) drops a null/empty token, so a failed
|
||||
// login is never cached.
|
||||
return cachedPromise(tokenCache, cacheKey, () => sharedLinkLogin(key, password, keyType))
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+98
-40
@@ -5,18 +5,20 @@ import express from 'express'
|
||||
import cookieSession from 'cookie-session'
|
||||
import {
|
||||
accessible,
|
||||
fetchAssetDetail,
|
||||
getKeyTypeFromShare,
|
||||
getShareByKey,
|
||||
handleShareRequest,
|
||||
isId,
|
||||
isKey
|
||||
} from './immich'
|
||||
import { buildAssetMetadata } from './gallery/metadata'
|
||||
import crypto from 'crypto'
|
||||
import { assetBuffer } from './stream/asset'
|
||||
import { downloadAssets, sweepStaleStagingDirs } from './stream/download'
|
||||
import dayjs from 'dayjs'
|
||||
import { NextFunction, Request, Response } from 'express-serve-static-core'
|
||||
import { Asset, AssetType, ImageSize, KeyType } from './types'
|
||||
import { Asset, AssetType, ImageSize, KeyType, SharedLink } from './types'
|
||||
import { getConfigOption } from './config/access'
|
||||
import { loadConfig } from './config/loader'
|
||||
import { addResponseHeaders } from './http'
|
||||
@@ -77,6 +79,54 @@ const decodeCookie = (req: Request, _res: Response, next: NextFunction) => {
|
||||
next()
|
||||
}
|
||||
|
||||
/*
|
||||
* Shared route guards. Several routes need the same "resolve a share, reject
|
||||
* invalid / password-protected ones, optionally find the requested asset"
|
||||
* preamble. These return a discriminated result so each route keeps control of
|
||||
* its own response (e.g. the photo route redirects on password where the meta
|
||||
* and download routes return 401), while the validation order and the
|
||||
* `valid`/`link`/`passwordRequired` checks live in one place.
|
||||
*/
|
||||
type ShareResolution =
|
||||
| { ok: true, link: SharedLink }
|
||||
| { ok: false, status: number, reason: string, passwordRequired?: boolean }
|
||||
|
||||
type SharedAssetResolution =
|
||||
| { ok: true, link: SharedLink, asset: Asset }
|
||||
| { ok: false, status: number, reason: string, passwordRequired?: boolean }
|
||||
|
||||
async function resolveShare (req: Request, keyType: KeyType): Promise<ShareResolution> {
|
||||
if (!isKey(req.params.key)) {
|
||||
return { ok: false, status: 404, reason: 'Invalid key for ' + req.path }
|
||||
}
|
||||
// The password is provided from the encrypted session cookie (if set) by
|
||||
// decodeCookie. Validating the share here prevents direct URL access from
|
||||
// bypassing password protection.
|
||||
const share = await getShareByKey(req.params.key, req.password, keyType)
|
||||
if (!share?.valid || !share.link) {
|
||||
return { ok: false, status: 404, reason: 'Invalid share link' }
|
||||
}
|
||||
if (share.passwordRequired) {
|
||||
return { ok: false, status: 401, reason: 'Password required', passwordRequired: true }
|
||||
}
|
||||
return { ok: true, link: share.link }
|
||||
}
|
||||
|
||||
async function resolveSharedAsset (req: Request, keyType: KeyType): Promise<SharedAssetResolution> {
|
||||
if (!isId(req.params.id)) {
|
||||
return { ok: false, status: 404, reason: 'Invalid ID for ' + req.path }
|
||||
}
|
||||
const resolved = await resolveShare(req, keyType)
|
||||
if (!resolved.ok) return resolved
|
||||
// Confirm the asset belongs to this share (defence in depth - Immich also
|
||||
// enforces this via the share key).
|
||||
const asset = resolved.link.assets.find(a => a.id === req.params.id)
|
||||
if (!asset) {
|
||||
return { ok: false, status: 404, reason: 'Asset not found in share' }
|
||||
}
|
||||
return { ok: true, link: resolved.link, asset }
|
||||
}
|
||||
|
||||
/*
|
||||
* [ROUTE] Healthcheck
|
||||
* The path matches for /share/healthcheck, and also the legacy /healthcheck
|
||||
@@ -148,28 +198,24 @@ app.post('/:shareType(share|s)/:key/download', decodeCookie, async (req, res) =>
|
||||
return
|
||||
}
|
||||
|
||||
const result = await getShareByKey(req.params.key, req.password, keyType)
|
||||
if (!result?.valid || !result.link) {
|
||||
respondToInvalidRequest(res, 404, 'Invalid share link')
|
||||
const resolved = await resolveShare(req, keyType)
|
||||
if (!resolved.ok) {
|
||||
respondToInvalidRequest(res, resolved.status, resolved.reason)
|
||||
return
|
||||
}
|
||||
if (result.passwordRequired) {
|
||||
respondToInvalidRequest(res, 401, 'Password required')
|
||||
return
|
||||
}
|
||||
if (!canDownload(result.link)) {
|
||||
if (!canDownload(resolved.link)) {
|
||||
respondToInvalidRequest(res, 403, 'Downloads disabled for this share')
|
||||
return
|
||||
}
|
||||
|
||||
const requested = new Set(requestedIds.map(String))
|
||||
const validAssets = result.link.assets.filter(a => requested.has(a.id))
|
||||
const validAssets = resolved.link.assets.filter(a => requested.has(a.id))
|
||||
if (validAssets.length === 0) {
|
||||
respondToInvalidRequest(res, 400, 'No valid assets in selection')
|
||||
return
|
||||
}
|
||||
|
||||
await downloadAssets(res, result.link, validAssets)
|
||||
await downloadAssets(res, resolved.link, validAssets)
|
||||
})
|
||||
|
||||
/*
|
||||
@@ -188,44 +234,29 @@ app.get('/share/:type(photo|video)/:key/:id/:size?', decodeCookie, async (req, r
|
||||
// Add the headers configured in config.json (most likely `cache-control`)
|
||||
addResponseHeaders(res)
|
||||
|
||||
// Check for valid key and ID
|
||||
if (!isKey(req.params.key) || !isId(req.params.id)) {
|
||||
respondToInvalidRequest(res, 404, 'Invalid key or ID for ' + req.path)
|
||||
return
|
||||
}
|
||||
|
||||
// Validate the size parameter
|
||||
if (req.params.size && !Object.values(ImageSize).includes(req.params.size as ImageSize)) {
|
||||
respondToInvalidRequest(res, 404, 'Invalid size parameter ' + req.path)
|
||||
return
|
||||
}
|
||||
|
||||
// Validate share link and check password before serving assets
|
||||
// This prevents direct URL access from bypassing password protection
|
||||
// The password is provided from the encrypted session cookie (if set)
|
||||
const share = await getShareByKey(req.params.key, req.password)
|
||||
if (!share) {
|
||||
respondToInvalidRequest(res, 404, 'Invalid share link')
|
||||
return
|
||||
}
|
||||
|
||||
// If password is required but not provided, redirect to the share page
|
||||
if (share.passwordRequired) {
|
||||
res.redirect('/share/' + req.params.key)
|
||||
return
|
||||
}
|
||||
|
||||
// Find the real asset on the share so assetBuffer has access to
|
||||
// originalMimeType and originalFileName (needed for Content-Disposition and
|
||||
// for requiresOriginal to recognise videos/animated images and bypass the
|
||||
// preview downgrade). Doubles as the "belongs to this share" check.
|
||||
const realAsset = share.link?.assets?.find(a => a.id === req.params.id)
|
||||
if (!realAsset) {
|
||||
respondToInvalidRequest(res, 404, 'Asset not found in share')
|
||||
// Resolve the share + asset (this is a `/share/...` route, always key auth).
|
||||
// The resolved asset gives assetBuffer access to originalMimeType and
|
||||
// originalFileName (needed for Content-Disposition and for requiresOriginal
|
||||
// to recognise videos/animated images and bypass the preview downgrade).
|
||||
const resolved = await resolveSharedAsset(req, KeyType.key)
|
||||
if (!resolved.ok) {
|
||||
// Password-protected: redirect to the share page so the visitor gets the
|
||||
// unlock prompt, rather than returning an error.
|
||||
if (resolved.passwordRequired) {
|
||||
res.redirect('/share/' + req.params.key)
|
||||
return
|
||||
}
|
||||
respondToInvalidRequest(res, resolved.status, resolved.reason)
|
||||
return
|
||||
}
|
||||
const asset: Asset = {
|
||||
...realAsset,
|
||||
...resolved.asset,
|
||||
type: req.params.type === 'video' ? AssetType.video : AssetType.image
|
||||
}
|
||||
|
||||
@@ -237,6 +268,33 @@ app.get('/share/:type(photo|video)/:key/:id/:size?', decodeCookie, async (req, r
|
||||
assetBuffer(request, res, asset, req.params.size).then()
|
||||
})
|
||||
|
||||
/*
|
||||
* [ROUTE] On-demand per-asset metadata for lazy album items.
|
||||
*
|
||||
* Album shares enumerate their assets from the timeline API, which yields
|
||||
* grid-only data (no exif / filename / description). When such an item opens
|
||||
* in the lightbox, the client fetches its detail from here. The id is
|
||||
* validated against the share's asset set (defence in depth - Immich also
|
||||
* enforces this via the share key) before we fetch `GET /assets/:id`.
|
||||
*/
|
||||
app.get('/:shareType(share|s)/meta/:key/:id', decodeCookie, async (req, res) => {
|
||||
addResponseHeaders(res)
|
||||
|
||||
const resolved = await resolveSharedAsset(req, getKeyTypeFromShare(req.params.shareType))
|
||||
if (!resolved.ok) {
|
||||
respondToInvalidRequest(res, resolved.status, resolved.reason)
|
||||
return
|
||||
}
|
||||
|
||||
const detail = await fetchAssetDetail(resolved.asset)
|
||||
if (!detail) {
|
||||
respondToInvalidRequest(res, 404, 'Asset detail unavailable for ' + req.params.id)
|
||||
return
|
||||
}
|
||||
|
||||
res.json(buildAssetMetadata(detail, resolved.link))
|
||||
})
|
||||
|
||||
/*
|
||||
* [ROUTE] Home page
|
||||
*
|
||||
|
||||
+19
-8
@@ -1,4 +1,4 @@
|
||||
/**
|
||||
/*
|
||||
* Types shared between the server (Preact SSR) and the client (gallery).
|
||||
* Only put a type here if it crosses the server/client boundary - i.e. it
|
||||
* describes data the server serialises into the gallery's init JSON block.
|
||||
@@ -40,20 +40,30 @@ export interface GalleryItem {
|
||||
// Pre-stringified JSON describing the video source (used to build a <video>
|
||||
// element for video slides in the PhotoSwipe lightbox)
|
||||
videoData?: string
|
||||
// Plain-text caption shown below the image in the lightbox and at the top
|
||||
// of the info sidebar. Rendered with `textContent` on the client.
|
||||
// Immich uses "description" but this is our caption
|
||||
description?: string
|
||||
downloadFilename: string
|
||||
// Display dimensions after EXIF orientation correction; needed for the
|
||||
// pre-computed justified-rows layout that virtualisation depends on.
|
||||
width?: number
|
||||
height?: number
|
||||
// Base64-encoded thumbhash for an optional blur placeholder behind each tile
|
||||
thumbhash?: string
|
||||
// ISO date string from Immich; used to group tiles by month when enabled.
|
||||
fileCreatedAt?: string
|
||||
// Per-field gated EXIF / location metadata for the sidebar (see GalleryExif).
|
||||
exif?: GalleryExif
|
||||
// True for album "grid" items whose exif / description / real download
|
||||
// filename haven't been loaded yet. The client fetches them from the
|
||||
// `/meta/` route the first time the item opens in the lightbox.
|
||||
needsDetail?: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Per-asset detail fetched on demand from the `/meta/` route when a lazy
|
||||
* (`needsDetail`) album item opens in the lightbox. Mirrors the subset of a
|
||||
* full asset the gallery actually renders. All fields respect the share's
|
||||
* `showMetadata` toggle and the operator's `ipp.showMetadata.*` config.
|
||||
*/
|
||||
export interface AssetMetadata {
|
||||
exif?: GalleryExif
|
||||
description?: string
|
||||
downloadFilename?: string
|
||||
}
|
||||
|
||||
export interface LightboxConfig {
|
||||
@@ -88,4 +98,5 @@ export interface InitParams {
|
||||
lightboxConfig?: LightboxConfig
|
||||
metadataConfig?: MetadataConfig
|
||||
groupByDate?: boolean
|
||||
metaBase?: string
|
||||
}
|
||||
|
||||
@@ -187,12 +187,55 @@ async function stageOne (asset: Asset, index: number, options: StagingOptions, a
|
||||
if (fetched === null) return null
|
||||
if ('failure' in fetched) return { failure: { ...fetched.failure, asset, url } }
|
||||
|
||||
// Album "grid" assets (timeline-sourced) lack originalFileName/Mime, so
|
||||
// getFilename would fall back to an id-based name. The `/original` response
|
||||
// carries the real name in Content-Disposition and the mime in Content-Type,
|
||||
// so recover them from the headers we already fetched - no extra calls.
|
||||
const stagedAsset = asset.originalFileName ? asset : enrichFromHeaders(asset, fetched.response)
|
||||
|
||||
// Use the array index in the path so we never collide on duplicate IDs.
|
||||
const tempfile = join(options.stagingDir, `${index}-${asset.id}`)
|
||||
const streamed = await streamBodyToTempFile(fetched.response, tempfile, options.idleTimeoutMs)
|
||||
if ('failure' in streamed) return { failure: { asset, url, error: streamed.failure } }
|
||||
|
||||
return { tempfile, asset, endpoint }
|
||||
return { tempfile, asset: stagedAsset, endpoint }
|
||||
}
|
||||
|
||||
/**
|
||||
* Fill in originalFileName / originalMimeType from an asset response's
|
||||
* `Content-Disposition` / `Content-Type` headers, for assets that arrived
|
||||
* without them (lazy album grid assets). Returns a shallow copy so the cached
|
||||
* share asset is never mutated.
|
||||
*/
|
||||
function enrichFromHeaders (asset: Asset, response: globalThis.Response): Asset {
|
||||
const fileName = filenameFromContentDisposition(response.headers.get('content-disposition'))
|
||||
const mime = (response.headers.get('content-type') || '').split(';')[0].trim() || undefined
|
||||
if (!fileName && !mime) return asset
|
||||
return {
|
||||
...asset,
|
||||
originalFileName: asset.originalFileName || fileName,
|
||||
originalMimeType: asset.originalMimeType || mime
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract a filename from a `Content-Disposition` header. Prefers the RFC 5987
|
||||
* `filename*=UTF-8''...` form (percent-decoded) over the plain `filename=`.
|
||||
* Returns undefined when neither is present.
|
||||
*/
|
||||
export function filenameFromContentDisposition (header: string | null): string | undefined {
|
||||
if (!header) return undefined
|
||||
const extended = header.match(/filename\*=(?:UTF-8'')?([^;]+)/i)
|
||||
if (extended) {
|
||||
const raw = extended[1].trim().replace(/^"|"$/g, '')
|
||||
try {
|
||||
return decodeURIComponent(raw)
|
||||
} catch (e) {
|
||||
return raw
|
||||
}
|
||||
}
|
||||
const plain = header.match(/filename="?([^";]+)"?/i)
|
||||
return plain ? plain[1].trim() : undefined
|
||||
}
|
||||
|
||||
type HeaderFetchOutcome =
|
||||
|
||||
+28
-9
@@ -45,7 +45,7 @@ export interface Asset {
|
||||
key: string;
|
||||
keyType: KeyType;
|
||||
originalFileName?: string;
|
||||
originalMimeType: string;
|
||||
originalMimeType?: string;
|
||||
password?: string;
|
||||
fileCreatedAt?: string; // May not exist - see https://github.com/alangrainger/immich-public-proxy/issues/61
|
||||
type: AssetType;
|
||||
@@ -55,12 +55,34 @@ export interface Asset {
|
||||
height?: number;
|
||||
// Base64-encoded thumbhash for tasteful blur placeholders during lazy-load
|
||||
thumbhash?: string;
|
||||
// True for album assets enumerated via the timeline API, which give us only
|
||||
// grid fields (id, type, ratio, thumbhash, isTrashed, fileCreatedAt). Their
|
||||
// exif / originalFileName / description are fetched lazily when the asset is
|
||||
// opened in the lightbox (see the `/meta/` route + client/metadata.ts).
|
||||
needsDetail?: boolean;
|
||||
}
|
||||
|
||||
export interface Album {
|
||||
id: string;
|
||||
assets: Asset[];
|
||||
albumThumbnailAssetId?: string;
|
||||
/**
|
||||
* One entry of `GET /timeline/buckets` - a time bucket (month) and its count.
|
||||
*/
|
||||
export interface TimelineBucket {
|
||||
timeBucket: string;
|
||||
count: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* `GET /timeline/bucket` columnar (struct-of-arrays) response. Each array is
|
||||
* index-aligned: element `i` of every array describes the same asset. Only
|
||||
* the fields the gallery grid needs are typed here; Immich returns more.
|
||||
*/
|
||||
export interface TimelineBucketAssets {
|
||||
id: string[];
|
||||
isImage: boolean[];
|
||||
// width / height ratio (Immich's `ratio` already accounts for orientation)
|
||||
ratio: number[];
|
||||
thumbhash: (string | null)[];
|
||||
isTrashed: boolean[];
|
||||
fileCreatedAt: string[];
|
||||
}
|
||||
|
||||
export interface SharedLink {
|
||||
@@ -70,10 +92,6 @@ export interface SharedLink {
|
||||
description?: string;
|
||||
assets: Asset[];
|
||||
allowDownload?: boolean;
|
||||
// Per-share "Show metadata" toggle from Immich. When `false`, the share owner
|
||||
// has asked that no EXIF / location / description / filename metadata be
|
||||
// surfaced to viewers. We treat this as a kill-switch over the operator's
|
||||
// own `ipp.showMetadata.*` config: see `gallery/builder.ts`.
|
||||
showMetadata?: boolean;
|
||||
password?: string;
|
||||
album?: {
|
||||
@@ -82,6 +100,7 @@ export interface SharedLink {
|
||||
order?: string;
|
||||
description?: string;
|
||||
albumThumbnailAssetId?: string;
|
||||
assetCount?: number;
|
||||
}
|
||||
expiresAt: string | null;
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@ export interface GalleryProps {
|
||||
lightboxConfig: LightboxConfig
|
||||
metadataConfig: MetadataConfig
|
||||
groupByDate: boolean
|
||||
metaBase?: string
|
||||
}
|
||||
|
||||
export function Gallery (props: GalleryProps) {
|
||||
@@ -25,7 +26,8 @@ export function Gallery (props: GalleryProps) {
|
||||
openItem: props.openItem,
|
||||
lightboxConfig: props.lightboxConfig,
|
||||
metadataConfig: props.metadataConfig,
|
||||
groupByDate: props.groupByDate
|
||||
groupByDate: props.groupByDate,
|
||||
metaBase: props.metaBase
|
||||
})
|
||||
const firstItem = props.items[0]
|
||||
// og:image prefers the album cover (passed via props); for videos, previewUrl
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
|
||||
import { getShareByKey } from '../src/immich'
|
||||
import { KeyType } from '../src/types'
|
||||
|
||||
// 3.0-shaped responses: album `/shared-links/me` returns an empty assets[],
|
||||
// and the album's assets are enumerated from the timeline API. This exercises
|
||||
// the regression fix end-to-end through getShareByKey -> fetchShareByKey.
|
||||
|
||||
interface MockResponse {
|
||||
ok: boolean
|
||||
status: number
|
||||
headers: { get: (h: string) => string | null }
|
||||
json: () => Promise<unknown>
|
||||
}
|
||||
|
||||
function jsonResponse (body: unknown, status = 200): MockResponse {
|
||||
return {
|
||||
ok: status >= 200 && status < 300,
|
||||
status,
|
||||
headers: { get: (h: string) => (h.toLowerCase() === 'content-type' ? 'application/json' : null) },
|
||||
json: async () => body
|
||||
}
|
||||
}
|
||||
|
||||
const ALBUM_ID = '0aab733a-3cb4-416f-b4b9-f94906533aaa'
|
||||
|
||||
const sharedLinkResponse = (order?: string) => ({
|
||||
type: 'ALBUM',
|
||||
assets: [],
|
||||
allowDownload: true,
|
||||
expiresAt: null,
|
||||
showMetadata: true,
|
||||
key: 'real-key',
|
||||
album: {
|
||||
id: ALBUM_ID,
|
||||
albumName: 'Test album',
|
||||
albumThumbnailAssetId: 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',
|
||||
order
|
||||
}
|
||||
})
|
||||
|
||||
const bucketsResponse = [{ timeBucket: '2026-06-01', count: 3 }]
|
||||
|
||||
// Columnar (struct-of-arrays). Index 1 is trashed and must be filtered out.
|
||||
const bucketResponse = {
|
||||
id: [
|
||||
'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',
|
||||
'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb',
|
||||
'cccccccc-cccc-cccc-cccc-cccccccccccc'
|
||||
],
|
||||
isImage: [true, true, false],
|
||||
ratio: [1.5, 0.5, 1],
|
||||
thumbhash: ['hashA', null, 'hashC'],
|
||||
isTrashed: [false, true, false],
|
||||
fileCreatedAt: ['2026-06-03T00:00:00.000Z', '2026-06-02T00:00:00.000Z', '2026-06-01T00:00:00.000Z']
|
||||
}
|
||||
|
||||
function routeFetch (sharedLink: unknown) {
|
||||
return vi.fn(async (url: string) => {
|
||||
if (url.includes('/shared-links/me')) return jsonResponse(sharedLink)
|
||||
if (url.includes('/timeline/buckets')) return jsonResponse(bucketsResponse)
|
||||
if (url.includes('/timeline/bucket')) return jsonResponse(bucketResponse)
|
||||
throw new Error('Unexpected fetch to ' + url)
|
||||
})
|
||||
}
|
||||
|
||||
let keyCounter = 0
|
||||
function uniqueKey () {
|
||||
// getShareByKey caches by key; a fresh key per test avoids cross-test reuse.
|
||||
return 'album-key-' + (keyCounter++)
|
||||
}
|
||||
|
||||
describe('album timeline enumeration (Immich 3.0)', () => {
|
||||
beforeEach(() => {
|
||||
process.env.IMMICH_URL = 'http://immich.test'
|
||||
})
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
it('populates grid assets from the timeline and filters trashed', async () => {
|
||||
vi.stubGlobal('fetch', routeFetch(sharedLinkResponse()))
|
||||
const result = await getShareByKey(uniqueKey(), undefined, KeyType.key)
|
||||
|
||||
expect(result.valid).toBe(true)
|
||||
const assets = result.link!.assets
|
||||
// 3 assets, 1 trashed -> 2 survive
|
||||
expect(assets.map(a => a.id)).toEqual([
|
||||
'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',
|
||||
'cccccccc-cccc-cccc-cccc-cccccccccccc'
|
||||
])
|
||||
// grid assets are flagged for lazy detail loading
|
||||
expect(assets.every(a => a.needsDetail)).toBe(true)
|
||||
// type derived from isImage
|
||||
expect(assets[0].type).toBe('IMAGE')
|
||||
expect(assets[1].type).toBe('VIDEO')
|
||||
// thumbhash carried through; null becomes undefined
|
||||
expect(assets[0].thumbhash).toBe('hashA')
|
||||
// dimensions derived from ratio (landscape 1.5 -> wider than tall)
|
||||
expect(assets[0].width!).toBeGreaterThan(assets[0].height!)
|
||||
})
|
||||
|
||||
it('stamps the share key/keyType onto every asset', async () => {
|
||||
vi.stubGlobal('fetch', routeFetch(sharedLinkResponse()))
|
||||
const key = uniqueKey()
|
||||
const result = await getShareByKey(key, undefined, KeyType.key)
|
||||
expect(result.link!.assets.every(a => a.key === key && a.keyType === KeyType.key)).toBe(true)
|
||||
})
|
||||
|
||||
it('respects album sort order asc', async () => {
|
||||
vi.stubGlobal('fetch', routeFetch(sharedLinkResponse('asc')))
|
||||
const result = await getShareByKey(uniqueKey(), undefined, KeyType.key)
|
||||
const dates = result.link!.assets.map(a => a.fileCreatedAt)
|
||||
expect(dates).toEqual([...dates].sort())
|
||||
})
|
||||
|
||||
it('respects album sort order desc', async () => {
|
||||
vi.stubGlobal('fetch', routeFetch(sharedLinkResponse('desc')))
|
||||
const result = await getShareByKey(uniqueKey(), undefined, KeyType.key)
|
||||
const dates = result.link!.assets.map(a => a.fileCreatedAt)
|
||||
expect(dates).toEqual([...dates].sort().reverse())
|
||||
})
|
||||
|
||||
it('keeps the album cover id from /shared-links/me (no extra album fetch)', async () => {
|
||||
vi.stubGlobal('fetch', routeFetch(sharedLinkResponse()))
|
||||
const result = await getShareByKey(uniqueKey(), undefined, KeyType.key)
|
||||
expect(result.link!.album!.albumThumbnailAssetId).toBe('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa')
|
||||
})
|
||||
|
||||
it('is invalid when the album share has no album id', async () => {
|
||||
const noId = { ...sharedLinkResponse(), album: undefined }
|
||||
vi.stubGlobal('fetch', routeFetch(noId))
|
||||
const result = await getShareByKey(uniqueKey(), undefined, KeyType.key)
|
||||
expect(result.valid).toBe(false)
|
||||
})
|
||||
|
||||
it('is invalid (not cached empty) when timeline enumeration fails upstream', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn(async (url: string) => {
|
||||
if (url.includes('/shared-links/me')) return jsonResponse(sharedLinkResponse())
|
||||
if (url.includes('/timeline/buckets')) return jsonResponse({ message: 'boom' }, 500)
|
||||
throw new Error('Unexpected fetch to ' + url)
|
||||
}))
|
||||
const result = await getShareByKey(uniqueKey(), undefined, KeyType.key)
|
||||
expect(result.valid).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,80 @@
|
||||
import { describe, it, expect, beforeEach } from 'vitest'
|
||||
import { buildAssetMetadata } from '../src/gallery/metadata'
|
||||
import { loadConfig } from '../src/config/loader'
|
||||
import { Asset, AssetType, KeyType, SharedLink } from '../src/types'
|
||||
|
||||
// buildAssetMetadata is the lazy-flow counterpart to the gallery builder's
|
||||
// per-item baking; it must apply the same showMetadata kill-switch and
|
||||
// ipp.showMetadata.* gating so nothing leaks that the operator didn't opt into.
|
||||
|
||||
function setConfig (config: unknown) {
|
||||
process.env.CONFIG = JSON.stringify(config)
|
||||
loadConfig()
|
||||
}
|
||||
|
||||
const asset = (): Asset => ({
|
||||
id: 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',
|
||||
key: 'k',
|
||||
keyType: KeyType.key,
|
||||
type: AssetType.image,
|
||||
isTrashed: false,
|
||||
originalFileName: 'IMG_1234.HEIC',
|
||||
originalMimeType: 'image/heic',
|
||||
exifInfo: {
|
||||
description: 'A nice photo',
|
||||
make: 'Canon',
|
||||
model: 'EOS R5',
|
||||
city: 'Paris',
|
||||
country: 'France',
|
||||
latitude: 48.8,
|
||||
longitude: 2.3
|
||||
}
|
||||
})
|
||||
|
||||
const share = (showMetadata?: boolean): SharedLink => ({
|
||||
key: 'k',
|
||||
keyType: KeyType.key,
|
||||
type: 'ALBUM',
|
||||
assets: [],
|
||||
showMetadata,
|
||||
expiresAt: null
|
||||
})
|
||||
|
||||
describe('buildAssetMetadata', () => {
|
||||
beforeEach(() => {
|
||||
delete process.env.CONFIG
|
||||
loadConfig()
|
||||
})
|
||||
|
||||
it('returns exif when the matching per-field flags are enabled', () => {
|
||||
setConfig({ ipp: { showMetadata: { exif: { make: true, model: true } } } })
|
||||
const meta = buildAssetMetadata(asset(), share())
|
||||
expect(meta.exif?.make).toBe('Canon')
|
||||
expect(meta.exif?.model).toBe('EOS R5')
|
||||
// location not enabled -> absent
|
||||
expect(meta.exif?.city).toBeUndefined()
|
||||
})
|
||||
|
||||
it('returns description when a description surface is enabled', () => {
|
||||
setConfig({ ipp: { showMetadata: { description: { sidebar: true } } } })
|
||||
const meta = buildAssetMetadata(asset(), share())
|
||||
expect(meta.description).toBe('A nice photo')
|
||||
})
|
||||
|
||||
it('suppresses everything when the share showMetadata is false', () => {
|
||||
setConfig({ ipp: { showMetadata: { exif: { make: true }, description: { sidebar: true } } } })
|
||||
const meta = buildAssetMetadata(asset(), share(false))
|
||||
expect(meta.exif).toBeUndefined()
|
||||
expect(meta.description).toBeUndefined()
|
||||
// filename is still returned (not gated by showMetadata - it's a download
|
||||
// affordance, mirroring the eager builder's downloadFilename)
|
||||
expect(meta.downloadFilename).toBeTruthy()
|
||||
})
|
||||
|
||||
it('always returns a download filename', () => {
|
||||
setConfig({})
|
||||
const meta = buildAssetMetadata(asset(), share())
|
||||
// HEIC original served as preview JPEG when downloadOriginalPhoto defaults on
|
||||
expect(meta.downloadFilename).toMatch(/IMG_1234/)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,25 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { filenameFromContentDisposition } from '../src/stream/download'
|
||||
|
||||
// Used by the zip download path to recover the real filename for album grid
|
||||
// assets (which arrive without originalFileName) from the /original response.
|
||||
|
||||
describe('filenameFromContentDisposition', () => {
|
||||
it('prefers the RFC 5987 filename* form and percent-decodes it', () => {
|
||||
const header = "attachment; filename=\"IMG.jpg\"; filename*=UTF-8''Photo%20%C3%A9t%C3%A9.jpg"
|
||||
expect(filenameFromContentDisposition(header)).toBe('Photo été.jpg')
|
||||
})
|
||||
|
||||
it('falls back to the plain quoted filename', () => {
|
||||
expect(filenameFromContentDisposition('attachment; filename="IMG_1234.HEIC"')).toBe('IMG_1234.HEIC')
|
||||
})
|
||||
|
||||
it('handles an unquoted plain filename', () => {
|
||||
expect(filenameFromContentDisposition('attachment; filename=clip.mp4')).toBe('clip.mp4')
|
||||
})
|
||||
|
||||
it('returns undefined when no filename is present', () => {
|
||||
expect(filenameFromContentDisposition('attachment')).toBeUndefined()
|
||||
expect(filenameFromContentDisposition(null)).toBeUndefined()
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user