From 3c7659feacee7f7100d5d3d801c7255ba5978d8d Mon Sep 17 00:00:00 2001 From: Broque Thomas Date: Sun, 14 Dec 2025 12:21:36 -0800 Subject: [PATCH] Improve wishlist track sorting robustness Refactored the sorting logic to handle cases where 'spotify_data' may be a JSON string or have varying structures. This ensures consistent sorting by artist and track name, even with malformed or unexpected data formats. --- core/wishlist_service.py | 29 +++++++++++++++++++++++++---- 1 file changed, 25 insertions(+), 4 deletions(-) diff --git a/core/wishlist_service.py b/core/wishlist_service.py index 47825780..6bc5102c 100644 --- a/core/wishlist_service.py +++ b/core/wishlist_service.py @@ -110,10 +110,31 @@ class WishlistService: # Sort by artist name, then track name for consistent display order try: - wishlist_tracks.sort(key=lambda x: ( - x['spotify_data'].get('artists', [{}])[0].get('name', '').lower(), - x['spotify_data'].get('name', '').lower() - )) + def get_sort_key(track): + spotify_data = track['spotify_data'] + # Parse JSON string if needed + if isinstance(spotify_data, str): + import json + try: + spotify_data = json.loads(spotify_data) + except: + return ('', '') # Fallback for invalid JSON + + artist_name = '' + track_name = '' + + if isinstance(spotify_data, dict): + artists = spotify_data.get('artists', []) + if artists and len(artists) > 0: + if isinstance(artists[0], dict): + artist_name = artists[0].get('name', '') + elif isinstance(artists[0], str): + artist_name = artists[0] + track_name = spotify_data.get('name', '') + + return (artist_name.lower(), track_name.lower()) + + wishlist_tracks.sort(key=get_sort_key) logger.debug(f"Successfully sorted {len(wishlist_tracks)} wishlist tracks by artist/track name") except Exception as sort_error: logger.warning(f"Failed to sort wishlist tracks, using original order: {sort_error}")