Files
immich-magic-proxy/app/src/immich.ts
T
Andrew Hyatt 83cc0f4bb6 Cache share and album metadata for 2 minutes.
Fixes 5 second loading time for every image that I experienced with an album of 2,500 photos.
2026-05-25 22:20:30 -04:00

378 lines
13 KiB
TypeScript

import {
Album,
AlbumType,
Asset,
AssetType,
ImageSize,
IncomingShareRequest,
KeyType,
SharedLink,
SharedLinkResult
} from './types'
import dayjs from 'dayjs'
import { addResponseHeaders, canDownload, getConfigOption, log } from './functions'
import render from './render'
import { Response } from 'express-serve-static-core'
import { h } from 'preact'
import { renderPage } from './views/_render'
import { Password } from './views/password'
import { respondToInvalidRequest } from './invalidRequestHandler'
import { encrypt } from './encrypt'
// 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.
type ShareCacheEntry = { promise: Promise<SharedLinkResult>; expiresAt: number }
const shareCache = new Map<string, ShareCacheEntry>()
const shareCacheTtlMs = 120_000
// Each entry can hold a SharedLink with thousands of assets, so cap entries
// to keep memory bounded on a public-facing proxy. Eviction is FIFO by
// insertion order (Map iteration order), which is good enough — TTL handles
// freshness.
const shareCacheMax = 100
class Immich {
/**
* Make a request to Immich API. We're not using the SDK to limit
* the possible attack surface of this app.
*/
async request (endpoint: string) {
try {
const res = await fetch(this.apiUrl() + endpoint)
if (res.status === 200) {
const contentType = res.headers.get('Content-Type') || ''
if (contentType.includes('application/json')) {
return res.json()
} else {
return res
}
} else {
log('Immich API status ' + res.status)
console.log(await res.text())
}
} catch (e) {
log('Unable to reach Immich on ' + process.env.IMMICH_URL)
log(`From the server IPP is running on, see if you can curl to ${this.apiUrl()}/server/ping and receive a JSON result.`)
}
}
apiUrl () {
return (process.env.IMMICH_URL || '').replace(/\/*$/, '') + '/api'
}
/**
* Handle an incoming request for a shared link `key`. This is the main function which
* communicates with Immich and returns the output back to the visitor.
*
* Possible HTTP responses are:
*
* 200 - either a photo gallery or the unlock page.
* 401 - the visitor provided a password but it was invalid.
* 404 - any other failed request. Check console.log for details.
*/
async handleShareRequest (request: IncomingShareRequest, res: Response) {
addResponseHeaders(res)
// Check that the key is a valid format
if (!immich.isKey(request.key)) {
respondToInvalidRequest(res, 404, 'Wrong key format ' + request.key)
return
}
// Get information about the shared link via Immich API
const sharedLinkRes = await immich.getShareByKey(request.key, request.password, request.keyType || KeyType.key)
if (!sharedLinkRes.valid) {
// This isn't a valid request - check the console for more information
respondToInvalidRequest(res, 404, 'Invalid request')
return
}
// A password is required, but the visitor-provided one doesn't match
if (sharedLinkRes.passwordRequired && request.password) {
log('Invalid password for key ' + request.key)
res.status(401)
// Delete the cookie-session data, so that it doesn't keep saying "Invalid password"
if (request.req?.session) delete request.req.session[request.key]
}
// Don't cache password-protected albums
if (sharedLinkRes.passwordRequired || request.password) {
res.header('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate')
res.header('Pragma', 'no-cache')
res.header('Expires', '0')
}
// Password required - show the visitor the password page
if (sharedLinkRes.passwordRequired) {
// `request.key` is already sanitised at this point, but it never hurts to be explicit
const shareKey = request.key.replace(/[^\w-]/g, '')
res.send(renderPage(h(Password, {
shareKey,
notifyInvalidPassword: !!request.password
})))
return
}
if (!sharedLinkRes.link) {
respondToInvalidRequest(res, 404, 'Unknown error with key ' + request.key)
return
}
const link = sharedLinkRes.link
// If this was a password-protected slug link, we need to also store session information for the ID-based key
if (request.password && request.req.session && !request.req.session[link.key]) {
request.req.session[link.key] = encrypt(JSON.stringify({
password: request.password,
expires: dayjs().add(1, 'hour').format()
}))
}
// Everything is ok - output the shared link data
if (request.mode === 'download' && canDownload(link)) {
// Download all assets as a zip file
await render.downloadAll(res, link)
} else if (link.assets.length === 1) {
// This is an individual item (not a gallery)
log('Serving link ' + request.key)
const asset = link.assets[0]
if (asset.type === AssetType.image && !getConfigOption('ipp.gallery.singleImage') && !request.password) {
// For photos, output the image directly unless configured to show a gallery,
// or unless it's a password-protected link
await render.assetBuffer(request, res, link.assets[0], ImageSize.preview)
} else {
// Show a gallery page
const openItem = getConfigOption('ipp.gallery.singleItemAutoOpen', true) ? 1 : 0
await render.gallery(res, link, openItem)
}
} else {
// Multiple images - render as a gallery
log('Serving link ' + request.key)
await render.gallery(res, link)
}
}
/**
* Query Immich for the SharedLink metadata for a given key, with a short
* 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.
* Negative results (`valid: false`) and rejections are dropped from the
* cache immediately so a transient Immich blip doesn't poison the cache.
*/
async getShareByKey (key: string, password?: string, keyType: KeyType = KeyType.key): Promise<SharedLinkResult> {
const cacheKey = `${keyType}:${key}:${password ?? ''}`
const now = Date.now()
const cached = shareCache.get(cacheKey)
if (cached && cached.expiresAt > now) return cached.promise
const promise = this.fetchShareByKey(key, password, keyType)
shareCache.set(cacheKey, { promise, expiresAt: now + shareCacheTtlMs })
if (shareCache.size > shareCacheMax) {
const oldest = shareCache.keys().next().value
if (oldest !== undefined && oldest !== cacheKey) shareCache.delete(oldest)
}
promise.then(
(result) => { if (!result?.valid) shareCache.delete(cacheKey) },
() => { shareCache.delete(cacheKey) }
)
return promise
}
/**
* Underlying fetch for getShareByKey. Always hits Immich; the public
* getShareByKey wraps this with the cache. Don't call this directly from
* outside the class — going through getShareByKey is what gives us the
* coalescing on cold misses.
*/
private async fetchShareByKey (key: string, password?: string, keyType: KeyType = KeyType.key): Promise<SharedLinkResult> {
let link
const url = this.buildUrl(this.apiUrl() + '/shared-links/me', {
[keyType]: key,
password
})
const res = await fetch(url)
if ((res.headers.get('Content-Type') || '').toLowerCase().includes('application/json')) {
const jsonBody = await res.json()
if (jsonBody) {
if (res.status === 200) {
// Normal response - get the shared assets
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
if (link.type === AlbumType.album) {
const albumRes = await fetch(this.buildUrl(this.apiUrl() + '/albums/' + link?.album?.id, {
[keyType]: key,
password
}))
const album = await albumRes.json() as Album
if (!album?.id) {
log('Invalid album ID - ' + link?.album?.id)
return {
valid: false
}
}
// Replace the empty link.assets array with the array of assets from the album
link.assets = album.assets
}
link.password = password
if (link.expiresAt && dayjs(link.expiresAt) < dayjs()) {
// This link has expired
log('Expired link ' + key)
} else {
// Filter assets to exclude trashed assets
link.assets = link.assets.filter(asset => !asset.isTrashed)
// Populate the shared assets with the public key/password
link.assets.forEach(asset => {
asset.key = key
asset.keyType = keyType
asset.password = password
})
// Sort album if there is a sort order specified
const sortOrder = link.album?.order
if (sortOrder === 'asc') {
link.assets.sort((a, b) => a?.fileCreatedAt?.localeCompare(b.fileCreatedAt || '') || 0)
} else if (sortOrder === 'desc') {
link.assets.sort((a, b) => b?.fileCreatedAt?.localeCompare(a.fileCreatedAt || '') || 0)
}
return {
valid: true,
link
}
}
} else if (res.status === 401) {
// Immich returns 401 for both invalid keys and password-protected shares.
// Check the message to distinguish between the two cases.
if (jsonBody?.message === 'Invalid share key' || jsonBody?.message === 'Invalid share slug') {
// Known invalid key/slug - treat as invalid request
log('Invalid share key ' + key)
} else {
// Default: treat as password required (fail-safe)
return {
valid: true,
passwordRequired: true
}
}
} else {
console.log(JSON.stringify(jsonBody))
}
}
} else {
// Otherwise return failure
log('Immich response ' + res.status + ' for key ' + key)
try {
console.log(res.headers.get('Content-Type'))
console.log((await res.text()).slice(0, 500))
log('Unexpected response from Immich API at ' + this.apiUrl())
log('Please make sure the IPP container is able to reach this path.')
} catch (e) {
console.log(e)
}
}
return {
valid: false
}
}
/**
* Get the content-type of a video, for the lightbox <video> element
*/
async getVideoContentType (asset: Asset) {
const data = await this.request(this.buildUrl('/assets/' + encodeURIComponent(asset.id) + '/video/playback', {
[asset.keyType]: asset.key,
password: asset.password
}))
return data.headers.get('Content-Type')
}
/**
* Build safely-encoded URL string
*/
buildUrl (baseUrl: string, params: { [key: string]: string | undefined } = {}) {
// Remove empty properties
params = Object.fromEntries(Object.entries(params).filter(([_, value]) => !!value))
let query = ''
// Safely encode query parameters
if (Object.entries(params).length) {
query = '?' + (new URLSearchParams(params as {
[key: string]: string
})).toString()
}
return baseUrl + query
}
/**
* Return the correct preview size, depending on the image MIME type
*/
getPreviewImageSize (asset: Asset) {
// For certain media types, use the original file rather than the preview
if (['image/gif'].includes(asset.originalMimeType || '')) {
return ImageSize.original
} else {
return ImageSize.preview
}
}
/**
* Return the image data URL for a photo
*/
photoUrl (key: string, id: string, size?: ImageSize) {
const path = ['photo', key, id]
if (size) path.push(size)
return this.buildUrl('/share/' + path.join('/'))
}
/**
* Return the video data URL for a video
*/
videoUrl (key: string, id: string) {
return this.buildUrl(`/share/video/${key}/${id}`)
}
/**
* Check if a provided ID matches the Immich ID format
*/
isId (id: string) {
return !!id.match(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/)
}
/**
* Check if a provided key matches the Immich shared-link key format.
* It appears that the key is always 67 chars long, but since I don't know that this
* will always be the case, I've left it open-ended.
*/
isKey (key: string) {
return !!key.match(/^[\w-]+$/)
}
async accessible () {
return !!(await immich.request('/server/ping'))
}
validateImageSize (size: unknown) {
if (!size || !Object.values(ImageSize).includes(size as ImageSize)) {
return ImageSize.preview
} else {
return size as ImageSize
}
}
getKeyTypeFromShare (shareType: string) {
return shareType === 's' ? KeyType.slug : KeyType.key
}
}
const immich = new Immich()
export default immich