Fix download file extensions when Immich serves WebP previews

With maxDownloadQuality=preview and Immich generating WebP previews, the
zip entries and per-asset downloads were named .jpg while carrying WebP
bytes. Previews, converted fullsize images and transcodes follow the
server's image settings, so derive the extension from the upstream
content-type for every non-/original endpoint, via a shared
servedMimeFrom() in gallery/sizing.ts.
This commit is contained in:
opencode
2026-10-04 11:05:07 +02:00
committed by Alan Grainger
parent 6a5ff3cd13
commit 2a99258278
8 changed files with 91 additions and 20 deletions
+3 -4
View File
@@ -53,10 +53,9 @@ function withMimeExtension (filename: string, mime: string | undefined): string
/**
* Generate a filename for the downloaded asset based on the configuration option chosen.
*
* The extension reflects what bytes the user will receive, not what the
* original was - when Immich downgrades an image-original to preview (see
* resolveImageEndpoint), the served bytes are JPEG even if the original is
* HEIC/DNG/RAW, and the filename must match the bytes.
* The extension reflects the served bytes, not the original: converted
* bytes follow Immich's image settings, so pass the upstream content-type
* as `servedMimeOverride`.
*
* @param asset
* @param [servedSize] - what size Immich will actually serve. Defaults to
+10
View File
@@ -165,3 +165,13 @@ function endpointFor (size: ImageSize, asset: Asset, attachment: boolean): Image
return { subpath: '/thumbnail', sizeQueryParam: 'preview', attachment, servedSize: ImageSize.preview }
}
}
/**
* Served content-type for filename derivation: everything but /original is
* Immich-generated (previews can be WebP), so the response headers are the
* only reliable extension signal.
*/
export function servedMimeFrom (subpath: string, response: globalThis.Response): string | undefined {
if (subpath === '/original') return undefined
return (response.headers.get('content-type') || '').split(';')[0].trim() || undefined
}
+2 -7
View File
@@ -8,7 +8,7 @@ import { Response } from 'express-serve-static-core'
import { Asset, ImageSize, IncomingShareRequest, SharedLink } from '../types'
import { respondToInvalidRequest } from '../invalidRequestHandler'
import { getFilename } from '../gallery/filename'
import { isVideoAsset, resolveDownloadEndpoint, resolveImageEndpoint } from '../gallery/sizing'
import { isVideoAsset, resolveDownloadEndpoint, resolveImageEndpoint, servedMimeFrom } from '../gallery/sizing'
import { pipeline } from 'stream/promises'
import { readableFromWeb } from '../utils/webStream'
import { log } from '../utils/log'
@@ -99,12 +99,7 @@ export async function assetBuffer (req: IncomingShareRequest, res: Response, ass
if (attachment) {
res.setHeader('X-Accel-Buffering', 'no')
if (asset.originalFileName) {
// Playback downloads serve Immich's transcode, so the filename extension
// must follow the response's content-type, not the original file's.
const playbackMime = useVideoPlayback
? (data.headers.get('content-type') || '').split(';')[0].trim() || undefined
: undefined
const filename = encodeURI(getFilename(asset, servedSize, playbackMime))
const filename = encodeURI(getFilename(asset, servedSize, servedMimeFrom(subpath, data)))
res.setHeader('Content-Disposition', `attachment; filename*=UTF-8''${filename}`)
}
}
+2 -8
View File
@@ -4,7 +4,7 @@ import { Asset, SharedLink } from '../types'
import { log } from '../utils/log'
import archiver, { Archiver } from 'archiver'
import { sanitize } from '../utils/sanitize'
import { resolveDownloadEndpoint, ImageEndpoint } from '../gallery/sizing'
import { resolveDownloadEndpoint, servedMimeFrom, ImageEndpoint } from '../gallery/sizing'
import { title } from '../share'
import { getFilename } from '../gallery/filename'
import { readableFromWeb } from '../utils/webStream'
@@ -220,13 +220,7 @@ async function fetchOne (share: SharedLink, asset: Asset, signal: AbortSignal):
// so recover them from the headers we already fetched - no extra calls.
const namedAsset = asset.originalFileName ? asset : enrichFromHeaders(asset, fetched.response)
// Playback-fallback downloads serve Immich's transcode; carry the response
// content-type so the zip entry's extension matches the actual bytes.
const servedMime = endpoint.subpath === '/video/playback'
? (fetched.response.headers.get('content-type') || '').split(';')[0].trim() || undefined
: undefined
return { response: fetched.response, asset: namedAsset, endpoint, servedMime, url }
return { response: fetched.response, asset: namedAsset, endpoint, servedMime: servedMimeFrom(endpoint.subpath, fetched.response), url }
}
/**
+24
View File
@@ -2,12 +2,20 @@ import { describe, it, expect, vi, afterEach } from 'vitest'
import { Writable } from 'stream'
import type { Request, Response } from 'express-serve-static-core'
import { assetBuffer } from '../src/stream/asset'
import { loadConfig } from '../src/config/loader'
import { Asset, AssetType, ImageSize, IncomingShareRequest, KeyType } from '../src/types'
afterEach(() => {
vi.unstubAllGlobals()
delete process.env.CONFIG
loadConfig()
})
function setConfig (config: unknown) {
process.env.CONFIG = JSON.stringify(config)
loadConfig()
}
const CHUNK = 64 * 1024
const asset: Asset = {
@@ -189,4 +197,20 @@ describe('assetBuffer streaming', () => {
expect(source.cancelled).toBe(true)
expect(res.headers['content-length']).toBe(String(4 * CHUNK))
})
it('names a preview-clamped download after the served bytes, not .jpg (WebP preview generation)', async () => {
// maxDownloadQuality=preview with Immich generating WebP previews: the
// Content-Disposition extension must follow the response content-type.
setConfig({ ipp: { maxDownloadQuality: 'preview' } })
vi.stubGlobal('fetch', vi.fn(async () => new globalThis.Response(
new ReadableStream({
start (controller) { controller.enqueue(new Uint8Array(1024)); controller.close() }
}),
{ status: 200, headers: { 'content-type': 'image/webp', 'content-length': '1024' } }
)))
const res = new FakeRes()
await assetBuffer(makeRequest(), asResponse(res), asset, ImageSize.original)
expect(res.headers['content-disposition']).toContain('a1.webp')
expect(res.headers['content-type']).toBe('image/webp')
})
})
+23
View File
@@ -3,6 +3,7 @@ import { Writable } from 'stream'
import { once } from 'events'
import type { Response } from 'express-serve-static-core'
import { downloadAssets } from '../src/stream/download'
import { loadConfig } from '../src/config/loader'
import { Asset, AssetType, KeyType, SharedLink } from '../src/types'
/*
@@ -16,8 +17,15 @@ dies mid-stream).
afterEach(() => {
vi.unstubAllGlobals()
vi.restoreAllMocks()
delete process.env.CONFIG
loadConfig()
})
function setConfig (config: unknown) {
process.env.CONFIG = JSON.stringify(config)
loadConfig()
}
function makeAsset (id: string): Asset {
return {
id,
@@ -276,4 +284,19 @@ describe('downloadAssets', () => {
expect(fetchMock).toHaveBeenCalledTimes(1)
expect(signals.every(s => s.aborted)).toBe(true)
}, 10_000)
it('names a preview-clamped entry after the served bytes, not .jpg (WebP preview generation)', async () => {
// Immich generates previews in an operator-chosen format; with WebP
// selected and maxDownloadQuality=preview, the zip entry must be .webp.
setConfig({ ipp: { maxDownloadQuality: 'preview' } })
const fetchMock = vi.fn(async () => new globalThis.Response(new Uint8Array(2048), {
status: 200,
headers: { 'content-type': 'image/webp' }
}))
vi.stubGlobal('fetch', fetchMock)
const res = new FakeRes()
await downloadAssets(asResponse(res), share, [makeAsset('a1')])
expect(String(fetchMock.mock.calls[0][0])).toContain('size=preview')
expect(centralDirectory(res.output)).toEqual([{ name: 'a1.webp', size: 2048 }])
})
})
+26
View File
@@ -24,6 +24,18 @@ function videoAsset (originalFileName: string, originalMimeType = 'video/x-msvid
}
}
function imageAsset (originalFileName: string, originalMimeType = 'image/heic'): Asset {
return {
id: 'asset-id',
key: 'k',
keyType: KeyType.key,
type: AssetType.image,
isTrashed: false,
originalFileName,
originalMimeType
}
}
describe('getFilename servedMime override (playback-fallback downloads)', () => {
it('swaps the extension to match the transcoded bytes', () => {
expect(getFilename(videoAsset('clip.avi'), ImageSize.original, 'video/mp4')).toBe('clip.mp4')
@@ -43,3 +55,17 @@ describe('getFilename servedMime override (playback-fallback downloads)', () =>
expect(getFilename(videoAsset('clip.avi'), ImageSize.original)).toBe('clip.avi')
})
})
describe('getFilename converted-byte previews (e.g. WebP preview generation)', () => {
it('swaps the extension to match the served preview bytes', () => {
expect(getFilename(imageAsset('holiday.heic'), ImageSize.preview, 'image/webp')).toBe('holiday.webp')
})
it('keeps a JPEG extension when the preview is JPEG', () => {
expect(getFilename(imageAsset('holiday.heic'), ImageSize.preview, 'image/jpeg')).toBe('holiday.jpg')
})
it('falls back to the hardcoded tier mime without an override', () => {
expect(getFilename(imageAsset('holiday.heic'), ImageSize.preview)).toBe('holiday.jpg')
})
})
+1 -1
View File
@@ -42,7 +42,7 @@ Highest quality served for a download (the download button and "download all" zi
- `"original"` - the full-resolution original file (default).
- `"fullsize"` - full resolution but always browser-displayable: the original for JPEG/PNG/WebP, Immich's converted JPEG for RAW/HEIF.
- `"preview"` - only the ~1440px preview JPEG.
- `"preview"` - only the ~1440px preview. The format is whatever Immich generates for its preview (JPEG or WebP, per the server's image settings), and downloaded filenames follow it.
## `maxZoomQuality`