Allow radio stations to be added to playlists (#2951)
* Add support for radio station URIs in playlists
Enable radio stations to be added to Music Assistant (builtin) playlists
by expanding the playlist track type system to support both Track and Radio items.
Changes:
- playlists.py: Add RADIO media type handling in add_playlist_tracks()
- playlists.py: Update return types to support Track | Radio
- music_provider.py: Expand get_playlist_tracks() return type to list[Track | Radio]
- builtin/__init__.py: Replace Track assertion with type check for Track | Radio
This allows users to mix tracks and radio stations in the same playlist,
with radio URIs stored and retrieved alongside track URIs.
* Add validation to restrict radio items to builtin playlists only
Radio items can only be added to builtin playlists because other streaming
providers (Spotify, Apple Music, etc.) don't support arbitrary radio stream
URLs in their playlists. This adds backend validation to enforce this
constraint and provide a clear error message when attempted.
* Fix bug: Radio URIs were being resolved as track IDs
When adding radio items with library URIs (library://radio/ID) to builtin
playlists, the code was incorrectly passing through track-specific resolution
logic that called tracks.get(ID) instead of radio.get(ID), causing the wrong
items to be added.
Fixed by handling all radio items for builtin playlists early in the URI
processing, adding them directly by URI before the track-specific logic runs.
This ensures library://radio/8 adds radio ID 8, not track ID 8.
* Fix metadata and queue controllers to handle Radio items in playlists
The metadata controller was crashing when processing playlists containing
radio items because it tried to access track.album on Radio objects.
The player_queues controller had incorrect type annotations that assumed
playlist items were always Tracks.
Changes:
- metadata.py: Add isinstance(track, Track) check before accessing .album
- player_queues.py: Update get_playlist_tracks() return type to Track | Radio
- player_queues.py: Add Radio to imports
Both controllers now properly handle playlists containing mixed Track and
Radio items.
* Fix mypy type errors for radio playlist support
The previous implementation changed the base MusicProvider.get_playlist_tracks()
interface to return list[Track | Radio], which caused type errors across all
provider implementations that only return list[Track].
Fixes:
1. Reverted base interface to return list[Track] (standard for all providers)
2. Builtin provider overrides with list[Track | Radio] (covariant return type)
3. Added type: ignore[override] for builtin's covariant override
4. Added type: ignore[return-value] where playlist controller calls providers
5. Fixed radio_mode_base_tracks to filter out Radio items (only works with Track)
6. Fixed variable naming: 'track' -> 'item' where both types are possible
This approach is correct because:
- Only builtin provider supports radio in playlists
- All other providers (Spotify, Tidal, etc.) only support tracks
- Python's type system supports covariant return types in overrides
- list[Track] is compatible with list[Track | Radio] at call sites
* Refactor playlist URI handling logic for clarity
The previous logic combined radio and track handling in one condition,
making it unclear why library URIs were being added for radio items.
Separated into two clear cases:
1. Radio items: ALWAYS add by URI (even library://radio/ID)
- Radio items cannot go through track-matching logic
- They must be retrieved by their full URI
- This is a necessary exception to the "no library URIs" rule
2. Track items: Only add non-library URIs directly
- Provider URIs (spotify://track/xyz) are portable
- Library URIs (library://track/123) fall through to matching logic
- This finds the actual provider URI to store instead
This addresses the review concern that the logic didn't make sense and
makes the special handling of radio items explicit.
* Convert library radio URIs to provider URIs for DB rebuild resilience
Previously, library radio URIs (library://radio/8) were being stored
directly in playlists. This would break on database rebuilds when the
radio item gets a different database ID.
Now when adding a library radio URI:
1. Fetch the full radio item from the library
2. Get its provider mapping (typically builtin)
3. Extract the actual provider item_id (the real stream URL)
4. Create and store the provider URI (builtin://radio/https://stream...)
This ensures playlists contain portable provider URIs with the actual
stream URLs, surviving database rebuilds.
Example:
- Before: Stored library://radio/8 (breaks on rebuild)
- After: Stored builtin://radio/https://stream.example.com/radio.mp3 (portable)
Provider radio URIs are already portable and stored as-is.
* Apply reviewer suggestion: simplify comment in radio_mode_base_tracks
Changed comment from 'filter out unavailable tracks and radio items' to
'filter out unavailable items' as suggested by reviewer for better clarity.
* Make playlist validation generic for non-track items
Changed validation from checking specifically for radio items to checking
for any non-track media type. This makes the code more future-proof for
supporting other media types like podcast episodes in playlists.
Applied reviewer suggestion to make the logic more generic.
* Make library URI conversion universal using get_item_by_uri
Refactored the radio-specific library URI conversion to work universally
for all non-track media types (radio, podcast episodes, audiobooks, etc.)
by using self.mass.music.get_item_by_uri() instead of calling media-type-
specific controllers.
This addresses reviewer feedback to avoid code duplication and makes the
backend ready to support additional media types in playlists as the
frontend adds support for them.
Changes:
- Changed condition from "media_type == MediaType.RADIO" to "media_type != MediaType.TRACK"
- Use get_item_by_uri() to fetch items generically
- Renamed variables from radio-specific to generic (prov_mapping, full_item)
- Updated comments to reflect universal support
* Add type safety check for items with provider_mappings
Fixed mypy error where get_item_by_uri can return BrowseFolder which
doesn't have provider_mappings attribute. Added hasattr check and
restructured to use if/else instead of early continue to properly
handle items without provider mappings.
* Replace hasattr with isinstance for type-safe media item checking
Replaced hasattr() check with isinstance() for better type safety:
- Added Audiobook and PodcastEpisode to imports
- Use isinstance(full_item, (Radio, Audiobook, PodcastEpisode))
- Removed need for type: ignore[attr-defined] comment
- mypy now understands full_item has provider_mappings attribute
This is more explicit, type-safe, and self-documenting about which
media types are supported in playlists.
* Add PlaylistItem type alias for better maintainability
Created a shared type alias PlaylistItem = Track | Radio | PodcastEpisode | Audiobook
to avoid hardcoding union types in multiple places.
Changes:
- playlists.py: Added PlaylistItem type alias at top of file
- playlists.py: Updated all Track | Radio annotations to use PlaylistItem
- player_queues.py: Added PlaylistItem type alias
- player_queues.py: Updated get_playlist_tracks to use PlaylistItem
- builtin/__init__.py: Added Audiobook and PodcastEpisode to imports
- builtin/__init__.py: Updated all type annotations to include all supported types
- builtin/__init__.py: Updated isinstance checks to include all types
Now there's a single source of truth for what media types can be in playlists.
Adding future types only requires changing the type alias definition.
* Add PlaylistItem type alias for better maintainability
Added type aliases and constants to keep all playlist item type definitions synchronized:
- PlaylistItem type alias defined in playlists.py, builtin/__init__.py, and player_queues.py
- PLAYLIST_MEDIA_TYPES constant for MediaType enum checks
- PLAYLIST_ITEM_CLASSES constant for isinstance checks
This ensures that adding new playlist item types in the future only requires updating the type alias and constants, with all runtime checks automatically including the new type.
* Centralize playlist item type definitions in constants.py
Moved all playlist item type definitions to a single location in constants.py to eliminate duplication and ensure consistency:
- PlaylistItem type alias
- PLAYLIST_MEDIA_TYPES tuple for MediaType enum checks
- PLAYLIST_ITEM_CLASSES tuple for isinstance checks
- PLAYLIST_NON_TRACK_ITEM_CLASSES for cases where Track needs separate handling
Updated playlists.py, builtin/__init__.py, and player_queues.py to import from constants.py.
Also improved comments:
- Better explanation of type ignore for covariant override
- More generic comment for radio mode filtering
- Updated to reference PlaylistItem instead of specific types
* Replace hardcoded types with type ignore comments
Removed cast statements with hardcoded types and replaced with type ignore comments for mypy:
- playlists.py: Added type: ignore[union-attr] for provider_mappings access
- builtin/__init__.py: Added type: ignore[attr-defined] and type: ignore[arg-type] for position and append
This ensures all type checking uses the constants from constants.py without any hardcoded type repetition.
* Use cast with type alias constants instead of type ignore
Added PlaylistNonTrackItem type alias to constants.py and updated code to use cast() with type aliases instead of type ignore comments:
- playlists.py: cast(PlaylistNonTrackItem, full_item)
- builtin/__init__.py: cast(PlaylistItem, track)
This maintains type safety while using only the centralized type definitions from constants.py.
* Simplify type definitions using get_args()
Reduced complexity by deriving PLAYLIST_ITEM_CLASSES from PlaylistItem using get_args():
- Removed PlaylistNonTrackItem type alias (only used once)
- PLAYLIST_ITEM_CLASSES now auto-derived from PlaylistItem
- Replaced cast with type ignore comment for single non-track case
This reduces maintenance: adding a new type only requires updating PlaylistItem and PLAYLIST_MEDIA_TYPES.
* Use get_args() inline instead of PLAYLIST_ITEM_CLASSES constant
Removed PLAYLIST_ITEM_CLASSES constant and use get_args(PlaylistItem) directly at the single call site.
This reduces to just 3 definitions in constants.py:
- PlaylistItem type alias
- PLAYLIST_MEDIA_TYPES tuple
- PLAYLIST_NON_TRACK_ITEM_CLASSES tuple
* Add type ignore for cast assignment in builtin provider
Added type: ignore[assignment] comment to fix mypy error where cast result is assigned to broader-typed variable.
* Use new variable name instead of type ignore for cast
Instead of reassigning track with a type ignore, use a new variable playlist_item.
This makes the isinstance check meaningful for type narrowing without needing type ignore comments.
* Clarify comments about playlist types in builtin provider
Updated comments to distinguish between:
- System-generated playlists (favorites, random, etc.) which only contain tracks
- User-created playlists which can contain Track, Radio, PodcastEpisode, and Audiobook items
This makes it clear that the new support for non-track items only applies to user-created playlists.
* Lint
* Unify track and non-track playlist item handling logic
Merged separate code paths for tracks and non-track items into unified logic:
- Same structure for all media types (Track, Radio, PodcastEpisode, Audiobook)
- For builtin playlists: Get full item, iterate provider mappings, add first available
- Tracks get quality sorting before selection
- Non-track items use first available mapping (typically only one)
This simplifies maintenance and follows the same pattern for all playlist item types.
* Fix mypy error in unified playlist logic
Added cast to Track type for match_provider call since full_item has broad union type from get_item_by_uri().
We know it's a Track from the media_type check but mypy can't infer this.
* Rename PlaylistItem to PlaylistPlayableItem to avoid naming conflict
The PlaylistItem union type conflicted with the existing PlaylistItem
dataclass in music_assistant.helpers.playlists, causing import collisions
and confusing type hints. Renamed the union type to PlaylistPlayableItem
to clearly distinguish it from the helper dataclass.
Changes:
- Renamed type alias in constants.py
- Updated all imports and usages in:
- playlists.py (import, return types, comments)
- builtin/__init__.py (import, return type, isinstance, cast)
- player_queues.py (import, return types)
- Updated comments to reference new name
* Remove unused constant and duplicate import
- Remove PLAYLIST_NON_TRACK_ITEM_CLASSES as it was declared but never used
- Remove duplicate AsyncGenerator import from TYPE_CHECKING block in playlists.py
* Sort provider mappings for deterministic non-track item selection
---------
Co-authored-by: Claude <noreply@anthropic.com>