Require Immich 3.x; code cleanup

This commit is contained in:
Alan Grainger
2026-10-06 09:23:57 +13:00
parent d03a77f691
commit 255260ccb3
33 changed files with 347 additions and 800 deletions
+1 -2
View File
@@ -127,8 +127,7 @@ function writePersistedState (open: boolean) {
// ----- content rendering ---------------------------------------------------
//
// Sidebar UI placement for each metadata field. Server-side gating lives in
// `gallery/exif.ts` (rules table); legacy-config migration lives in
// `config/migrations.ts`. Adding a new field requires updating all three.
// `gallery/exif.ts` (rules table). Adding a new field requires updating both.
function renderContents (root: HTMLElement, item: GalleryItem | undefined) {
root.replaceChildren()
-5
View File
@@ -1,5 +0,0 @@
/*
Kept for operators who mount a copy of invalidRequestHandler.js taken from
IPP 3.x, which requires './config/access'. Delete in 4.0 with an upgrade note.
*/
export { getConfigOption } from '@ipp/core'
-241
View File
@@ -1,241 +0,0 @@
/*
Backward-compatibility shims that map legacy `config.json` key shapes
onto their current locations. Each shim mutates the in-memory config
only - the on-disk file is never touched, so read-only mounts are safe.
CONVENTION for keeping this file pruneable:
1. Every shim function starts its JSDoc with a `SHIM:` marker line.
To list all current shims: grep -rn 'SHIM:' app/src
2. Every shim is registered in `SHIMS` below with the version it
should be deleted in. When that version comes up, remove the
function, its registry entry, and any tests for it.
3. Each shim should be self-contained and side-effect-free beyond
mutating the passed-in config. No imports from app code.
*/
type Config = Record<string, unknown>
interface Shim {
name: string
removeIn: string
apply: (config: Config) => void
}
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: 'downloadOriginalPhoto', removeIn: 'v4.0', apply: applyDownloadQualityShim },
{ name: 'allowDownloadAll', removeIn: 'v4.0', apply: applyAllowDownloadRenameShim }
]
/**
* Apply every registered legacy-config shim to `config` in place.
* Called from `loadConfig()` after reading the file or env JSON.
*/
export function applyMigrations (config: Config): void {
for (const shim of SHIMS) shim.apply(config)
}
/**
* SHIM: lightGallery -> ipp.lightbox (1.x users with a legacy
* `lightGallery.*` config section). Maps `lightGallery.controls`,
* `lightGallery.download`, and `lightGallery.mobileSettings.controls`
* onto `ipp.lightbox.*`.
*/
function applyLightGalleryShim (config: Config): void {
if (!config.lightGallery || typeof config.lightGallery !== 'object') return
const lg = config.lightGallery as Record<string, unknown>
const mobile = (lg.mobileSettings || {}) as Record<string, unknown>
const ipp = (config.ipp || (config.ipp = {})) as Record<string, unknown>
const lightbox = (ipp.lightbox || (ipp.lightbox = {})) as Record<string, unknown>
if (lightbox.showArrows === undefined && lg.controls !== undefined) {
lightbox.showArrows = !!lg.controls
}
if (lightbox.showDownload === undefined && lg.download !== undefined) {
lightbox.showDownload = !!lg.download
}
if (lightbox.mobileArrows === undefined && mobile.controls !== undefined) {
lightbox.mobileArrows = !!mobile.controls
}
console.log(
'[IPP] The `lightGallery` config section is deprecated; relevant keys ' +
'have been mapped to `ipp.lightbox.*`. See README for the current options.'
)
}
/**
* 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`.
* Maps legacy keys forward, only filling in fields the user hasn't
* already set on the new path.
*/
function applyTopLevelGalleryShim (config: Config): void {
const ipp = (config.ipp || (config.ipp = {})) as Record<string, unknown>
const galleryKeyMigrations: Array<[string, string]> = [
['singleImageGallery', 'singleImage'],
['singleItemAutoOpen', 'singleItemAutoOpen'],
['showGalleryTitle', 'showTitle'],
['showGalleryDescription', 'showDescription'],
['groupGalleryByDate', 'groupByDate']
]
const legacyPresent = galleryKeyMigrations.some(([oldKey]) => ipp[oldKey] !== undefined)
if (!legacyPresent) return
const gallery = (ipp.gallery || (ipp.gallery = {})) as Record<string, unknown>
for (const [oldKey, newKey] of galleryKeyMigrations) {
if (ipp[oldKey] !== undefined && gallery[newKey] === undefined) {
gallery[newKey] = ipp[oldKey]
}
}
console.log(
'[IPP] Top-level gallery keys (singleImageGallery, singleItemAutoOpen, ' +
'showGalleryTitle, showGalleryDescription, groupGalleryByDate) are ' +
'deprecated; please move them under `ipp.gallery.*`. See README.'
)
}
/**
* SHIM: showMetadata.description boolean -> { caption, sidebar } object.
* `ipp.showMetadata.description` used to be a single boolean controlling
* both the lightbox caption and (later) the sidebar. It is now an object
* with separate `caption` and `sidebar` flags. A legacy boolean value is
* migrated to `{ caption: <bool>, sidebar: <bool> }` so existing configs
* continue to render description in both places.
*/
function applyDescriptionSplitShim (config: Config): void {
const ipp = (config.ipp || (config.ipp = {})) as Record<string, unknown>
const showMetadata = ipp.showMetadata as Record<string, unknown> | undefined
if (!showMetadata) return
if (typeof showMetadata.description !== 'boolean') return
const legacy = showMetadata.description
showMetadata.description = { caption: legacy, sidebar: legacy }
console.log(
'[IPP] `ipp.showMetadata.description` as a boolean is deprecated; use ' +
'`{ "caption": <bool>, "sidebar": <bool> }` to control each surface ' +
'independently. See README.'
)
}
/**
* SHIM: showMetadata.{exif,location}.enabled removed. Per-field flags are
* now the only gate, and they all default to `false`.
*
* The 2.3.0 shipped `config.json` had `enabled: false` plus every per-
* field flag set to `true` as documentation. Without this shim those
* `true`s would become live opt-ins on upgrade, silently exposing GPS
* coordinates and EXIF data on share pages. The shim rewrites legacy
* configs in memory at startup:
*
* - `enabled: true`: for each known field in the group, if the per-
* field flag is `undefined`, set it to `true` (the old default).
* Explicit `false` per-field flags are kept, so "all except X"
* patterns continue to work.
* - `enabled: false`: clear any per-field flag that is `true`. Under
* the old semantic those flags were dead code (the master switch
* hid them), so wiping them preserves the "nothing visible"
* behaviour the user had.
*
* The field lists below are frozen at v2.x. If new fields are added in
* future versions, they will not auto-appear for legacy `enabled: true`
* users - which is the safer privacy default and matches the policy the
* new design is establishing.
*/
// These lists are frozen at v2.3.0 and intentionally do NOT track the
// current field set. The server's source-of-truth rules table lives in
// `gallery/exif.ts`, and the sidebar's UI placement lives in
// `client/sidebar.ts`. New fields added in future versions deliberately
// won't auto-appear for legacy `enabled: true` users via this shim - they
// should opt in explicitly.
const LEGACY_EXIF_FIELDS = [
'dateTimeOriginal', 'fileName', 'dimensions', 'fileSize',
'make', 'model', 'lensModel', 'exposureTime', 'iso',
'fNumber', 'focalLength'
]
const LEGACY_LOCATION_FIELDS = ['city', 'state', 'country', 'gps']
function applyMetadataEnabledShim (config: Config): void {
const ipp = (config.ipp || (config.ipp = {})) as Record<string, unknown>
const showMetadata = ipp.showMetadata as Record<string, unknown> | undefined
if (!showMetadata) return
let migrated = false
const groups: Array<[string, string[]]> = [
['exif', LEGACY_EXIF_FIELDS],
['location', LEGACY_LOCATION_FIELDS]
]
for (const [groupName, fields] of groups) {
const group = showMetadata[groupName] as Record<string, unknown> | undefined
if (!group || typeof group !== 'object') continue
if (group.enabled === undefined) continue
const legacyEnabled = !!group.enabled
delete group.enabled
if (legacyEnabled) {
for (const field of fields) {
if (group[field] === undefined) group[field] = true
}
} else {
for (const field of fields) {
if (group[field] === true) group[field] = false
}
}
migrated = true
}
if (migrated) {
console.log(
'[IPP] `ipp.showMetadata.exif.enabled` / `.location.enabled` are ' +
'deprecated and have been removed. Per-field flags are now the ' +
'only gate (all default `false`). Your legacy config has been ' +
'rewritten in memory to preserve current behaviour; please update ' +
'your `config.json` to the explicit per-field form. See README.'
)
}
}
+13 -27
View File
@@ -25,30 +25,21 @@ function copy (key: keyof ExifInfo & keyof GalleryExif): FieldRule {
}
}
/*
EXIF orientation values meaning the image is stored rotated 90/270 degrees,
so its displayed width and height are the stored ones swapped. 5-8 are the
standard EXIF set (see https://magnushoff.com/articles/jpeg-orientation/);
90 / -90 are degree-style values Immich also emits - see `isFlipped` in its
`web/src/lib/utils/asset-utils.ts`.
*/
const FLIPPED_ORIENTATIONS = [5, 6, 90, 7, 8, -90]
/**
* An asset's dimensions as displayed. Prefers the asset-level width/height,
* which Immich provides orientation-corrected from 3.0.0
* Config paths of any `ipp.showMetadata.{exif,location}.enabled` key. IPP
* refuses to start while one is set: per-field flags are the only gate, and
* `true` flags beside such a key may not be meant for visitors.
*/
export function removedMetadataSwitches (): string[] {
return ['exif', 'location']
.map(group => 'ipp.showMetadata.' + group + '.enabled')
.filter(path => getConfigOption(path) !== undefined)
}
/** An asset's dimensions as displayed; Immich stores them orientation-corrected. */
export function displayDimensions (asset: Asset): { width?: number, height?: number } {
if (asset.width && asset.height) return { width: asset.width, height: asset.height }
// Fallback for Immich 2.x
const info = asset.exifInfo
const width = info?.exifImageWidth
const height = info?.exifImageHeight
if (!width || !height) return {}
return FLIPPED_ORIENTATIONS.includes(Number(info?.orientation))
? { width: height, height: width }
: { width, height }
return {}
}
/*
@@ -57,13 +48,8 @@ export function displayDimensions (asset: Asset): { width?: number, height?: num
written inline in the `*_RULES` arrays below.
Adding a new metadata field: this rules table is the server-side source
of truth. Two other places carry parallel knowledge of the field set:
- `client/sidebar.ts` (renderRow specs decide where the field appears
in the info sidebar UI)
- `config/migrations.ts` LEGACY_* arrays (frozen v2.x field list used
by the `enabled -> per-field` shim; do NOT extend when adding new
fields - new fields should not retroactively appear for legacy
`enabled: true` users).
of truth. `client/sidebar.ts` carries parallel knowledge of the field set
(renderRow specs decide where the field appears in the info sidebar UI).
*/
const EXIF_FIELDS = [
'make', 'model', 'lensModel',
+37
View File
@@ -118,3 +118,40 @@ export function responseMime (response: globalThis.Response): string | undefined
export function servedMimeFrom (subpath: string, response: globalThis.Response): string | undefined {
return subpath === '/original' ? undefined : responseMime(response)
}
/**
* Fill in originalFileName / originalMimeType from an asset response's
* `Content-Disposition` / `Content-Type` headers, for assets that arrived
* without them (lazy album grid assets). Returns a shallow copy so the cached
* share asset is never mutated.
*/
export function enrichFromHeaders (asset: Asset, response: globalThis.Response): Asset {
const fileName = filenameFromContentDisposition(response.headers.get('content-disposition'))
const mime = responseMime(response)
if (!fileName && !mime) return asset
return {
...asset,
originalFileName: asset.originalFileName || fileName,
originalMimeType: asset.originalMimeType || mime
}
}
/**
* Extract a filename from a `Content-Disposition` header. Prefers the RFC 5987
* `filename*=UTF-8''...` form (percent-decoded) over the plain `filename=`.
* Returns undefined when neither is present.
*/
export function filenameFromContentDisposition (header: string | null): string | undefined {
if (!header) return undefined
const extended = header.match(/filename\*=(?:UTF-8'')?([^;]+)/i)
if (extended) {
const raw = extended[1].trim().replace(/^"|"$/g, '')
try {
return decodeURIComponent(raw)
} catch (e) {
return raw
}
}
const plain = header.match(/filename="?([^";]+)"?/i)
return plain ? plain[1].trim() : undefined
}
+3 -3
View File
@@ -23,7 +23,7 @@ import {
TtlLruCache
} from '@ipp/core'
import { ImageSize, IncomingShareRequest, TimelineBucket, TimelineBucketAssets } from './types'
import { canDownload } from './share'
import { canDownload, servableAssets } from './share'
import { assetBuffer } from './stream/asset'
import { downloadAll } from './stream/download'
import { gallery } from './gallery/builder'
@@ -204,8 +204,8 @@ async function fetchShareByKey (key: string, password?: string, keyType: KeyType
log('Shared link ' + key + ' returned no assets array (type ' + link.type + ')')
link.assets = []
}
// Filter assets to exclude trashed assets
link.assets = link.assets.filter(asset => !asset.isTrashed)
// Drop trashed assets, and any Immich hasn't finished processing
link.assets = servableAssets(link.assets)
// Populate the shared assets with the public key/password
link.assets.forEach(asset => {
asset.key = key
+15 -6
View File
@@ -28,23 +28,32 @@ import {
} from '@ipp/core'
import { fetchAssetDetail, getShareByKey, handleShareRequest } from './immich'
import { buildAssetMetadata } from './gallery/metadata'
import { removedMetadataSwitches } from './gallery/exif'
import { assetBuffer } from './stream/asset'
import { downloadAssets } from './stream/download'
import dayjs from 'dayjs'
import { Request } from 'express-serve-static-core'
import { ImageSize } from './types'
import { applyMigrations } from './config/migrations'
import { canDownload, findMotionPhotoStill } from './share'
import { respondToInvalidRequest as ippInvalidRequestHandler } from './invalidRequestHandler'
import { ASSET_VERSION } from './version'
import { h } from 'preact'
import { Home } from './view/home'
// Read config.json (or the inline CONFIG env var) and apply backward-compat
// migrations. Must run before any code that calls getConfigOption. The
// bundled config.json sits one level above this file (src/ in dev, dist/ in
// the image), which is /app/config.json in the image.
loadConfig({ defaultPath: resolve(__dirname, '../config.json'), migrate: applyMigrations })
// Read config.json (or the inline CONFIG env var). Must run before any code
// that calls getConfigOption. The bundled config.json sits one level above
// this file (src/ in dev, dist/ in the image), which is /app/config.json in
// the image.
loadConfig({ defaultPath: resolve(__dirname, '../config.json') })
const removedSwitches = removedMetadataSwitches()
if (removedSwitches.length) {
console.error(dayjs().format() + ' FATAL: The config has ' + removedSwitches.join(' and ') +
', which IPP no longer reads. Every per-field flag set to true in that group would now be shown to visitors. ' +
'Remove the key, and set to true only the fields you want visitors to see. ' +
'See https://docs.ipp.nz/config/upgrading')
process.exit(1)
}
// Route every invalid response, including core's, through IPP's handler file,
// so an operator's mounted replacement applies everywhere.
+32 -11
View File
@@ -1,4 +1,4 @@
import { Asset, getConfigOption, SharedLink } from '@ipp/core'
import { Asset, getConfigOption, log, SharedLink, TtlLruCache } from '@ipp/core'
import { DownloadAll } from './types'
import dayjs from 'dayjs'
@@ -10,17 +10,38 @@ import dayjs from 'dayjs'
* does not affect image quality (see `gallery/sizing.ts`).
*/
export function canDownload (share: SharedLink): boolean {
const allowDownloadConfig = getConfigOption('ipp.allowDownload', 0) as DownloadAll
if (!allowDownloadConfig) {
// Downloading is disabled in config.json
return false
} else if (allowDownloadConfig === DownloadAll.always) {
// Always allowed to download in config.json
return true
} else {
// Return Immich's setting for this shared link
return !!share.allowDownload
const policy = getConfigOption('ipp.allowDownload', DownloadAll.disabled)
if (policy === DownloadAll.always) return true
if (policy === DownloadAll.perImmich) return !!share.allowDownload
if (policy !== DownloadAll.disabled && !warnedInvalidDownloadPolicy) {
warnedInvalidDownloadPolicy = true
log.warn('ipp.allowDownload is ' + JSON.stringify(policy) + ', which is not 0, 1 or 2. Downloads are off.')
}
return false
}
let warnedInvalidDownloadPolicy = false
// Asset ids already warned about, so each warns at most once a day
const warnedUnprocessed = new TtlLruCache<true>({ ttlMs: 24 * 60 * 60_000, max: 1000 })
/**
* Narrow a share's assets to what IPP can render: not trashed, and finished
* processing in Immich. `thumbhash` is the readiness signal: Immich's
* thumbnail job writes the files and only then sets it, so until it appears
* every image URL IPP hands out would 404.
*/
export function servableAssets (assets: Asset[]): Asset[] {
return assets.filter(asset => {
if (asset.isTrashed) return false
if (asset.thumbhash) return true
if (!warnedUnprocessed.get(asset.id)) {
warnedUnprocessed.set(asset.id, true)
log.warn('Asset ' + asset.id + ' is hidden because Immich has not generated its thumbnail yet. ' +
'If it never appears, check the thumbnail job for that asset in Immich.')
}
return false
})
}
const DEFAULT_EXPIRY_FORMAT = 'YYYY-MM-DD'
+7 -4
View File
@@ -7,7 +7,7 @@ import {
} from '../immich'
import { Response } from 'express-serve-static-core'
import { ImageSize, IncomingShareRequest } from '../types'
import { attachmentDisposition, getFilename, servedMimeFrom } from '../gallery/filename'
import { attachmentDisposition, enrichFromHeaders, getFilename, servedMimeFrom } from '../gallery/filename'
import { isVideoAsset, resolveDownloadEndpoint, resolveImageEndpoint } from '../gallery/sizing'
import { pipeline } from 'stream/promises'
@@ -94,11 +94,14 @@ export async function assetBuffer (req: IncomingShareRequest, res: Response, ass
return
}
// An original can be any format Immich accepts, so never let a browser sniff it
res.setHeader('X-Content-Type-Options', 'nosniff')
if (attachment) {
res.setHeader('X-Accel-Buffering', 'no')
if (asset.originalFileName) {
res.setHeader('Content-Disposition', attachmentDisposition(getFilename(asset, servedSize, servedMimeFrom(subpath, data))))
}
// Always an attachment, so an SVG can't render inline. Album assets have
// no originalFileName; Immich's own Content-Disposition carries it.
const named = asset.originalFileName ? asset : enrichFromHeaders(asset, data)
res.setHeader('Content-Disposition', attachmentDisposition(getFilename(named, servedSize, servedMimeFrom(subpath, data))))
}
headerList.forEach(header => {
const value = data.headers.get(header)
+1 -38
View File
@@ -3,7 +3,7 @@ import { assetFetchUrl, authHeadersForAsset } from '../immich'
import { Response } from 'express-serve-static-core'
import archiver, { Archiver } from 'archiver'
import { resolveDownloadEndpoint, ImageEndpoint } from '../gallery/sizing'
import { attachmentDisposition, getFilename, responseMime, servedMimeFrom } from '../gallery/filename'
import { attachmentDisposition, enrichFromHeaders, getFilename, servedMimeFrom } from '../gallery/filename'
/** Attempts to get response headers from Immich for one asset before giving up. */
const MAX_ATTEMPTS = 3
@@ -216,43 +216,6 @@ async function fetchOne (share: SharedLink, asset: Asset, signal: AbortSignal):
return { response: fetched.response, asset: namedAsset, endpoint, servedMime: servedMimeFrom(endpoint.subpath, fetched.response), url }
}
/**
* Fill in originalFileName / originalMimeType from an asset response's
* `Content-Disposition` / `Content-Type` headers, for assets that arrived
* without them (lazy album grid assets). Returns a shallow copy so the cached
* share asset is never mutated.
*/
function enrichFromHeaders (asset: Asset, response: globalThis.Response): Asset {
const fileName = filenameFromContentDisposition(response.headers.get('content-disposition'))
const mime = responseMime(response)
if (!fileName && !mime) return asset
return {
...asset,
originalFileName: asset.originalFileName || fileName,
originalMimeType: asset.originalMimeType || mime
}
}
/**
* Extract a filename from a `Content-Disposition` header. Prefers the RFC 5987
* `filename*=UTF-8''...` form (percent-decoded) over the plain `filename=`.
* Returns undefined when neither is present.
*/
export function filenameFromContentDisposition (header: string | null): string | undefined {
if (!header) return undefined
const extended = header.match(/filename\*=(?:UTF-8'')?([^;]+)/i)
if (extended) {
const raw = extended[1].trim().replace(/^"|"$/g, '')
try {
return decodeURIComponent(raw)
} catch (e) {
return raw
}
}
const plain = header.match(/filename="?([^";]+)"?/i)
return plain ? plain[1].trim() : undefined
}
type HeaderFetchOutcome =
| { response: globalThis.Response }
| { failure: { status?: number, error?: unknown } }
-5
View File
@@ -1,5 +0,0 @@
/*
Kept for operators who mount a copy of invalidRequestHandler.js taken from
IPP 3.x, which requires './utils/log'. Delete in 4.0 with an upgrade note.
*/
export { log } from '@ipp/core'
+51
View File
@@ -105,6 +105,57 @@ describe('album timeline enumeration (Immich 3.0)', () => {
expect(assets[0].width!).toBeGreaterThan(assets[0].height!)
})
it('withholds assets Immich has not finished generating thumbnails for', async () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
const pending = {
...bucketResponse,
id: bucketResponse.id.map(id => id.replace(/^a/, 'e')),
thumbhash: [null, null, 'hashC'],
isTrashed: [false, true, false]
}
vi.stubGlobal('fetch', vi.fn(async (url: string) => {
if (url.includes('/shared-links/me')) return jsonResponse(sharedLinkResponse())
if (url.includes('/timeline/buckets')) return jsonResponse(bucketsResponse)
if (url.includes('/timeline/bucket')) return jsonResponse(pending)
throw new Error('Unexpected fetch to ' + url)
}))
const first = await getShareByKey(uniqueKey(), undefined, KeyType.key)
// A second share key stands in for the next cache refresh.
await getShareByKey(uniqueKey(), undefined, KeyType.key)
expect(first.valid).toBe(true)
expect(first.link!.assets.map(a => a.id)).toEqual(['cccccccc-cccc-cccc-cccc-cccccccccccc'])
const warnings = warn.mock.calls.filter(c => String(c[0]).includes('eaaaaaaa-'))
expect(warnings).toHaveLength(1)
warn.mockRestore()
})
it('withholds unprocessed assets on an individual share too', async () => {
// Individual shares carry their assets inline on /shared-links/me rather
// than via the timeline, so the filter has to sit downstream of both.
vi.spyOn(console, 'warn').mockImplementation(() => {})
const individual = {
type: 'INDIVIDUAL',
key: 'real-key',
allowDownload: true,
expiresAt: null,
showMetadata: true,
assets: [
{ id: 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', type: 'IMAGE', isTrashed: false, thumbhash: 'hashA' },
{ id: 'ffffffff-ffff-ffff-ffff-ffffffffffff', type: 'IMAGE', isTrashed: false, thumbhash: null }
]
}
vi.stubGlobal('fetch', vi.fn(async (url: string) => {
if (url.includes('/shared-links/me')) return jsonResponse(individual)
throw new Error('Unexpected fetch to ' + url)
}))
const result = await getShareByKey(uniqueKey(), undefined, KeyType.key)
expect(result.valid).toBe(true)
expect(result.link!.assets.map(a => a.id)).toEqual(['aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa'])
vi.mocked(console.warn).mockRestore()
})
it('requests each bucket with an explicit UTC key so non-UTC databases match (#260)', async () => {
const fetchMock = routeFetch(sharedLinkResponse())
vi.stubGlobal('fetch', fetchMock)
+11 -24
View File
@@ -1,6 +1,7 @@
import { describe, it, expect, beforeEach } from 'vitest'
import { Asset, AssetType, KeyType, loadConfig, SharedLink } from '@ipp/core'
import { buildAssetMetadata } from '../src/gallery/metadata'
import { removedMetadataSwitches } from '../src/gallery/exif'
// buildAssetMetadata is the lazy-flow counterpart to the gallery builder's
// per-item baking; it must apply the same showMetadata kill-switch and
@@ -56,17 +57,11 @@ describe('buildAssetMetadata', () => {
expect(meta.exif?.city).toBeUndefined()
})
// Immich 3.x applies EXIF orientation before storing asset.width / height,
// so a rotated photo reports portrait dimensions there while the exifImage*
// pair stays landscape. The asset-level pair must win.
it('reports dimensions in display orientation', () => {
it('reports the asset-level dimensions', () => {
setConfig({ ipp: { showMetadata: { exif: { dimensions: true } } } })
const photo = asset()
photo.width = 3000
photo.height = 4000
photo.exifInfo!.exifImageWidth = 4000
photo.exifInfo!.exifImageHeight = 3000
photo.exifInfo!.orientation = '6'
expect(buildAssetMetadata(photo, share()).exif).toMatchObject({
width: 3000,
@@ -74,25 +69,17 @@ describe('buildAssetMetadata', () => {
})
})
// Immich 2.x has no asset-level width / height, so the raw EXIF pair is
// used, swapped when the orientation marks the image as stored rotated.
const exifOrientationCases: Array<[string | null, number, number]> = [
['6', 3000, 4000],
['8', 3000, 4000],
['90', 3000, 4000],
['-90', 3000, 4000],
['1', 4000, 3000],
[null, 4000, 3000]
]
it('finds the removed metadata master switches, whatever their value', () => {
setConfig({ ipp: { showMetadata: { exif: { enabled: false, gps: true }, location: { enabled: true } } } })
expect(removedMetadataSwitches()).toEqual(['ipp.showMetadata.exif.enabled', 'ipp.showMetadata.location.enabled'])
it.each(exifOrientationCases)('falls back to swapped exif dimensions without asset dimensions (orientation %s)', (orientation, width, height) => {
setConfig({ ipp: { showMetadata: { exif: { make: true } } } })
expect(removedMetadataSwitches()).toEqual([])
})
it('omits dimensions when Immich has no asset-level width / height', () => {
setConfig({ ipp: { showMetadata: { exif: { dimensions: true } } } })
const photo = asset()
photo.exifInfo!.exifImageWidth = 4000
photo.exifInfo!.exifImageHeight = 3000
photo.exifInfo!.orientation = orientation
expect(buildAssetMetadata(photo, share()).exif).toMatchObject({ width, height })
expect(buildAssetMetadata(asset(), share()).exif?.width).toBeUndefined()
})
it('returns the photo timezone only when both date and timezone are enabled', () => {
+35
View File
@@ -211,4 +211,39 @@ describe('assetBuffer streaming', () => {
expect(res.headers['content-disposition']).toContain('a1.webp')
expect(res.headers['content-type']).toBe('image/webp')
})
describe('original tier on an album asset', () => {
// Album assets come from the timeline with no originalFileName or mime.
const albumAsset: Asset = { id: 'a2', key: 'testkey', keyType: KeyType.key, type: AssetType.image, isTrashed: false }
function svgFetch (headers: Record<string, string>) {
return vi.fn(async () => new globalThis.Response('<svg xmlns="http://www.w3.org/2000/svg"/>', {
status: 200,
headers: { 'content-type': 'image/svg+xml', ...headers }
}))
}
it('sends an attachment named from Immich\'s header, with nosniff', async () => {
vi.stubGlobal('fetch', svgFetch({ 'content-disposition': 'attachment; filename="drawing.svg"' }))
const res = new FakeRes()
await assetBuffer(makeRequest(), asResponse(res), albumAsset, ImageSize.original)
expect(res.headers['content-disposition']).toBe("attachment; filename*=UTF-8''drawing.svg")
expect(res.headers['x-content-type-options']).toBe('nosniff')
})
it('falls back to the asset id when Immich sends no filename', async () => {
vi.stubGlobal('fetch', svgFetch({}))
const res = new FakeRes()
await assetBuffer(makeRequest(), asResponse(res), albumAsset, ImageSize.original)
expect(res.headers['content-disposition']).toBe("attachment; filename*=UTF-8''a2.svg")
})
})
it('serves display sizes inline, still with nosniff', async () => {
vi.stubGlobal('fetch', pullFetch(CHUNK, newSource()))
const res = new FakeRes()
await assetBuffer(makeRequest(), asResponse(res), asset, ImageSize.preview)
expect(res.headers['content-disposition']).toBeUndefined()
expect(res.headers['x-content-type-options']).toBe('nosniff')
})
})
+47
View File
@@ -0,0 +1,47 @@
import { describe, it, expect, beforeEach, vi } from 'vitest'
import { KeyType, loadConfig, SharedLink } from '@ipp/core'
import { canDownload } from '../src/share'
// canDownload gates the download UI on ipp.allowDownload: 0 off, 1 follow the
// Immich share's toggle, 2 always. Anything else fails closed.
function setConfig (config: unknown) {
process.env.CONFIG = JSON.stringify(config)
loadConfig()
}
const share = (allowDownload: boolean): SharedLink => ({
key: 'k',
keyType: KeyType.key,
type: 'ALBUM',
assets: [],
allowDownload
})
describe('canDownload', () => {
beforeEach(() => {
delete process.env.CONFIG
loadConfig()
vi.spyOn(console, 'warn').mockImplementation(() => {})
})
it('is off by default', () => {
expect(canDownload(share(true))).toBe(false)
})
it('follows the Immich toggle with 1', () => {
setConfig({ ipp: { allowDownload: 1 } })
expect(canDownload(share(true))).toBe(true)
expect(canDownload(share(false))).toBe(false)
})
it('is always on with 2', () => {
setConfig({ ipp: { allowDownload: 2 } })
expect(canDownload(share(false))).toBe(true)
})
it.each([true, '1', '2', 3, -1])('fails closed for %j', value => {
setConfig({ ipp: { allowDownload: value } })
expect(canDownload(share(true))).toBe(false)
})
})
+1 -2
View File
@@ -1,6 +1,5 @@
import { describe, it, expect } from 'vitest'
import { filenameFromContentDisposition } from '../src/stream/download'
import { attachmentDisposition } from '../src/gallery/filename'
import { attachmentDisposition, filenameFromContentDisposition } from '../src/gallery/filename'
// Used by the zip download path to recover the real filename for album grid
// assets (which arrive without originalFileName) from the /original response.
+2
View File
@@ -66,6 +66,7 @@ class FakeRes extends Writable {
}
setHeader (name: string, value: string) { this.headers[name] = value; return this }
set (name: string, value: string) { return this.setHeader(name, value) }
status (code: number) { this.statusCode = code; return this }
send () { this.end(); return this }
@@ -245,6 +246,7 @@ describe('downloadAssets', () => {
expect(res.writableEnded).toBe(true)
expect(res.received).toBe(0)
expect(res.headers['Content-Type']).toBeUndefined()
expect(res.headers['Cache-Control']).toContain('no-store')
}, 10_000)
it('destroys the response when a later asset keeps failing', async () => {
-364
View File
@@ -1,364 +0,0 @@
import { describe, it, expect, beforeEach, vi, afterEach } from 'vitest'
import { applyMigrations } from '../src/config/migrations'
/*
The migrations module mutates the passed-in config object in place and
logs a one-line deprecation notice when it makes a change. These tests
cover all four shims registered in `SHIMS`. Console output is silenced
per-test so the suite stays quiet and so we can assert on it where the
deprecation message is part of the contract.
*/
let logSpy: ReturnType<typeof vi.spyOn>
beforeEach(() => {
logSpy = vi.spyOn(console, 'log').mockImplementation(() => {})
})
afterEach(() => {
logSpy.mockRestore()
})
describe('applyMigrations', () => {
it('is a no-op for a fresh config that has no legacy keys', () => {
const config = {
ipp: {
showMetadata: {
exif: { dateTimeOriginal: true },
location: { city: true }
},
gallery: { showTitle: true },
lightbox: { showArrows: true }
}
}
const before = JSON.stringify(config)
applyMigrations(config)
expect(JSON.stringify(config)).toBe(before)
expect(logSpy).not.toHaveBeenCalled()
})
it('is a no-op for a completely empty config', () => {
const config = {}
applyMigrations(config)
// applyMigrations seeds an `ipp` object on its way through, so empty in
// means `{ ipp: {} }` out - that's fine, just check no crash + no logs.
expect(logSpy).not.toHaveBeenCalled()
})
})
describe('lightGallery shim', () => {
it('maps lightGallery.controls / download / mobileSettings to ipp.lightbox.*', () => {
const config = {
lightGallery: {
controls: false,
download: false,
mobileSettings: { controls: true }
}
} as Record<string, unknown>
applyMigrations(config)
const ipp = config.ipp as Record<string, unknown>
const lightbox = ipp.lightbox as Record<string, unknown>
expect(lightbox.showArrows).toBe(false)
expect(lightbox.showDownload).toBe(false)
expect(lightbox.mobileArrows).toBe(true)
expect(logSpy).toHaveBeenCalledOnce()
})
it('does not overwrite values the user has already set on the new path', () => {
const config = {
lightGallery: { controls: false, download: false },
ipp: {
lightbox: { showArrows: true, showDownload: true }
}
} as Record<string, unknown>
applyMigrations(config)
const lightbox = (config.ipp as Record<string, unknown>).lightbox as Record<string, unknown>
expect(lightbox.showArrows).toBe(true)
expect(lightbox.showDownload).toBe(true)
})
it('does nothing when lightGallery is absent', () => {
const config = { ipp: { lightbox: { showArrows: true } } } as Record<string, unknown>
applyMigrations(config)
expect(logSpy).not.toHaveBeenCalled()
})
})
describe('topLevelGallery shim', () => {
it('moves legacy top-level keys under ipp.gallery.*', () => {
const config = {
ipp: {
singleImageGallery: true,
showGalleryTitle: false,
groupGalleryByDate: true
}
} as Record<string, unknown>
applyMigrations(config)
const gallery = (config.ipp as Record<string, unknown>).gallery as Record<string, unknown>
expect(gallery.singleImage).toBe(true)
expect(gallery.showTitle).toBe(false)
expect(gallery.groupByDate).toBe(true)
expect(logSpy).toHaveBeenCalledOnce()
})
it('keeps the user-set value on the new path when both forms are present', () => {
const config = {
ipp: {
singleImageGallery: false,
gallery: { singleImage: true }
}
} as Record<string, unknown>
applyMigrations(config)
const gallery = (config.ipp as Record<string, unknown>).gallery as Record<string, unknown>
expect(gallery.singleImage).toBe(true)
})
it('does nothing when no legacy keys are present', () => {
const config = {
ipp: { gallery: { singleImage: true } }
} as Record<string, unknown>
applyMigrations(config)
expect(logSpy).not.toHaveBeenCalled()
})
})
describe('descriptionSplit shim', () => {
it('expands boolean true to { caption: true, sidebar: true }', () => {
const config = {
ipp: { showMetadata: { description: true } }
} as Record<string, unknown>
applyMigrations(config)
const description = ((config.ipp as Record<string, unknown>).showMetadata as Record<string, unknown>).description
expect(description).toEqual({ caption: true, sidebar: true })
expect(logSpy).toHaveBeenCalledOnce()
})
it('expands boolean false to { caption: false, sidebar: false }', () => {
const config = {
ipp: { showMetadata: { description: false } }
} as Record<string, unknown>
applyMigrations(config)
const description = ((config.ipp as Record<string, unknown>).showMetadata as Record<string, unknown>).description
expect(description).toEqual({ caption: false, sidebar: false })
})
it('leaves an existing object form alone', () => {
const config = {
ipp: {
showMetadata: {
description: { caption: false, sidebar: true }
}
}
} as Record<string, unknown>
applyMigrations(config)
const description = ((config.ipp as Record<string, unknown>).showMetadata as Record<string, unknown>).description
expect(description).toEqual({ caption: false, sidebar: true })
expect(logSpy).not.toHaveBeenCalled()
})
})
describe('metadataEnabled shim', () => {
it('legacy enabled=true defaults every unset per-field flag to true', () => {
const config = {
ipp: {
showMetadata: {
exif: { enabled: true }
}
}
} as Record<string, unknown>
applyMigrations(config)
const exif = ((config.ipp as Record<string, unknown>).showMetadata as Record<string, unknown>).exif as Record<string, unknown>
expect(exif.enabled).toBeUndefined()
expect(exif.dateTimeOriginal).toBe(true)
expect(exif.timeZone).toBeUndefined()
expect(exif.fileName).toBe(true)
expect(exif.dimensions).toBe(true)
expect(exif.fileSize).toBe(true)
expect(exif.make).toBe(true)
expect(exif.model).toBe(true)
expect(exif.lensModel).toBe(true)
expect(exif.exposureTime).toBe(true)
expect(exif.iso).toBe(true)
expect(exif.fNumber).toBe(true)
expect(exif.focalLength).toBe(true)
expect(logSpy).toHaveBeenCalledOnce()
})
it('legacy enabled=true preserves explicit per-field false ("all except X")', () => {
const config = {
ipp: {
showMetadata: {
location: { enabled: true, gps: false }
}
}
} as Record<string, unknown>
applyMigrations(config)
const location = ((config.ipp as Record<string, unknown>).showMetadata as Record<string, unknown>).location as Record<string, unknown>
expect(location.enabled).toBeUndefined()
expect(location.city).toBe(true)
expect(location.state).toBe(true)
expect(location.country).toBe(true)
expect(location.gps).toBe(false)
})
it('legacy enabled=false clears any per-field flags that were true', () => {
// This is the shipped 2.3.0 default shape: enabled=false + every per-
// field=true as documentation. Under the new semantic those `true`s
// would otherwise become live opt-ins; the shim zeroes them.
const config = {
ipp: {
showMetadata: {
exif: {
enabled: false,
dateTimeOriginal: true,
fileName: true,
make: true,
iso: true
}
}
}
} as Record<string, unknown>
applyMigrations(config)
const exif = ((config.ipp as Record<string, unknown>).showMetadata as Record<string, unknown>).exif as Record<string, unknown>
expect(exif.enabled).toBeUndefined()
expect(exif.dateTimeOriginal).toBe(false)
expect(exif.fileName).toBe(false)
expect(exif.make).toBe(false)
expect(exif.iso).toBe(false)
expect(logSpy).toHaveBeenCalledOnce()
})
it('legacy enabled=false leaves explicit per-field false alone', () => {
const config = {
ipp: {
showMetadata: {
location: { enabled: false, gps: false }
}
}
} as Record<string, unknown>
applyMigrations(config)
const location = ((config.ipp as Record<string, unknown>).showMetadata as Record<string, unknown>).location as Record<string, unknown>
expect(location.gps).toBe(false)
})
it('handles both exif and location groups in one pass', () => {
const config = {
ipp: {
showMetadata: {
exif: { enabled: true },
location: { enabled: false, gps: true }
}
}
} as Record<string, unknown>
applyMigrations(config)
const showMetadata = (config.ipp as Record<string, unknown>).showMetadata as Record<string, unknown>
const exif = showMetadata.exif as Record<string, unknown>
const location = showMetadata.location as Record<string, unknown>
expect(exif.dateTimeOriginal).toBe(true)
expect(location.gps).toBe(false)
// One deprecation log call regardless of how many groups were migrated
expect(logSpy).toHaveBeenCalledOnce()
})
it('does nothing when no legacy enabled key is present', () => {
const config = {
ipp: {
showMetadata: {
exif: { dateTimeOriginal: true }
}
}
} as Record<string, unknown>
applyMigrations(config)
const exif = ((config.ipp as Record<string, unknown>).showMetadata as Record<string, unknown>).exif as Record<string, unknown>
expect(exif.dateTimeOriginal).toBe(true)
expect(logSpy).not.toHaveBeenCalled()
})
it('does nothing when showMetadata is absent', () => {
const config = { ipp: {} } as Record<string, unknown>
applyMigrations(config)
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()
})
})