Change default download filenames to anonymised hash
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
import { Asset, AssetType, getConfigOption, getNumericConfigOption, renderPage, SharedLink, title, toString } from '@ipp/core'
|
||||
import { AssetType, getConfigOption, getNumericConfigOption, renderPage, SharedLink, title, toString } from '@ipp/core'
|
||||
import {
|
||||
getVideoContentType,
|
||||
photoUrl,
|
||||
@@ -9,8 +9,8 @@ import { ImageSize } from '../types'
|
||||
import { canDownload, expiryDate, uploadHealthcheck, uploadLink } from '../share'
|
||||
import { h } from 'preact'
|
||||
import { Gallery, GalleryItem, GalleryProps } from '../view/gallery'
|
||||
import type { GroupByDateMode } from '../shared/types'
|
||||
import { downloadFilename } from './filename'
|
||||
import { downloadFilename, positionInShare } from './filename'
|
||||
import { groupByDateMode } from './order'
|
||||
import { requiresOriginal } from './sizing'
|
||||
import { displayDimensions, metadataGroupActive, pickExif } from './exif'
|
||||
|
||||
@@ -26,14 +26,9 @@ export async function gallery (res: Response, share: SharedLink, openItem?: numb
|
||||
// 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; follow the album's own sort
|
||||
// direction, defaulting to newest-first when it has none (individual shares).
|
||||
// Sort by the same local timestamp the grouping buckets on, so buckets stay
|
||||
// contiguous / ordered.
|
||||
// `share.assets` is already in display order, date grouping included
|
||||
// (see gallery/order.ts), so no sort happens here.
|
||||
const groupByDate = groupByDateMode()
|
||||
if (groupByDate) {
|
||||
share.assets.sort(dateSortComparator(share.album?.order))
|
||||
}
|
||||
|
||||
// Metadata display flags. Read once here and forwarded to the client via
|
||||
// `metadataConfig` in the init JSON.
|
||||
@@ -51,7 +46,7 @@ export async function gallery (res: Response, share: SharedLink, openItem?: numb
|
||||
const descriptionInSidebar = shareMetadataAllowed && !!getConfigOption('ipp.showMetadata.description.sidebar', false)
|
||||
const sidebarHasContent = shareMetadataAllowed && (descriptionInSidebar || metadataGroupActive('exif') || metadataGroupActive('location'))
|
||||
|
||||
const items: GalleryItem[] = await Promise.all(share.assets.map(async (asset): Promise<GalleryItem> => {
|
||||
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) }
|
||||
@@ -100,7 +95,7 @@ export async function gallery (res: Response, share: SharedLink, openItem?: numb
|
||||
videoData,
|
||||
motionUrl,
|
||||
description: itemDescription || undefined,
|
||||
downloadFilename: downloadFilename(asset),
|
||||
downloadFilename: downloadFilename(asset, positionInShare(share, index)),
|
||||
width,
|
||||
height,
|
||||
thumbhash: asset.thumbhash,
|
||||
@@ -175,32 +170,3 @@ export async function gallery (res: Response, share: SharedLink, openItem?: numb
|
||||
function description (share: SharedLink) {
|
||||
return share?.album?.description || ''
|
||||
}
|
||||
|
||||
/**
|
||||
* Comparator for the date-grouping sort: ascending when the album's order is
|
||||
* `'asc'`, otherwise newest-first (individual shares and orderless albums).
|
||||
* Undated assets always sort last regardless of direction, so the client's
|
||||
* "Undated" group renders at the bottom.
|
||||
*/
|
||||
export function dateSortComparator (order?: string): (a: Asset, b: Asset) => number {
|
||||
const ascending = order === 'asc'
|
||||
const sortKey = (a: Asset) => a.localDateTime || a.fileCreatedAt || ''
|
||||
return (a, b) => {
|
||||
const ka = sortKey(a)
|
||||
const kb = sortKey(b)
|
||||
if (!ka || !kb) return ka ? -1 : kb ? 1 : 0 // undated always last
|
||||
return ascending ? ka.localeCompare(kb) : kb.localeCompare(ka)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalise the operator's `ipp.gallery.groupByDate` config into a grouping
|
||||
* mode. Accepts `false` (off), `true` / `'month'` (legacy = month buckets) or
|
||||
* `'day'` (day buckets); anything else is treated as off.
|
||||
*/
|
||||
function groupByDateMode (): GroupByDateMode | false {
|
||||
const v = getConfigOption('ipp.gallery.groupByDate', false)
|
||||
if (v === 'day') return 'day'
|
||||
if (v === true || v === 'month') return 'month'
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -1,7 +1,58 @@
|
||||
import { Asset, getConfigOption, sanitize } from '@ipp/core'
|
||||
import { Asset, getConfigOption, sanitize, SharedLink } from '@ipp/core'
|
||||
import { createHash } from 'crypto'
|
||||
import { ImageSize } from '../types'
|
||||
import { resolveImageEndpoint } from './sizing'
|
||||
|
||||
/**
|
||||
* Where an asset sits in its share, for the position-based download names of
|
||||
* `downloadedFilename: 2`. Built with `positionInShare` / `findPositionInShare`.
|
||||
*/
|
||||
export interface AssetPosition {
|
||||
/** The share's key. Only its hash reaches a filename, never the key itself. */
|
||||
shareKey: string
|
||||
/** 1-based index of the asset in the share's display order */
|
||||
position: number
|
||||
/** Number of assets in the share, which sets the zero-padding width */
|
||||
count: number
|
||||
}
|
||||
|
||||
/**
|
||||
* The position of the asset at `index` in `share.assets`, which is already in
|
||||
* display order (see gallery/order.ts).
|
||||
*/
|
||||
export function positionInShare (share: SharedLink, index: number): AssetPosition {
|
||||
return { shareKey: share.key, position: index + 1, count: share.assets.length }
|
||||
}
|
||||
|
||||
/**
|
||||
* Look up an asset's position in its share by id. A motion photo's clip takes
|
||||
* the position of the still it belongs to. Undefined when the id is not in
|
||||
* the share, which `getFilename` treats as "no position".
|
||||
*/
|
||||
export function findPositionInShare (share: SharedLink, assetId: string): AssetPosition | undefined {
|
||||
const index = share.assets.findIndex(a => a.id === assetId || a.livePhotoVideoId === assetId)
|
||||
return index === -1 ? undefined : positionInShare(share, index)
|
||||
}
|
||||
|
||||
/** `ipp.downloadedFilename` when the operator's config omits it: share hash plus position */
|
||||
const DEFAULT_FILENAME_MODE = 2
|
||||
|
||||
/** Shortest zero-padding for a position: the digits in the asset count, minimum 3 */
|
||||
const MIN_POSITION_DIGITS = 3
|
||||
|
||||
/**
|
||||
* Filename stem for `downloadedFilename: 2`: the first 8 hex characters of
|
||||
* SHA-256 of the share key, an underscore, then the zero-padded position,
|
||||
* e.g. `a3f9c2e1_001`. Hashing the key keeps the share's secret out of the
|
||||
* name; it is the key, not the slug, so a share reached either way gets the
|
||||
* same names.
|
||||
*/
|
||||
export function positionStem ({ shareKey, position, count }: AssetPosition): string {
|
||||
const prefix = createHash('sha256').update(shareKey).digest('hex').slice(0, 8)
|
||||
const digits = Math.max(MIN_POSITION_DIGITS, String(count).length)
|
||||
return prefix + '_' + String(position).padStart(digits, '0')
|
||||
}
|
||||
|
||||
/**
|
||||
* Map a MIME type to a file extension (including the dot), case-insensitively.
|
||||
* Returns '' for unknown types; obscure RAW types fall through to '' so
|
||||
@@ -59,8 +110,10 @@ function withMimeExtension (filename: string, mime: string | undefined): string
|
||||
* 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.
|
||||
* @param [position] - the asset's place in its share, which `downloadedFilename: 2`
|
||||
* names by. Without it that mode falls back to the asset ID.
|
||||
*/
|
||||
export function getFilename (asset: Asset, servedSize: ImageSize = ImageSize.original, servedMimeOverride?: string): string {
|
||||
export function getFilename (asset: Asset, servedSize: ImageSize = ImageSize.original, servedMimeOverride?: string, position?: AssetPosition): string {
|
||||
const override = mimeToExt(servedMimeOverride) ? servedMimeOverride : undefined
|
||||
let servedMime: string | undefined
|
||||
if (override) {
|
||||
@@ -73,13 +126,14 @@ export function getFilename (asset: Asset, servedSize: ImageSize = ImageSize.ori
|
||||
servedMime = 'image/jpeg'
|
||||
}
|
||||
|
||||
switch (getConfigOption('ipp.downloadedFilename')) {
|
||||
switch (getConfigOption('ipp.downloadedFilename', DEFAULT_FILENAME_MODE)) {
|
||||
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)
|
||||
// Anonymous and deterministic: share-hash prefix plus album position,
|
||||
// so a re-download of the same share overwrites the first copy.
|
||||
return withMimeExtension(position ? positionStem(position) : asset.id, servedMime)
|
||||
default: {
|
||||
// By default, use the asset's original filename
|
||||
const cleanName = asset.originalFileName ? sanitize(asset.originalFileName) : ''
|
||||
@@ -98,8 +152,8 @@ export function getFilename (asset: Asset, servedSize: ImageSize = ImageSize.ori
|
||||
* 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)
|
||||
export function downloadFilename (asset: Asset, position?: AssetPosition): string {
|
||||
return getFilename(asset, resolveImageEndpoint(ImageSize.original, asset).servedSize, undefined, position)
|
||||
}
|
||||
|
||||
/** Download Content-Disposition, RFC 5987-encoded so `,` and `;` can't split the header. */
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Asset, getConfigOption, SharedLink } from '@ipp/core'
|
||||
import { AssetMetadata } from '../shared/types'
|
||||
import { pickExif } from './exif'
|
||||
import { downloadFilename } from './filename'
|
||||
import { downloadFilename, findPositionInShare } from './filename'
|
||||
|
||||
/**
|
||||
* Build the on-demand metadata payload for a single asset, served by the
|
||||
@@ -27,6 +27,6 @@ export function buildAssetMetadata (asset: Asset, share: SharedLink): AssetMetad
|
||||
return {
|
||||
exif: shareMetadataAllowed ? pickExif(asset) : undefined,
|
||||
description,
|
||||
downloadFilename: downloadFilename(asset)
|
||||
downloadFilename: downloadFilename(asset, findPositionInShare(share, asset.id))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import { Asset, getConfigOption } from '@ipp/core'
|
||||
import type { GroupByDateMode } from '../shared/types'
|
||||
|
||||
/**
|
||||
* Put a share's assets in the order the gallery renders them. Applied once,
|
||||
* when the share is loaded, so the gallery, the zip download and the single
|
||||
* download all see the same order and an asset's position is its index.
|
||||
*
|
||||
* An album with a sort order is sorted by capture time in that direction.
|
||||
* Date grouping then sorts by the local timestamp the client buckets on, so
|
||||
* buckets stay contiguous (`dateSortComparator`).
|
||||
*
|
||||
* Sorts in place and returns the same array.
|
||||
*/
|
||||
export function displayOrder (assets: Asset[], albumOrder?: string): Asset[] {
|
||||
if (albumOrder === 'asc') {
|
||||
assets.sort((a, b) => a?.fileCreatedAt?.localeCompare(b.fileCreatedAt || '') || 0)
|
||||
} else if (albumOrder === 'desc') {
|
||||
assets.sort((a, b) => b?.fileCreatedAt?.localeCompare(a.fileCreatedAt || '') || 0)
|
||||
}
|
||||
if (groupByDateMode()) {
|
||||
assets.sort(dateSortComparator(albumOrder))
|
||||
}
|
||||
return assets
|
||||
}
|
||||
|
||||
/**
|
||||
* Comparator for the date-grouping sort: ascending when the album's order is
|
||||
* `'asc'`, otherwise newest-first (individual shares and orderless albums).
|
||||
* Undated assets always sort last regardless of direction, so the client's
|
||||
* "Undated" group renders at the bottom.
|
||||
*/
|
||||
export function dateSortComparator (order?: string): (a: Asset, b: Asset) => number {
|
||||
const ascending = order === 'asc'
|
||||
const sortKey = (a: Asset) => a.localDateTime || a.fileCreatedAt || ''
|
||||
return (a, b) => {
|
||||
const ka = sortKey(a)
|
||||
const kb = sortKey(b)
|
||||
if (!ka || !kb) return ka ? -1 : kb ? 1 : 0 // undated always last
|
||||
return ascending ? ka.localeCompare(kb) : kb.localeCompare(ka)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalise the operator's `ipp.gallery.groupByDate` config into a grouping
|
||||
* mode. Accepts `false` (off), `true` / `'month'` (legacy = month buckets) or
|
||||
* `'day'` (day buckets); anything else is treated as off.
|
||||
*/
|
||||
export function groupByDateMode (): GroupByDateMode | false {
|
||||
const v = getConfigOption('ipp.gallery.groupByDate', false)
|
||||
if (v === 'day') return 'day'
|
||||
if (v === true || v === 'month') return 'month'
|
||||
return false
|
||||
}
|
||||
+5
-10
@@ -24,6 +24,7 @@ import {
|
||||
} from '@ipp/core'
|
||||
import { ImageSize, IncomingShareRequest, TimelineBucket, TimelineBucketAssets } from './types'
|
||||
import { canDownload, servableAssets } from './share'
|
||||
import { displayOrder } from './gallery/order'
|
||||
import { assetBuffer } from './stream/asset'
|
||||
import { downloadAll } from './stream/download'
|
||||
import { gallery } from './gallery/builder'
|
||||
@@ -43,9 +44,8 @@ import { h } from 'preact'
|
||||
CAUTION: a cache hit returns the SAME SharedLinkResult reference across
|
||||
requests. Callers MUST treat the result (and its `link.assets`) as
|
||||
read-only. In-place mutation persists for the cache lifetime and leaks
|
||||
across concurrent requests. Current callers (notably the in-place
|
||||
`share.assets.sort(...)` in render.ts) happen to be idempotent so this is
|
||||
safe today, but new callers should clone before mutating.
|
||||
across concurrent requests. The assets are sorted into display order here,
|
||||
before caching, so no caller needs to sort them; clone before mutating.
|
||||
*/
|
||||
const shareCache = new TtlLruCache<Promise<SharedLinkResult>>({ ttlMs: 120_000, max: 100 })
|
||||
|
||||
@@ -212,13 +212,8 @@ async function fetchShareByKey (key: string, password?: string, keyType: KeyType
|
||||
asset.keyType = keyType
|
||||
asset.password = password
|
||||
})
|
||||
// Sort album if there is a sort order specified
|
||||
const sortOrder = link.album?.order
|
||||
if (sortOrder === 'asc') {
|
||||
link.assets.sort((a, b) => a?.fileCreatedAt?.localeCompare(b.fileCreatedAt || '') || 0)
|
||||
} else if (sortOrder === 'desc') {
|
||||
link.assets.sort((a, b) => b?.fileCreatedAt?.localeCompare(a.fileCreatedAt || '') || 0)
|
||||
}
|
||||
// The order the gallery shows, which download filenames also number by
|
||||
displayOrder(link.assets, link.album?.order)
|
||||
return result
|
||||
}
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
} from '../immich'
|
||||
import { Response } from 'express-serve-static-core'
|
||||
import { ImageSize, IncomingShareRequest } from '../types'
|
||||
import { attachmentDisposition, enrichFromHeaders, getFilename, servedMimeFrom } from '../gallery/filename'
|
||||
import { attachmentDisposition, enrichFromHeaders, findPositionInShare, getFilename, servedMimeFrom } from '../gallery/filename'
|
||||
import { isVideoAsset, resolveDownloadEndpoint, resolveImageEndpoint } from '../gallery/sizing'
|
||||
import { pipeline } from 'stream/promises'
|
||||
|
||||
@@ -95,7 +95,8 @@ export async function assetBuffer (req: IncomingShareRequest, res: Response, ass
|
||||
// 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))))
|
||||
const position = share && findPositionInShare(share, asset.id)
|
||||
res.setHeader('Content-Disposition', attachmentDisposition(getFilename(named, servedSize, servedMimeFrom(subpath, data), position)))
|
||||
}
|
||||
headerList.forEach(header => {
|
||||
const value = data.headers.get(header)
|
||||
|
||||
@@ -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, enrichFromHeaders, getFilename, servedMimeFrom } from '../gallery/filename'
|
||||
import { AssetPosition, attachmentDisposition, enrichFromHeaders, findPositionInShare, getFilename, servedMimeFrom } from '../gallery/filename'
|
||||
|
||||
/** Attempts to get response headers from Immich for one asset before giving up. */
|
||||
const MAX_ATTEMPTS = 3
|
||||
@@ -17,7 +17,7 @@ export async function downloadAll (res: Response, share: SharedLink) {
|
||||
await downloadAssets(res, share, share.assets)
|
||||
}
|
||||
|
||||
type FetchedAsset = { response: globalThis.Response, asset: Asset, endpoint: ImageEndpoint, servedMime?: string, url: string }
|
||||
type FetchedAsset = { response: globalThis.Response, asset: Asset, endpoint: ImageEndpoint, servedMime?: string, url: string, position?: AssetPosition }
|
||||
type Failure = { asset: Asset, url: string, status?: number, error?: unknown }
|
||||
type FetchOutcome = FetchedAsset | { failure: Failure } | null
|
||||
|
||||
@@ -161,7 +161,7 @@ function appendEntry (archive: Archiver, fetched: FetchedAsset): Promise<'done'
|
||||
archive.once('entry', onEntry)
|
||||
archive.once('error', onError)
|
||||
body.once('error', onError)
|
||||
archive.append(body, { name: getFilename(fetched.asset, fetched.endpoint.servedSize, fetched.servedMime) })
|
||||
archive.append(body, { name: getFilename(fetched.asset, fetched.endpoint.servedSize, fetched.servedMime, fetched.position) })
|
||||
})
|
||||
}
|
||||
|
||||
@@ -213,7 +213,9 @@ async function fetchOne (share: SharedLink, asset: Asset, signal: AbortSignal):
|
||||
// so recover them from the headers we already fetched - no extra calls.
|
||||
const namedAsset = asset.originalFileName ? asset : enrichFromHeaders(asset, fetched.response)
|
||||
|
||||
return { response: fetched.response, asset: namedAsset, endpoint, servedMime: servedMimeFrom(endpoint.subpath, fetched.response), url }
|
||||
// A multi-select download keeps each asset's position in the whole share
|
||||
const position = findPositionInShare(share, asset.id)
|
||||
return { response: fetched.response, asset: namedAsset, endpoint, servedMime: servedMimeFrom(endpoint.subpath, fetched.response), url, position }
|
||||
}
|
||||
|
||||
type HeaderFetchOutcome =
|
||||
|
||||
Reference in New Issue
Block a user