#302 add name field for uploads

This commit is contained in:
Alan Grainger
2026-10-19 15:43:29 +13:00
parent b1e053426f
commit a620d0b3ae
19 changed files with 257 additions and 24 deletions
+22
View File
@@ -29,6 +29,7 @@ const MAX_RETRY_WAIT_MS = 60_000
const config = JSON.parse(document.getElementById('upload-init')?.textContent || '{}') as UploadPageConfig
const run = createLimiter(CONCURRENT_UPLOADS)
const nameEl = document.getElementById('upload-name') as HTMLInputElement | null
const panelEl = document.getElementById('upload-panel') as HTMLElement
const progressEl = document.getElementById('upload-progress') as HTMLElement
const countsEl = document.getElementById('upload-counts') as HTMLElement
@@ -217,6 +218,9 @@ function attempt (row: UploadRow, attemptNumber: number): Promise<Attempt> {
return new Promise(resolve => {
const timestamp = new Date(row.file.lastModified || Date.now()).toISOString()
const query = new URLSearchParams({ filename: row.file.name, fileCreatedAt: timestamp, fileModifiedAt: timestamp })
// Read when the file is sent, so a name typed after choosing the files still counts
const uploader = nameEl?.value.trim()
if (uploader) query.set('uploader', uploader)
const xhr = new XMLHttpRequest()
row.xhr = xhr
const started = Date.now()
@@ -361,6 +365,24 @@ function setupDragAndDrop () {
})
}
/*
Remember the visitor's name across shares. One origin serves every share on
an install, so the name typed for one gallery is offered for the next. The
storage may be unavailable, as in a private window, and the field then works
for this visit only.
*/
const NAME_KEY = 'ipp-uploader-name'
if (nameEl) {
try {
nameEl.value = localStorage.getItem(NAME_KEY) || ''
} catch { }
nameEl.addEventListener('change', () => {
try {
localStorage.setItem(NAME_KEY, nameEl.value.trim())
} catch { }
})
}
const input = document.getElementById('upload-input') as HTMLInputElement
document.getElementById('upload-choose')?.addEventListener('click', () => input.click())
input.addEventListener('change', () => {
+5
View File
@@ -32,6 +32,11 @@ export function filenamePrefix (): string {
return typeof configured === 'string' ? configured : ''
}
/** Whether the upload page asks the visitor's name, from `ipp.upload.askName`. */
export function askName (): boolean {
return getConfigOption('ipp.upload.askName', true) !== false
}
/** Text shown under the placeholder on the upload page, from `ipp.upload.notice`. Empty hides it. */
export function uploadNotice (): string {
const configured = getConfigOption('ipp.upload.notice', 'Uploaded photos may not appear in the gallery immediately.')
+45 -7
View File
@@ -9,13 +9,49 @@ const MAX_FILENAME_LENGTH = 254
*/
const formatCharsRe = /[\u200B-\u200F\u202A-\u202E\u2060-\u2064\u2066-\u2069\uFEFF]/g
const MAX_UPLOADER_LENGTH = 32
/*
A stored name is `<prefix><header><original>`. The header is the visitor
fields, each a slug, each followed by a comma: `ipp_upload_jane-smith,IMG_0042.jpg`.
Fields are positional, so a field added later goes on the end and an empty
one is written empty: `ipp_upload_,34,IMG_0042.jpg`. When every field is
empty there is no header at all, and the name is as it was before fields
existed. The visitor's own filename never keeps a comma, so a stem with no
comma has no fields and otherwise the last comma ends the header.
*/
const FIELD_SEPARATOR = ','
/**
* The visitor's name as a filename slug: lower case, letters and digits in any
* script, runs of anything else become one hyphen. Empty when nothing usable
* is left. A slug never contains the field separator.
*/
export function uploaderSlug (raw: unknown): string {
if (typeof raw !== 'string') return ''
return raw.normalize('NFC')
.replace(formatCharsRe, '')
.toLowerCase()
.replace(/[^\p{L}\p{N}]+/gu, '-')
.replace(/^-+|-+$/g, '')
.slice(0, MAX_UPLOADER_LENGTH)
.replace(/-+$/, '')
}
/** The header for these fields, in order, or empty when none has a value. */
function fieldHeader (fields: string[]): string {
if (!fields.some(Boolean)) return ''
return fields.map(field => field + FIELD_SEPARATOR).join('')
}
/**
* Turn the visitor-supplied filename into the name Immich will store, with
* `prefix` applied once. Returns undefined when nothing usable is left, or
* when there is no extension: Immich types an asset by its extension and
* would refuse it.
* `prefix` applied once and the uploader's slug after it, as
* `ipp_upload_jane-smith,IMG_0042.jpg`. Returns undefined when nothing usable
* is left, or when there is no extension: Immich types an asset by its
* extension and would refuse it.
*/
export function uploadFilename (raw: unknown, prefix: string): string | undefined {
export function uploadFilename (raw: unknown, prefix: string, uploader = ''): string | undefined {
if (typeof raw !== 'string') return undefined
const base = (raw.normalize('NFC').replace(formatCharsRe, '').split(/[\\/]/).pop() || '')
// Split the extension off first: `sanitize` truncates at 254 characters,
@@ -23,13 +59,15 @@ export function uploadFilename (raw: unknown, prefix: string): string | undefine
const parts = base.match(/^(.*)(\.[A-Za-z0-9]{1,16})$/)
if (!parts) return undefined
const extension = parts[2]
const stem = sanitize(parts[1]).trim()
// The separator is removed from the visitor's name so it only ever marks a field
const stem = sanitize(parts[1]).split(FIELD_SEPARATOR).join('').trim()
// An empty stem is a dotfile; a leading dot is a traversal remnant.
if (!stem || stem.startsWith('.')) return undefined
const cleanPrefix = sanitize(prefix).trim()
// Don't stack the prefix on a file that already carries it
const wanted = stem.startsWith(cleanPrefix) ? '' : cleanPrefix
// Don't stack the prefix, or the name, on a file that already carries the prefix
const hasPrefix = cleanPrefix !== '' && stem.startsWith(cleanPrefix)
const wanted = hasPrefix ? '' : cleanPrefix + fieldHeader([uploader])
const room = MAX_FILENAME_LENGTH - wanted.length - extension.length
return wanted + stem.slice(0, Math.max(1, room)) + extension
}
+3 -2
View File
@@ -28,7 +28,7 @@ import {
title,
unlockHandler
} from '@ipp/core'
import { galleryUrl, maxFileSize, uploadNotice } from './config'
import { askName, galleryUrl, maxFileSize, uploadNotice } from './config'
import { uploadAllowed } from './gate'
import { createUploadReceiver } from './receive'
import { getShare } from './share'
@@ -141,7 +141,8 @@ router.get('/:shareType(share|s)/:key', decodeCookie, asyncHandler(async (req, r
config: {
uploadUrl: `${req.baseUrl}/${req.params.shareType}/${encodeURIComponent(key)}/upload`,
maxFileSize: maxFileSize(),
title: title(resolved.link)
title: title(resolved.link),
askName: askName()
},
basePath: req.baseUrl,
galleryLink: gallery && `${gallery}/${req.params.shareType}/${encodeURIComponent(key)}`,
+8 -3
View File
@@ -17,6 +17,8 @@ export interface UploadNotification {
share: { type: 'album' | 'individual', id: string, title: string }
file: { name: string, size: number, type: string }
asset: { id: string, status: 'created' | 'duplicate' }
/** The visitor's name as stored in the filename, or empty when none was given. */
uploader: string
}
}
@@ -28,13 +30,15 @@ export interface UploadNotification {
export function buildNotification (
share: SharedLink,
file: { name: string, size: number, type: string },
asset: { id: string, status: 'created' | 'duplicate' }
asset: { id: string, status: 'created' | 'duplicate' },
uploader = ''
): UploadNotification {
const isAlbum = share.type === AlbumType.album
const shareTitle = title(share)
const sender = uploader ? ` by ${uploader}` : ''
return {
title: 'Photo sent to ' + shareTitle,
message: `${file.name} (${formatSize(file.size)}) was uploaded to ${shareTitle}.`,
message: `${file.name} (${formatSize(file.size)}) was uploaded to ${shareTitle}${sender}.`,
data: {
event: 'upload',
time: new Date().toISOString(),
@@ -45,7 +49,8 @@ export function buildNotification (
title: shareTitle
},
file,
asset
asset,
uploader
}
}
}
+8 -4
View File
@@ -2,8 +2,8 @@ import { pipeline } from 'stream'
import { Request, Response } from 'express-serve-static-core'
import dayjs from 'dayjs'
import { abortOnClose, KeyType, log, respondToInvalidRequest, SharedLink } from '@ipp/core'
import { byteBudget, filenamePrefix, maxFileSize, rateLimit } from './config'
import { uploadFilename } from './filename'
import { askName, byteBudget, filenamePrefix, maxFileSize, rateLimit } from './config'
import { uploaderSlug, uploadFilename } from './filename'
import { forwardUpload } from './forward'
import { authoriseUpload } from './gate'
import { createIdleTimeoutStream, IdleTimeoutError } from './idleTimeoutStream'
@@ -66,6 +66,7 @@ export function createUploadReceiver () {
const budget = createWindowBudget({ limit: byteBudget(), windowMs: 60 * 60_000 })
const maxBytes = maxFileSize()
const prefix = filenamePrefix()
const withName = askName()
return async function receiveUpload (req: Request, res: Response, link: SharedLink, keyType: KeyType): Promise<void> {
const key = req.params.key
@@ -90,7 +91,9 @@ export function createUploadReceiver () {
return
}
const filename = uploadFilename(req.query.filename, prefix)
// The name is the visitor's claim, kept only as part of the filename
const uploader = withName ? uploaderSlug(req.query.uploader) : ''
const filename = uploadFilename(req.query.filename, prefix, uploader)
if (!filename) {
refuse(res, 400, 'Missing or unusable filename')
return
@@ -146,7 +149,8 @@ export function createUploadReceiver () {
sendNotification(buildNotification(
link,
{ name: filename, size: result.bytes, type: mimeType },
{ id: result.id, status: result.status }
{ id: result.id, status: result.status },
uploader
))
}
}
+2
View File
@@ -86,6 +86,8 @@ export interface UploadPageConfig {
maxFileSize: number
/** Share title, for the drop overlay and the completion message. */
title: string
/** Whether the page has a name field, sent with each file as `uploader`. */
askName: boolean
}
/** Success body of `POST <share>/upload`. */
+6
View File
@@ -52,6 +52,12 @@ export function UploadPage ({ config, basePath, galleryLink, notice }: UploadPag
</div>
</header>
<main id="upload-main">
{config.askName && (
<label class="upload-name">
<span class="upload-name-label">Your name</span>
<input id="upload-name" type="text" maxLength={64} autocomplete="name" placeholder="Optional"/>
</label>
)}
<button id="upload-choose" type="button" class="upload-placeholder">
<Icon path={ICON_CLOUD_UPLOAD} class="upload-placeholder-icon"/>
<span class="upload-placeholder-title">Add photos</span>