Files
immich-magic-proxy/app/src/gallery/builder.ts
T

184 lines
8.7 KiB
TypeScript

import { AssetType, getConfigOption, renderPage, SharedLink, title, toString } from '@ipp/core'
import {
getVideoContentType,
photoUrl,
videoUrl
} from '../immich'
import { Response } from 'express-serve-static-core'
import { ImageSize } from '../types'
import { canDownload, expiryDate, uploadHealthcheck, uploadLink } from '../share'
import { h } from 'preact'
import { Gallery, GalleryItem, GalleryProps } from '../view/gallery'
import { downloadFilename, positionInShare } from './filename'
import { groupByDateMode } from './order'
import { requiresOriginal } from './sizing'
import { displayDimensions, metadataGroupActive, pickExif } from './exif'
import { getStore } from '../magic/store'
/**
* 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)
// `share.assets` is already in display order, date grouping included
// (see gallery/order.ts), so no sort happens here.
const groupByDate = groupByDateMode()
// Metadata display flags. Read once here and forwarded to the client via
// `metadataConfig` in the init JSON.
// The share owner's "Show metadata" toggle in Immich is a kill-switch over
// the operator's own config: when explicitly `false`, no EXIF / location /
// description fields are surfaced, regardless of `ipp.showMetadata.*`
const shareMetadataAllowed = share.showMetadata !== false
// Offer a zoom upgrade only when the operator opted in AND Immich would serve
// it: web `fullsize` resolves to `/original`, which Immich refuses unless the
// share's own download toggle (`share.allowDownload`) is on. Deliberately
// independent of IPP's `allowDownload` config.
const zoomUpgrade = getConfigOption('ipp.maxZoomQuality', 'preview') === 'fullsize' && share.allowDownload !== false
const motionPhotos = !!getConfigOption('ipp.motionPhotos', true)
const descriptionInCaption = shareMetadataAllowed && !!getConfigOption('ipp.showMetadata.description.caption', false)
const descriptionInSidebar = shareMetadataAllowed && !!getConfigOption('ipp.showMetadata.description.sidebar', false)
// A recipient given this share can comment, which lives in the sidebar too.
// Anyone else viewing a public share (signed in or not) never sees comments.
const viewer = res.req.recipient
const comments = viewer && res.req.grantedShare?.key === share.key
? { base: '/share/comments/' + share.key, counts: getStore().countComments(share.key) }
: undefined
const sidebarHasContent = !!comments ||
(shareMetadataAllowed && (descriptionInSidebar || metadataGroupActive('exif') || metadataGroupActive('location')))
const items: GalleryItem[] = await Promise.all(share.assets.map(async (asset, index): Promise<GalleryItem> => {
let videoData: string | undefined
if (asset.type === AssetType.video) {
const source: { src: string, type?: string } = { src: videoUrl(share.key, asset.id) }
// Album "grid" videos defer the content-type probe (one upstream call
// per video) - a <source> with no type lets the browser fall back to
// the proxy's response Content-Type, keeping grid render O(buckets).
if (!asset.needsDetail) source.type = await getVideoContentType(asset)
videoData = JSON.stringify({
source: [source],
attributes: {
playsinline: 'playsinline',
controls: 'controls'
}
})
}
const downloadUrl = photoUrl(share.key, asset.id, ImageSize.original)
const thumbnailUrl = photoUrl(share.key, asset.id, ImageSize.thumbnail)
// Always request `preview`; the resolver floors gif/video up to the
// original on its own (their preview is a static frame).
const previewUrl = photoUrl(share.key, asset.id, ImageSize.preview)
// Still images only - gif/video are already served at their highest tier.
const fullUrl = zoomUpgrade && asset.type === AssetType.image && !requiresOriginal(asset)
? photoUrl(share.key, asset.id, ImageSize.fullsize)
: undefined
// Motion photo clip, served through the video route under the same key.
const motionUrl = motionPhotos && asset.type === AssetType.image && asset.livePhotoVideoId
? videoUrl(share.key, asset.livePhotoVideoId)
: undefined
// 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
: ''
const { width, height } = displayDimensions(asset)
return {
id: asset.id,
type: asset.type,
previewUrl,
fullUrl,
thumbnailUrl,
downloadUrl,
videoData,
motionUrl,
description: itemDescription || undefined,
downloadFilename: downloadFilename(asset, positionInShare(share, index)),
width,
height,
thumbhash: asset.thumbhash,
fileCreatedAt: asset.fileCreatedAt,
localDateTime: asset.localDateTime,
exif: shareMetadataAllowed ? pickExif(asset) : undefined,
// Album grid items carry no exif / description / real filename yet; the
// client fetches them from `metaBase` the first time the item opens.
needsDetail: asset.needsDetail || undefined
}
}))
// Album shares contain lazy items; expose the on-demand metadata route so
// the client can fetch per-asset detail on lightbox open. Individual shares
// bake everything in, so no metaBase is needed there.
const metaBase = items.some(item => item.needsDetail) ? '/share/meta/' + share.key : undefined
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,
showDownloadZip: downloadAllowed && !!getConfigOption('ipp.gallery.showDownloadZip', true),
showTitle: !!getConfigOption('ipp.gallery.showTitle', true),
expiryDate: expiryDate(share),
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),
autoPlayVideos: !!getConfigOption('ipp.lightbox.autoPlayVideos', false),
options: lightboxOptions
},
metadataConfig: {
descriptionInCaption,
descriptionInSidebar,
sidebarHasContent,
locationWebLink: !!getConfigOption('ipp.showMetadata.location.webLink', true)
},
groupByDate,
metaBase,
uploadLink: uploadLink(share),
uploadHealthcheck: uploadHealthcheck(),
comments,
accountLink: viewer ? '/me' : undefined
}
// The page is per-viewer (comment counts, account link) and behind a
// session, so it must never sit in a shared cache, and the browser should
// recheck it so new photos and comments show up. A password-protected
// gallery keeps the no-store that handleShareRequest set.
if (!share.password) {
res.header('Cache-Control', 'private, no-cache')
}
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 || ''
}