#302 add name field for uploads
This commit is contained in:
@@ -8,6 +8,7 @@
|
||||
"byteBudget": 10240,
|
||||
"filenamePrefix": "ipp_upload_",
|
||||
"notice": "Uploaded photos may not appear in the gallery immediately.",
|
||||
"askName": true,
|
||||
"notifyUrl": "",
|
||||
"notifyHeaders": {},
|
||||
"notifyTimeout": 10000
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
"scripts": {
|
||||
"predev": "tsc -b ../shared",
|
||||
"dev": "concurrently -n core,server,client -c magenta,blue,green \"tsc -b -w --preserveWatchOutput ../shared\" \"tsx watch src/index.ts\" \"tsc -w -p tsconfig.client.json\"",
|
||||
"dev:app": "concurrently -n server,client -c blue,green \"tsx watch src/index.ts\" \"tsc -w -p tsconfig.client.json\"",
|
||||
"build": "tsc -b && tsc -p tsconfig.client.json",
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest",
|
||||
|
||||
@@ -71,6 +71,33 @@ html.dark .upload-placeholder:focus-visible {
|
||||
opacity: 0.7;
|
||||
}
|
||||
|
||||
/* The optional name field, when ipp.upload.askName is on */
|
||||
.upload-name {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.upload-name-label {
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.upload-name input {
|
||||
font: inherit;
|
||||
font-size: 16px;
|
||||
padding: 10px 12px;
|
||||
border: 1px solid color-mix(in srgb, var(--color-fg) 20%, transparent);
|
||||
border-radius: 8px;
|
||||
background: var(--color-subtle);
|
||||
color: var(--color-fg);
|
||||
}
|
||||
|
||||
.upload-name input:focus-visible {
|
||||
outline: 2px solid var(--color-primary);
|
||||
outline-offset: 1px;
|
||||
}
|
||||
|
||||
/* The owner's notice, from ipp.upload.notice */
|
||||
.upload-notice {
|
||||
margin: -8px 0 0;
|
||||
|
||||
@@ -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', () => {
|
||||
|
||||
@@ -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.')
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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)}`,
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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`. */
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect, afterEach } from 'vitest'
|
||||
import { byteBudget, filenamePrefix, maxFileSize, notifyConfig, uploadNotice } from '../src/config'
|
||||
import { askName, byteBudget, filenamePrefix, maxFileSize, notifyConfig, uploadNotice } from '../src/config'
|
||||
import { resetConfig, setConfig } from './helpers'
|
||||
|
||||
afterEach(resetConfig)
|
||||
@@ -13,6 +13,14 @@ describe('upload options', () => {
|
||||
expect(filenamePrefix()).toBe('ipp_upload_')
|
||||
expect(notifyConfig()).toBeUndefined()
|
||||
expect(uploadNotice()).toBe('Uploaded photos may not appear in the gallery immediately.')
|
||||
expect(askName()).toBe(true)
|
||||
})
|
||||
|
||||
it('turns the name field off only on an explicit false', () => {
|
||||
setConfig({ ipp: { upload: { askName: false } } })
|
||||
expect(askName()).toBe(false)
|
||||
setConfig({ ipp: { upload: { askName: 0 } } })
|
||||
expect(askName()).toBe(true)
|
||||
})
|
||||
|
||||
it('shows the owner\'s notice, and hides one that is not a string', () => {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { uploadFilename } from '../src/filename'
|
||||
import { uploaderSlug, uploadFilename } from '../src/filename'
|
||||
|
||||
describe('uploadFilename', () => {
|
||||
it('keeps an ordinary filename', () => {
|
||||
@@ -46,6 +46,21 @@ describe('uploadFilename', () => {
|
||||
expect(uploadFilename('IMG_0042.jpg', '../ev"il/')).toBe('..evilIMG_0042.jpg')
|
||||
})
|
||||
|
||||
it('puts the uploader after the prefix, and leaves a file that already carries the prefix alone', () => {
|
||||
expect(uploadFilename('IMG_0042.jpg', 'ipp_upload_', 'jane-smith')).toBe('ipp_upload_jane-smith,IMG_0042.jpg')
|
||||
expect(uploadFilename('IMG_0042.jpg', '', 'jane-smith')).toBe('jane-smith,IMG_0042.jpg')
|
||||
expect(uploadFilename('ipp_upload_IMG_0042.jpg', 'ipp_upload_', 'jane-smith')).toBe('ipp_upload_IMG_0042.jpg')
|
||||
})
|
||||
|
||||
it('writes no header without a name, so an anonymous file is unchanged from 4.0', () => {
|
||||
expect(uploadFilename('IMG_0042.jpg', 'ipp_upload_', '')).toBe('ipp_upload_IMG_0042.jpg')
|
||||
})
|
||||
|
||||
it('removes commas from the visitor filename, so a comma only ever ends a field', () => {
|
||||
expect(uploadFilename('Paris, France.jpg', 'ipp_upload_')).toBe('ipp_upload_Paris France.jpg')
|
||||
expect(uploadFilename('a,b,c.jpg', 'ipp_upload_', 'jane-smith')).toBe('ipp_upload_jane-smith,abc.jpg')
|
||||
})
|
||||
|
||||
it('stays within 254 characters with the extension intact', () => {
|
||||
const result = uploadFilename('x'.repeat(400) + '.jpg', 'ipp_upload_') || ''
|
||||
expect(result.startsWith('ipp_upload_')).toBe(true)
|
||||
@@ -53,3 +68,36 @@ describe('uploadFilename', () => {
|
||||
expect(result.length).toBeLessThanOrEqual(254)
|
||||
})
|
||||
})
|
||||
|
||||
describe('uploaderSlug', () => {
|
||||
it('makes a lower-case hyphenated slug', () => {
|
||||
expect(uploaderSlug('Jane Smith')).toBe('jane-smith')
|
||||
expect(uploaderSlug(" O'Brien, Pat ")).toBe('o-brien-pat')
|
||||
})
|
||||
|
||||
it('keeps letters and digits in any script', () => {
|
||||
expect(uploaderSlug('Zoë Müller 2')).toBe('zoë-müller-2')
|
||||
expect(uploaderSlug('山田 太郎')).toBe('山田-太郎')
|
||||
})
|
||||
|
||||
it('never keeps a comma or an underscore', () => {
|
||||
expect(uploaderSlug('Smith, Jane')).toBe('smith-jane')
|
||||
expect(uploaderSlug('jane_smith')).toBe('jane-smith')
|
||||
})
|
||||
|
||||
it('removes zero-width and direction-changing characters', () => {
|
||||
expect(uploaderSlug('ja\u200Bne\u202E')).toBe('jane')
|
||||
})
|
||||
|
||||
it('is empty for nothing usable or non-string input', () => {
|
||||
expect(uploaderSlug('')).toBe('')
|
||||
expect(uploaderSlug('!!!')).toBe('')
|
||||
expect(uploaderSlug(undefined)).toBe('')
|
||||
expect(uploaderSlug(['jane'])).toBe('')
|
||||
})
|
||||
|
||||
it('is at most 32 characters, with no hyphen left at the end', () => {
|
||||
expect(uploaderSlug('a'.repeat(40))).toBe('a'.repeat(32))
|
||||
expect(uploaderSlug('a'.repeat(31) + ' b')).toBe('a'.repeat(31))
|
||||
})
|
||||
})
|
||||
|
||||
@@ -30,6 +30,15 @@ describe('buildNotification', () => {
|
||||
expect(payload.message).toBe('ipp_upload_IMG_0042.jpg (3.0 MB) was uploaded to Holiday 2025.')
|
||||
})
|
||||
|
||||
it('names the uploader in the message and the data, and leaves both plain without one', () => {
|
||||
const named = buildNotification(share(), { ...file, name: 'ipp_upload_jane-smith,IMG_0042.jpg' }, asset, 'jane-smith')
|
||||
expect(named.message).toBe('ipp_upload_jane-smith,IMG_0042.jpg (3.0 MB) was uploaded to Holiday 2025 by jane-smith.')
|
||||
expect(named.data.uploader).toBe('jane-smith')
|
||||
const anonymous = buildNotification(share(), file, asset)
|
||||
expect(anonymous.message).toBe('ipp_upload_IMG_0042.jpg (3.0 MB) was uploaded to Holiday 2025.')
|
||||
expect(anonymous.data.uploader).toBe('')
|
||||
})
|
||||
|
||||
it('never carries the share key, slug or password', () => {
|
||||
const payload = JSON.stringify(buildNotification(share({ key: 'secret-key', slug: 'secret-slug', password: 'hunter2' }), file, asset))
|
||||
expect(payload).not.toContain('secret-key')
|
||||
|
||||
Reference in New Issue
Block a user