Change default download filenames to anonymised hash

This commit is contained in:
Alan Grainger
2026-10-08 10:31:35 +13:00
parent e7836b85f7
commit 5cddddd9f7
16 changed files with 328 additions and 83 deletions
+1 -1
View File
@@ -7,7 +7,7 @@
"maxDownloadQuality": "original",
"maxZoomQuality": "preview",
"motionPhotos": true,
"downloadedFilename": 0,
"downloadedFilename": 2,
"allowDownload": 0,
"uploadUrl": "/upload",
"allowSlugLinks": true,
+7 -41
View File
@@ -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
}
+61 -7
View File
@@ -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. */
+2 -2
View File
@@ -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))
}
}
+54
View File
@@ -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
View File
@@ -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
}
+3 -2
View File
@@ -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)
+6 -4
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, 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 =
+1 -1
View File
@@ -112,7 +112,7 @@ describe('buildAssetMetadata', () => {
})
it('always returns a download filename', () => {
setConfig({})
setConfig({ ipp: { downloadedFilename: 0 } })
const meta = buildAssetMetadata(asset(), share())
// HEIC original served as preview JPEG when downloadOriginalPhoto defaults on
expect(meta.downloadFilename).toMatch(/IMG_1234/)
+1
View File
@@ -224,6 +224,7 @@ describe('assetBuffer streaming', () => {
}
it('sends an attachment named from Immich\'s header, with nosniff', async () => {
setConfig({ ipp: { downloadedFilename: 0 } })
vi.stubGlobal('fetch', svgFetch({ 'content-disposition': 'attachment; filename="drawing.svg"' }))
const res = new FakeRes()
await assetBuffer(makeRequest(), asResponse(res), albumAsset, ImageSize.original)
+44 -4
View File
@@ -1,12 +1,18 @@
import { describe, it, expect } from 'vitest'
import { Asset, AssetType, KeyType } from '@ipp/core'
import { dateSortComparator } from '../src/gallery/builder'
import { describe, it, expect, afterEach } from 'vitest'
import { Asset, AssetType, KeyType, loadConfig } from '@ipp/core'
import { dateSortComparator, displayOrder } from '../src/gallery/order'
/*
The date-grouping sort must follow the album's own order while
keeping undated assets last in BOTH directions.
keeping undated assets last in BOTH directions. displayOrder applies it,
after the album's own sort, when `gallery.groupByDate` is on.
*/
afterEach(() => {
delete process.env.CONFIG
loadConfig()
})
const asset = (localDateTime?: string): Asset => ({
id: localDateTime || 'undated',
key: 'k',
@@ -57,3 +63,37 @@ describe('dateSortComparator', () => {
expect(sorted[1]).toBe(a)
})
})
describe('displayOrder', () => {
const dated = (id: string, fileCreatedAt: string, localDateTime?: string): Asset =>
({ ...asset(localDateTime), id, fileCreatedAt })
// Capture order c, a, b; local time disagrees for b (shot late at night)
const album = () => [
dated('a', '2024-02-01T10:00:00.000Z'),
dated('b', '2024-03-01T01:00:00.000Z', '2024-01-31T23:00:00.000Z'),
dated('c', '2024-01-01T10:00:00.000Z')
]
const ids = (assets: Asset[]) => assets.map(a => a.id)
it('leaves an orderless share as Immich returned it', () => {
expect(ids(displayOrder(album()))).toEqual(['a', 'b', 'c'])
})
it('sorts an album by capture time in its own direction', () => {
expect(ids(displayOrder(album(), 'asc'))).toEqual(['c', 'a', 'b'])
expect(ids(displayOrder(album(), 'desc'))).toEqual(['b', 'a', 'c'])
})
it('sorts by local time when date grouping is on, so buckets stay contiguous', () => {
process.env.CONFIG = JSON.stringify({ ipp: { gallery: { groupByDate: 'day' } } })
loadConfig()
expect(ids(displayOrder(album(), 'asc'))).toEqual(['c', 'b', 'a'])
// Newest-first without an album order
expect(ids(displayOrder(album()))).toEqual(['a', 'b', 'c'])
})
it('sorts in place and returns the same array', () => {
const assets = album()
expect(displayOrder(assets, 'asc')).toBe(assets)
})
})
+17 -1
View File
@@ -1,5 +1,6 @@
import { describe, it, expect, vi, afterEach } from 'vitest'
import { Asset, AssetType, KeyType, loadConfig, SharedLink } from '@ipp/core'
import { createHash } from 'crypto'
import { Writable } from 'stream'
import { once } from 'events'
import type { Response } from 'express-serve-static-core'
@@ -164,6 +165,7 @@ function countOf (zip: Buffer, signature: string): number {
describe('downloadAssets', () => {
it('streams a valid zip with one entry per asset', async () => {
setConfig({ ipp: { downloadedFilename: 0 } })
vi.stubGlobal('fetch', instantFetch(2048))
const res = new FakeRes()
await downloadAssets(asResponse(res), share, [makeAsset('a1'), makeAsset('a2')])
@@ -286,8 +288,22 @@ describe('downloadAssets', () => {
expect(signals.every(s => s.aborted)).toBe(true)
}, 10_000)
it('numbers multi-select entries by their position in the whole share (downloadedFilename: 2)', async () => {
setConfig({ ipp: { downloadedFilename: 2 } })
vi.stubGlobal('fetch', instantFetch(2048))
const album: SharedLink = { ...share, assets: ['a1', 'a2', 'a3', 'a4', 'a5'].map(makeAsset) }
const prefix = createHash('sha256').update(album.key).digest('hex').slice(0, 8)
const res = new FakeRes()
// Selected out of order: entries follow the request order, names the album order
await downloadAssets(asResponse(res), album, [album.assets[3], album.assets[1]])
expect(centralDirectory(res.output)).toEqual([
{ name: `${prefix}_004.jpg`, size: 2048 },
{ name: `${prefix}_002.jpg`, size: 2048 }
])
})
it('names a WebP preview zip entry .webp', async () => {
setConfig({ ipp: { maxDownloadQuality: 'preview' } })
setConfig({ ipp: { maxDownloadQuality: 'preview', downloadedFilename: 0 } })
const fetchMock = vi.fn(async () => new globalThis.Response(new Uint8Array(2048), {
status: 200,
headers: { 'content-type': 'image/webp' }
+96 -6
View File
@@ -1,19 +1,25 @@
import { describe, it, expect, vi } from 'vitest'
import { describe, it, expect, vi, afterEach } from 'vitest'
import { AssetType, KeyType } from '@ipp/core'
import type { Asset } from '@ipp/core'
import type { Asset, SharedLink } from '@ipp/core'
import { createHash } from 'crypto'
import { ImageSize } from '../src/types'
import { getFilename } from '../src/gallery/filename'
import { findPositionInShare, getFilename, positionInShare, positionStem } from '../src/gallery/filename'
/*
getFilename reads `ipp.downloadedFilename` via getConfigOption; mock it in
@ipp/core so tests exercise the default (original filename) mode
without loading a real config file.
@ipp/core so tests pick the naming mode directly, without loading a real
config file. Tests start in mode 0 (original filename); the position-name
tests switch to 2.
*/
const mocked = vi.hoisted(() => ({ downloadedFilename: 0 as unknown }))
vi.mock('@ipp/core', async (importOriginal) => ({
...await importOriginal<typeof import('@ipp/core')>(),
getConfigOption: (_path: string, fallback?: unknown) => fallback
getConfigOption: (path: string, fallback?: unknown) =>
path === 'ipp.downloadedFilename' ? mocked.downloadedFilename ?? fallback : fallback
}))
afterEach(() => { mocked.downloadedFilename = 0 })
function videoAsset (originalFileName: string, originalMimeType = 'video/x-msvideo'): Asset {
return {
id: 'asset-id',
@@ -75,3 +81,87 @@ describe('getFilename WebP previews', () => {
expect(getFilename(imageAsset('holiday.heic'), ImageSize.preview)).toBe('holiday.jpg')
})
})
/** A share of `count` images whose ids are `asset-1` .. `asset-N`. */
function shareOf (count: number, key = 'sharekey', keyType = KeyType.key): SharedLink {
const assets: Asset[] = Array.from({ length: count }, (_, i) => ({ ...imageAsset(`IMG_${i + 1}.heic`), id: `asset-${i + 1}` }))
return { key, keyType, slug: keyType === KeyType.slug ? 'my-album' : null, type: 'ALBUM', assets, expiresAt: null }
}
const HASH_OF_SHAREKEY = createHash('sha256').update('sharekey').digest('hex').slice(0, 8)
describe('getFilename position names (downloadedFilename: 2)', () => {
it('names by share hash and position, with the served extension', () => {
mocked.downloadedFilename = 2
const share = shareOf(5)
expect(getFilename(share.assets[0], ImageSize.original, undefined, positionInShare(share, 0))).toBe(`${HASH_OF_SHAREKEY}_001.heic`)
expect(getFilename(share.assets[4], ImageSize.original, undefined, positionInShare(share, 4))).toBe(`${HASH_OF_SHAREKEY}_005.heic`)
})
it('never puts the share key itself in the name', () => {
expect(HASH_OF_SHAREKEY).toMatch(/^[0-9a-f]{8}$/)
expect(positionStem(positionInShare(shareOf(1), 0))).not.toContain('sharekey')
})
it('pads to the digits of the asset count, minimum three', () => {
const stem = (count: number, index: number) => positionStem(positionInShare(shareOf(count), index)).split('_')[1]
expect(stem(1, 0)).toBe('001')
expect(stem(9, 8)).toBe('009')
expect(stem(10, 9)).toBe('010')
expect(stem(999, 998)).toBe('999')
expect(stem(1000, 0)).toBe('0001')
expect(stem(1000, 999)).toBe('1000')
})
it('gives the same prefix whether the share was opened by key or by slug', () => {
const byKey = positionStem(positionInShare(shareOf(3, 'sharekey', KeyType.key), 1))
const bySlug = positionStem(positionInShare(shareOf(3, 'sharekey', KeyType.slug), 1))
expect(bySlug).toBe(byKey)
expect(positionStem(positionInShare(shareOf(3, 'otherkey'), 1))).not.toBe(byKey)
})
it('is deterministic for an unchanged share', () => {
const a = positionStem(positionInShare(shareOf(20), 7))
const b = positionStem(positionInShare(shareOf(20), 7))
expect(a).toBe(b)
})
it('finds an asset by id, and a motion photo clip by its still', () => {
const share = shareOf(4)
share.assets[2].livePhotoVideoId = 'clip-id'
expect(findPositionInShare(share, 'asset-2')).toEqual({ shareKey: 'sharekey', position: 2, count: 4 })
expect(findPositionInShare(share, 'clip-id')).toEqual({ shareKey: 'sharekey', position: 3, count: 4 })
expect(findPositionInShare(share, 'not-shared')).toBeUndefined()
})
it('falls back to the asset id when there is no position', () => {
mocked.downloadedFilename = 2
expect(getFilename(imageAsset('holiday.heic', 'image/jpeg'))).toBe('asset-id.jpg')
})
it('is the mode used when the config omits downloadedFilename', () => {
mocked.downloadedFilename = undefined
const share = shareOf(1)
expect(getFilename(share.assets[0], ImageSize.original, undefined, positionInShare(share, 0))).toBe(`${HASH_OF_SHAREKEY}_001.heic`)
})
it('follows the served bytes for the extension, as the other modes do', () => {
mocked.downloadedFilename = 2
const share = shareOf(2)
const position = positionInShare(share, 1)
expect(getFilename(share.assets[1], ImageSize.preview, undefined, position)).toBe(`${HASH_OF_SHAREKEY}_002.jpg`)
expect(getFilename(share.assets[1], ImageSize.preview, 'image/webp', position)).toBe(`${HASH_OF_SHAREKEY}_002.webp`)
expect(getFilename(share.assets[1], ImageSize.thumbnail, undefined, position)).toBe(`${HASH_OF_SHAREKEY}_002.webp`)
expect(getFilename(videoAsset('clip.avi'), ImageSize.original, 'video/mp4', position)).toBe(`${HASH_OF_SHAREKEY}_002.mp4`)
expect(getFilename(videoAsset('clip.avi'), ImageSize.original, undefined, position)).toBe(`${HASH_OF_SHAREKEY}_002.avi`)
})
it('leaves modes 0 and 1 unchanged', () => {
const share = shareOf(2)
const position = positionInShare(share, 0)
mocked.downloadedFilename = 0
expect(getFilename(share.assets[0], ImageSize.original, undefined, position)).toBe('IMG_1.heic')
mocked.downloadedFilename = 1
expect(getFilename(share.assets[0], ImageSize.original, undefined, position)).toBe('asset-1.heic')
})
})