feat: add artist image uploads and image-folder artwork source (#5198)

* feat: add shared ImageUploadService for entity image management

* feat: add UploadedImage field and methods to Artist model

* feat: add uploaded_image column to artist table

* feat: add ArtistImageFolder config option

* refactor: wire ImageUploadService and delegate playlist file ops to it

Wire ImageUploadService into the DI container and refactor the playlist
service to delegate image file operations (SetImage/RemoveImage) to the
shared ImageUploadService, removing duplicated file I/O logic. A local
ImageUploadService interface is defined in core/playlists to avoid an
import cycle between core and core/playlists.

* feat: artist artwork reader checks uploaded image first

* feat: add image-folder priority source for artist artwork

* feat: cache key invalidation for image-folder and uploaded images

* refactor: extract shared image upload HTTP helpers

* feat: add artist image upload/delete API endpoints

* refactor: playlist handlers use shared image upload helpers

* feat: add shared ImageUploadOverlay component

* feat: add i18n keys for artist image upload

* feat: add image upload overlay to artist detail pages

* refactor: playlist details uses shared ImageUploadOverlay component

* fix: add gosec nolint directive for ParseMultipartForm

* refactor: deduplicate image upload code and optimize dir scanning

- Remove dead ImageFilename methods from Artist and Playlist models
  (production code uses core.imageFilename exclusively)
- Extract shared uploadedImagePath helper in model/image.go
- Extract findImageInArtistFolder to deduplicate dir-scanning logic
  between fromArtistImageFolder and getArtistImageFolderModTime
- Fix fileInputRef in useCallback dependency array

* fix: include artist UpdatedAt in artwork cache key

Without this, uploading or deleting an artist image would not
invalidate the cached artwork because the cache key was only based
on album folder timestamps, not the artist's own UpdatedAt field.

* feat: add Portuguese translations for artist image upload

* refactor: use shared i18n keys for cover art upload messages

Move cover art upload/remove translations from per-entity sections
(artist, playlist) to a shared top-level "message" section, avoiding
duplication across entity types and translation files.

* refactor: move cover art i18n keys to shared message section for all languages

* refactor: simplify image upload code and eliminate redundancies

Extracted duplicate image loading/lightbox state logic from
DesktopArtistDetails and MobileArtistDetails into a shared
useArtistImageState hook. Moved entity type constants to the consts
package and replaced raw string literals throughout model, core, and
nativeapi packages. Exported model.UploadedImagePath and reused it in
core/image_upload.go to consolidate path construction. Cached the
ArtistImageFolder lookup result in artistReader to eliminate a redundant
os.ReadDir call on every artwork request.

Signed-off-by: Deluan <deluan@navidrome.org>

* style: fix prettier formatting in ImageUploadOverlay

* fix: address code review feedback on image upload error handling

- RemoveImage now returns errors instead of swallowing them
- Artist handlers distinguish not-found from other DB errors
- Defer multipart temp file cleanup after parsing

* fix: enforce hard request size limit with MaxBytesReader for image uploads

Signed-off-by: Deluan <deluan@navidrome.org>

---------

Signed-off-by: Deluan <deluan@navidrome.org>
This commit is contained in:
Deluan Quintão
2026-03-15 22:19:55 -04:00
committed by GitHub
parent be06196168
commit ab8a58157a
57 changed files with 1169 additions and 567 deletions
+17 -31
View File
@@ -6,12 +6,13 @@ import CardContent from '@material-ui/core/CardContent'
import CardMedia from '@material-ui/core/CardMedia'
import ArtistExternalLinks from './ArtistExternalLink'
import config from '../config'
import { LoveButton, RatingField } from '../common'
import { LoveButton, RatingField, ImageUploadOverlay } from '../common'
import Lightbox from 'react-image-lightbox'
import ExpandInfoDialog from '../dialogs/ExpandInfoDialog'
import AlbumInfo from '../album/AlbumInfo'
import subsonic from '../subsonic'
import { SafeHTML } from '../common/SafeHTML'
import useArtistImageState from './useArtistImageState'
const useStyles = makeStyles(
(theme) => ({
@@ -57,6 +58,7 @@ const useStyles = makeStyles(
alignItems: 'center',
justifyContent: 'center',
boxShadow: 'none',
position: 'relative',
},
artistDetail: {
flex: '1',
@@ -85,36 +87,15 @@ const DesktopArtistDetails = ({ artistInfo, record, biography }) => {
const [expanded, setExpanded] = useState(false)
const classes = useStyles()
const title = record.name
const [isLightboxOpen, setLightboxOpen] = React.useState(false)
const [imageLoading, setImageLoading] = React.useState(false)
const [imageError, setImageError] = React.useState(false)
// Reset image state when artist changes
React.useEffect(() => {
setImageLoading(true)
setImageError(false)
}, [record.id])
const handleImageLoad = React.useCallback(() => {
setImageLoading(false)
setImageError(false)
}, [])
const handleImageError = React.useCallback(() => {
setImageLoading(false)
setImageError(true)
}, [])
const handleOpenLightbox = React.useCallback(() => {
if (!imageError) {
setLightboxOpen(true)
}
}, [imageError])
const handleCloseLightbox = React.useCallback(
() => setLightboxOpen(false),
[],
)
const {
imageLoading,
imageError,
isLightboxOpen,
handleImageLoad,
handleImageError,
handleOpenLightbox,
handleCloseLightbox,
} = useArtistImageState(record.id)
return (
<div className={classes.root}>
@@ -135,6 +116,11 @@ const DesktopArtistDetails = ({ artistInfo, record, biography }) => {
}}
/>
)}
<ImageUploadOverlay
entityType="artist"
entityId={record.id}
hasUploadedImage={!!record.uploadedImage}
/>
</Card>
<div className={classes.details}>
<CardContent className={classes.content}>
+17 -31
View File
@@ -4,10 +4,11 @@ import { makeStyles } from '@material-ui/core/styles'
import Card from '@material-ui/core/Card'
import CardMedia from '@material-ui/core/CardMedia'
import config from '../config'
import { LoveButton, RatingField } from '../common'
import { LoveButton, RatingField, ImageUploadOverlay } from '../common'
import Lightbox from 'react-image-lightbox'
import subsonic from '../subsonic'
import { SafeHTML } from '../common/SafeHTML'
import useArtistImageState from './useArtistImageState'
const useStyles = makeStyles(
(theme) => ({
@@ -67,6 +68,7 @@ const useStyles = makeStyles(
minWidth: '7rem',
display: 'flex',
borderRadius: '5em',
position: 'relative',
},
loveButton: {
top: theme.spacing(-0.2),
@@ -87,36 +89,15 @@ const MobileArtistDetails = ({ artistInfo, biography, record }) => {
const [expanded, setExpanded] = useState(false)
const classes = useStyles({ img, expanded })
const title = record.name
const [isLightboxOpen, setLightboxOpen] = React.useState(false)
const [imageLoading, setImageLoading] = React.useState(false)
const [imageError, setImageError] = React.useState(false)
// Reset image state when artist changes
React.useEffect(() => {
setImageLoading(true)
setImageError(false)
}, [record.id])
const handleImageLoad = React.useCallback(() => {
setImageLoading(false)
setImageError(false)
}, [])
const handleImageError = React.useCallback(() => {
setImageLoading(false)
setImageError(true)
}, [])
const handleOpenLightbox = React.useCallback(() => {
if (!imageError) {
setLightboxOpen(true)
}
}, [imageError])
const handleCloseLightbox = React.useCallback(
() => setLightboxOpen(false),
[],
)
const {
imageLoading,
imageError,
isLightboxOpen,
handleImageLoad,
handleImageError,
handleOpenLightbox,
handleCloseLightbox,
} = useArtistImageState(record.id)
return (
<>
@@ -138,6 +119,11 @@ const MobileArtistDetails = ({ artistInfo, biography, record }) => {
}}
/>
)}
<ImageUploadOverlay
entityType="artist"
entityId={record.id}
hasUploadedImage={!!record.uploadedImage}
/>
</Card>
<div className={classes.details}>
<Typography
+46
View File
@@ -0,0 +1,46 @@
import { useState, useEffect, useCallback } from 'react'
/**
* Manages image loading/error state and lightbox open/close for artist detail views.
* Resets when record.id changes.
*/
const useArtistImageState = (recordId) => {
const [imageLoading, setImageLoading] = useState(false)
const [imageError, setImageError] = useState(false)
const [isLightboxOpen, setLightboxOpen] = useState(false)
useEffect(() => {
setImageLoading(true)
setImageError(false)
}, [recordId])
const handleImageLoad = useCallback(() => {
setImageLoading(false)
setImageError(false)
}, [])
const handleImageError = useCallback(() => {
setImageLoading(false)
setImageError(true)
}, [])
const handleOpenLightbox = useCallback(() => {
if (!imageError) {
setLightboxOpen(true)
}
}, [imageError])
const handleCloseLightbox = useCallback(() => setLightboxOpen(false), [])
return {
imageLoading,
imageError,
isLightboxOpen,
handleImageLoad,
handleImageError,
handleOpenLightbox,
handleCloseLightbox,
}
}
export default useArtistImageState
+139
View File
@@ -0,0 +1,139 @@
import { IconButton, Tooltip } from '@material-ui/core'
import { makeStyles } from '@material-ui/core/styles'
import PhotoCameraIcon from '@material-ui/icons/PhotoCamera'
import DeleteIcon from '@material-ui/icons/Delete'
import { useTranslate, useNotify, useRefresh } from 'react-admin'
import { useCallback, useRef } from 'react'
import config from '../config'
import { REST_URL } from '../consts'
import { httpClient } from '../dataProvider'
const useStyles = makeStyles(() => ({
coverOverlay: {
position: 'absolute',
bottom: 0,
right: 0,
display: 'flex',
gap: '2px',
padding: '2px',
backgroundColor: 'rgba(0,0,0,0.5)',
borderRadius: '4px 0 0 0',
opacity: 0,
transition: 'opacity 0.2s ease-in-out',
'*:hover > &': {
opacity: 1,
},
},
overlayButton: {
color: '#fff',
padding: '4px',
'&:hover': {
backgroundColor: 'rgba(255,255,255,0.2)',
},
},
overlayIcon: {
fontSize: '1.2rem',
},
}))
export const ImageUploadOverlay = ({
entityType,
entityId,
hasUploadedImage,
onImageChange,
}) => {
const translate = useTranslate()
const notify = useNotify()
const refresh = useRefresh()
const classes = useStyles()
const fileInputRef = useRef(null)
const canEdit =
config.enableCoverArtUpload || localStorage.getItem('role') === 'admin'
const handleUploadClick = useCallback((e) => {
e.stopPropagation()
if (fileInputRef.current) {
fileInputRef.current.click()
}
}, [])
const handleFileChange = useCallback(
async (e) => {
const file = e.target.files[0]
if (!file || !entityId) return
const formData = new FormData()
formData.append('image', file)
try {
await httpClient(`${REST_URL}/${entityType}/${entityId}/image`, {
method: 'POST',
headers: new Headers({}),
body: formData,
})
notify(`message.coverUploaded`, 'success')
if (onImageChange) onImageChange()
refresh()
} catch (err) {
notify(`message.coverUploadError`, 'warning')
}
e.target.value = ''
},
[entityType, entityId, notify, refresh, onImageChange],
)
const handleRemoveCover = useCallback(
async (e) => {
e.stopPropagation()
if (!entityId) return
try {
await httpClient(`${REST_URL}/${entityType}/${entityId}/image`, {
method: 'DELETE',
})
notify(`message.coverRemoved`, 'success')
if (onImageChange) onImageChange()
refresh()
} catch (err) {
notify(`message.coverRemoveError`, 'warning')
}
},
[entityType, entityId, notify, refresh, onImageChange],
)
if (!canEdit) return null
return (
<div className={classes.coverOverlay}>
<Tooltip title={translate(`message.uploadCover`)}>
<IconButton
className={classes.overlayButton}
onClick={handleUploadClick}
size="small"
>
<PhotoCameraIcon className={classes.overlayIcon} />
</IconButton>
</Tooltip>
{hasUploadedImage && (
<Tooltip title={translate(`message.removeCover`)}>
<IconButton
className={classes.overlayButton}
onClick={handleRemoveCover}
size="small"
>
<DeleteIcon className={classes.overlayIcon} />
</IconButton>
</Tooltip>
)}
<input
ref={fileInputRef}
type="file"
accept="image/*"
style={{ display: 'none' }}
onChange={handleFileChange}
/>
</div>
)
}
+1
View File
@@ -43,3 +43,4 @@ export * from './PathField.jsx'
export * from './ParticipantsInfo'
export * from './OverflowTooltip'
export * from './useSearchRefocus'
export * from './ImageUploadOverlay'
+7 -7
View File
@@ -219,15 +219,9 @@
"makePrivate": "Make Private",
"searchOrCreate": "Search playlists or type to create new...",
"pressEnterToCreate": "Press Enter to create new playlist",
"removeFromSelection": "Remove from selection",
"uploadCover": "Upload Cover",
"removeCover": "Remove Cover"
"removeFromSelection": "Remove from selection"
},
"message": {
"coverUploaded": "Cover art updated",
"coverRemoved": "Cover art removed",
"coverUploadError": "Error uploading cover art",
"coverRemoveError": "Error removing cover art",
"duplicate_song": "Add duplicated songs",
"song_exist": "There are duplicates being added to the playlist. Would you like to add the duplicates or skip them?",
"noPlaylistsFound": "No playlists found",
@@ -563,6 +557,12 @@
}
},
"message": {
"uploadCover": "Upload Cover",
"removeCover": "Remove Cover",
"coverUploaded": "Cover art updated",
"coverRemoved": "Cover art removed",
"coverUploadError": "Error uploading cover art",
"coverRemoveError": "Error removing cover art",
"note": "NOTE",
"transcodingDisabled": "Changing the transcoding configuration through the web interface is disabled for security reasons. If you would like to change (edit or add) transcoding options, restart the server with the %{config} configuration option.",
"transcodingEnabled": "Navidrome is currently running with %{config}, making it possible to run system commands from the transcoding settings using the web interface. We recommend to disable it for security reasons and only enable it when configuring Transcoding options.",
+9 -128
View File
@@ -2,29 +2,23 @@ import {
Card,
CardContent,
CardMedia,
IconButton,
Tooltip,
Typography,
useMediaQuery,
} from '@material-ui/core'
import { makeStyles } from '@material-ui/core/styles'
import PhotoCameraIcon from '@material-ui/icons/PhotoCamera'
import DeleteIcon from '@material-ui/icons/Delete'
import { useTranslate, useNotify, useRefresh } from 'react-admin'
import { useCallback, useRef, useState, useEffect } from 'react'
import { useTranslate } from 'react-admin'
import { useCallback, useState, useEffect } from 'react'
import Lightbox from 'react-image-lightbox'
import 'react-image-lightbox/style.css'
import {
CollapsibleComment,
DurationField,
ImageUploadOverlay,
SizeField,
isWritable,
OverflowTooltip,
} from '../common'
import config from '../config'
import subsonic from '../subsonic'
import { REST_URL } from '../consts'
import { httpClient } from '../dataProvider'
const useStyles = makeStyles(
(theme) => ({
@@ -82,31 +76,6 @@ const useStyles = makeStyles(
coverLoading: {
opacity: 0.5,
},
coverOverlay: {
position: 'absolute',
bottom: 0,
right: 0,
display: 'flex',
gap: '2px',
padding: '2px',
backgroundColor: 'rgba(0,0,0,0.5)',
borderRadius: '4px 0 0 0',
opacity: 0,
transition: 'opacity 0.2s ease-in-out',
'$coverParent:hover &': {
opacity: 1,
},
},
overlayButton: {
color: '#fff',
padding: '4px',
'&:hover': {
backgroundColor: 'rgba(255,255,255,0.2)',
},
},
overlayIcon: {
fontSize: '1.2rem',
},
title: {
overflow: 'hidden',
textOverflow: 'ellipsis',
@@ -125,20 +94,14 @@ const useStyles = makeStyles(
const PlaylistDetails = (props) => {
const { record = {} } = props
const translate = useTranslate()
const notify = useNotify()
const refresh = useRefresh()
const classes = useStyles()
const isDesktop = useMediaQuery((theme) => theme.breakpoints.up('lg'))
const [isLightboxOpen, setLightboxOpen] = useState(false)
const [imageLoading, setImageLoading] = useState(false)
const [imageError, setImageError] = useState(false)
const fileInputRef = useRef(null)
const imageUrl = subsonic.getCoverArtUrl(record, 300, true)
const fullImageUrl = subsonic.getCoverArtUrl(record)
const canEdit =
isWritable(record.ownerId) &&
(config.enableCoverArtUpload || localStorage.getItem('role') === 'admin')
// Reset image state when playlist changes
useEffect(() => {
@@ -164,60 +127,6 @@ const PlaylistDetails = (props) => {
const handleCloseLightbox = useCallback(() => setLightboxOpen(false), [])
const handleUploadClick = useCallback(
(e) => {
e.stopPropagation()
if (fileInputRef.current) {
fileInputRef.current.click()
}
},
[fileInputRef],
)
const handleFileChange = useCallback(
async (e) => {
const file = e.target.files[0]
if (!file || !record.id) return
const formData = new FormData()
formData.append('image', file)
try {
await httpClient(`${REST_URL}/playlist/${record.id}/image`, {
method: 'POST',
headers: new Headers({}),
body: formData,
})
notify('resources.playlist.message.coverUploaded', 'success')
refresh()
} catch (err) {
notify('resources.playlist.message.coverUploadError', 'warning')
}
// Reset file input so the same file can be re-selected
e.target.value = ''
},
[record.id, notify, refresh],
)
const handleRemoveCover = useCallback(
async (e) => {
e.stopPropagation()
if (!record.id) return
try {
await httpClient(`${REST_URL}/playlist/${record.id}/image`, {
method: 'DELETE',
})
notify('resources.playlist.message.coverRemoved', 'success')
refresh()
} catch (err) {
notify('resources.playlist.message.coverRemoveError', 'warning')
}
},
[record.id, notify, refresh],
)
return (
<Card className={classes.root}>
<div className={classes.cardContents}>
@@ -237,40 +146,12 @@ const PlaylistDetails = (props) => {
cursor: imageError ? 'default' : 'pointer',
}}
/>
{canEdit && (
<div className={classes.coverOverlay}>
<Tooltip
title={translate('resources.playlist.actions.uploadCover')}
>
<IconButton
className={classes.overlayButton}
onClick={handleUploadClick}
size="small"
>
<PhotoCameraIcon className={classes.overlayIcon} />
</IconButton>
</Tooltip>
{record.uploadedImage && (
<Tooltip
title={translate('resources.playlist.actions.removeCover')}
>
<IconButton
className={classes.overlayButton}
onClick={handleRemoveCover}
size="small"
>
<DeleteIcon className={classes.overlayIcon} />
</IconButton>
</Tooltip>
)}
<input
ref={fileInputRef}
type="file"
accept="image/*"
style={{ display: 'none' }}
onChange={handleFileChange}
/>
</div>
{isWritable(record.ownerId) && (
<ImageUploadOverlay
entityType="playlist"
entityId={record.id}
hasUploadedImage={!!record.uploadedImage}
/>
)}
</div>
<div className={classes.details}>