Files
immich-magic-proxy/app/src/gallery/filename.ts
T
2026-10-05 15:55:18 +13:00

121 lines
4.7 KiB
TypeScript

import { Asset, getConfigOption, sanitize } from '@ipp/core'
import { ImageSize } from '../types'
import { resolveImageEndpoint } from './sizing'
/**
* Map a MIME type to a file extension (including the dot), case-insensitively.
* Returns '' for unknown types; obscure RAW types fall through to '' so
* the original filename (which usually has the correct extension) is
* preserved by `withMimeExtension`.
*/
function mimeToExt (mime: string | undefined): string {
if (!mime) return ''
const map: Record<string, string> = {
'image/jpeg': '.jpg',
'image/png': '.png',
'image/webp': '.webp',
'image/gif': '.gif',
'image/heic': '.heic',
'image/heif': '.heif',
'image/avif': '.avif',
'image/tiff': '.tiff',
'image/svg+xml': '.svg',
'image/x-adobe-dng': '.dng',
'video/mp4': '.mp4',
'video/quicktime': '.mov',
'video/webm': '.webm',
'video/x-msvideo': '.avi',
'video/x-matroska': '.mkv'
}
return map[mime.toLowerCase()] || ''
}
/**
* Append the MIME-derived extension to `filename` if it isn't already
* present (case-insensitive). Returns the filename unchanged when the
* MIME isn't in our map. Aliases that share a MIME type (`.jpg`/`.jpeg`,
* `.tif`/`.tiff`) are accepted as already-present so we don't produce
* `IMG.jpeg.jpg` for an `image/jpeg` asset.
*/
function withMimeExtension (filename: string, mime: string | undefined): string {
const ext = mimeToExt(mime)
if (!ext) return filename
const aliases: Record<string, string[]> = {
'.jpg': ['.jpg', '.jpeg'],
'.tiff': ['.tif', '.tiff']
}
const acceptable = aliases[ext] ?? [ext]
const lower = filename.toLowerCase()
return acceptable.some(a => lower.endsWith(a)) ? filename : filename + ext
}
/**
* Generate a filename for the downloaded asset based on the configuration option chosen.
*
* The extension follows the served bytes, not the original.
*
* @param asset
* @param [servedSize] - what size Immich will actually serve. Defaults to
* ImageSize.original (the bytes match the original asset).
* @param [servedMimeOverride] - MIME of Immich-generated bytes (see servedMimeFrom).
* Ignored if unmapped, so it can't strip the extension.
*/
export function getFilename (asset: Asset, servedSize: ImageSize = ImageSize.original, servedMimeOverride?: string): string {
const override = mimeToExt(servedMimeOverride) ? servedMimeOverride : undefined
let servedMime: string | undefined
if (override) {
servedMime = override
} else if (servedSize === ImageSize.original) {
servedMime = asset.originalMimeType
} else if (servedSize === ImageSize.thumbnail) {
servedMime = 'image/webp'
} else {
servedMime = 'image/jpeg'
}
switch (getConfigOption('ipp.downloadedFilename')) {
case 1:
// Immich's ID number for this asset
return withMimeExtension(asset.id, servedMime)
case 2:
// A sanitised version of the ID number
return withMimeExtension('img_' + asset.id.slice(0, 8), servedMime)
default: {
// By default, use the asset's original filename
const cleanName = asset.originalFileName ? sanitize(asset.originalFileName) : ''
if (!cleanName) return withMimeExtension(asset.id, servedMime)
// Keep the original extension only when the served bytes really are the
// original file; a size downgrade or playback transcode replaces it.
const stem = servedSize === ImageSize.original && !override
? cleanName
: cleanName.replace(/\.[a-zA-Z0-9]{2,5}$/, '')
return withMimeExtension(stem, servedMime)
}
}
}
/**
* Filename for a download link's `download` attribute. Converted tiers are assumed
* JPEG; the download's Content-Disposition, which browsers prefer, has the real name.
*/
export function downloadFilename (asset: Asset): string {
return getFilename(asset, resolveImageEndpoint(ImageSize.original, asset).servedSize)
}
/** Download Content-Disposition, RFC 5987-encoded so `,` and `;` can't split the header. */
export function attachmentDisposition (filename: string): string {
const encoded = encodeURIComponent(filename)
.replace(/['()*]/g, c => '%' + c.charCodeAt(0).toString(16).toUpperCase())
return `attachment; filename*=UTF-8''${encoded}`
}
/** Content-type without its parameters, or undefined if absent. */
export function responseMime (response: globalThis.Response): string | undefined {
return (response.headers.get('content-type') || '').split(';')[0].trim() || undefined
}
/** Content-type of Immich-generated bytes (anything but /original), to name the file by. */
export function servedMimeFrom (subpath: string, response: globalThis.Response): string | undefined {
return subpath === '/original' ? undefined : responseMime(response)
}