diff --git a/app/services/player.py b/app/services/player.py index d9d38f6..f395cba 100644 --- a/app/services/player.py +++ b/app/services/player.py @@ -576,6 +576,11 @@ class PlayerService: current_id, ) + # Clear play_next queue when playlist changes + if self.state.play_next_queue: + logger.info("Clearing play_next queue due to playlist change") + self.state.play_next_queue.clear() + if self.state.status != PlayerStatus.STOPPED: await self._stop_playback() @@ -591,6 +596,9 @@ class PlayerService: sounds: list[Sound], ) -> None: """Handle track checking when playlist ID is the same.""" + # Remove tracks from play_next queue that are no longer in the playlist + self._clean_play_next_queue(sounds) + # Find the current track in the new playlist new_index = self._find_sound_index(previous_sound_id, sounds) @@ -648,6 +656,29 @@ class PlayerService: return i return None + def _clean_play_next_queue(self, playlist_sounds: list[Sound]) -> None: + """Remove tracks from play_next queue that are no longer in the playlist.""" + if not self.state.play_next_queue: + return + + # Get IDs of all sounds in the current playlist + playlist_sound_ids = {sound.id for sound in playlist_sounds} + + # Filter out tracks that are no longer in the playlist + original_length = len(self.state.play_next_queue) + self.state.play_next_queue = [ + sound + for sound in self.state.play_next_queue + if sound.id in playlist_sound_ids + ] + + removed_count = original_length - len(self.state.play_next_queue) + if removed_count > 0: + logger.info( + "Removed %s track(s) from play_next queue (no longer in playlist)", + removed_count, + ) + def _set_first_track_as_current(self, sounds: list[Sound]) -> None: """Set the first track as the current track.""" self.state.current_sound_index = 0 diff --git a/tests/api/v1/test_player_endpoints.py b/tests/api/v1/test_player_endpoints.py index e87a3a6..bb86c23 100644 --- a/tests/api/v1/test_player_endpoints.py +++ b/tests/api/v1/test_player_endpoints.py @@ -537,6 +537,7 @@ class TestPlayerEndpoints: "duration": 30000, "sounds": [], }, + "play_next_queue": [], } mock_player_service.get_state.return_value = mock_state