Merge PR #281: fall back to video playback for downloads on download-disabled shares

This commit is contained in:
Alan Grainger
2026-08-20 07:31:59 +12:00
6 changed files with 89 additions and 23 deletions
+27 -6
View File
@@ -24,14 +24,12 @@ export interface ImageEndpoint {
* listed because Immich doesn't expose a distinct MIME type for them - they * listed because Immich doesn't expose a distinct MIME type for them - they
* share `image/png` / `image/webp` with their static counterparts. * share `image/png` / `image/webp` with their static counterparts.
* *
* Used by both the display path (lightbox preview URL) and the download path * Used by display sizing and by downloads that Immich can serve from the
* (single-asset download + zip), so the lightbox shows the same bytes the * original endpoint. IPP-forced video downloads have their own playback
* user gets when they hit "download". * fallback in `resolveDownloadEndpoint`.
*/ */
export function requiresOriginal (asset: Asset): boolean { export function requiresOriginal (asset: Asset): boolean {
if (asset.type === AssetType.video) { if (isVideoAsset(asset)) {
return true
} else if (asset.originalMimeType?.startsWith('video/')) {
return true return true
} else if (asset.originalMimeType === 'image/gif') { } else if (asset.originalMimeType === 'image/gif') {
return true return true
@@ -39,6 +37,15 @@ export function requiresOriginal (asset: Asset): boolean {
return false return false
} }
/**
* Whether an asset is a video. Route handlers can coerce `type` from the URL,
* while detailed Immich asset responses identify video originals by MIME type;
* endpoint selection accepts either signal.
*/
export function isVideoAsset (asset: Asset): boolean {
return asset.type === AssetType.video || !!asset.originalMimeType?.startsWith('video/')
}
/* /*
MIME types a browser can render directly, mirroring Immich's MIME types a browser can render directly, mirroring Immich's
`isWebSupportedImage`. For these the `fullsize` tier resolves to the original `isWebSupportedImage`. For these the `fullsize` tier resolves to the original
@@ -125,6 +132,20 @@ export function resolveImageEndpoint (requested: ImageSize, asset: Asset): Image
return endpointFor(served, asset, attachment) return endpointFor(served, asset, attachment)
} }
/**
* Resolve the endpoint for an IPP download. This is usually the same as an
* `original` image-size request. The exception is a video on a shared link
* whose Immich download permission is off: Immich refuses `/original` with
* `asset.download` access, while `/video/playback` can still serve the
* transcoded playback file that visitors are allowed to stream.
*/
export function resolveDownloadEndpoint (asset: Asset, immichAllowsOriginalDownload = true): ImageEndpoint {
if (!immichAllowsOriginalDownload && isVideoAsset(asset)) {
return { subpath: '/video/playback', attachment: true, servedSize: ImageSize.original }
}
return resolveImageEndpoint(ImageSize.original, asset)
}
/** /**
* The one place that maps a (clamped) ImageSize onto a concrete Immich path, * The one place that maps a (clamped) ImageSize onto a concrete Immich path,
* and the only place that knows `fullsize` is per-asset. * and the only place that knows `fullsize` is per-asset.
+1 -1
View File
@@ -209,7 +209,7 @@ export async function handleShareRequest (req: IncomingShareRequest, res: Respon
if ((directImage || directVideo) && !req.password) { if ((directImage || directVideo) && !req.password) {
// Output the asset directly rather than a gallery page, unless it's a // Output the asset directly rather than a gallery page, unless it's a
// password-protected link // password-protected link
await assetBuffer(req, res, link.assets[0], ImageSize.preview) await assetBuffer(req, res, link.assets[0], ImageSize.preview, link, directVideo)
} else { } else {
// Show a gallery page // Show a gallery page
const openItem = getConfigOption('ipp.gallery.singleItemAutoOpen', true) ? 1 : 0 const openItem = getConfigOption('ipp.gallery.singleItemAutoOpen', true) ? 1 : 0
+2 -2
View File
@@ -266,7 +266,7 @@ app.get('/share/:type(photo|video)/:key/:id/:size?', decodeCookie, asyncHandler(
} }
const asset: Asset = { const asset: Asset = {
...resolved.asset, ...resolved.asset,
type: req.params.type === 'video' ? AssetType.video : AssetType.image type: req.params.type === 'video' ? AssetType.video : resolved.asset.type
} }
const request = { const request = {
@@ -274,7 +274,7 @@ app.get('/share/:type(photo|video)/:key/:id/:size?', decodeCookie, asyncHandler(
key: req.params.key, key: req.params.key,
range: req.headers.range || '' range: req.headers.range || ''
} }
await assetBuffer(request, res, asset, req.params.size) await assetBuffer(request, res, asset, req.params.size, resolved.link, req.params.type === 'video')
})) }))
/* /*
+12 -6
View File
@@ -5,10 +5,10 @@ import {
validateImageSize validateImageSize
} from '../immich' } from '../immich'
import { Response } from 'express-serve-static-core' import { Response } from 'express-serve-static-core'
import { Asset, AssetType, ImageSize, IncomingShareRequest } from '../types' import { Asset, ImageSize, IncomingShareRequest, SharedLink } from '../types'
import { respondToInvalidRequest } from '../invalidRequestHandler' import { respondToInvalidRequest } from '../invalidRequestHandler'
import { getFilename } from '../gallery/filename' import { getFilename } from '../gallery/filename'
import { resolveImageEndpoint } from '../gallery/sizing' import { isVideoAsset, resolveDownloadEndpoint, resolveImageEndpoint } from '../gallery/sizing'
/** /**
* Stream an asset from Immich back to the client. * Stream an asset from Immich back to the client.
@@ -18,7 +18,7 @@ import { resolveImageEndpoint } from '../gallery/sizing'
* or locked assets are handled implicitly: Immich's own endpoints refuse * or locked assets are handled implicitly: Immich's own endpoints refuse
* to serve them, and the upstream failure surfaces as a client 404. * to serve them, and the upstream failure surfaces as a client 404.
*/ */
export async function assetBuffer (req: IncomingShareRequest, res: Response, asset: Asset, size?: ImageSize | string) { export async function assetBuffer (req: IncomingShareRequest, res: Response, asset: Asset, size?: ImageSize | string, share?: SharedLink, forceVideoPlayback = false) {
const headerList = ['content-type', 'content-length', 'last-modified', 'etag'] const headerList = ['content-type', 'content-length', 'last-modified', 'etag']
const fetchHeaders: Record<string, string> = {} const fetchHeaders: Record<string, string> = {}
let subpath: string let subpath: string
@@ -26,8 +26,13 @@ export async function assetBuffer (req: IncomingShareRequest, res: Response, ass
let attachment = false let attachment = false
let servedSize: ImageSize | undefined let servedSize: ImageSize | undefined
if (asset.type === AssetType.video) { const requested = validateImageSize(size)
const useVideoPlayback = forceVideoPlayback || (isVideoAsset(asset) && requested === ImageSize.original && share?.allowDownload === false)
if (useVideoPlayback) {
subpath = '/video/playback' subpath = '/video/playback'
attachment = requested === ImageSize.original
servedSize = ImageSize.original
res.setHeader('accept-ranges', 'bytes') res.setHeader('accept-ranges', 'bytes')
// Only chunk when the client sent a Range header. A browser <video> // Only chunk when the client sent a Range header. A browser <video>
// element does, so playback still streams in 2.5 MB chunks. Clients // element does, so playback still streams in 2.5 MB chunks. Clients
@@ -43,7 +48,6 @@ export async function assetBuffer (req: IncomingShareRequest, res: Response, ass
res.status(206) // Partial Content res.status(206) // Partial Content
} }
} else { } else {
const requested = validateImageSize(size)
// Album "grid" items arrive without originalMimeType. The fullsize tier // Album "grid" items arrive without originalMimeType. The fullsize tier
// needs it to pick /original (web formats) vs ?size=fullsize (RAW/HEIF), so // needs it to pick /original (web formats) vs ?size=fullsize (RAW/HEIF), so
// fetch the asset detail on demand (cached) before resolving. // fetch the asset detail on demand (cached) before resolving.
@@ -51,7 +55,9 @@ export async function assetBuffer (req: IncomingShareRequest, res: Response, ass
const detail = await fetchAssetDetail(asset) const detail = await fetchAssetDetail(asset)
if (detail?.originalMimeType) asset = { ...asset, originalMimeType: detail.originalMimeType } if (detail?.originalMimeType) asset = { ...asset, originalMimeType: detail.originalMimeType }
} }
const endpoint = resolveImageEndpoint(requested, asset) const endpoint = requested === ImageSize.original
? resolveDownloadEndpoint(asset, share?.allowDownload !== false)
: resolveImageEndpoint(requested, asset)
subpath = endpoint.subpath subpath = endpoint.subpath
sizeQueryParam = endpoint.sizeQueryParam sizeQueryParam = endpoint.sizeQueryParam
attachment = endpoint.attachment attachment = endpoint.attachment
+7 -7
View File
@@ -1,6 +1,6 @@
import { assetFetchUrl, authHeadersForAsset } from '../immich' import { assetFetchUrl, authHeadersForAsset } from '../immich'
import { Response } from 'express-serve-static-core' import { Response } from 'express-serve-static-core'
import { Asset, ImageSize, SharedLink } from '../types' import { Asset, SharedLink } from '../types'
import { getNumericConfigOption } from '../config/access' import { getNumericConfigOption } from '../config/access'
import { log } from '../utils/log' import { log } from '../utils/log'
import archiver, { Archiver } from 'archiver' import archiver, { Archiver } from 'archiver'
@@ -10,7 +10,7 @@ import { pipeline } from 'stream/promises'
import { promises as fs, createWriteStream } from 'fs' import { promises as fs, createWriteStream } from 'fs'
import { tmpdir } from 'os' import { tmpdir } from 'os'
import { join } from 'path' import { join } from 'path'
import { resolveImageEndpoint, ImageEndpoint } from '../gallery/sizing' import { resolveDownloadEndpoint, ImageEndpoint } from '../gallery/sizing'
import { title } from '../share' import { title } from '../share'
import { getFilename } from '../gallery/filename' import { getFilename } from '../gallery/filename'
import { createLimiter } from '../utils/limiter' import { createLimiter } from '../utils/limiter'
@@ -114,7 +114,7 @@ export async function downloadAssets (res: Response, share: SharedLink, assets:
}) })
try { try {
const stages = stageAssetsToDisk(assets, options, controller.signal) const stages = stageAssetsToDisk(share, assets, options, controller.signal)
const failure = await archiveStaged(archive, stages, controller) const failure = await archiveStaged(archive, stages, controller)
if (clientGone) { if (clientGone) {
log(`Zip download for share ${share.key} cancelled by client`) log(`Zip download for share ${share.key} cancelled by client`)
@@ -148,9 +148,9 @@ export async function downloadAssets (res: Response, share: SharedLink, assets:
* concurrently. Returns the promise array in input order so the consumer can * concurrently. Returns the promise array in input order so the consumer can
* archive in order. * archive in order.
*/ */
function stageAssetsToDisk (assets: Asset[], options: StagingOptions, signal: AbortSignal): Promise<StageOutcome>[] { function stageAssetsToDisk (share: SharedLink, assets: Asset[], options: StagingOptions, signal: AbortSignal): Promise<StageOutcome>[] {
const limit = createLimiter(options.concurrency) const limit = createLimiter(options.concurrency)
return assets.map((asset, index) => limit(() => stageOne(asset, index, options, signal))) return assets.map((asset, index) => limit(() => stageOne(share, asset, index, options, signal)))
} }
/** /**
@@ -199,10 +199,10 @@ function abortDownload (archive: Archiver, res: Response, share: SharedLink, fai
* Returns the staged asset on success, a wrapped Failure on error, or null * Returns the staged asset on success, a wrapped Failure on error, or null
* if we observed the abort flag and bailed without doing work. * if we observed the abort flag and bailed without doing work.
*/ */
async function stageOne (asset: Asset, index: number, options: StagingOptions, signal: AbortSignal): Promise<StageOutcome> { async function stageOne (share: SharedLink, asset: Asset, index: number, options: StagingOptions, signal: AbortSignal): Promise<StageOutcome> {
if (signal.aborted) return null if (signal.aborted) return null
const endpoint = resolveImageEndpoint(ImageSize.original, asset) const endpoint = resolveDownloadEndpoint(asset, share.allowDownload !== false)
const url = assetFetchUrl(asset, endpoint.subpath, endpoint.sizeQueryParam) const url = assetFetchUrl(asset, endpoint.subpath, endpoint.sizeQueryParam)
const reqAuthHeaders = await authHeadersForAsset(asset) const reqAuthHeaders = await authHeadersForAsset(asset)
+40 -1
View File
@@ -1,7 +1,7 @@
import { describe, it, expect, vi, beforeEach } from 'vitest' import { describe, it, expect, vi, beforeEach } from 'vitest'
import { AssetType, ImageSize } from '../src/types' import { AssetType, ImageSize } from '../src/types'
import type { Asset } from '../src/types' import type { Asset } from '../src/types'
import { resolveImageEndpoint, requiresOriginal } from '../src/gallery/sizing' import { isVideoAsset, resolveDownloadEndpoint, resolveImageEndpoint, requiresOriginal } from '../src/gallery/sizing'
/* /*
resolveImageEndpoint reads `ipp.maxDownloadQuality` and `ipp.maxZoomQuality` resolveImageEndpoint reads `ipp.maxDownloadQuality` and `ipp.maxZoomQuality`
@@ -47,6 +47,14 @@ describe('requiresOriginal', () => {
}) })
}) })
describe('isVideoAsset', () => {
it('accepts either the asset type or the original MIME type as the video signal', () => {
expect(isVideoAsset(video)).toBe(true)
expect(isVideoAsset(videoMimeImage)).toBe(true)
expect(isVideoAsset(jpeg)).toBe(false)
})
})
describe('thumbnail - always the grid poster, never clamped', () => { describe('thumbnail - always the grid poster, never clamped', () => {
it('serves thumbnail as-is for every asset type', () => { it('serves thumbnail as-is for every asset type', () => {
for (const a of [jpeg, heic, gif, video, videoMimeImage]) { for (const a of [jpeg, heic, gif, video, videoMimeImage]) {
@@ -122,3 +130,34 @@ describe('gif / video (requiresOriginal) - always the original file, ceilings by
} }
}) })
}) })
describe('download endpoint', () => {
it('keeps videos on /original when Immich allows original downloads', () => {
cfg['ipp.maxDownloadQuality'] = 'preview'
expect(resolveDownloadEndpoint(video, true)).toEqual({
subpath: '/original', attachment: true, servedSize: ImageSize.original
})
})
it('falls back to video playback when Immich blocks original downloads', () => {
cfg['ipp.maxDownloadQuality'] = 'preview'
expect(resolveDownloadEndpoint(video, false)).toEqual({
subpath: '/video/playback', attachment: true, servedSize: ImageSize.original
})
expect(resolveDownloadEndpoint(videoMimeImage, false).subpath).toBe('/video/playback')
})
it('keeps image downloads on the maxDownloadQuality policy', () => {
cfg['ipp.maxDownloadQuality'] = 'preview'
expect(resolveDownloadEndpoint(jpeg, false)).toEqual({
subpath: '/thumbnail', sizeQueryParam: 'preview', attachment: true, servedSize: ImageSize.preview
})
})
it('keeps animated image downloads on /original', () => {
cfg['ipp.maxDownloadQuality'] = 'preview'
expect(resolveDownloadEndpoint(gif, false)).toEqual({
subpath: '/original', attachment: true, servedSize: ImageSize.original
})
})
})