feat(podcast): add podcast feature with UX improvements - #5420

Backend
- Add podcast data model (PodcastChannel, PodcastEpisode) with migrations
- Implement Subsonic API endpoints: getPodcasts, getNewestPodcasts,
  createPodcastChannel, refreshPodcasts, deletePodcastChannel,
  deletePodcastEpisode, downloadPodcastEpisode, getPodcastEpisode
- Add native REST API endpoints: GET/DELETE /api/podcast,
  GET /api/podcast/preview (feed info without creating channel)
- Inject events.Broker into podcast service for SSE support
- Emit PodcastEpisodeProgress SSE events during download (every 512 KB)
  and on completion/error with status field
- Use HTTP Content-Length as fallback when RSS feed omits enclosure size
- Write ID3 tags (title, album, genre=Podcast) to downloaded files via
  ffmpeg so the library scanner reads correct metadata
- Set MediaFile fields (Title, Album, AlbumID=channelId, AlbumArtist,
  Genre) on episode registration
- Add duplicate URL check in AddChannel
- Add ExistsByURL to PodcastChannelRepository

Frontend - Podcast list
- Add grid/list view toggle (Redux podcastViewReducer) matching album list
- New PodcastGridView component with responsive column count (2-6 cols)
- Cover image 100px in table view
- Remove Feed URL column; add inline copy-to-clipboard button

Frontend - Podcast show (episode list)
- Real-time download progress (%) in Status column via SSE, no polling
  - Spinner only before first SSE event; N% once data arrives
  - Size column removed; Downloading badge replaced with progress
- Completed episodes play on row click; separate play button removed
- Play / Shuffle / Play Next / Add to Queue buttons above episode list
  (only shown when completed episodes exist)
- On download completion, reload episodes to obtain streamId for
  immediate playback without page refresh
- Clicking album name in AudioTitle navigates to podcast channel page

Frontend - Podcast create
- Full-width URL input with Fetch Feed Info button and Enter key support
- Preview card (cover image, title, episode count, description) before
  committing channel creation
- Add Channel button appears only after preview; shows already-registered
  message if channel URL exists

Frontend - Playlist
- Album link navigates to podcast channel page for podcast tracks
  (identified by genre=Podcast)
- Artist column shows '-' for podcast tracks with empty artist field

Closes #5420

Signed-off-by: ji-ho lee <search5@gmail.com>
This commit is contained in:
Jiho Andrew Lee 2026-04-27 23:40:15 +09:00
commit 775747264b
50 changed files with 3769 additions and 36 deletions

View file

@ -19,6 +19,7 @@ import album from './album'
import artist from './artist'
import playlist from './playlist'
import radio from './radio'
import podcast from './podcast'
import share from './share'
import library from './library'
import plugin from './plugin'
@ -33,6 +34,7 @@ import {
saveQueueDialogReducer,
playerReducer,
albumViewReducer,
podcastViewReducer,
activityReducer,
settingsReducer,
replayGainReducer,
@ -69,6 +71,7 @@ const adminStore = createAdminStore({
library: libraryReducer,
player: playerReducer,
albumView: albumViewReducer,
podcastView: podcastViewReducer,
theme: themeReducer,
addToPlaylistDialog: addToPlaylistDialogReducer,
downloadMenuDialog: downloadMenuDialogReducer,
@ -131,6 +134,10 @@ const Admin = (props) => {
name="radio"
{...(permissions === 'admin' ? radio.admin : radio.all)}
/>,
<Resource
name="podcast"
{...(permissions === 'admin' ? podcast.admin : podcast.all)}
/>,
config.enableSharing && <Resource name="share" {...share} />,
<Resource
name="playlist"

View file

@ -2,6 +2,7 @@ export * from './library'
export * from './player'
export * from './themes'
export * from './albumView'
export * from './podcastView'
export * from './dialogs'
export * from './replayGain'
export * from './serverEvents'

View file

@ -0,0 +1,5 @@
export const PODCAST_MODE_GRID = 'PODCAST_GRID_MODE'
export const PODCAST_MODE_TABLE = 'PODCAST_TABLE_MODE'
export const podcastViewGrid = () => ({ type: PODCAST_MODE_GRID })
export const podcastViewTable = () => ({ type: PODCAST_MODE_TABLE })

View file

@ -49,9 +49,11 @@ const AudioTitle = React.memo(({ audioInfo, gainInfo, isMobile }) => {
const linkTo = audioInfo.isRadio
? `/radio/${audioInfo.trackId}/show`
: song.playlistId
? `/playlist/${song.playlistId}/show`
: `/album/${song.albumId}/show`
: song.isPodcast
? `/podcast/${song.channelId}/show`
: song.playlistId
? `/playlist/${song.playlistId}/show`
: `/album/${song.albumId}/show`
return (
<Link to={linkTo} className={className} ref={dragSongRef}>

View file

@ -24,6 +24,9 @@ const setupHandlers = (stream, dispatchFn) => {
stream.addEventListener('nowPlayingCount', eventHandler(dispatchFn))
}
stream.addEventListener('keepAlive', eventHandler(dispatchFn))
stream.addEventListener('podcastEpisodeProgress', (event) => {
window.dispatchEvent(new CustomEvent('podcastEpisodeProgress', { detail: JSON.parse(event.data) }))
})
stream.onerror = (e) => {
// eslint-disable-next-line no-console
console.log('EventStream error', e)
@ -80,6 +83,9 @@ const startEventStreamLegacy = async (dispatchFn) => {
newStream.addEventListener('nowPlayingCount', eventHandler(dispatchFn))
}
newStream.addEventListener('keepAlive', eventHandler(dispatchFn))
newStream.addEventListener('podcastEpisodeProgress', (event) => {
window.dispatchEvent(new CustomEvent('podcastEpisodeProgress', { detail: JSON.parse(event.data) }))
})
newStream.onerror = (e) => {
// eslint-disable-next-line no-console
console.log('EventStream error', e)

View file

@ -138,7 +138,8 @@
"actions": {
"topSongs": "Top Songs",
"shuffle": "Shuffle",
"radio": "Radio"
"radio": "Radio",
"podcast": "Podcasts"
}
},
"user": {
@ -251,6 +252,42 @@
"playNow": "Play Now"
}
},
"podcast": {
"name": "Podcast |||| Podcasts",
"fields": {
"title": "Title",
"url": "Feed URL",
"description": "Description",
"status": "Status",
"publishDate": "Published",
"duration": "Duration",
"episodeCount": "Episodes"
},
"actions": {
"refresh": "Refresh All",
"download": "Download",
"addChannel": "Add Channel",
"fetchFeed": "Fetch Feed Info",
"copyUrl": "Copy Feed URL"
},
"notifications": {
"refreshStarted": "Podcast refresh started",
"downloadStarted": "Download started",
"channelAdded": "Channel added",
"urlCopied": "Feed URL copied to clipboard",
"alreadyExists": "This channel is already registered.",
"channelDeleted": "Channel deleted",
"episodeDeleted": "Episode deleted"
},
"status": {
"new": "New",
"downloading": "Downloading",
"completed": "Downloaded",
"error": "Error",
"skipped": "Skipped",
"deleted": "Deleted"
}
},
"share": {
"name": "Share |||| Shares",
"fields": {

View file

@ -1,14 +1,15 @@
import React, { useCallback, useEffect, useMemo } from 'react'
import {
BulkActionsToolbar,
FunctionField,
Link,
ListToolbar,
TextField,
NumberField,
TextField,
useDataProvider,
useListContext,
useNotify,
useVersion,
useListContext,
FunctionField,
} from 'react-admin'
import clsx from 'clsx'
import { useDispatch } from 'react-redux'
@ -16,24 +17,53 @@ import { Card, useMediaQuery } from '@material-ui/core'
import { makeStyles } from '@material-ui/core/styles'
import ReactDragListView from 'react-drag-listview'
import {
ArtistLinkField,
DateField,
DurationField,
SongInfo,
QualityInfo,
RatingField,
SongContextMenu,
SongDatagrid,
SongInfo,
SongTitleField,
QualityInfo,
useSelectedFields,
useResourceRefresh,
DateField,
ArtistLinkField,
RatingField,
useSelectedFields,
} from '../common'
import { AlbumLinkField } from '../song/AlbumLinkField'
import { playTracks } from '../actions'
import { closeExtendedInfoDialog, playTracks } from '../actions'
import PlaylistSongBulkActions from './PlaylistSongBulkActions'
import ExpandInfoDialog from '../dialogs/ExpandInfoDialog'
import config from '../config'
const AlbumOrChannelLinkField = (props) => {
const dispatch = useDispatch()
const record = props.record
const isPodcast = record?.genre === 'Podcast'
const linkTo = isPodcast
? `/podcast/${record.albumId}/show`
: `/album/${record.albumId}/show`
return (
<Link
to={linkTo}
onClick={(e) => {
e.stopPropagation()
dispatch(closeExtendedInfoDialog())
}}
>
{record?.album}
</Link>
)
}
AlbumOrChannelLinkField.defaultProps = { addLabel: true, sortBy: 'album' }
const PodcastAwareArtistField = (props) => {
const record = props.record
if (record?.genre === 'Podcast' && !record?.artist) {
return <span>-</span>
}
return <ArtistLinkField {...props} />
}
PodcastAwareArtistField.defaultProps = { addLabel: true, sortBy: 'artist' }
const useStyles = makeStyles(
(theme) => ({
root: {},
@ -148,8 +178,8 @@ const PlaylistSongs = ({ playlistId, readOnly, actions, ...props }) => {
return {
trackNumber: isDesktop && <TextField source="id" label={'#'} />,
title: <SongTitleField source="title" showTrackNumbers={false} />,
album: isDesktop && <AlbumLinkField source="album" />,
artist: isDesktop && <ArtistLinkField source="artist" />,
album: isDesktop && <AlbumOrChannelLinkField source="album" />,
artist: isDesktop && <PodcastAwareArtistField source="artist" />,
albumArtist: isDesktop && <ArtistLinkField source="albumArtist" />,
duration: (
<DurationField source="duration" className={classes.draggable} />

View file

@ -0,0 +1,47 @@
import React from 'react'
import { IconButton, CircularProgress } from '@material-ui/core'
import GetAppIcon from '@material-ui/icons/GetApp'
import DeleteIcon from '@material-ui/icons/Delete'
import subsonic from '../subsonic'
const EpisodeActions = ({ episode, onRefresh }) => {
const handleDownload = async () => {
await subsonic.downloadPodcastEpisode(episode.id)
onRefresh?.()
}
const handleDelete = async () => {
await subsonic.deletePodcastEpisode(episode.id)
onRefresh?.()
}
if (episode.status === 'downloading') {
return <CircularProgress size={20} />
}
if (episode.status === 'completed') {
return (
<IconButton aria-label="delete" size="small" onClick={handleDelete}>
<DeleteIcon fontSize="small" />
</IconButton>
)
}
if (episode.status === 'new' || episode.status === 'error') {
return (
<>
<IconButton aria-label="download" size="small" onClick={handleDownload}>
<GetAppIcon fontSize="small" />
</IconButton>
<IconButton aria-label="delete" size="small" onClick={handleDelete}>
<DeleteIcon fontSize="small" />
</IconButton>
</>
)
}
return null
}
export default EpisodeActions

View file

@ -0,0 +1,83 @@
import React from 'react'
import { render, screen, fireEvent } from '@testing-library/react'
import { describe, it, expect, vi, beforeEach } from 'vitest'
vi.mock('../subsonic', () => ({
default: {
downloadPodcastEpisode: vi.fn().mockResolvedValue({}),
deletePodcastEpisode: vi.fn().mockResolvedValue({}),
},
}))
vi.mock('react-redux', () => ({
useDispatch: () => vi.fn(),
}))
import subsonic from '../subsonic'
import EpisodeActions from './EpisodeActions'
describe('EpisodeActions', () => {
const onRefresh = vi.fn()
beforeEach(() => {
vi.clearAllMocks()
})
it('shows play and delete buttons for completed episode', () => {
render(
<EpisodeActions episode={{ id: 'ep-1', status: 'completed' }} onRefresh={onRefresh} />,
)
expect(screen.getByLabelText('play')).toBeTruthy()
expect(screen.getByLabelText('delete')).toBeTruthy()
expect(screen.queryByLabelText('download')).toBeNull()
})
it('shows download and delete buttons for new episode', () => {
render(
<EpisodeActions episode={{ id: 'ep-1', status: 'new' }} onRefresh={onRefresh} />,
)
expect(screen.getByLabelText('download')).toBeTruthy()
expect(screen.getByLabelText('delete')).toBeTruthy()
expect(screen.queryByLabelText('play')).toBeNull()
})
it('shows download and delete buttons for error episode', () => {
render(
<EpisodeActions episode={{ id: 'ep-1', status: 'error' }} onRefresh={onRefresh} />,
)
expect(screen.getByLabelText('download')).toBeTruthy()
expect(screen.getByLabelText('delete')).toBeTruthy()
})
it('shows spinner only for downloading episode', () => {
render(
<EpisodeActions episode={{ id: 'ep-1', status: 'downloading' }} onRefresh={onRefresh} />,
)
expect(screen.getByRole('progressbar')).toBeTruthy()
expect(screen.queryByLabelText('play')).toBeNull()
expect(screen.queryByLabelText('download')).toBeNull()
})
it('renders nothing for deleted episode', () => {
const { container } = render(
<EpisodeActions episode={{ id: 'ep-1', status: 'deleted' }} onRefresh={onRefresh} />,
)
expect(container).toBeEmptyDOMElement()
})
it('calls downloadPodcastEpisode when download clicked', () => {
render(
<EpisodeActions episode={{ id: 'ep-1', status: 'new' }} onRefresh={onRefresh} />,
)
fireEvent.click(screen.getByLabelText('download'))
expect(subsonic.downloadPodcastEpisode).toHaveBeenCalledWith('ep-1')
})
it('calls deletePodcastEpisode when delete clicked on completed episode', () => {
render(
<EpisodeActions episode={{ id: 'ep-1', status: 'completed' }} onRefresh={onRefresh} />,
)
fireEvent.click(screen.getByLabelText('delete'))
expect(subsonic.deletePodcastEpisode).toHaveBeenCalledWith('ep-1')
})
})

View file

@ -0,0 +1,170 @@
import React, { useState } from 'react'
import { useTranslate, useNotify, useRedirect, useRefresh, Title } from 'react-admin'
import {
Avatar,
Card,
CardContent,
CircularProgress,
Divider,
InputAdornment,
TextField,
Typography,
makeStyles,
} from '@material-ui/core'
import { Button } from 'react-admin'
import MicIcon from '@material-ui/icons/Mic'
import SearchIcon from '@material-ui/icons/Search'
import AddIcon from '@material-ui/icons/Add'
import subsonic from '../subsonic'
const useStyles = makeStyles((theme) => ({
root: { marginTop: theme.spacing(2) },
urlRow: { display: 'flex', gap: theme.spacing(1), alignItems: 'flex-start' },
urlInput: { flex: 1 },
preview: {
marginTop: theme.spacing(3),
display: 'flex',
gap: theme.spacing(2),
alignItems: 'flex-start',
},
previewImage: { width: 120, height: 120, borderRadius: 4, flexShrink: 0 },
previewInfo: { flex: 1 },
previewTitle: { fontWeight: 600, marginBottom: theme.spacing(0.5) },
previewDesc: { color: theme.palette.text.secondary, marginBottom: theme.spacing(1) },
addButton: { marginTop: theme.spacing(2) },
}))
const PodcastCreate = () => {
const translate = useTranslate()
const notify = useNotify()
const redirect = useRedirect()
const refresh = useRefresh()
const classes = useStyles()
const [feedUrl, setFeedUrl] = useState('')
const [fetching, setFetching] = useState(false)
const [adding, setAdding] = useState(false)
const [preview, setPreview] = useState(null)
const title = translate('ra.page.create', {
name: translate('resources.podcast.name', { smart_count: 1 }),
})
const handleFetch = async () => {
if (!feedUrl) return
setFetching(true)
setPreview(null)
try {
const res = await subsonic.previewPodcastFeed(feedUrl)
setPreview(res.json)
} catch {
notify('ra.notification.http_error', { type: 'error' })
} finally {
setFetching(false)
}
}
const handleAdd = async () => {
setAdding(true)
try {
await subsonic.createPodcastChannel(feedUrl)
notify('resources.podcast.notifications.channelAdded')
redirect('/podcast')
refresh()
} catch {
notify('ra.notification.http_error', { type: 'error' })
} finally {
setAdding(false)
}
}
const handleKeyDown = (e) => {
if (e.key === 'Enter') {
e.preventDefault()
handleFetch()
}
}
return (
<Card className={classes.root}>
<Title subTitle={title} />
<CardContent>
<div className={classes.urlRow}>
<TextField
className={classes.urlInput}
label={translate('resources.podcast.fields.url')}
value={feedUrl}
onChange={(e) => { setFeedUrl(e.target.value); setPreview(null) }}
onKeyDown={handleKeyDown}
type="url"
variant="outlined"
InputProps={{
startAdornment: (
<InputAdornment position="start">
<MicIcon color="action" />
</InputAdornment>
),
}}
/>
<Button
variant="contained"
color="primary"
onClick={handleFetch}
disabled={fetching || !feedUrl}
label="resources.podcast.actions.fetchFeed"
style={{ marginTop: 8 }}
>
{fetching ? <CircularProgress size={18} color="inherit" /> : <SearchIcon />}
</Button>
</div>
{preview && (
<>
<Divider style={{ marginTop: 24, marginBottom: 8 }} />
<div className={classes.preview}>
{preview.imageUrl ? (
<img src={preview.imageUrl} alt={preview.title} className={classes.previewImage} />
) : (
<Avatar variant="rounded" className={classes.previewImage}>
<MicIcon style={{ fontSize: 48 }} />
</Avatar>
)}
<div className={classes.previewInfo}>
<Typography variant="h6" className={classes.previewTitle}>
{preview.title}
</Typography>
{preview.episodeCount > 0 && (
<Typography variant="body2" color="textSecondary">
{translate('resources.podcast.fields.episodeCount')}: {preview.episodeCount}
</Typography>
)}
{preview.description && (
<Typography variant="body2" className={classes.previewDesc}>
{preview.description}
</Typography>
)}
{preview.alreadyExists ? (
<Typography variant="body2" color="error" style={{ marginTop: 8 }}>
{translate('resources.podcast.notifications.alreadyExists')}
</Typography>
) : (
<Button
className={classes.addButton}
variant="contained"
color="primary"
onClick={handleAdd}
disabled={adding}
label="resources.podcast.actions.addChannel"
>
{adding ? <CircularProgress size={18} color="inherit" /> : <AddIcon />}
</Button>
)}
</div>
</div>
</>
)}
</CardContent>
</Card>
)
}
export default PodcastCreate

View file

@ -0,0 +1,72 @@
import React from 'react'
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
import { describe, it, expect, vi, beforeEach } from 'vitest'
vi.mock('../subsonic', () => ({
default: { createPodcastChannel: vi.fn().mockResolvedValue({}) },
}))
const mockRedirect = vi.fn()
const mockRefresh = vi.fn()
const mockNotify = vi.fn()
vi.mock('react-admin', async (importOriginal) => {
const actual = await importOriginal()
return {
...actual,
useTranslate: () => (key) => key,
useNotify: () => mockNotify,
useRedirect: () => mockRedirect,
useRefresh: () => mockRefresh,
Title: () => null,
}
})
import subsonic from '../subsonic'
import PodcastCreate from './PodcastCreate'
describe('PodcastCreate', () => {
beforeEach(() => vi.clearAllMocks())
it('renders a URL input field', () => {
render(<PodcastCreate />)
expect(screen.getByRole('textbox')).toBeTruthy()
})
it('calls createPodcastChannel with the entered URL on submit', async () => {
render(<PodcastCreate />)
fireEvent.change(screen.getByRole('textbox'), {
target: { value: 'https://example.com/feed.xml' },
})
fireEvent.submit(screen.getByRole('form'))
await waitFor(() => {
expect(subsonic.createPodcastChannel).toHaveBeenCalledWith(
'https://example.com/feed.xml',
)
})
})
it('redirects to /podcast after successful submit', async () => {
render(<PodcastCreate />)
fireEvent.change(screen.getByRole('textbox'), {
target: { value: 'https://example.com/feed.xml' },
})
fireEvent.submit(screen.getByRole('form'))
await waitFor(() => {
expect(mockRedirect).toHaveBeenCalledWith('/podcast')
})
})
it('notifies on success', async () => {
render(<PodcastCreate />)
fireEvent.change(screen.getByRole('textbox'), {
target: { value: 'https://example.com/feed.xml' },
})
fireEvent.submit(screen.getByRole('form'))
await waitFor(() => {
expect(mockNotify).toHaveBeenCalledWith(
'resources.podcast.notifications.channelAdded',
)
})
})
})

View file

@ -0,0 +1,90 @@
import React from 'react'
import {
GridList,
GridListTile,
GridListTileBar,
Typography,
useMediaQuery,
} from '@material-ui/core'
import { makeStyles } from '@material-ui/core/styles'
import MicIcon from '@material-ui/icons/Mic'
import { useListContext, linkToRecord } from 'react-admin'
import { Link } from 'react-router-dom'
import withWidth from '@material-ui/core/withWidth'
const useStyles = makeStyles((theme) => ({
root: { margin: theme.spacing(1) },
tileContainer: { cursor: 'pointer' },
link: { display: 'block', textDecoration: 'none', color: 'inherit' },
cover: { width: '100%', display: 'block', objectFit: 'cover' },
placeholder: {
width: '100%',
paddingBottom: '100%',
position: 'relative',
backgroundColor: theme.palette.grey[300],
},
placeholderIcon: {
position: 'absolute',
top: '50%',
left: '50%',
transform: 'translate(-50%, -50%)',
},
tileBar: {
background: 'linear-gradient(to top, rgba(0,0,0,0.6) 0%, rgba(0,0,0,0) 100%)',
},
title: {
fontSize: '0.85rem',
fontWeight: 500,
marginTop: theme.spacing(0.5),
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
},
}))
const getColsForWidth = (width) => {
if (width === 'xs') return 2
if (width === 'sm') return 3
if (width === 'md') return 4
if (width === 'lg') return 5
return 6
}
const PodcastGridView = ({ width, ...props }) => {
const classes = useStyles()
const { ids, data, basePath } = useListContext(props)
if (!ids || !data) return null
return (
<div className={classes.root}>
<GridList cellHeight="auto" cols={getColsForWidth(width)} spacing={16}>
{ids.map((id) => {
const record = data[id]
if (!record) return null
return (
<GridListTile key={id}>
<div className={classes.tileContainer}>
<Link className={classes.link} to={linkToRecord(basePath, id, 'show')}>
{record.imageUrl ? (
<img src={record.imageUrl} alt={record.title} className={classes.cover} />
) : (
<div className={classes.placeholder}>
<MicIcon className={classes.placeholderIcon} style={{ fontSize: 48, color: '#888' }} />
</div>
)}
<GridListTileBar className={classes.tileBar} title="" />
</Link>
<Link className={classes.link} to={linkToRecord(basePath, id, 'show')}>
<Typography className={classes.title}>{record.title}</Typography>
</Link>
</div>
</GridListTile>
)
})}
</GridList>
</div>
)
}
export default withWidth()(PodcastGridView)

View file

@ -0,0 +1,192 @@
import React from 'react'
import { Avatar, ButtonGroup, IconButton, makeStyles, Tooltip, Typography, useMediaQuery } from '@material-ui/core'
import FileCopyIcon from '@material-ui/icons/FileCopy'
import MicIcon from '@material-ui/icons/Mic'
import RefreshIcon from '@material-ui/icons/Refresh'
import ViewModuleIcon from '@material-ui/icons/ViewModule'
import ViewHeadlineIcon from '@material-ui/icons/ViewHeadline'
import {
Button,
CreateButton,
Datagrid,
DateField,
Filter,
sanitizeListRestProps,
SearchInput,
SimpleList,
TextField,
TopToolbar,
useNotify,
useRefresh,
useTranslate,
} from 'react-admin'
import { useDispatch, useSelector } from 'react-redux'
import { List } from '../common'
import subsonic from '../subsonic'
import StatusBadge from './StatusBadge'
import PodcastGridView from './PodcastGridView'
import { podcastViewGrid, podcastViewTable } from '../actions'
const useStyles = makeStyles({
row: { '&:hover': { '& $contextMenu': { visibility: 'visible' } } },
contextMenu: { visibility: 'hidden' },
toggleTitle: { margin: '1rem' },
buttonGroup: { width: '100%', justifyContent: 'center' },
leftButton: { paddingRight: '0.5rem' },
rightButton: { paddingLeft: '0.5rem' },
})
const PodcastFilter = (props) => (
<Filter {...props} variant="outlined">
<SearchInput id="search" source="title" alwaysOn />
</Filter>
)
const CoverArtField = ({ record }) => {
if (!record) return null
if (record.imageUrl) {
return (
<Avatar src={record.imageUrl} variant="rounded" style={{ width: 55, height: 55 }} alt={record.title} />
)
}
return (
<Avatar variant="rounded" style={{ width: 55, height: 55 }}>
<MicIcon />
</Avatar>
)
}
CoverArtField.defaultProps = { label: '', sortable: false }
const FeedUrlField = ({ record }) => {
const notify = useNotify()
const translate = useTranslate()
if (!record?.url) return null
const handleCopy = (e) => {
e.stopPropagation()
navigator.clipboard.writeText(record.url)
notify('resources.podcast.notifications.urlCopied')
}
return (
<span style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
<span style={{ maxWidth: 300, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{record.url}
</span>
<Tooltip title={translate('resources.podcast.actions.copyUrl', { _: 'Copy URL' })}>
<IconButton size="small" onClick={handleCopy}>
<FileCopyIcon fontSize="small" />
</IconButton>
</Tooltip>
</span>
)
}
FeedUrlField.defaultProps = { label: 'resources.podcast.fields.url', sortable: false }
const StatusField = ({ record }) => {
if (!record || record.status !== 'error') return null
return <StatusBadge status="error" errorMessage={record.errorMessage} />
}
StatusField.defaultProps = { label: '' }
const RefreshButton = () => {
const notify = useNotify()
const refresh = useRefresh()
const handleClick = async () => {
await subsonic.refreshPodcasts()
notify('resources.podcast.notifications.refreshStarted')
refresh()
}
return (
<Button onClick={handleClick} label="resources.podcast.actions.refresh">
<RefreshIcon />
</Button>
)
}
const PodcastViewToggler = React.forwardRef(({ showTitle = true }, ref) => {
const dispatch = useDispatch()
const podcastView = useSelector((state) => state.podcastView)
const classes = useStyles()
const translate = useTranslate()
return (
<div ref={ref}>
{showTitle && (
<Typography className={classes.toggleTitle}>
{translate('ra.toggleFieldsMenu.layout')}
</Typography>
)}
<ButtonGroup variant="text" color="primary" className={classes.buttonGroup}>
<Button
size="small"
className={classes.leftButton}
label={translate('ra.toggleFieldsMenu.grid')}
color={podcastView.grid ? 'primary' : 'secondary'}
onClick={() => dispatch(podcastViewGrid())}
>
<ViewModuleIcon fontSize="inherit" />
</Button>
<Button
size="small"
className={classes.rightButton}
label={translate('ra.toggleFieldsMenu.table')}
color={podcastView.grid ? 'secondary' : 'primary'}
onClick={() => dispatch(podcastViewTable())}
>
<ViewHeadlineIcon fontSize="inherit" />
</Button>
</ButtonGroup>
</div>
)
})
PodcastViewToggler.displayName = 'PodcastViewToggler'
const PodcastListActions = ({ className, filters, resource, showFilter, displayedFilters, filterValues, isAdmin, ...rest }) => {
return (
<TopToolbar className={className} {...sanitizeListRestProps(rest)}>
{isAdmin && <RefreshButton />}
{isAdmin && <CreateButton basePath="/podcast" />}
{filters && React.cloneElement(filters, { resource, showFilter, displayedFilters, filterValues, context: 'button' })}
<PodcastViewToggler showTitle={false} />
</TopToolbar>
)
}
const PodcastList = ({ permissions, ...props }) => {
const classes = useStyles()
const isXsmall = useMediaQuery((theme) => theme.breakpoints.down('xs'))
const isAdmin = permissions === 'admin'
const podcastView = useSelector((state) => state.podcastView)
return (
<List
{...props}
exporter={false}
sort={{ field: 'title', order: 'ASC' }}
bulkActionButtons={isAdmin ? undefined : false}
hasCreate={isAdmin}
actions={<PodcastListActions isAdmin={isAdmin} />}
filters={<PodcastFilter />}
>
{isXsmall ? (
<SimpleList
leftAvatar={(r) => <CoverArtField record={r} />}
primaryText={(r) => r.title}
secondaryText={(r) => r.url}
/>
) : podcastView.grid ? (
<PodcastGridView />
) : (
<Datagrid rowClick="show" classes={{ row: classes.row }}>
<CoverArtField source="id" />
<TextField source="title" />
<FeedUrlField source="url" />
<StatusField source="status" sortable={false} />
<DateField source="updatedAt" showTime />
</Datagrid>
)}
</List>
)
}
export default PodcastList

View file

@ -0,0 +1,220 @@
import React, { useEffect, useState } from 'react'
import {
Card,
CardContent,
Typography,
Table,
TableBody,
TableCell,
TableHead,
TableRow,
makeStyles,
Link,
} from '@material-ui/core'
import { Button, useTranslate, useShowController, Title } from 'react-admin'
import { useDispatch } from 'react-redux'
import MicIcon from '@material-ui/icons/Mic'
import PlayArrowIcon from '@material-ui/icons/PlayArrow'
import ShuffleIcon from '@material-ui/icons/Shuffle'
import { RiPlayList2Fill, RiPlayListAddFill } from 'react-icons/ri'
import StatusBadge from './StatusBadge'
import EpisodeActions from './EpisodeActions'
import subsonic from '../subsonic'
import { setTrack, playTracks, shuffleTracks, playNext, addTracks } from '../actions'
const songFromEpisode = (episode, channelTitle) => ({
id: episode.streamId,
title: episode.title,
album: channelTitle || episode.channelId,
artist: '',
duration: episode.duration,
suffix: episode.suffix,
isPodcast: true,
channelId: episode.channelId,
})
const buildTracksData = (episodes, channelTitle) => {
const data = {}
const ids = []
episodes
.filter((ep) => ep.status === 'completed' && ep.streamId)
.forEach((ep) => {
const song = songFromEpisode(ep, channelTitle)
data[song.id] = song
ids.push(song.id)
})
return { data, ids }
}
const EpisodePlayButtons = ({ episodes, channelTitle }) => {
const dispatch = useDispatch()
const translate = useTranslate()
const { data, ids } = buildTracksData(episodes, channelTitle)
if (!ids.length) return null
return (
<div style={{ marginBottom: 8 }}>
<Button onClick={() => dispatch(playTracks(data, ids))} label={translate('resources.album.actions.playAll')}>
<PlayArrowIcon />
</Button>
<Button onClick={() => dispatch(shuffleTracks(data, ids))} label={translate('resources.album.actions.shuffle')}>
<ShuffleIcon />
</Button>
<Button onClick={() => dispatch(playNext(data, ids))} label={translate('resources.album.actions.playNext')}>
<RiPlayList2Fill />
</Button>
<Button onClick={() => dispatch(addTracks(data, ids))} label={translate('resources.album.actions.addToQueue')}>
<RiPlayListAddFill />
</Button>
</div>
)
}
const useStyles = makeStyles((theme) => ({
card: { marginTop: theme.spacing(2) },
header: { display: 'flex', gap: theme.spacing(2), marginBottom: theme.spacing(3) },
playableRow: { cursor: 'pointer', '&:hover': { backgroundColor: theme.palette.action.hover } },
avatar: {
width: 192,
height: 192,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
backgroundColor: theme.palette.grey[300],
borderRadius: 4,
flexShrink: 0,
},
meta: { flex: 1 },
description: { marginTop: theme.spacing(1), color: theme.palette.text.secondary },
tableWrapper: { marginTop: theme.spacing(2), overflowX: 'auto' },
}))
const formatDuration = (seconds) => {
if (!seconds) return ''
const h = Math.floor(seconds / 3600)
const m = Math.floor((seconds % 3600) / 60)
const s = seconds % 60
if (h > 0) return `${h}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`
return `${m}:${String(s).padStart(2, '0')}`
}
const PodcastShow = (props) => {
const classes = useStyles()
const translate = useTranslate()
const dispatch = useDispatch()
const { record } = useShowController(props)
const [episodes, setEpisodes] = useState([])
const loadEpisodes = () => {
if (!record?.id) return
subsonic
.getPodcasts(record.id, true)
.then((res) => {
const channels = res?.json?.['subsonic-response']?.podcasts?.channel || []
const ch = channels.find((c) => c.id === record.id)
setEpisodes(ch?.episode || [])
})
.catch(() => {})
}
useEffect(loadEpisodes, [record?.id])
// Subscribe to SSE progress only while episodes are downloading
const hasDownloading = episodes.some((ep) => ep.status === 'downloading')
useEffect(() => {
if (!hasDownloading) return
const handler = (e) => {
const { episodeId, downloadedBytes, size, duration, status } = e.detail
if (status === 'completed' || status === 'error') {
// Reload to get updated streamId and full episode data
loadEpisodes()
return
}
setEpisodes((prev) =>
prev.map((ep) =>
ep.id === episodeId
? { ...ep, downloadedBytes, size, ...(duration ? { duration } : {}) }
: ep,
),
)
}
window.addEventListener('podcastEpisodeProgress', handler)
return () => window.removeEventListener('podcastEpisodeProgress', handler)
}, [hasDownloading])
if (!record) return null
return (
<Card className={classes.card}>
<Title subTitle={record.title} />
<CardContent>
<div className={classes.header}>
<div className={classes.avatar}>
{record.imageUrl ? (
<img
src={record.imageUrl}
alt={record.title}
style={{ width: '100%', height: '100%', objectFit: 'cover', borderRadius: 4 }}
/>
) : (
<MicIcon style={{ fontSize: 40, color: '#888' }} />
)}
</div>
<div className={classes.meta}>
<Typography variant="h5">{record.title}</Typography>
<Link href={record.url} target="_blank" rel="noopener noreferrer" variant="body2">
{record.url}
</Link>
{record.description && (
<Typography variant="body2" className={classes.description}>
{record.description}
</Typography>
)}
{record.status === 'error' && (
<StatusBadge status="error" errorMessage={record.errorMessage} />
)}
</div>
</div>
<EpisodePlayButtons episodes={episodes} channelTitle={record.title} />
<div className={classes.tableWrapper}>
<Table size="small">
<TableHead>
<TableRow>
<TableCell>{translate('resources.podcast.fields.title')}</TableCell>
<TableCell>{translate('resources.podcast.fields.publishDate')}</TableCell>
<TableCell>{translate('resources.podcast.fields.duration')}</TableCell>
<TableCell>{translate('resources.podcast.fields.status')}</TableCell>
<TableCell />
</TableRow>
</TableHead>
<TableBody>
{episodes.map((ep) => (
<TableRow
key={ep.id}
className={ep.status === 'completed' ? classes.playableRow : undefined}
onClick={() => ep.status === 'completed' && dispatch(setTrack(songFromEpisode(ep, record.title)))}
>
<TableCell>{ep.title}</TableCell>
<TableCell>
{ep.publishDate ? new Date(ep.publishDate).toLocaleDateString() : ''}
</TableCell>
<TableCell>{formatDuration(ep.duration)}</TableCell>
<TableCell>
<StatusBadge status={ep.status} errorMessage={ep.errorMessage} downloadedBytes={ep.downloadedBytes} size={ep.size} />
</TableCell>
<TableCell>
<EpisodeActions episode={ep} onRefresh={loadEpisodes} />
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
</CardContent>
</Card>
)
}
export default PodcastShow

View file

@ -0,0 +1,47 @@
import React from 'react'
import { Chip, CircularProgress, Tooltip, Typography, Box, makeStyles } from '@material-ui/core'
import { useTranslate } from 'react-admin'
const useStyles = makeStyles((theme) => ({
completed: { backgroundColor: theme.palette.success?.main || '#4caf50', color: '#fff' },
error: { backgroundColor: theme.palette.error.main, color: '#fff', cursor: 'default' },
new: {},
skipped: { backgroundColor: theme.palette.warning?.main || '#ff9800', color: '#fff' },
}))
const StatusBadge = ({ status, errorMessage, downloadedBytes, size }) => {
const translate = useTranslate()
const classes = useStyles()
if (!status || status === 'deleted') return null
const label = translate(`resources.podcast.status.${status}`, { _: status })
if (status === 'downloading') {
const pct = size > 0 && downloadedBytes > 0 ? Math.round((downloadedBytes / size) * 100) : null
return (
<Box display="flex" alignItems="center" style={{ gap: 6 }}>
<CircularProgress size={14} />
{pct !== null && <Typography variant="caption">{`${pct}%`}</Typography>}
</Box>
)
}
if (status === 'error' && errorMessage) {
return (
<Tooltip title={errorMessage}>
<Chip className={classes.error} label={label} size="small" />
</Tooltip>
)
}
return (
<Chip
className={classes[status] || classes.new}
label={label}
size="small"
/>
)
}
export default StatusBadge

View file

@ -0,0 +1,53 @@
import React from 'react'
import { render, screen } from '@testing-library/react'
import { describe, it, expect, vi } from 'vitest'
import StatusBadge from './StatusBadge'
vi.mock('react-admin', () => ({
useTranslate: () => (key) => key,
}))
vi.mock('@material-ui/core', async (importOriginal) => {
const actual = await importOriginal()
return {
...actual,
Tooltip: ({ children }) => children,
}
})
describe('StatusBadge', () => {
it('renders label for completed status', () => {
render(<StatusBadge status="completed" />)
expect(screen.getByText('resources.podcast.status.completed')).toBeTruthy()
})
it('renders label for downloading status', () => {
render(<StatusBadge status="downloading" />)
expect(screen.getByText('resources.podcast.status.downloading')).toBeTruthy()
})
it('renders label for error status', () => {
render(<StatusBadge status="error" errorMessage="Connection refused" />)
expect(screen.getByText('resources.podcast.status.error')).toBeTruthy()
})
it('renders label for new status', () => {
render(<StatusBadge status="new" />)
expect(screen.getByText('resources.podcast.status.new')).toBeTruthy()
})
it('renders label for skipped status', () => {
render(<StatusBadge status="skipped" />)
expect(screen.getByText('resources.podcast.status.skipped')).toBeTruthy()
})
it('renders nothing for deleted status', () => {
const { container } = render(<StatusBadge status="deleted" />)
expect(container).toBeEmptyDOMElement()
})
it('renders nothing when status is undefined', () => {
const { container } = render(<StatusBadge />)
expect(container).toBeEmptyDOMElement()
})
})

26
ui/src/podcast/index.jsx Normal file
View file

@ -0,0 +1,26 @@
import React from 'react'
import MicIcon from '@material-ui/icons/Mic'
import MicNoneIcon from '@material-ui/icons/MicNone'
import DynamicMenuIcon from '../layout/DynamicMenuIcon'
import PodcastList from './PodcastList'
import PodcastShow from './PodcastShow'
import PodcastCreate from './PodcastCreate'
const all = {
list: PodcastList,
show: PodcastShow,
icon: (
<DynamicMenuIcon
path={'podcast'}
icon={MicNoneIcon}
activeIcon={MicIcon}
/>
),
}
const admin = {
...all,
create: PodcastCreate,
}
export default { all, admin }

View file

@ -3,6 +3,7 @@ export * from './themeReducer'
export * from './dialogReducer'
export * from './playerReducer'
export * from './albumView'
export * from './podcastView'
export * from './activityReducer'
export * from './settingsReducer'
export * from './replayGainReducer'

View file

@ -0,0 +1,15 @@
import { PODCAST_MODE_GRID, PODCAST_MODE_TABLE } from '../actions'
export const podcastViewReducer = (
previousState = { grid: true },
payload,
) => {
const { type } = payload
switch (type) {
case PODCAST_MODE_GRID:
case PODCAST_MODE_TABLE:
return { ...previousState, grid: type === PODCAST_MODE_GRID }
default:
return previousState
}
}

View file

@ -131,6 +131,29 @@ const getTopSongs = (artist, count = 50) => {
return httpClient(url('getTopSongs', null, { artist, count }))
}
const getPodcasts = (id = null, includeEpisodes = true) =>
httpClient(url('getPodcasts', id, { includeEpisodes }))
const getNewestPodcasts = (count = 20) =>
httpClient(url('getNewestPodcasts', null, { count }))
const createPodcastChannel = (feedUrl) =>
httpClient(url('createPodcastChannel', null, { url: feedUrl }))
const previewPodcastFeed = (feedUrl) =>
httpClient(baseUrl(`/api/podcast/preview?url=${encodeURIComponent(feedUrl)}`))
const refreshPodcasts = () => httpClient(url('refreshPodcasts'))
const deletePodcastChannel = (id) =>
httpClient(url('deletePodcastChannel', id))
const deletePodcastEpisode = (id) =>
httpClient(url('deletePodcastEpisode', id))
const downloadPodcastEpisode = (id) =>
httpClient(url('downloadPodcastEpisode', id))
const streamUrl = (id, options) => {
return baseUrl(
url('stream', id, {
@ -160,4 +183,12 @@ export default {
getArtistInfo,
getTopSongs,
getSimilarSongs2,
getPodcasts,
getNewestPodcasts,
createPodcastChannel,
previewPodcastFeed,
refreshPodcasts,
deletePodcastChannel,
deletePodcastEpisode,
downloadPodcastEpisode,
}

View file

@ -265,3 +265,61 @@ describe('reportPlayback', () => {
expect(url).toContain('state=playing')
})
})
describe('podcast API URL builders', () => {
beforeEach(() => {
const localStorageMock = {
getItem: vi.fn((key) => {
const values = {
username: 'testuser',
'subsonic-token': 'testtoken',
'subsonic-salt': 'testsalt',
}
return values[key] || null
}),
}
Object.defineProperty(window, 'localStorage', { value: localStorageMock })
})
it('getPodcasts includes includeEpisodes param', () => {
const result = subsonic.url('getPodcasts', null, { includeEpisodes: true })
expect(result).toContain('getPodcasts')
expect(result).toContain('includeEpisodes=true')
})
it('getPodcasts includes id when provided', () => {
const result = subsonic.url('getPodcasts', 'ch-1', { includeEpisodes: true })
expect(result).toContain('id=ch-1')
})
it('getNewestPodcasts includes count', () => {
const result = subsonic.url('getNewestPodcasts', null, { count: 5 })
expect(result).toContain('getNewestPodcasts')
expect(result).toContain('count=5')
})
it('createPodcastChannel includes url param', () => {
const feedUrl = 'https://example.com/feed.xml'
const result = subsonic.url('createPodcastChannel', null, { url: feedUrl })
expect(result).toContain('createPodcastChannel')
expect(result).toContain(encodeURIComponent(feedUrl))
})
it('deletePodcastChannel includes id', () => {
const result = subsonic.url('deletePodcastChannel', 'ch-1')
expect(result).toContain('deletePodcastChannel')
expect(result).toContain('id=ch-1')
})
it('deletePodcastEpisode includes id', () => {
const result = subsonic.url('deletePodcastEpisode', 'ep-1')
expect(result).toContain('deletePodcastEpisode')
expect(result).toContain('id=ep-1')
})
it('downloadPodcastEpisode includes id', () => {
const result = subsonic.url('downloadPodcastEpisode', 'ep-1')
expect(result).toContain('downloadPodcastEpisode')
expect(result).toContain('id=ep-1')
})
})