Merge upstream/master into feat-podcast-ux-improvements/5420

Resolve conflicts with the stateless-repositories refactor (#6149):
- port podcast repositories, model interfaces, mocks, service and handlers to per-call ctx
- podcast channel repo now implements generic rest.Repository/Persistable
- register podcast repos in SQLStore and MockDataStore
- merge OpenSubsonic extensions (apiKeyAuthentication + podcast extensions)
- renumber podcast migrations after upstream's latest (20260930...)
This commit is contained in:
Jiho Andrew Lee 2026-09-30 15:23:00 +09:00
commit 19385dc28b
508 changed files with 13229 additions and 8764 deletions

View file

@ -148,7 +148,7 @@ const Admin = (props) => {
<Resource
name="player"
{...player}
options={{ subMenu: 'settings' }}
options={{ subMenu: 'settings', label: 'resources.player.menuName' }}
/>,
permissions === 'admin' ? (
<Resource

View file

@ -16,6 +16,7 @@ import {
useRecordContext,
useTranslate,
} from 'react-admin'
import clsx from 'clsx'
import Lightbox from 'react-image-lightbox'
import config from '../config'
import 'react-image-lightbox/style.css'
@ -79,6 +80,9 @@ const useStyles = makeStyles(
alignItems: 'center',
justifyContent: 'center',
},
noCoverAnimation: {
'&, &::before, &::after': { animation: 'none' },
},
cover: {
objectFit: 'contain',
cursor: 'pointer',
@ -250,7 +254,12 @@ const AlbumDetails = (props) => {
return (
<Card className={classes.root}>
<div className={classes.cardContents}>
<div className={classes.coverParent}>
<div
className={clsx(
classes.coverParent,
!config.enableCoverAnimation && classes.noCoverAnimation,
)}
>
<Artwork
record={record}
fit="contain"

View file

@ -3,7 +3,29 @@ import { describe, test, expect, beforeEach, afterEach } from 'vitest'
import { render } from '@testing-library/react'
import { RecordContextProvider } from 'react-admin'
import { useMediaQuery } from '@material-ui/core'
import { Details } from './AlbumDetails'
import { createTheme, ThemeProvider } from '@material-ui/core/styles'
import config from '../config'
import AlbumDetails, { Details } from './AlbumDetails'
vi.mock('../subsonic', () => ({
default: {
getAlbumInfo: () =>
Promise.resolve({
json: { 'subsonic-response': { status: 'ok', albumInfo: {} } },
}),
getCoverArtUrl: () => '',
},
}))
vi.mock('react-admin', async () => {
const actual = await vi.importActual('react-admin')
return {
...actual,
useDataProvider: () => ({ getOne: vi.fn() }),
useNotify: () => vi.fn(),
useRefresh: () => vi.fn(),
}
})
// Mock useMediaQuery
vi.mock('@material-ui/core', async () => {
@ -343,3 +365,49 @@ describe('Details component', () => {
})
})
})
describe('AlbumDetails cover animation', () => {
const albumRecord = {
id: '123',
name: 'Test Album',
songCount: 12,
duration: 3600,
size: 102400,
}
const originalEnableCoverAnimation = config.enableCoverAnimation
beforeEach(() => {
vi.mocked(useMediaQuery).mockReturnValue(false)
})
afterEach(() => {
config.enableCoverAnimation = originalEnableCoverAnimation
})
const renderAlbum = () =>
render(
<ThemeProvider theme={createTheme()}>
<RecordContextProvider value={albumRecord}>
<AlbumDetails />
</RecordContextProvider>
</ThemeProvider>,
)
test('applies noCoverAnimation when enableCoverAnimation is false', () => {
config.enableCoverAnimation = false
const { container } = renderAlbum()
const cover = container.querySelector('[class*="coverParent"]')
expect(cover).not.toBeNull()
expect(cover.className).toMatch(/noCoverAnimation/)
})
test('omits noCoverAnimation when enableCoverAnimation is true', () => {
config.enableCoverAnimation = true
const { container } = renderAlbum()
const cover = container.querySelector('[class*="coverParent"]')
expect(cover).not.toBeNull()
expect(cover.className).not.toMatch(/noCoverAnimation/)
})
})

View file

@ -163,6 +163,7 @@ const AlbumFilter = (props) => {
/>
</ReferenceInput>
<NullableBooleanInput source="compilation" />
<NullableBooleanInput source="played" defaultValue={false} />
<NumberInput source="year" />
{config.enableFavourites && (
<NullableBooleanInput

View file

@ -0,0 +1,99 @@
import React from 'react'
import PropTypes from 'prop-types'
import get from 'lodash/get'
import { FieldTitle, useRecordContext } from 'react-admin'
import { TextField } from '@material-ui/core'
import { makeStyles } from '@material-ui/core/styles'
import { useDateLocale } from '../i18n/useDateLocale'
import {
formatBytes,
formatDateTime,
formatDuration2,
formatNumber,
} from '../utils/formatters'
import { isDateSet } from '../utils/validations'
const useStyles = makeStyles(
(theme) => ({
inputRoot: {
'&:hover $notchedOutline': {
borderColor: theme.palette.divider,
},
},
notchedOutline: {
borderColor: theme.palette.divider,
},
}),
{ name: 'NDReadOnlyField' },
)
const identity = (v) => v
// Renders a record value as a dimmed, non-editable input, so it lines up with the inputs in a form
export const ReadOnlyTextField = ({
source,
label,
resource,
className,
fullWidth,
format = identity,
...props
}) => {
const classes = useStyles(props)
const record = useRecordContext(props)
const value = get(record, source)
return (
<TextField
id={source}
className={className}
label={<FieldTitle label={label} source={source} resource={resource} />}
value={value == null ? '' : format(value)}
variant="outlined"
margin="dense"
fullWidth={fullWidth}
focused={false}
helperText=" "
InputProps={{
readOnly: true,
classes: {
root: classes.inputRoot,
notchedOutline: classes.notchedOutline,
},
}}
inputProps={{ tabIndex: -1 }}
/>
)
}
ReadOnlyTextField.propTypes = {
source: PropTypes.string.isRequired,
label: PropTypes.oneOfType([PropTypes.string, PropTypes.bool]),
record: PropTypes.object,
resource: PropTypes.string,
className: PropTypes.string,
classes: PropTypes.object,
fullWidth: PropTypes.bool,
format: PropTypes.func,
}
export const ReadOnlyDateField = (props) => {
const locale = useDateLocale()
const format = (v) => (isDateSet(v) ? formatDateTime(v, locale) : '')
return <ReadOnlyTextField format={format} {...props} />
}
export const ReadOnlyNumberField = (props) => {
const locale = useDateLocale()
return (
<ReadOnlyTextField format={(v) => formatNumber(v, locale)} {...props} />
)
}
export const ReadOnlySizeField = (props) => (
<ReadOnlyTextField format={formatBytes} {...props} />
)
export const ReadOnlyDurationField = (props) => (
<ReadOnlyTextField format={formatDuration2} {...props} />
)

View file

@ -0,0 +1,121 @@
import React from 'react'
import { render, screen } from '@testing-library/react'
import { describe, it, expect, beforeEach, vi } from 'vitest'
import {
ReadOnlyDateField,
ReadOnlyDurationField,
ReadOnlyNumberField,
ReadOnlySizeField,
ReadOnlyTextField,
} from './ReadOnlyFields'
vi.mock('react-admin', async (importOriginal) => ({
...(await importOriginal()),
useLocale: vi.fn(),
}))
describe('ReadOnlyFields', () => {
const record = {
id: '1',
client: 'NavidromeUI',
createdAt: '2026-09-17T14:30:00Z',
lastVisitedAt: '0001-01-01T00:00:00Z',
count: 1234567,
zero: 0,
size: 1536000,
duration: 3725,
}
beforeEach(async () => {
vi.clearAllMocks()
vi.spyOn(navigator, 'languages', 'get').mockReturnValue([])
const { useLocale } = await import('react-admin')
vi.mocked(useLocale).mockReturnValue('de')
})
const renderField = (Field, props) =>
render(<Field record={record} resource="player" {...props} />)
describe('<ReadOnlyTextField>', () => {
it('shows the record value with the translated field label', () => {
renderField(ReadOnlyTextField, { source: 'client' })
const input = screen.getByLabelText('resources.player.fields.client')
expect(input).toHaveValue('NavidromeUI')
})
it('cannot be edited or reached with the Tab key', () => {
renderField(ReadOnlyTextField, { source: 'client' })
const input = screen.getByRole('textbox')
expect(input).toHaveAttribute('readonly')
expect(input).toHaveAttribute('tabindex', '-1')
})
it('shows an empty value when the record has no value', () => {
renderField(ReadOnlyTextField, { source: 'userName' })
expect(screen.getByRole('textbox')).toHaveValue('')
})
it('uses an explicit label when given', () => {
renderField(ReadOnlyTextField, { source: 'client', label: 'Custom' })
expect(screen.getByLabelText('Custom')).toBeInTheDocument()
})
it('applies a custom format', () => {
renderField(ReadOnlyTextField, {
source: 'client',
format: (v) => v.toUpperCase(),
})
expect(screen.getByRole('textbox')).toHaveValue('NAVIDROMEUI')
})
it('exposes theme-overridable class names', () => {
const { container } = renderField(ReadOnlyTextField, {
source: 'client',
})
expect(
container.querySelector('[class*="NDReadOnlyField-inputRoot"]'),
).toBeInTheDocument()
expect(
container.querySelector('[class*="NDReadOnlyField-notchedOutline"]'),
).toBeInTheDocument()
})
})
describe('<ReadOnlyDateField>', () => {
it('formats the date using the selected language', () => {
renderField(ReadOnlyDateField, { source: 'createdAt' })
expect(screen.getByRole('textbox').value).toMatch(/^17\.9\.2026, /)
})
it('shows an empty value when the date is not set', () => {
renderField(ReadOnlyDateField, { source: 'lastVisitedAt' })
expect(screen.getByRole('textbox')).toHaveValue('')
})
})
describe('<ReadOnlyNumberField>', () => {
it('formats the number using the selected language', () => {
renderField(ReadOnlyNumberField, { source: 'count' })
expect(screen.getByRole('textbox')).toHaveValue('1.234.567')
})
it('shows zero', () => {
renderField(ReadOnlyNumberField, { source: 'zero' })
expect(screen.getByRole('textbox')).toHaveValue('0')
})
})
describe('<ReadOnlySizeField>', () => {
it('formats bytes as a human-readable size', () => {
renderField(ReadOnlySizeField, { source: 'size' })
expect(screen.getByRole('textbox')).toHaveValue('1.46 MB')
})
})
describe('<ReadOnlyDurationField>', () => {
it('formats seconds as a human-readable duration', () => {
renderField(ReadOnlyDurationField, { source: 'duration' })
expect(screen.getByRole('textbox')).toHaveValue('1h 2m 5s')
})
})
})

View file

@ -15,6 +15,7 @@ export * from './perPageStore'
export * from './PlayButton'
export * from './QuickFilter'
export * from './RangeField'
export * from './ReadOnlyFields'
export * from './ShuffleAllButton'
export * from './SimpleList'
export * from './SizeField'

View file

@ -148,6 +148,12 @@ const updateUser = async (params) => {
return userResponse
}
// ra-data-json-server merges the request body into the result; re-read so the plaintext key is never cached
const createPlayer = async (resource, params) => {
const { data } = await dataProvider.create(resource, params)
return dataProvider.getOne(resource, { id: data.id })
}
const wrapperDataProvider = {
...dataProvider,
getList: (resource, params) => {
@ -194,6 +200,9 @@ const wrapperDataProvider = {
return createUser(params)
}
const [r, p] = mapResource(resource, params)
if (resource === 'player') {
return createPlayer(r, p)
}
return dataProvider.create(r, p)
},
delete: (resource, params) => {

View file

@ -88,6 +88,21 @@ describe('wrapperDataProvider', () => {
})
})
describe('create player', () => {
it('returns the server record, never the plaintext API key', async () => {
const data = { name: 'Phone', apiKey: 'nds_0123456789abcdefghijkl' }
const saved = { id: 'p1', name: 'Phone', hasApiKey: true, userId: 'u1' }
mockProvider.create.mockResolvedValue({ data: { ...data, id: 'p1' } })
mockProvider.getOne.mockResolvedValue({ data: saved })
const result = await wrapperDataProvider.create('player', { data })
expect(mockProvider.create).toHaveBeenCalledWith('player', { data })
expect(mockProvider.getOne).toHaveBeenCalledWith('player', { id: 'p1' })
expect(result.data).toEqual(saved)
})
})
describe('refreshMetadata', () => {
it('posts to the album metadata refresh endpoint', () => {
mockHttpClient.mockResolvedValue({ json: {} })

View file

@ -83,7 +83,8 @@
"grouping": "Grouping",
"media": "Media",
"mood": "Mood",
"missing": "Missing"
"missing": "Missing",
"played": "Played"
},
"actions": {
"playAll": "Play",
@ -183,6 +184,7 @@
},
"player": {
"name": "Player |||| Players",
"menuName": "Players & API keys",
"fields": {
"name": "Name",
"transcodingId": "Transcoding",
@ -191,7 +193,29 @@
"userName": "Username",
"lastSeen": "Last Seen At",
"reportRealPath": "Report Real Path",
"scrobbleEnabled": "Send Scrobbles to external services"
"scrobbleEnabled": "Send Scrobbles to external services",
"hasApiKey": "API Key"
},
"actions": {
"generateApiKey": "Generate API key",
"regenerateApiKey": "Regenerate",
"revokeApiKey": "Revoke",
"copyApiKey": "Copy"
},
"message": {
"apiKeyActive": "This player has an API key. Use it in your app as the API key, or as the password if the app does not use token authentication.",
"apiKeyNone": "No API key. Generate one to connect an app to this player.",
"apiKeyNoneOther": "No API key.",
"apiKeyPending": "Copy this key now. It is saved when you click Save and will not be shown again.",
"apiKeyRevokePending": "The API key will be removed when you save.",
"deleteWithKeyTitle": "Delete player",
"deleteWithKeyContent": "This player has an API key. Apps using it will stop working."
},
"notifications": {
"apiKeyCopied": "API key copied to clipboard"
},
"validation": {
"apiKeyFormat": "Invalid API key format"
}
},
"transcoding": {

View file

@ -102,9 +102,11 @@ const CustomUserMenu = ({ onClick, ...rest }) => {
}
const renderSettingsMenuItemLink = (resource, id) => {
const label = translate(`resources.${resource.name}.name`, {
smart_count: id ? 1 : 2,
})
const label = resource.options.label
? translate(resource.options.label)
: translate(`resources.${resource.name}.name`, {
smart_count: id ? 1 : 2,
})
const link = id ? `/${resource.name}/${id}` : `/${resource.name}`
return (
<MenuItemLink

View file

@ -9,11 +9,14 @@ import config from '../config'
let store
const mocks = vi.hoisted(() => ({ resources: [] }))
vi.mock('react-admin', () => ({
AppBar: ({ userMenu }) => <div data-testid="appbar">{userMenu}</div>,
MenuItemLink: ({ primaryText }) => <div>{primaryText}</div>,
useTranslate: () => (x) => x,
usePermissions: () => ({ permissions: 'admin' }),
getResources: () => [],
getResources: () => mocks.resources,
}))
vi.mock('./NowPlayingPanel', () => ({
@ -41,6 +44,7 @@ describe('<AppBar />', () => {
config.devActivityPanel = true
config.enableNowPlaying = true
config.enableQuickConnect = false
mocks.resources = []
store = createStore(combineReducers({ activity: activityReducer }), {
activity: { nowPlayingCount: 0 },
})
@ -84,4 +88,22 @@ describe('<AppBar />', () => {
expect(screen.queryAllByText('menu.quickConnect.name')).toHaveLength(0)
expect(screen.queryAllByText('menu.about')).not.toHaveLength(0)
})
it('uses the resource label for settings items when set', () => {
mocks.resources = [
{
name: 'player',
hasList: true,
options: { subMenu: 'settings', label: 'resources.player.menuName' },
},
{ name: 'transcoding', hasList: true, options: { subMenu: 'settings' } },
]
render(
<Provider store={store}>
<AppBar />
</Provider>,
)
expect(screen.getByText('resources.player.menuName')).toBeInTheDocument()
expect(screen.getByText('resources.transcoding.name')).toBeInTheDocument()
})
})

View file

@ -1,11 +1,26 @@
import React from 'react'
import { Notification as RANotification } from 'react-admin'
import { makeStyles } from '@material-ui/core/styles'
const Notification = (props) => (
<RANotification
{...props}
anchorOrigin={{ vertical: 'top', horizontal: 'center' }}
/>
// RA's primary.light Undo is unreadable on the light snackbar of dark themes
const useStyles = makeStyles(
{
undo: {
color: 'inherit',
},
},
{ name: 'NDNotification' },
)
const Notification = (props) => {
const classes = useStyles()
return (
<RANotification
{...props}
classes={{ undo: classes.undo }}
anchorOrigin={{ vertical: 'top', horizontal: 'center' }}
/>
)
}
export default Notification

View file

@ -6,7 +6,6 @@ import {
BooleanInput,
required,
SaveButton,
DateField,
useTranslate,
useMutation,
useNotify,
@ -16,8 +15,13 @@ import {
import { Typography, Box } from '@material-ui/core'
import { makeStyles } from '@material-ui/core/styles'
import DeleteLibraryButton from './DeleteLibraryButton'
import { Title } from '../common'
import { formatBytes, formatDuration2, formatNumber } from '../utils/index.js'
import {
ReadOnlyDateField,
ReadOnlyDurationField,
ReadOnlyNumberField,
ReadOnlySizeField,
Title,
} from '../common'
const useStyles = makeStyles({
toolbar: {
@ -26,6 +30,8 @@ const useStyles = makeStyles({
},
})
const readOnlyProps = { resource: 'library', fullWidth: true }
const LibraryTitle = ({ record }) => {
const translate = useTranslate()
const resourceName = translate('resources.library.name', { smart_count: 1 })
@ -125,132 +131,40 @@ const LibraryEdit = (props) => {
{translate('resources.library.sections.statistics')}
</Typography>
<Box display="flex">
<Box flex={1} mr="0.5em">
<TextInput
InputProps={{ readOnly: true }}
resource={'library'}
source={'totalSongs'}
label={translate('resources.library.fields.totalSongs')}
fullWidth
variant="outlined"
/>
</Box>
<Box flex={1} ml="0.5em">
<TextInput
InputProps={{ readOnly: true }}
resource={'library'}
source={'totalAlbums'}
label={translate(
'resources.library.fields.totalAlbums',
)}
fullWidth
variant="outlined"
/>
</Box>
</Box>
<Box display="flex">
<Box flex={1} mr="0.5em">
<TextInput
InputProps={{ readOnly: true }}
resource={'library'}
source={'totalArtists'}
label={translate(
'resources.library.fields.totalArtists',
)}
fullWidth
variant="outlined"
/>
</Box>
<Box flex={1} ml="0.5em">
<TextInput
InputProps={{ readOnly: true }}
resource={'library'}
source={'totalSize'}
label={translate('resources.library.fields.totalSize')}
format={(v) => formatBytes(v, 2)}
fullWidth
variant="outlined"
/>
</Box>
</Box>
<Box display="flex">
<Box flex={1} mr="0.5em">
<TextInput
InputProps={{ readOnly: true }}
resource={'library'}
source={'totalDuration'}
label={translate(
'resources.library.fields.totalDuration',
)}
format={formatDuration2}
fullWidth
variant="outlined"
/>
</Box>
<Box flex={1} ml="0.5em">
<TextInput
InputProps={{ readOnly: true }}
resource={'library'}
source={'totalMissingFiles'}
label={translate(
'resources.library.fields.totalMissingFiles',
)}
fullWidth
variant="outlined"
/>
</Box>
</Box>
{/* Timestamps Section */}
<Box mb="1em">
<Typography
variant="body2"
color="textSecondary"
gutterBottom
>
{translate('resources.library.fields.lastScanAt')}
</Typography>
<DateField
variant="body1"
source="lastScanAt"
showTime
record={formProps.record}
<Box
display="grid"
gridTemplateColumns="1fr 1fr"
gridColumnGap="1em"
>
<ReadOnlyNumberField
source="totalSongs"
{...readOnlyProps}
/>
</Box>
<Box mb="1em">
<Typography
variant="body2"
color="textSecondary"
gutterBottom
>
{translate('resources.library.fields.updatedAt')}
</Typography>
<DateField
variant="body1"
source="updatedAt"
showTime
record={formProps.record}
<ReadOnlyNumberField
source="totalAlbums"
{...readOnlyProps}
/>
</Box>
<Box mb="2em">
<Typography
variant="body2"
color="textSecondary"
gutterBottom
>
{translate('resources.library.fields.createdAt')}
</Typography>
<DateField
variant="body1"
source="createdAt"
showTime
record={formProps.record}
<ReadOnlyNumberField
source="totalArtists"
{...readOnlyProps}
/>
<ReadOnlySizeField source="totalSize" {...readOnlyProps} />
<ReadOnlyDurationField
source="totalDuration"
{...readOnlyProps}
/>
<ReadOnlyNumberField
source="totalMissingFiles"
{...readOnlyProps}
/>
<Box gridColumn="1 / -1">
<ReadOnlyDateField
source="lastScanAt"
{...readOnlyProps}
/>
</Box>
<ReadOnlyDateField source="updatedAt" {...readOnlyProps} />
<ReadOnlyDateField source="createdAt" {...readOnlyProps} />
</Box>
</Box>
</Box>

View file

@ -0,0 +1,107 @@
import React from 'react'
import PropTypes from 'prop-types'
import { useInput, useNotify, useTranslate } from 'react-admin'
import { Button, TextField } from '@material-ui/core'
import { FaKey } from 'react-icons/fa'
import { MdContentCopy, MdDelete, MdRefresh } from 'react-icons/md'
import { isWritable } from '../common/playlistUtils'
import { generateApiKey } from './apiKey'
const identity = (v) => v
const MASK = '•'.repeat(26)
const ApiKeyInput = ({ record, isCreate, fullWidth, className, ...props }) => {
const translate = useTranslate()
const notify = useNotify()
// Identity format/parse keep "" (revoke) distinct from undefined (untouched)
const {
input: { value, onChange },
meta: { error, touched },
} = useInput({ ...props, format: identity, parse: identity })
const isOwner = isCreate || record?.userId === localStorage.getItem('userId')
const pending = !!value
const revoking = value === '' && !!record?.hasApiKey
const saved = value == null && !!record?.hasApiKey
const hasKey = pending || saved
const copy = () => {
const fallback = () =>
prompt(translate('message.shareCopyToClipboard'), value)
if (navigator.clipboard && window.isSecureContext) {
navigator.clipboard
.writeText(value)
.then(
() => notify('resources.player.notifications.apiKeyCopied'),
fallback,
)
} else {
fallback()
}
}
const helperText = pending
? 'resources.player.message.apiKeyPending'
: revoking
? 'resources.player.message.apiKeyRevokePending'
: saved
? 'resources.player.message.apiKeyActive'
: isOwner
? 'resources.player.message.apiKeyNone'
: 'resources.player.message.apiKeyNoneOther'
return (
<div>
<TextField
label={translate('resources.player.fields.hasApiKey')}
value={pending ? value : saved ? MASK : ''}
variant="outlined"
margin="dense"
fullWidth={fullWidth}
className={className}
// Monospace keeps the whole key visible in a standard-width input
inputProps={{
style: { fontFamily: 'monospace', fontSize: '0.875rem' },
}}
InputProps={{ readOnly: true }}
error={!!(touched && error)}
helperText={translate(touched && error ? error : helperText)}
/>
<div>
{pending && (
<Button startIcon={<MdContentCopy />} onClick={copy}>
{translate('resources.player.actions.copyApiKey')}
</Button>
)}
{isOwner && (
<Button
startIcon={hasKey ? <MdRefresh /> : <FaKey />}
onClick={() => onChange(generateApiKey())}
>
{translate(
hasKey
? 'resources.player.actions.regenerateApiKey'
: 'resources.player.actions.generateApiKey',
)}
</Button>
)}
{saved && isWritable(record?.userId) && (
<Button startIcon={<MdDelete />} onClick={() => onChange('')}>
{translate('resources.player.actions.revokeApiKey')}
</Button>
)}
</div>
</div>
)
}
ApiKeyInput.propTypes = {
source: PropTypes.string.isRequired,
record: PropTypes.object,
isCreate: PropTypes.bool,
fullWidth: PropTypes.bool,
className: PropTypes.string,
validate: PropTypes.oneOfType([PropTypes.func, PropTypes.array]),
}
export default ApiKeyInput

View file

@ -0,0 +1,172 @@
import * as React from 'react'
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
import { Form } from 'react-final-form'
import { describe, it, expect, vi, beforeEach } from 'vitest'
import ApiKeyInput from './ApiKeyInput'
const hooks = vi.hoisted(() => ({ notify: vi.fn() }))
const KEY = 'nds_0123456789abcdefghijkl'
const KEY_FORMAT = /^nds_[0-9A-Za-z]{22}$/
vi.mock('react-admin', async () => {
const actual = await vi.importActual('react-admin')
return {
...actual,
useNotify: () => hooks.notify,
useTranslate: () => (key) => key,
}
})
const renderInput = ({
record,
initialValues = {},
isCreate = false,
fullWidth,
}) => {
let values
const utils = render(
<Form
onSubmit={() => {}}
initialValues={initialValues}
render={({ values: v }) => {
values = v
return (
<ApiKeyInput
source="apiKey"
record={record}
isCreate={isCreate}
fullWidth={fullWidth}
/>
)
}}
/>,
)
return { ...utils, values: () => values }
}
const text = (key) => screen.queryByText(key)
describe('ApiKeyInput', () => {
beforeEach(() => {
vi.clearAllMocks()
localStorage.setItem('userId', 'owner')
localStorage.setItem('role', 'regular')
})
it('shows a pending key with copy and regenerate on create', () => {
const { values } = renderInput({
record: {},
isCreate: true,
initialValues: { apiKey: KEY },
})
expect(screen.getByDisplayValue(KEY)).toBeInTheDocument()
expect(text('resources.player.message.apiKeyPending')).toBeInTheDocument()
expect(
screen.getByRole('button', {
name: 'resources.player.actions.copyApiKey',
}),
).toBeInTheDocument()
expect(
text('resources.player.actions.revokeApiKey'),
).not.toBeInTheDocument()
fireEvent.click(
screen.getByText('resources.player.actions.regenerateApiKey'),
)
expect(values().apiKey).toMatch(KEY_FORMAT)
expect(values().apiKey).not.toBe(KEY)
})
it('masks a saved key and lets the owner regenerate or revoke', () => {
const { values } = renderInput({
record: { id: 'p1', userId: 'owner', hasApiKey: true },
})
expect(screen.queryByDisplayValue(/^nds_/)).not.toBeInTheDocument()
expect(text('resources.player.message.apiKeyActive')).toBeInTheDocument()
expect(
text('resources.player.actions.regenerateApiKey'),
).toBeInTheDocument()
fireEvent.click(screen.getByText('resources.player.actions.revokeApiKey'))
expect(values().apiKey).toBe('')
expect(
text('resources.player.message.apiKeyRevokePending'),
).toBeInTheDocument()
expect(text('resources.player.actions.generateApiKey')).toBeInTheDocument()
})
it('lets the owner generate a key when there is none', () => {
const { values } = renderInput({
record: { id: 'p1', userId: 'owner', hasApiKey: false },
})
expect(values().apiKey).toBeUndefined()
expect(text('resources.player.message.apiKeyNone')).toBeInTheDocument()
fireEvent.click(screen.getByText('resources.player.actions.generateApiKey'))
expect(values().apiKey).toMatch(KEY_FORMAT)
expect(text('resources.player.message.apiKeyPending')).toBeInTheDocument()
})
it('lets an admin revoke but not set a key on another user player', () => {
localStorage.setItem('role', 'admin')
renderInput({ record: { id: 'p1', userId: 'someone', hasApiKey: true } })
expect(
text('resources.player.actions.regenerateApiKey'),
).not.toBeInTheDocument()
expect(text('resources.player.actions.revokeApiKey')).toBeInTheDocument()
})
it('falls back to a prompt when the clipboard write fails', async () => {
vi.stubGlobal('isSecureContext', true)
vi.stubGlobal('prompt', vi.fn())
Object.defineProperty(navigator, 'clipboard', {
configurable: true,
value: { writeText: vi.fn().mockRejectedValue(new Error('denied')) },
})
try {
renderInput({
record: {},
isCreate: true,
initialValues: { apiKey: KEY },
})
fireEvent.click(
screen.getByRole('button', {
name: 'resources.player.actions.copyApiKey',
}),
)
await waitFor(() =>
expect(window.prompt).toHaveBeenCalledWith(
'message.shareCopyToClipboard',
KEY,
),
)
expect(hooks.notify).not.toHaveBeenCalled()
} finally {
vi.unstubAllGlobals()
delete navigator.clipboard
}
})
it('shows a neutral message to an admin viewing another user player with no key', () => {
localStorage.setItem('role', 'admin')
renderInput({ record: { id: 'p1', userId: 'someone', hasApiKey: false } })
expect(text('resources.player.message.apiKeyNoneOther')).toBeInTheDocument()
expect(text('resources.player.message.apiKeyNone')).not.toBeInTheDocument()
expect(screen.queryAllByRole('button')).toHaveLength(0)
})
it('shows no actions to another regular user', () => {
renderInput({ record: { id: 'p1', userId: 'someone', hasApiKey: true } })
expect(screen.queryAllByRole('button')).toHaveLength(0)
})
it('is not full width unless asked', () => {
const record = { id: 'p1', userId: 'owner', hasApiKey: true }
const { container, unmount } = renderInput({ record })
expect(container.querySelector('.MuiFormControl-fullWidth')).toBeNull()
unmount()
const { container: wide } = renderInput({ record, fullWidth: true })
expect(wide.querySelector('.MuiFormControl-fullWidth')).not.toBeNull()
})
})

View file

@ -0,0 +1,33 @@
import React, { useMemo } from 'react'
import { Create, SimpleForm, required, useTranslate } from 'react-admin'
import { Title } from '../common'
import { playerInputs } from './playerInputs'
import ApiKeyInput from './ApiKeyInput'
import { generateApiKey } from './apiKey'
const PlayerCreateTitle = () => {
const translate = useTranslate()
const resourceName = translate('resources.player.name', { smart_count: 1 })
return (
<Title subTitle={translate('ra.page.create', { name: resourceName })} />
)
}
const PlayerCreate = (props) => {
// Memoized so re-renders don't swap the key the user may have already copied
const initialValues = useMemo(() => ({ apiKey: generateApiKey() }), [])
return (
<Create title={<PlayerCreateTitle />} {...props}>
<SimpleForm
variant="outlined"
redirect="list"
initialValues={initialValues}
>
{playerInputs()}
<ApiKeyInput source="apiKey" isCreate validate={required()} />
</SimpleForm>
</Create>
)
}
export default PlayerCreate

View file

@ -0,0 +1,47 @@
import * as React from 'react'
import { render } from '@testing-library/react'
import { describe, it, expect, vi, beforeEach } from 'vitest'
import PlayerCreate from './PlayerCreate'
import ApiKeyInput from './ApiKeyInput'
const hooks = vi.hoisted(() => ({ forms: [] }))
vi.mock('react-admin', async () => {
const actual = await vi.importActual('react-admin')
return {
...actual,
Create: ({ children }) => children,
SimpleForm: (props) => {
hooks.forms.push(props)
return null
},
}
})
describe('PlayerCreate', () => {
beforeEach(() => {
hooks.forms = []
})
it('pre-fills one generated API key that survives re-renders', () => {
const { rerender } = render(<PlayerCreate resource="player" />)
rerender(<PlayerCreate resource="player" />)
const [first, second] = hooks.forms.map((f) => f.initialValues)
expect(hooks.forms).toHaveLength(2)
expect(first.apiKey).toMatch(/^nds_[0-9A-Za-z]{22}$/)
expect(second).toBe(first)
})
it('requires the API key', () => {
render(<PlayerCreate resource="player" />)
const input = React.Children.toArray(hooks.forms[0].children).find(
(child) => child.type === ApiKeyInput,
)
expect(input.props.source).toBe('apiKey')
expect(input.props.isCreate).toBe(true)
expect(input.props.validate('')).toBeTruthy()
expect(input.props.validate('nds_0123456789abcdefghijkl')).toBeUndefined()
})
})

View file

@ -1,17 +1,16 @@
import {
TextInput,
BooleanInput,
TextField,
Edit,
required,
SimpleForm,
SelectInput,
ReferenceInput,
useTranslate,
DeleteButton,
DeleteWithConfirmButton,
SaveButton,
Toolbar,
} from 'react-admin'
import { Title } from '../common'
import config from '../config'
import { BITRATE_CHOICES } from '../consts'
import { makeStyles } from '@material-ui/core/styles'
import { ReadOnlyTextField, Title } from '../common'
import ApiKeyInput from './ApiKeyInput'
import { playerInputs } from './playerInputs'
const PlayerTitle = ({ record }) => {
const translate = useTranslate()
@ -19,24 +18,35 @@ const PlayerTitle = ({ record }) => {
return <Title subTitle={`${resourceName} ${record ? record.name : ''}`} />
}
const useToolbarStyles = makeStyles({
toolbar: {
display: 'flex',
justifyContent: 'space-between',
},
})
const PlayerEditToolbar = (props) => (
<Toolbar {...props} classes={useToolbarStyles()}>
<SaveButton />
{props.record?.hasApiKey ? (
<DeleteWithConfirmButton
mutationMode="pessimistic"
confirmTitle="resources.player.message.deleteWithKeyTitle"
confirmContent="resources.player.message.deleteWithKeyContent"
/>
) : (
<DeleteButton />
)}
</Toolbar>
)
const PlayerEdit = (props) => (
<Edit title={<PlayerTitle />} {...props}>
<SimpleForm variant={'outlined'}>
<TextInput source="name" validate={[required()]} />
<ReferenceInput
source="transcodingId"
reference="transcoding"
sort={{ field: 'name', order: 'ASC' }}
>
<SelectInput source="name" resettable />
</ReferenceInput>
<SelectInput source="maxBitRate" resettable choices={BITRATE_CHOICES} />
<BooleanInput source="reportRealPath" fullWidth />
{(config.lastFMEnabled || config.listenBrainzEnabled) && (
<BooleanInput source="scrobbleEnabled" fullWidth />
)}
<TextField source="client" />
<TextField source="userName" />
<Edit title={<PlayerTitle />} mutationMode="pessimistic" {...props}>
<SimpleForm variant={'outlined'} toolbar={<PlayerEditToolbar />}>
{playerInputs()}
<ReadOnlyTextField source="client" />
<ReadOnlyTextField source="userName" />
<ApiKeyInput source="apiKey" />
</SimpleForm>
</Edit>
)

View file

@ -0,0 +1,25 @@
import * as React from 'react'
import { render } from '@testing-library/react'
import { describe, it, expect, vi } from 'vitest'
import PlayerEdit from './PlayerEdit'
const hooks = vi.hoisted(() => ({ editProps: null }))
vi.mock('react-admin', async () => {
const actual = await vi.importActual('react-admin')
return {
...actual,
Edit: (props) => {
hooks.editProps = props
return null
},
}
})
describe('PlayerEdit', () => {
// An optimistic or undoable save would put the new key in react-admin's cache
it('saves pessimistically', () => {
render(<PlayerEdit resource="player" id="p1" />)
expect(hooks.editProps.mutationMode).toBe('pessimistic')
})
})

View file

@ -2,18 +2,20 @@ import React from 'react'
import {
Datagrid,
TextField,
DateField,
FunctionField,
ReferenceField,
Filter,
SearchInput,
NullableBooleanInput,
} from 'react-admin'
import { useMediaQuery } from '@material-ui/core'
import { SimpleList, List } from '../common'
import { FaKey } from 'react-icons/fa'
import { SimpleList, List, DateField } from '../common'
const PlayerFilter = (props) => (
<Filter {...props} variant={'outlined'}>
<SearchInput id="search" source="name" alwaysOn />
<NullableBooleanInput source="hasApiKey" alwaysOn />
</Filter>
)
@ -30,7 +32,11 @@ const PlayerList = ({ permissions, ...props }) => {
<SimpleList
primaryText={(r) => r.name}
secondaryText={(r) => r.userName}
tertiaryText={(r) => (r.maxBitRate ? r.maxBitRate : '-')}
tertiaryText={(r) => (
<>
{r.hasApiKey && <FaKey />} {r.maxBitRate ? r.maxBitRate : '-'}
</>
)}
/>
) : (
<Datagrid rowClick="edit">
@ -43,6 +49,11 @@ const PlayerList = ({ permissions, ...props }) => {
source="maxBitRate"
render={(r) => (r.maxBitRate ? r.maxBitRate : '-')}
/>
<FunctionField
source="hasApiKey"
sortable={false}
render={(r) => (r.hasApiKey ? <FaKey /> : null)}
/>
<DateField source="lastSeen" showTime sortByOrder={'DESC'} />
</Datagrid>
)}

15
ui/src/player/apiKey.js Normal file
View file

@ -0,0 +1,15 @@
const API_KEY_PREFIX = 'nds_'
const ALPHABET =
'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
const KEY_LENGTH = 22
// Bytes >= 248 are dropped so every character is equally likely (248 = 4 * 62).
export const generateApiKey = () => {
let key = ''
while (key.length < KEY_LENGTH) {
for (const b of window.crypto.getRandomValues(new Uint8Array(32))) {
if (b < 248 && key.length < KEY_LENGTH) key += ALPHABET[b % 62]
}
}
return API_KEY_PREFIX + key
}

View file

@ -0,0 +1,15 @@
import { describe, it, expect } from 'vitest'
import { generateApiKey } from './apiKey'
describe('generateApiKey', () => {
it('returns the prefix plus 22 base62 characters', () => {
for (let i = 0; i < 50; i++) {
expect(generateApiKey()).toMatch(/^nds_[0-9A-Za-z]{22}$/)
}
})
it('returns a different key each time', () => {
const keys = new Set(Array.from({ length: 100 }, generateApiKey))
expect(keys.size).toBe(100)
})
})

View file

@ -1,9 +1,11 @@
import { BsFillMusicPlayerFill } from 'react-icons/bs'
import PlayerList from './PlayerList'
import PlayerEdit from './PlayerEdit'
import PlayerCreate from './PlayerCreate'
export default {
list: PlayerList,
edit: PlayerEdit,
create: PlayerCreate,
icon: BsFillMusicPlayerFill,
}

View file

@ -0,0 +1,34 @@
import React from 'react'
import {
BooleanInput,
ReferenceInput,
SelectInput,
TextInput,
required,
} from 'react-admin'
import config from '../config'
import { BITRATE_CHOICES } from '../consts'
// Returned as an array, not a component, so SimpleForm still injects its props into each input.
export const playerInputs = () =>
[
<TextInput key="name" source="name" validate={[required()]} />,
<ReferenceInput
key="transcodingId"
source="transcodingId"
reference="transcoding"
sort={{ field: 'name', order: 'ASC' }}
>
<SelectInput source="name" resettable />
</ReferenceInput>,
<SelectInput
key="maxBitRate"
source="maxBitRate"
resettable
choices={BITRATE_CHOICES}
/>,
<BooleanInput key="reportRealPath" source="reportRealPath" fullWidth />,
(config.lastFMEnabled || config.listenBrainzEnabled) && (
<BooleanInput key="scrobbleEnabled" source="scrobbleEnabled" fullWidth />
),
].filter(Boolean)

View file

@ -3,7 +3,6 @@ import {
FormDataConsumer,
SimpleForm,
TextInput,
TextField,
BooleanInput,
required,
useTranslate,
@ -11,13 +10,14 @@ import {
ReferenceInput,
SelectInput,
} from 'react-admin'
import { isWritable, Title } from '../common'
import { isWritable, ReadOnlyTextField, Title } from '../common'
const SyncFragment = ({ formData, variant, ...rest }) => {
if (!formData.path) return null
return (
<>
{formData.path && <BooleanInput source="sync" {...rest} />}
{formData.path && <TextField source="path" {...rest} />}
<BooleanInput source="sync" {...rest} />
<ReadOnlyTextField source="path" {...rest} />
</>
)
}
@ -56,10 +56,10 @@ const PlaylistEditForm = (props) => {
/>
</ReferenceInput>
) : (
<TextField source="ownerName" />
<ReadOnlyTextField source="ownerName" />
)}
<BooleanInput source="public" disabled={!isWritable(record.ownerId)} />
<FormDataConsumer>
<FormDataConsumer fullWidth>
{(formDataProps) => <SyncFragment {...formDataProps} />}
</FormDataConsumer>
</SimpleForm>

View file

@ -67,15 +67,15 @@ const PlaylistFilter = (props) => {
)
}
const TogglePublicInput = ({ resource, source }) => {
export const ToggleField = ({ resource, source }) => {
const record = useRecordContext()
const notify = useNotify()
const [togglePublic] = useUpdate(
const [toggle] = useUpdate(
resource,
record.id,
record?.id,
{
...record,
public: !record.public,
[source]: !record?.[source],
},
{
undoable: false,
@ -86,10 +86,12 @@ const TogglePublicInput = ({ resource, source }) => {
)
const handleClick = (e) => {
togglePublic()
toggle()
e.stopPropagation()
}
if (!record) return null
return (
<Switch
checked={record[source]}
@ -99,35 +101,9 @@ const TogglePublicInput = ({ resource, source }) => {
)
}
const ToggleAutoImport = ({ resource, source }) => {
export const ToggleAutoImport = (props) => {
const record = useRecordContext()
const notify = useNotify()
const [ToggleAutoImport] = useUpdate(
resource,
record.id,
{
...record,
sync: !record.sync,
},
{
undoable: false,
onFailure: (error) => {
notify('ra.page.error', 'warning')
},
},
)
const handleClick = (e) => {
ToggleAutoImport()
e.stopPropagation()
}
return record.path ? (
<Switch
checked={record[source]}
onClick={handleClick}
disabled={!isWritable(record.ownerId)}
/>
) : null
return record?.path ? <ToggleField {...props} /> : null
}
const PlaylistListBulkActions = (props) => {
@ -169,9 +145,7 @@ const PlaylistList = (props) => {
updatedAt: isDesktop && (
<DateField source="updatedAt" sortByOrder={'DESC'} />
),
public: !isXsmall && (
<TogglePublicInput source="public" sortByOrder={'DESC'} />
),
public: !isXsmall && <ToggleField source="public" sortByOrder={'DESC'} />,
comment: <TextField source="comment" />,
sync: !isXsmall && (
<ToggleAutoImport source="sync" sortByOrder={'DESC'} />

View file

@ -1,7 +1,8 @@
import React from 'react'
import { render, screen } from '@testing-library/react'
import { describe, it, expect, vi } from 'vitest'
import { PlaylistLove } from './PlaylistList'
import { TestContext } from 'ra-test'
import { PlaylistLove, ToggleField, ToggleAutoImport } from './PlaylistList'
vi.mock('../config', () => ({
default: { enableFavourites: true },
@ -32,3 +33,25 @@ describe('<PlaylistLove />', () => {
})
})
})
// react-admin evicts records older than 10 minutes while the list still holds
// their ids, so rows can render with no record.
describe('playlist toggles without a record', () => {
it('<ToggleField /> renders nothing', () => {
const { container } = render(
<TestContext>
<ToggleField resource="playlist" source="public" />
</TestContext>,
)
expect(container.innerHTML).toBe('')
})
it('<ToggleAutoImport /> renders nothing', () => {
const { container } = render(
<TestContext>
<ToggleAutoImport resource="playlist" source="sync" />
</TestContext>,
)
expect(container.innerHTML).toBe('')
})
})

View file

@ -1,5 +1,4 @@
import {
DateField,
Edit,
required,
SimpleForm,
@ -9,7 +8,12 @@ import {
import { CardMedia } from '@material-ui/core'
import { makeStyles } from '@material-ui/core/styles'
import { urlValidate } from '../utils/validations'
import { Title, ImageUploadOverlay, useImageLoadingState } from '../common'
import {
Title,
ImageUploadOverlay,
ReadOnlyDateField,
useImageLoadingState,
} from '../common'
import subsonic from '../subsonic'
import config from '../config'
import { RADIO_PLACEHOLDER_IMAGE } from '../consts'
@ -65,8 +69,8 @@ const RadioEdit = (props) => {
fullWidth
validate={[urlValidate]}
/>
<DateField variant="body1" source="updatedAt" showTime />
<DateField variant="body1" source="createdAt" showTime />
<ReadOnlyDateField source="updatedAt" />
<ReadOnlyDateField source="createdAt" />
</SimpleForm>
</Edit>
)

View file

@ -2,13 +2,16 @@ import {
DateTimeInput,
BooleanInput,
Edit,
NumberField,
SimpleForm,
TextInput,
} from 'react-admin'
import { sharePlayerUrl } from '../utils'
import { Link } from '@material-ui/core'
import { DateField } from '../common'
import {
ReadOnlyDateField,
ReadOnlyNumberField,
ReadOnlyTextField,
} from '../common'
import config from '../config'
export const ShareEdit = (props) => {
@ -16,20 +19,26 @@ export const ShareEdit = (props) => {
const url = sharePlayerUrl(id)
return (
<Edit {...props}>
<SimpleForm {...rest}>
<Link source="URL" href={url} target="_blank" rel="noopener noreferrer">
<SimpleForm variant={'outlined'} {...rest}>
<Link
source="URL"
href={url}
target="_blank"
rel="noopener noreferrer"
variant="inherit"
>
{url}
</Link>
<TextInput source="description" />
{config.enableDownloads && <BooleanInput source="downloadable" />}
<DateTimeInput source="expiresAt" />
<TextInput source="contents" disabled />
<TextInput source="format" disabled />
<TextInput source="maxBitRate" disabled />
<TextInput source="username" disabled />
<NumberField source="visitCount" disabled />
<DateField source="lastVisitedAt" disabled showTime />
<DateField source="createdAt" disabled showTime />
<ReadOnlyTextField source="contents" />
<ReadOnlyTextField source="format" />
<ReadOnlyTextField source="maxBitRate" />
<ReadOnlyTextField source="username" />
<ReadOnlyNumberField source="visitCount" />
<ReadOnlyDateField source="lastVisitedAt" />
<ReadOnlyDateField source="createdAt" />
</SimpleForm>
</Edit>
)

View file

@ -79,6 +79,16 @@ export default {
color: '#eee',
backgroundColor: '#ff4e6b',
},
containedPrimary: {
color: '#fff',
backgroundColor: '#D60017',
'&:hover': {
backgroundColor: '#a30011',
'@media (hover: none)': {
backgroundColor: '#D60017',
},
},
},
textSizeSmall: {
fontSize: '0.8rem',
paddingRight: '0.5rem',
@ -192,6 +202,11 @@ export default {
paddingBottom: '1rem',
},
},
NDNotification: {
undo: {
color: '#fff',
},
},
RaConfirm: {
confirmPrimary: {
color: '#fff',

View file

@ -86,6 +86,13 @@ export default {
},
},
},
NDNotification: {
undo: {
'& .MuiButton-label': {
color: 'inherit',
},
},
},
MuiChip: {
root: {
backgroundColor: nukeCol['accent'],

View file

@ -3,7 +3,6 @@ import { makeStyles } from '@material-ui/core/styles'
import {
TextInput,
BooleanInput,
DateField,
PasswordInput,
Edit,
required,
@ -21,7 +20,7 @@ import {
useRecordContext,
} from 'react-admin'
import { Typography } from '@material-ui/core'
import { Title } from '../common'
import { ReadOnlyDateField, Title } from '../common'
import DeleteUserButton from './DeleteUserButton'
import { LibrarySelectionField } from './LibrarySelectionField.jsx'
import { validateUserForm } from './userValidation'
@ -183,10 +182,10 @@ const UserEdit = (props) => {
helperText={translate('resources.user.helperTexts.scrobbleFilter')}
/>
<DateField variant="body1" source="lastLoginAt" showTime />
<DateField variant="body1" source="lastAccessAt" showTime />
<DateField variant="body1" source="updatedAt" showTime />
<DateField variant="body1" source="createdAt" showTime />
<ReadOnlyDateField source="lastLoginAt" />
<ReadOnlyDateField source="lastAccessAt" />
<ReadOnlyDateField source="updatedAt" />
<ReadOnlyDateField source="createdAt" />
</SimpleForm>
</Edit>
)

View file

@ -51,9 +51,6 @@ vi.mock('react-admin', () => ({
BooleanInput: ({ source }) => (
<input type="checkbox" data-testid={`boolean-input-${source}`} />
),
DateField: ({ source }) => (
<div data-testid={`date-field-${source}`}>Date</div>
),
PasswordInput: ({ source }) => (
<input type="password" data-testid={`password-input-${source}`} />
),
@ -82,6 +79,9 @@ vi.mock('./DeleteUserButton', () => ({
vi.mock('../common', () => ({
Title: ({ subTitle }) => <div data-testid="title">{subTitle}</div>,
ReadOnlyDateField: ({ source }) => (
<div data-testid={`date-field-${source}`}>Date</div>
),
}))
// Mock Material-UI