#162 #258 Serve fullsize image on zoom (configurable)

This commit is contained in:
Alan Grainger
2026-06-30 13:01:54 +12:00
parent 494fbe36c7
commit 00da9018cf
18 changed files with 561 additions and 135 deletions
+3 -2
View File
@@ -4,9 +4,10 @@
"Cache-Control": "public, max-age=2592000",
"Access-Control-Allow-Origin": "*"
},
"downloadOriginalPhoto": true,
"maxDownloadQuality": "original",
"maxZoomQuality": "preview",
"downloadedFilename": 0,
"allowDownloadAll": 0,
"allowDownload": 0,
"downloadFromImmichConcurrencyLimit": 20,
"allowSlugLinks": true,
"showHomePage": true,
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "immich-public-proxy",
"version": "2.5.0",
"version": "3.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "immich-public-proxy",
"version": "2.5.0",
"version": "3.0.0",
"license": "AGPL-3.0",
"dependencies": {
"archiver": "^7.0.1",
+101 -3
View File
@@ -47,13 +47,19 @@ function escapeAttr (s: string): string {
return String(s).replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
}
// Per-slide bookkeeping for the zoom-to-upgrade + native-resolution cap, keyed
// by the gallery item index (stamped on each dataSource entry as `_ippIndex`).
// Reset on every lightbox open.
const loadedBitmapWidth = new Map<number, number>() // index -> naturalWidth of the bitmap now in the <img>
const upgradedSlides = new Set<number>() // indices already swapped to fullUrl
/**
* Translate `state.items` into PhotoSwipe's dataSource array. Images use
* `src`/`width`/`height`; videos use the `html` slide with a `<video>`
* element so PhotoSwipe streams from the server's `/share/video/...` URL.
*/
function buildDataSource () {
return state.items.map(item => {
return state.items.map((item, idx) => {
if (item.type === 'VIDEO') {
const v = parseVideoData(item)
const typeAttr = v.type ? ' type="' + escapeAttr(v.type) + '"' : ''
@@ -71,11 +77,95 @@ function buildDataSource () {
width: item.width || 1600,
height: item.height || 1200,
msrc: item.thumbnailUrl,
alt: item.description || ''
alt: item.description || '',
// Custom fields (PhotoSwipe passes them through on slideData untouched):
// the higher-res URL to swap in on zoom, and our item index so the zoom
// handlers can map a slide back to its loaded-bitmap bookkeeping.
fullUrl: item.fullUrl,
_ippIndex: idx
}
})
}
/**
* Wire up the zoom-to-upgrade + native-resolution cap on a PhotoSwipe lightbox.
*
* Two cooperating pieces, mirroring Immich's AdaptiveImage:
* 1. Cap the maximum zoom to the native pixels of whatever bitmap is currently
* loaded (at most 1:1). The cap follows the loaded bitmap, so it is
* self-correcting: if a `fullUrl` upgrade turns out to be a no-op (Immich
* handed back the preview again), the cap stays put.
* 2. When the user zooms past fit-to-screen, swap the slide's <img> to `fullUrl`
* once (if the server offered one), then recompute the cap against the new,
* larger bitmap to unlock deeper zoom.
*/
function registerZoomUpgrade (lightbox: { on: (ev: string, cb: (e: any) => void) => void }) { // eslint-disable-line @typescript-eslint/no-explicit-any
lightbox.on('zoomLevelsUpdate', (e) => {
const zoomLevels = e.zoomLevels
const idx = e.slideData?._ippIndex
const naturalWidth = (typeof idx === 'number') ? loadedBitmapWidth.get(idx) : undefined
const declaredWidth = zoomLevels?.elementSize?.x
if (naturalWidth && naturalWidth > 0 && declaredWidth > 0) {
// Display at most 1:1 with the loaded bitmap (cap = native px / declared
// px), but never below the fit level so the image can always be shown.
const cap = Math.max(zoomLevels.initial, naturalWidth / declaredWidth)
zoomLevels.max = cap
zoomLevels.secondary = Math.min(zoomLevels.secondary, cap)
}
})
// Record each image's real pixel width as it loads, then refresh that slide's
// cap (the first zoomLevelsUpdate usually runs before the bitmap is decoded).
lightbox.on('loadComplete', (e) => {
if (e.content?.type === 'image') recordAndRefresh(e.content)
})
// Upgrade on zoom-in, once per slide.
lightbox.on('zoomPanUpdate', (e) => {
const slide = e.slide
if (slide?.content?.type !== 'image') return
const data = slide.content.data || {}
const idx = data._ippIndex
if (typeof idx !== 'number' || upgradedSlides.has(idx) || !data.fullUrl) return
// Only when genuinely zoomed past the fit/initial level.
if (slide.currZoomLevel <= slide.zoomLevels.initial + 0.01) return
const img = slide.content.element
if (!(img instanceof HTMLImageElement)) return
upgradedSlides.add(idx)
// Preload first so the visible preview isn't blanked while the upgrade
// downloads; swap the src once it's ready, then recompute the cap.
const hi = new Image()
hi.addEventListener('load', () => {
img.addEventListener('load', () => recordAndRefresh(slide.content), { once: true })
img.src = data.fullUrl
})
hi.addEventListener('error', () => { upgradedSlides.delete(idx) }) // let a retry happen
hi.src = data.fullUrl
})
}
/**
* Record the loaded bitmap's natural width for a slide, then re-run its zoom
* calculation so the cap recomputes against that bitmap. `calculateSize()`
* re-dispatches `zoomLevelsUpdate`, where the cap is applied.
*/
function recordAndRefresh (content: any) { // eslint-disable-line @typescript-eslint/no-explicit-any
const img = content?.element
if (img instanceof HTMLImageElement && img.naturalWidth > 0 && typeof content.index === 'number') {
loadedBitmapWidth.set(content.index, img.naturalWidth)
}
const slide = content?.slide
if (slide && typeof slide.calculateSize === 'function') {
slide.calculateSize()
slide.updateContentSize(true)
// If a tighter cap just dropped below the current zoom (e.g. the preview
// finished loading after the user already zoomed in), snap back into range.
if (slide.isActive && slide.currZoomLevel > slide.zoomLevels.max) {
slide.zoomTo(slide.zoomLevels.max, false, 0)
}
}
}
/**
* Construct the PhotoSwipe lightbox, register its UI elements, set up hash
* navigation, and call `init()`. Reads config from `state.lightboxConfig`
@@ -107,6 +197,9 @@ export function initLightbox () {
closeOnVerticalDrag: true,
arrowKeys: true,
loop: false,
// Plain mouse wheel zooms the image (à la the Immich web viewer), instead of
// PhotoSwipe's default of requiring Ctrl/Alt+wheel.
wheelToZoom: true,
// Hidden by default to match Immich; operators can re-enable via
// ipp.lightbox.options, which is why these sit before the `...options` spread.
counter: false,
@@ -135,8 +228,13 @@ export function initLightbox () {
// 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 = [] })
state.lightbox.on('beforeOpen', () => {
state.slideRefreshers = []
loadedBitmapWidth.clear()
upgradedSlides.clear()
})
registerZoomUpgrade(state.lightbox)
registerBackButton(state.lightbox)
if (state.lightboxConfig.showDownload) registerDownloadButton(state.lightbox)
registerFullscreenButton(state.lightbox)
+39 -1
View File
@@ -25,7 +25,9 @@ const SHIMS: Shim[] = [
{ name: 'lightGallery', removeIn: 'v3.0', apply: applyLightGalleryShim },
{ name: 'topLevelGallery', removeIn: 'v3.0', apply: applyTopLevelGalleryShim },
{ name: 'descriptionSplit', removeIn: 'v3.0', apply: applyDescriptionSplitShim },
{ name: 'metadataEnabled', removeIn: 'v3.0', apply: applyMetadataEnabledShim }
{ name: 'metadataEnabled', removeIn: 'v3.0', apply: applyMetadataEnabledShim },
{ name: 'downloadOriginalPhoto', removeIn: 'v4.0', apply: applyDownloadQualityShim },
{ name: 'allowDownloadAll', removeIn: 'v4.0', apply: applyAllowDownloadRenameShim }
]
/**
@@ -66,6 +68,42 @@ function applyLightGalleryShim (config: Config): void {
)
}
/**
* SHIM: downloadOriginalPhoto -> maxDownloadQuality. The boolean is superseded
* by the `preview | fullsize | original` tier. Maps `true -> 'original'`,
* `false -> 'preview'`, only when `maxDownloadQuality` isn't already set.
*/
function applyDownloadQualityShim (config: Config): void {
const ipp = (config.ipp || (config.ipp = {})) as Record<string, unknown>
if (typeof ipp.downloadOriginalPhoto !== 'boolean') return
if (ipp.maxDownloadQuality !== undefined) return
ipp.maxDownloadQuality = ipp.downloadOriginalPhoto ? 'original' : 'preview'
console.log(
'[IPP] `ipp.downloadOriginalPhoto` is deprecated; it has been mapped to ' +
'`ipp.maxDownloadQuality` (' + JSON.stringify(ipp.maxDownloadQuality) +
'). See README for the new `maxDownloadQuality` / `maxZoomQuality` options.'
)
}
/**
* SHIM: allowDownloadAll -> allowDownload (rename, same 0/1/2 values). Maps the
* legacy key forward only when the new one hasn't been set.
*/
function applyAllowDownloadRenameShim (config: Config): void {
const ipp = (config.ipp || (config.ipp = {})) as Record<string, unknown>
if (ipp.allowDownloadAll === undefined) return
if (ipp.allowDownload !== undefined) return
ipp.allowDownload = ipp.allowDownloadAll
console.log(
'[IPP] `ipp.allowDownloadAll` has been renamed to `ipp.allowDownload` ' +
'(same `0` / `1` / `2` values). Please update your config.json. See README.'
)
}
/**
* SHIM: top-level ipp.* gallery keys -> ipp.gallery.*. Gallery-related
* keys that used to live directly on `ipp` now live under `ipp.gallery`.
+16 -13
View File
@@ -1,8 +1,6 @@
import {
getPreviewImageSize,
getVideoContentType,
photoUrl,
requiresOriginal,
videoUrl
} from '../immich'
import { Response } from 'express-serve-static-core'
@@ -13,7 +11,8 @@ import { toString } from '../utils/text'
import { h } from 'preact'
import { renderPage } from '../view/render'
import { Gallery, GalleryItem, GalleryProps } from '../view/gallery'
import { getFilename } from './filename'
import { downloadFilename } from './filename'
import { requiresOriginal } from './sizing'
import { metadataGroupActive, pickExif } from './exif'
/**
@@ -41,6 +40,11 @@ export async function gallery (res: Response, share: SharedLink, openItem?: numb
// the operator's own config: when explicitly `false`, no EXIF / location /
// description fields are surfaced, regardless of `ipp.showMetadata.*`
const shareMetadataAllowed = share.showMetadata !== false
// Offer a zoom upgrade only when the operator opted in AND Immich would serve
// it: web `fullsize` resolves to `/original`, which Immich refuses unless the
// share's own download toggle (`share.allowDownload`) is on. Deliberately
// independent of IPP's `allowDownload` config.
const zoomUpgrade = getConfigOption('ipp.maxZoomQuality', 'preview') === 'fullsize' && share.allowDownload !== false
const descriptionInCaption = shareMetadataAllowed && !!getConfigOption('ipp.showMetadata.description.caption', false)
const descriptionInSidebar = shareMetadataAllowed && !!getConfigOption('ipp.showMetadata.description.sidebar', false)
const sidebarHasContent = shareMetadataAllowed && (descriptionInSidebar || metadataGroupActive('exif') || metadataGroupActive('location'))
@@ -63,17 +67,15 @@ export async function gallery (res: Response, share: SharedLink, openItem?: numb
})
}
// Compute the filename so the client-side `<a download="...">` attribute
// matches the bytes the server will return. Without this, a HEIC
// original served as a preview JPEG would download as "photo.heic"
// with JPEG bytes inside.
const downloadUrl = photoUrl(share.key, asset.id, ImageSize.original)
const downloadServedSize = (getConfigOption('ipp.downloadOriginalPhoto', true) || requiresOriginal(asset))
? ImageSize.original
: ImageSize.preview
const thumbnailUrl = photoUrl(share.key, asset.id, ImageSize.thumbnail)
const previewUrl = photoUrl(share.key, asset.id, getPreviewImageSize(asset))
// Always request `preview`; the resolver floors gif/video up to the
// original on its own (their preview is a static frame).
const previewUrl = photoUrl(share.key, asset.id, ImageSize.preview)
// Still images only - gif/video are already served at their highest tier.
const fullUrl = zoomUpgrade && asset.type === AssetType.image && !requiresOriginal(asset)
? photoUrl(share.key, asset.id, ImageSize.fullsize)
: undefined
// Plain text; the client uses textContent so no escaping needed here.
// Description is included if EITHER surface (caption or sidebar) wants it.
const descriptionEnabled = descriptionInCaption || descriptionInSidebar
@@ -96,11 +98,12 @@ export async function gallery (res: Response, share: SharedLink, openItem?: numb
id: asset.id,
type: asset.type,
previewUrl,
fullUrl,
thumbnailUrl,
downloadUrl,
videoData,
description: itemDescription || undefined,
downloadFilename: getFilename(asset, downloadServedSize),
downloadFilename: downloadFilename(asset),
width,
height,
thumbhash: asset.thumbhash,
+10
View File
@@ -1,6 +1,7 @@
import { Asset, ImageSize } from '../types'
import { getConfigOption } from '../config/access'
import { sanitize } from '../utils/sanitize'
import { resolveImageEndpoint } from './sizing'
/**
* Map an Immich asset MIME type to a file extension (including the dot).
@@ -89,3 +90,12 @@ export function getFilename (asset: Asset, servedSize: ImageSize = ImageSize.ori
}
}
}
/**
* Filename for a downloaded asset, whose extension matches the bytes a download
* (`/original` request) actually returns after the `maxDownloadQuality` clamp.
* Used by both the eager (gallery builder) and lazy (`/meta/`) item paths.
*/
export function downloadFilename (asset: Asset): string {
return getFilename(asset, resolveImageEndpoint(ImageSize.original, asset).servedSize)
}
+3 -10
View File
@@ -1,9 +1,8 @@
import { Asset, ImageSize, SharedLink } from '../types'
import { Asset, 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'
import { downloadFilename } from './filename'
/**
* Build the on-demand metadata payload for a single asset, served by the
@@ -26,15 +25,9 @@ export function buildAssetMetadata (asset: Asset, share: SharedLink): AssetMetad
? 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)
downloadFilename: downloadFilename(asset)
}
}
+146
View File
@@ -0,0 +1,146 @@
import { Asset, AssetType, ImageSize } from '../types'
import { getConfigOption } from '../config/access'
/*
Single source of truth for image-size policy: given a requested ImageSize
and an asset, decide which Immich endpoint actually serves it.
*/
export interface ImageEndpoint {
subpath: string
sizeQueryParam?: string
attachment: boolean
servedSize: ImageSize
}
/**
* Whether this asset must be served from `/original` to remain useful,
* bypassing the operator's quality ceilings.
*
* - Videos: Immich's preview/thumbnail endpoints return a poster JPEG, not the
* video, so the downgrade would replace a video file with a still image.
* - Animated images (currently just GIF): Immich's preview is a static JPEG,
* so the downgrade silently strips the animation. APNG/animated-WebP aren't
* listed because Immich doesn't expose a distinct MIME type for them - they
* share `image/png` / `image/webp` with their static counterparts.
*
* Used by both the display path (lightbox preview URL) and the download path
* (single-asset download + zip), so the lightbox shows the same bytes the
* user gets when they hit "download".
*/
export function requiresOriginal (asset: Asset): boolean {
if (asset.type === AssetType.video) {
return true
} else if (asset.originalMimeType?.startsWith('video/')) {
return true
} else if (asset.originalMimeType === 'image/gif') {
return true
}
return false
}
/*
MIME types a browser can render directly, mirroring Immich's
`isWebSupportedImage`. For these the `fullsize` tier resolves to the original
bytes (`/original`); everything else (RAW/HEIF/TIFF/...) gets Immich's
converted full-size JPEG via `?size=fullsize`.
*/
const WEB_DISPLAYABLE_MIME = new Set(['image/jpeg', 'image/png', 'image/webp'])
function isWebDisplayable (asset: Asset): boolean {
return !!asset.originalMimeType && WEB_DISPLAYABLE_MIME.has(asset.originalMimeType)
}
/*
Detail ladder for the photo tiers, ascending. THUMBNAIL is deliberately
excluded: it is the grid poster and is always served exactly as requested
(for a video/gif it is the correct still frame), so it short-circuits before
the clamp below and is never promoted or demoted.
*/
const LADDER = [ImageSize.preview, ImageSize.fullsize, ImageSize.original]
const rank = (size: ImageSize) => LADDER.indexOf(size)
const clamp = (size: ImageSize, lo: ImageSize, hi: ImageSize) =>
LADDER[Math.min(Math.max(rank(size), rank(lo)), rank(hi))]
/**
* Operator ceiling for the download tier (`ipp.maxDownloadQuality`). `original`
* is allowed here because a download needn't be browser-renderable.
*/
function maxDownloadQuality (): ImageSize {
const value = getConfigOption('ipp.maxDownloadQuality', 'original')
if (value === 'preview') return ImageSize.preview
if (value === 'fullsize') return ImageSize.fullsize
return ImageSize.original
}
/**
* Operator ceiling for the zoom tier (`ipp.maxZoomQuality`). `original` is
* deliberately not an option: a zoom upgrade must stay browser-displayable, and
* the original could be an unviewable RAW/DNG or a huge file.
*/
function maxZoomQuality (): ImageSize {
return getConfigOption('ipp.maxZoomQuality', 'preview') === 'fullsize'
? ImageSize.fullsize
: ImageSize.preview
}
/**
* Highest tier permitted for `requested`, which doubles as the intent:
* `original` (download) caps at `maxDownloadQuality`, `fullsize` (zoom) caps at
* `maxZoomQuality`. `preview` / `thumbnail` are never capped.
*/
function ceiling (requested: ImageSize): ImageSize {
if (requested === ImageSize.original) return maxDownloadQuality()
if (requested === ImageSize.fullsize) return maxZoomQuality()
return requested
}
/**
* Resolve the Immich endpoint that serves `requested` for `asset`.
*
* `servedSize` is the tier Immich will actually return after clamping, which
* may be lower than requested (e.g. an `original` downgraded to `preview` when
* `ipp.maxDownloadQuality` is `preview`). Callers use it to derive a filename
* whose extension matches the bytes (see getFilename).
*
* `attachment` reflects intent and is keyed off the REQUESTED size, not the
* served one: an `original` request is a download (gets Content-Disposition);
* preview/fullsize/thumbnail are for display. This is what lets a gif served
* from `/original` for inline display stay inline, while a gif *download* from
* the same endpoint gets the attachment header.
*/
export function resolveImageEndpoint (requested: ImageSize, asset: Asset): ImageEndpoint {
const attachment = requested === ImageSize.original
// Thumbnail is the grid poster: served as-is, never clamped (a video/gif
// thumbnail must stay a small still, not get promoted to the original file).
if (requested === ImageSize.thumbnail) {
return { subpath: '/thumbnail', attachment, servedSize: ImageSize.thumbnail }
}
// gif/video have no usable preview or fullsize (a static frame), so they are
// always served from the original file, bypassing the operator ceilings.
if (requiresOriginal(asset)) {
return endpointFor(ImageSize.original, asset, attachment)
}
const served = clamp(requested, ImageSize.preview, ceiling(requested))
return endpointFor(served, asset, attachment)
}
/**
* The one place that maps a (clamped) ImageSize onto a concrete Immich path,
* and the only place that knows `fullsize` is per-asset.
*/
function endpointFor (size: ImageSize, asset: Asset, attachment: boolean): ImageEndpoint {
switch (size) {
case ImageSize.original:
return { subpath: '/original', attachment, servedSize: ImageSize.original }
case ImageSize.fullsize:
// Web formats: fullsize is the original bytes, served from /original.
// Non-web (RAW/HEIF): Immich's converted full-size JPEG via ?size=fullsize
// (falls back to preview unless full-size generation is enabled in Immich).
return isWebDisplayable(asset)
? { subpath: '/original', attachment, servedSize: ImageSize.original }
: { subpath: '/thumbnail', sizeQueryParam: 'fullsize', attachment, servedSize: ImageSize.fullsize }
default: // preview
return { subpath: '/thumbnail', sizeQueryParam: 'preview', attachment, servedSize: ImageSize.preview }
}
}
+23 -40
View File
@@ -439,10 +439,8 @@ async function fetchAlbumAssets (albumId: string, keyType: KeyType, key: string,
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 })
const headers = await authHeadersForAsset(asset)
const res = await fetch(assetFetchUrl(asset, ''), { headers })
if (!res.ok) return undefined
return await res.json() as Asset
})
@@ -452,7 +450,7 @@ export function fetchAssetDetail (asset: Asset): Promise<Asset | undefined> {
* Get the content-type of a video, for the lightbox <video> element
*/
export async function getVideoContentType (asset: Asset) {
const headers = await authHeaders(asset.keyType, asset.key, asset.password)
const headers = await authHeadersForAsset(asset)
const data = await request(buildUrl('/assets/' + encodeURIComponent(asset.id) + '/video/playback', {
[asset.keyType]: asset.key
}), { headers })
@@ -471,6 +469,26 @@ export async function authHeaders (keyType: KeyType, key: string, password?: str
return token ? { Cookie: `immich_shared_link_token=${token}` } : {}
}
/**
* `authHeaders` for an asset whose key/keyType/password are already stamped on
* it (the common case for share-scoped fetches).
*/
export function authHeadersForAsset (asset: Asset): Promise<Record<string, string>> {
return authHeaders(asset.keyType || KeyType.key, asset.key, asset.password)
}
/**
* Build the Immich URL that serves `subpath` for `asset` (e.g. `/original`,
* `/video/playback`), with the share key and optional `size` query param
* encoded. `buildUrl` drops the `size` param when it is undefined.
*/
export function assetFetchUrl (asset: Asset, subpath: string, sizeQueryParam?: string): string {
return buildUrl(apiUrl() + '/assets/' + encodeURIComponent(asset.id) + subpath, {
[asset.keyType || KeyType.key]: asset.key,
size: sizeQueryParam
})
}
/**
* Cached login: fetch an `immich_shared_link_token` for the given password,
* or return null on failure. The cache is per (keyType, key, password) so
@@ -522,41 +540,6 @@ export function buildUrl (baseUrl: string, params: { [key: string]: string | und
return baseUrl + query
}
/**
* Whether this asset must be served from `/original` to remain useful, bypassing
* the `ipp.downloadOriginalPhoto` downgrade.
*
* - Videos: Immich's preview/thumbnail endpoints return a poster JPEG, not the
* video, so the downgrade would replace a video file with a still image.
* - Animated images (currently just GIF): Immich's preview is a static JPEG,
* so the downgrade silently strips the animation. APNG/animated-WebP aren't
* listed because Immich doesn't expose a distinct MIME type for them - they
* share `image/png` / `image/webp` with their static counterparts.
*
* Used by both the display path (lightbox preview URL) and the download path
* (single-asset download + zip), so the lightbox shows the same bytes the
* user gets when they hit "download".
*/
export function requiresOriginal (asset: Asset): boolean {
if (asset.type === AssetType.video) {
return true
} else if (asset.originalMimeType?.startsWith('video/')) {
return true
} else if (asset.originalMimeType === 'image/gif') {
return true
}
return false
}
/**
* Return the correct preview size, depending on the image MIME type.
* For animated formats, use the original file rather than the preview so
* animation is preserved (Immich's preview is a static JPEG frame).
*/
export function getPreviewImageSize (asset: Asset) {
return requiresOriginal(asset) ? ImageSize.original : ImageSize.preview
}
/**
* Return the image data URL for a photo
*/
+6 -4
View File
@@ -12,12 +12,14 @@ export function title (share: SharedLink): string {
}
/**
* Decide whether the given shared link is downloadable. The `ipp.allowDownloadAll`
* config controls the policy: disabled, follow the per-share Immich setting,
* or always allowed.
* Decide whether the given shared link's download UI is shown (the "download
* all" zip, multi-select download, and the per-asset lightbox button). The
* `ipp.allowDownload` config controls the policy: disabled, follow the
* per-share Immich setting, or always allowed. This is purely a UI gate - it
* does not affect image quality (see `gallery/sizing.ts`).
*/
export function canDownload (share: SharedLink): boolean {
const allowDownloadConfig = getConfigOption('ipp.allowDownloadAll', 0) as DownloadAll
const allowDownloadConfig = getConfigOption('ipp.allowDownload', 0) as DownloadAll
if (!allowDownloadConfig) {
// Downloading is disabled in config.json
return false
+1
View File
@@ -35,6 +35,7 @@ export interface GalleryItem {
id: string
type: 'IMAGE' | 'VIDEO'
previewUrl: string
fullUrl?: string
thumbnailUrl: string
downloadUrl?: string
// Pre-stringified JSON describing the video source (used to build a <video>
+16 -48
View File
@@ -1,22 +1,14 @@
import {
apiUrl,
authHeaders,
buildUrl,
requiresOriginal,
assetFetchUrl,
authHeadersForAsset,
fetchAssetDetail,
validateImageSize
} from '../immich'
import { Response } from 'express-serve-static-core'
import { Asset, AssetType, ImageSize, IncomingShareRequest, KeyType } from '../types'
import { getConfigOption } from '../config/access'
import { Asset, AssetType, ImageSize, IncomingShareRequest } from '../types'
import { respondToInvalidRequest } from '../invalidRequestHandler'
import { getFilename } from '../gallery/filename'
export interface ImageEndpoint {
subpath: string
sizeQueryParam?: string
attachment: boolean
servedSize: ImageSize
}
import { resolveImageEndpoint } from '../gallery/sizing'
/**
* Stream an asset from Immich back to the client.
@@ -51,18 +43,23 @@ export async function assetBuffer (req: IncomingShareRequest, res: Response, ass
res.status(206) // Partial Content
}
} else {
const endpoint = resolveImageEndpoint(validateImageSize(size), asset)
const requested = validateImageSize(size)
// Album "grid" items arrive without originalMimeType. The fullsize tier
// needs it to pick /original (web formats) vs ?size=fullsize (RAW/HEIF), so
// fetch the asset detail on demand (cached) before resolving.
if (requested === ImageSize.fullsize && !asset.originalMimeType) {
const detail = await fetchAssetDetail(asset)
if (detail?.originalMimeType) asset = { ...asset, originalMimeType: detail.originalMimeType }
}
const endpoint = resolveImageEndpoint(requested, asset)
subpath = endpoint.subpath
sizeQueryParam = endpoint.sizeQueryParam
attachment = endpoint.attachment
servedSize = endpoint.servedSize
}
const url = buildUrl(apiUrl() + '/assets/' + encodeURIComponent(asset.id) + subpath, {
[asset.keyType || 'key']: asset.key,
size: sizeQueryParam
})
const reqHeaders = await authHeaders(asset.keyType || KeyType.key, asset.key, asset.password)
const url = assetFetchUrl(asset, subpath, sizeQueryParam)
const reqHeaders = await authHeadersForAsset(asset)
const data = await fetch(url, { headers: { ...fetchHeaders, ...reqHeaders } })
if (data.status < 200 || data.status >= 300) {
@@ -90,32 +87,3 @@ export async function assetBuffer (req: IncomingShareRequest, res: Response, ass
)
res.end()
}
/**
* Map an ImageSize to the Immich endpoint that serves it.
*
* Policy: when `ipp.downloadOriginalPhoto` is off, requests for the original
* image are silently downgraded to preview - the operator has opted out of
* serving full-resolution files. (The original may also be a RAW/HEIC file
* the browser can't render.)
*
* The downgrade is bypassed for assets where `requiresOriginal` is true
* (videos, animated images), because for those formats the preview is an
* entirely different artifact (still poster / static JPEG) rather than a
* lower-res version of the same content.
*
* `servedSize` reflects what Immich will actually return after the downgrade,
* which may differ from the requested `size`. Callers use it to derive a
* filename whose extension matches the bytes (see getFilename).
*/
export function resolveImageEndpoint (size: ImageSize, asset: Asset): ImageEndpoint {
const allowOriginal = getConfigOption('ipp.downloadOriginalPhoto', true) || requiresOriginal(asset)
if (size === ImageSize.original && allowOriginal) {
return { subpath: '/original', attachment: true, servedSize: ImageSize.original }
}
if (size === ImageSize.thumbnail) {
return { subpath: '/thumbnail', attachment: false, servedSize: ImageSize.thumbnail }
}
// preview, or original downgraded because downloadOriginalPhoto is off
return { subpath: '/thumbnail', sizeQueryParam: 'preview', attachment: false, servedSize: ImageSize.preview }
}
+5 -8
View File
@@ -1,6 +1,6 @@
import { apiUrl, authHeaders, buildUrl } from '../immich'
import { assetFetchUrl, authHeadersForAsset } from '../immich'
import { Response } from 'express-serve-static-core'
import { Asset, ImageSize, KeyType, SharedLink } from '../types'
import { Asset, ImageSize, SharedLink } from '../types'
import { getConfigOption } from '../config/access'
import { log } from '../utils/log'
import archiver, { Archiver } from 'archiver'
@@ -10,7 +10,7 @@ import { pipeline } from 'stream/promises'
import { promises as fs, createWriteStream } from 'fs'
import { tmpdir } from 'os'
import { join } from 'path'
import { resolveImageEndpoint, ImageEndpoint } from './asset'
import { resolveImageEndpoint, ImageEndpoint } from '../gallery/sizing'
import { title } from '../share'
import { getFilename } from '../gallery/filename'
import { createLimiter } from '../utils/limiter'
@@ -177,11 +177,8 @@ async function stageOne (asset: Asset, index: number, options: StagingOptions, a
if (abortFlag.aborted) return null
const endpoint = resolveImageEndpoint(ImageSize.original, asset)
const url = buildUrl(apiUrl() + '/assets/' + encodeURIComponent(asset.id) + endpoint.subpath, {
[asset.keyType || 'key']: asset.key,
size: endpoint.sizeQueryParam
})
const reqAuthHeaders = await authHeaders(asset.keyType || KeyType.key, asset.key, asset.password)
const url = assetFetchUrl(asset, endpoint.subpath, endpoint.sizeQueryParam)
const reqAuthHeaders = await authHeadersForAsset(asset)
const fetched = await fetchHeadersWithRetry(url, reqAuthHeaders, options.maxAttempts, options.headerTimeoutMs, abortFlag, asset)
if (fetched === null) return null
+1
View File
@@ -115,6 +115,7 @@ export interface SharedLinkResult {
export enum ImageSize {
thumbnail = 'thumbnail',
preview = 'preview',
fullsize = 'fullsize',
original = 'original'
}
+56
View File
@@ -305,3 +305,59 @@ describe('metadataEnabled shim', () => {
expect(logSpy).not.toHaveBeenCalled()
})
})
describe('downloadOriginalPhoto shim', () => {
it('maps true -> maxDownloadQuality: original', () => {
const config = { ipp: { downloadOriginalPhoto: true } } as Record<string, unknown>
applyMigrations(config)
expect((config.ipp as Record<string, unknown>).maxDownloadQuality).toBe('original')
expect(logSpy).toHaveBeenCalledOnce()
})
it('maps false -> maxDownloadQuality: preview', () => {
const config = { ipp: { downloadOriginalPhoto: false } } as Record<string, unknown>
applyMigrations(config)
expect((config.ipp as Record<string, unknown>).maxDownloadQuality).toBe('preview')
})
it('does not overwrite an explicitly-set maxDownloadQuality', () => {
const config = { ipp: { downloadOriginalPhoto: false, maxDownloadQuality: 'fullsize' } } as Record<string, unknown>
applyMigrations(config)
expect((config.ipp as Record<string, unknown>).maxDownloadQuality).toBe('fullsize')
expect(logSpy).not.toHaveBeenCalled()
})
it('does nothing when downloadOriginalPhoto is absent', () => {
const config = { ipp: { maxDownloadQuality: 'original' } } as Record<string, unknown>
applyMigrations(config)
expect(logSpy).not.toHaveBeenCalled()
})
})
describe('allowDownloadAll rename shim', () => {
it('maps allowDownloadAll -> allowDownload, preserving the int value', () => {
const config = { ipp: { allowDownloadAll: 2 } } as Record<string, unknown>
applyMigrations(config)
expect((config.ipp as Record<string, unknown>).allowDownload).toBe(2)
expect(logSpy).toHaveBeenCalledOnce()
})
it('maps the falsy 0 value through (not skipped as "absent")', () => {
const config = { ipp: { allowDownloadAll: 0 } } as Record<string, unknown>
applyMigrations(config)
expect((config.ipp as Record<string, unknown>).allowDownload).toBe(0)
})
it('does not overwrite an explicitly-set allowDownload', () => {
const config = { ipp: { allowDownloadAll: 2, allowDownload: 1 } } as Record<string, unknown>
applyMigrations(config)
expect((config.ipp as Record<string, unknown>).allowDownload).toBe(1)
expect(logSpy).not.toHaveBeenCalled()
})
it('does nothing when allowDownloadAll is absent', () => {
const config = { ipp: { allowDownload: 1 } } as Record<string, unknown>
applyMigrations(config)
expect(logSpy).not.toHaveBeenCalled()
})
})
+124
View File
@@ -0,0 +1,124 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { AssetType, ImageSize } from '../src/types'
import type { Asset } from '../src/types'
import { resolveImageEndpoint, requiresOriginal } from '../src/gallery/sizing'
/*
resolveImageEndpoint reads `ipp.maxDownloadQuality` and `ipp.maxZoomQuality`
via getConfigOption, so we mock the config-access module and set the tiers per
test rather than loading a real config file. vitest hoists vi.mock above the
imports, so the mock is in place by the time sizing.ts resolves config/access.
*/
const cfg: Record<string, unknown> = {}
vi.mock('../src/config/access', () => ({
getConfigOption: (path: string, fallback?: unknown) =>
path in cfg ? cfg[path] : fallback
}))
function asset (overrides: Partial<Asset> = {}): Asset {
return {
id: 'a',
key: 'k',
keyType: 'key' as Asset['keyType'],
type: AssetType.image,
isTrashed: false,
originalMimeType: 'image/jpeg',
...overrides
}
}
const jpeg = asset({ originalMimeType: 'image/jpeg' })
const heic = asset({ originalMimeType: 'image/heic' }) // non-web-displayable
const gif = asset({ originalMimeType: 'image/gif' })
const video = asset({ type: AssetType.video, originalMimeType: 'video/mp4' })
const videoMimeImage = asset({ type: AssetType.image, originalMimeType: 'video/mp4' })
beforeEach(() => {
for (const k of Object.keys(cfg)) delete cfg[k]
})
describe('requiresOriginal', () => {
it('is true for videos, video-MIME assets and gifs, false for plain images', () => {
expect(requiresOriginal(video)).toBe(true)
expect(requiresOriginal(videoMimeImage)).toBe(true)
expect(requiresOriginal(gif)).toBe(true)
expect(requiresOriginal(jpeg)).toBe(false)
expect(requiresOriginal(heic)).toBe(false)
})
})
describe('thumbnail - always the grid poster, never clamped', () => {
it('serves thumbnail as-is for every asset type', () => {
for (const a of [jpeg, heic, gif, video, videoMimeImage]) {
expect(resolveImageEndpoint(ImageSize.thumbnail, a)).toEqual({
subpath: '/thumbnail', attachment: false, servedSize: ImageSize.thumbnail
})
}
})
})
describe('preview', () => {
it('serves the preview JPEG (display) regardless of ceilings', () => {
cfg['ipp.maxDownloadQuality'] = 'preview'
cfg['ipp.maxZoomQuality'] = 'preview'
expect(resolveImageEndpoint(ImageSize.preview, jpeg)).toEqual({
subpath: '/thumbnail', sizeQueryParam: 'preview', attachment: false, servedSize: ImageSize.preview
})
})
})
describe('original (download tier, gated by maxDownloadQuality)', () => {
it('default (maxDownloadQuality unset => original) serves /original as attachment', () => {
expect(resolveImageEndpoint(ImageSize.original, jpeg)).toEqual({
subpath: '/original', attachment: true, servedSize: ImageSize.original
})
})
it('maxDownloadQuality=preview downgrades to preview, still an attachment (intent=download)', () => {
cfg['ipp.maxDownloadQuality'] = 'preview'
expect(resolveImageEndpoint(ImageSize.original, jpeg)).toEqual({
subpath: '/thumbnail', sizeQueryParam: 'preview', attachment: true, servedSize: ImageSize.preview
})
})
})
describe('fullsize (zoom tier, gated by maxZoomQuality)', () => {
it('caps at preview when maxZoomQuality is preview (the default)', () => {
expect(resolveImageEndpoint(ImageSize.fullsize, jpeg).servedSize).toBe(ImageSize.preview)
})
it('web format: fullsize resolves to the original bytes, served inline (no attachment)', () => {
cfg['ipp.maxZoomQuality'] = 'fullsize'
expect(resolveImageEndpoint(ImageSize.fullsize, jpeg)).toEqual({
subpath: '/original', attachment: false, servedSize: ImageSize.original
})
})
it('non-web format: fullsize resolves to the converted JPEG via ?size=fullsize', () => {
cfg['ipp.maxZoomQuality'] = 'fullsize'
expect(resolveImageEndpoint(ImageSize.fullsize, heic)).toEqual({
subpath: '/thumbnail', sizeQueryParam: 'fullsize', attachment: false, servedSize: ImageSize.fullsize
})
})
})
describe('gif / video (requiresOriginal) - always the original file, ceilings bypassed', () => {
it('serves preview/fullsize/original requests from /original', () => {
cfg['ipp.maxDownloadQuality'] = 'preview' // would downgrade a normal image
cfg['ipp.maxZoomQuality'] = 'preview'
expect(resolveImageEndpoint(ImageSize.preview, gif).servedSize).toBe(ImageSize.original)
expect(resolveImageEndpoint(ImageSize.fullsize, gif).servedSize).toBe(ImageSize.original)
expect(resolveImageEndpoint(ImageSize.original, gif).servedSize).toBe(ImageSize.original)
})
it('keeps attachment keyed to intent: preview/fullsize display inline, original downloads', () => {
expect(resolveImageEndpoint(ImageSize.preview, gif).attachment).toBe(false)
expect(resolveImageEndpoint(ImageSize.original, gif).attachment).toBe(true)
})
it('still serves a thumbnail request as the grid poster, never the whole video', () => {
for (const a of [gif, video, videoMimeImage]) {
expect(resolveImageEndpoint(ImageSize.thumbnail, a).servedSize).toBe(ImageSize.thumbnail)
}
})
})
+1 -1
View File
@@ -1,4 +1,4 @@
import { describe, it, expect, beforeEach, afterEach } from 'vitest'
import { describe, it, expect, afterEach } from 'vitest'
import { promises as fs } from 'fs'
import { tmpdir } from 'os'
import { join } from 'path'