Refactor to TypeScript ES modules and add metadata sidebar

This commit is contained in:
Alan Grainger
2026-06-04 07:40:52 +12:00
parent d86c8721cc
commit e43b57d644
49 changed files with 5909 additions and 2409 deletions
+150
View File
@@ -0,0 +1,150 @@
import {
getPreviewImageSize,
getVideoContentType,
photoUrl,
requiresOriginal,
videoUrl
} from '../immich'
import { Response } from 'express-serve-static-core'
import { AssetType, ImageSize, SharedLink } from '../types'
import { getConfigOption } from '../config/access'
import { canDownload, title } from '../share'
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 { pickExif } from './exif'
/**
* Render a gallery page for a given SharedLink.
*
* @param res - ExpressJS Response
* @param share - Immich `shared-link` containing the assets to show in the gallery
* @param [openItem] - Immediately open the lightbox to the Nth item when the gallery loads
*/
export async function gallery (res: Response, share: SharedLink, openItem?: number) {
// publicBaseUrl is used for the og:image, which requires a fully qualified URL.
// You can specify this in your docker-compose file via the PUBLIC_BASE_URL env var.
const publicBaseUrl = process.env.PUBLIC_BASE_URL || (res.req.protocol + '://' + res.req.headers.host)
// Date grouping needs chronological order; sort newest-first when enabled
// (overrides any album.order the upstream applied).
const groupByDate = !!getConfigOption('ipp.gallery.groupByDate', false)
if (groupByDate) {
share.assets.sort((a, b) => (b.fileCreatedAt || '').localeCompare(a.fileCreatedAt || ''))
}
// Metadata display flags. Read once here and forwarded to the client via
// `metadataConfig` in the init JSON.
const descriptionInCaption = !!getConfigOption('ipp.showMetadata.description.caption', false)
const descriptionInSidebar = !!getConfigOption('ipp.showMetadata.description.sidebar', false)
const exifGroupEnabled = !!getConfigOption('ipp.showMetadata.exif.enabled', false)
const locationGroupEnabled = !!getConfigOption('ipp.showMetadata.location.enabled', false)
const sidebarHasContent = descriptionInSidebar || exifGroupEnabled || locationGroupEnabled
// Build structured items in parallel
const items: GalleryItem[] = await Promise.all(share.assets.map(async (asset): Promise<GalleryItem> => {
let videoData: string | undefined
if (asset.type === AssetType.video) {
videoData = JSON.stringify({
source: [
{
src: videoUrl(share.key, asset.id),
type: await getVideoContentType(asset)
}
],
attributes: {
playsinline: 'playsinline',
controls: 'controls'
}
})
}
// 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))
// 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
const itemDescription = descriptionEnabled && typeof asset?.exifInfo?.description === 'string'
? asset.exifInfo.description
: ''
let width = asset.exifInfo?.exifImageWidth
let height = asset.exifInfo?.exifImageHeight
const orientation = asset.exifInfo?.orientation
if (orientation && ['5', '6', '7', '8'].includes(orientation) && width && height) {
[width, height] = [height, width]
}
return {
id: asset.id,
type: asset.type,
previewUrl,
thumbnailUrl,
downloadUrl,
videoData,
description: itemDescription || undefined,
downloadFilename: getFilename(asset, downloadServedSize),
width,
height,
thumbhash: asset.thumbhash,
fileCreatedAt: asset.fileCreatedAt,
exif: pickExif(asset)
}
}))
const downloadAllowed = canDownload(share)
// Prefer the album's owner-chosen cover for og:image; fall back to first
// item if the cover asset has been filtered out (e.g. trashed).
const coverId = share.album?.albumThumbnailAssetId
const ogImageItem = (coverId && items.find(i => i.id === coverId)) || items[0]
// Guard against an operator setting ipp.lightbox.options to a non-object;
// a string would otherwise spread character-by-character into PhotoSwipe.
const rawLightboxOptions = getConfigOption('ipp.lightbox.options', {})
const lightboxOptions: Record<string, unknown> = (rawLightboxOptions && typeof rawLightboxOptions === 'object' && !Array.isArray(rawLightboxOptions))
? rawLightboxOptions as Record<string, unknown>
: {}
const props: GalleryProps = {
items,
title: title(share),
description: getConfigOption('ipp.gallery.showDescription', false) ? description(share) : '',
publicBaseUrl: toString(publicBaseUrl),
path: '/share/' + share.key,
showDownload: downloadAllowed,
showTitle: !!getConfigOption('ipp.gallery.showTitle', true),
openItem,
ogImageItem,
lightboxConfig: {
// Show download button only if downloading is allowed AND configured.
showDownload: downloadAllowed && !!getConfigOption('ipp.lightbox.showDownload', true),
showArrows: !!getConfigOption('ipp.lightbox.showArrows', true),
mobileArrows: !!getConfigOption('ipp.lightbox.mobileArrows', false),
options: lightboxOptions
},
metadataConfig: {
descriptionInCaption,
descriptionInSidebar,
sidebarHasContent
},
groupByDate
}
res.send(renderPage(h(Gallery, props)))
}
/**
* Get the Immich shared link description (album-level, not per-asset).
*/
function description (share: SharedLink) {
return share?.album?.description || ''
}
+70
View File
@@ -0,0 +1,70 @@
import { Asset } from '../types'
import { GalleryExif } from '../shared/types'
import { getConfigOption } from '../config/access'
/**
* Build the per-asset metadata sub-object included in the gallery JSON.
* Reads `ipp.showMetadata.exif.*` and `ipp.showMetadata.location.*` config:
* each group has a master `enabled` toggle, and within each group the
* per-field flags default to `true`. A field appears in the output only
* when both the group is enabled AND the field's own flag is true.
*
* Returns `undefined` when neither group is enabled, or when no fields
* survive gating (so the client knows there's no metadata to show).
*
* The server never sends Immich values that the operator hasn't opted in
* to via config; the client just renders what's present.
*/
export function pickExif (asset: Asset): GalleryExif | undefined {
const exifInfo = asset?.exifInfo
if (!exifInfo) return undefined
const exifEnabled = !!getConfigOption('ipp.showMetadata.exif.enabled', false)
const locationEnabled = !!getConfigOption('ipp.showMetadata.location.enabled', false)
if (!exifEnabled && !locationEnabled) return undefined
const out: GalleryExif = {}
if (exifEnabled) {
if (allow('exif.dateTimeOriginal') && exifInfo.dateTimeOriginal) {
out.dateTimeOriginal = exifInfo.dateTimeOriginal
}
if (allow('exif.fileName') && asset.originalFileName) {
out.fileName = asset.originalFileName
}
if (allow('exif.dimensions') && exifInfo.exifImageWidth && exifInfo.exifImageHeight) {
out.width = exifInfo.exifImageWidth
out.height = exifInfo.exifImageHeight
}
if (allow('exif.fileSize') && exifInfo.fileSizeInByte) {
out.fileSizeInByte = exifInfo.fileSizeInByte
}
if (allow('exif.make') && exifInfo.make) out.make = exifInfo.make
if (allow('exif.model') && exifInfo.model) out.model = exifInfo.model
if (allow('exif.lensModel') && exifInfo.lensModel) out.lensModel = exifInfo.lensModel
if (allow('exif.exposureTime') && exifInfo.exposureTime) out.exposureTime = exifInfo.exposureTime
if (allow('exif.iso') && exifInfo.iso) out.iso = exifInfo.iso
if (allow('exif.fNumber') && exifInfo.fNumber) out.fNumber = exifInfo.fNumber
if (allow('exif.focalLength') && exifInfo.focalLength) out.focalLength = exifInfo.focalLength
}
if (locationEnabled) {
if (allow('location.city') && exifInfo.city) out.city = exifInfo.city
if (allow('location.state') && exifInfo.state) out.state = exifInfo.state
if (allow('location.country') && exifInfo.country) out.country = exifInfo.country
if (allow('location.gps') && exifInfo.latitude != null && exifInfo.longitude != null) {
out.latitude = exifInfo.latitude
out.longitude = exifInfo.longitude
}
}
return Object.keys(out).length ? out : undefined
}
/**
* Per-field gate. Defaults to `true` so that turning on a group exposes
* every field unless the operator explicitly opts out of one.
*/
function allow (field: string): boolean {
return !!getConfigOption(`ipp.showMetadata.${field}`, true)
}
+91
View File
@@ -0,0 +1,91 @@
import { Asset, ImageSize } from '../types'
import { getConfigOption } from '../config/access'
import { sanitize } from '../utils/sanitize'
/**
* Map an Immich asset MIME type to a file extension (including the dot).
* 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] || ''
}
/**
* 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 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.
*
* @param asset
* @param [servedSize] - what size Immich will actually serve. Defaults to
* ImageSize.original (the bytes match the original asset).
*/
export function getFilename (asset: Asset, servedSize: ImageSize = ImageSize.original): string {
let servedMime: string | undefined
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)
const stem = servedSize === ImageSize.original
? cleanName
: cleanName.replace(/\.[a-zA-Z0-9]{2,5}$/, '')
return withMimeExtension(stem, servedMime)
}
}
}