Add comprehensive playlist support for v1.0.0

Features:
- Exact matching for all search types (artists, albums, tracks, playlists)
- User playlist search (type=user_playlist) with exact and partial matching
- Performance caching for user playlist data
- Comprehensive documentation and test cases
- HACS integration support (hacs.json)

All search types now use limit=10 and prefer exact name matches to avoid
Spotify's personalized recommendations, ensuring you get what you ask for.
This commit is contained in:
Chad Auld committed 2025-11-17 21:34:23 -07:00
1 parent c1908a549f
commit 61ce9c0e09
8 files changed
+650 -44

No files matched your search

+116 -13
View File
@@ -7,12 +7,13 @@ from homeassistant.helpers.typing import ConfigType
_LOGGER = logging.getLogger(__name__)
DOMAIN = "spotify_search"
VALID_SEARCH_TYPES = {"artist", "album", "track", "playlist"}
VALID_SEARCH_TYPES = {"artist", "album", "track", "playlist", "user_playlist"}
# Cache Spotify client to avoid repeated lookups
_spotify_cache = {
"client": None,
"entity_id": None,
"user_playlists": None,
}
@@ -140,21 +141,122 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
else:
_LOGGER.warning("No artists found for query: %s", query)
return {"error": f"No artist found for: {query}"}
else:
# For albums, tracks, playlists - use direct search
results = await client.search(query, [search_type], limit=1)
items_list = getattr(results, f"{search_type}s", None)
elif search_type == "playlist":
# For playlists, search with higher limit and check for exact matches
_LOGGER.debug("Searching for playlist: %s", query)
results = await client.search(query, ["playlist"], limit=10)
items_list = results.playlists
if items_list and len(items_list) > 0:
item = items_list[0]
# Check if any playlist name matches exactly (case-insensitive)
exact_match = None
query_lower = query.lower()
for playlist in items_list:
# Defensive attribute check
if hasattr(playlist, "name") and playlist.name.lower() == query_lower:
exact_match = playlist
break
# Use exact match if found, otherwise use first result
selected_playlist = exact_match if exact_match else items_list[0]
# Defensive attribute checks
if not hasattr(item, "uri") or not hasattr(item, "name"):
if not hasattr(selected_playlist, "uri") or not hasattr(selected_playlist, "name"):
_LOGGER.error("Playlist result missing required attributes")
return {"error": "Invalid playlist data from Spotify"}
uri = selected_playlist.uri
name = selected_playlist.name
match_type = "exact match" if exact_match else "first result"
_LOGGER.info("Found Spotify playlist: %s (%s) - %s", name, uri, match_type)
return {"uri": uri, "name": name, "type": "playlist"}
else:
_LOGGER.warning("No playlists found for query: %s", query)
return {"error": f"No playlist found for: {query}"}
elif search_type == "user_playlist":
# Search within user's saved playlists
_LOGGER.debug("Searching user's playlists for: %s", query)
try:
# Get user's playlists (with caching)
if _spotify_cache["user_playlists"] is None:
_LOGGER.debug("Cache miss, fetching user playlists")
user_playlists = await client.get_playlists_for_current_user()
_spotify_cache["user_playlists"] = user_playlists
else:
_LOGGER.debug("Using cached user playlists")
user_playlists = _spotify_cache["user_playlists"]
if not user_playlists or not hasattr(user_playlists, "items"):
_LOGGER.warning("No user playlists found or invalid response")
return {"error": "Could not retrieve user playlists"}
items_list = user_playlists.items
if not items_list or len(items_list) == 0:
_LOGGER.warning("User has no saved playlists")
return {"error": "No saved playlists found"}
# Search for exact match in user's playlists
exact_match = None
query_lower = query.lower()
for playlist in items_list:
if hasattr(playlist, "name") and playlist.name.lower() == query_lower:
exact_match = playlist
break
# If no exact match, search for partial match
partial_match = None
if not exact_match:
for playlist in items_list:
if hasattr(playlist, "name") and query_lower in playlist.name.lower():
partial_match = playlist
break
selected_playlist = exact_match or partial_match
if not selected_playlist:
_LOGGER.warning("No matching playlist found in user's library for: %s", query)
return {"error": f"No playlist matching '{query}' found in your library"}
# Defensive attribute checks
if not hasattr(selected_playlist, "uri") or not hasattr(selected_playlist, "name"):
_LOGGER.error("User playlist result missing required attributes")
return {"error": "Invalid playlist data"}
uri = selected_playlist.uri
name = selected_playlist.name
match_type = "exact match" if exact_match else "partial match"
_LOGGER.info("Found user playlist: %s (%s) - %s", name, uri, match_type)
return {"uri": uri, "name": name, "type": "playlist"}
except Exception as err:
_LOGGER.error("Error retrieving user playlists: %s", err)
return {"error": "Failed to retrieve user playlists"}
else:
# For albums, tracks - search with higher limit and check for exact matches
_LOGGER.debug("Searching for %s: %s", search_type, query)
results = await client.search(query, [search_type], limit=10)
items_list = getattr(results, f"{search_type}s", None)
if items_list and len(items_list) > 0:
# Check if any item name matches exactly (case-insensitive)
exact_match = None
query_lower = query.lower()
for item in items_list:
# Defensive attribute check
if hasattr(item, "name") and item.name.lower() == query_lower:
exact_match = item
break
# Use exact match if found, otherwise use first result
selected_item = exact_match if exact_match else items_list[0]
# Defensive attribute checks
if not hasattr(selected_item, "uri") or not hasattr(selected_item, "name"):
_LOGGER.error("%s result missing required attributes", search_type)
return {"error": f"Invalid {search_type} data from Spotify"}
uri = item.uri
name = item.name
_LOGGER.info("Found Spotify %s: %s (%s)", search_type, name, uri)
uri = selected_item.uri
name = selected_item.name
match_type = "exact match" if exact_match else "first result"
_LOGGER.info("Found Spotify %s: %s (%s) - %s", search_type, name, uri, match_type)
return {"uri": uri, "name": name, "type": search_type}
else:
_LOGGER.warning("No results found for query: %s", query)
@@ -168,11 +270,12 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
return {"error": "Search failed"}
async def clear_cache(call: ServiceCall):
"""Clear Spotify client cache."""
if _spotify_cache["client"] is not None:
_LOGGER.info("Manually clearing Spotify client cache")
"""Clear Spotify client and user playlists cache."""
if _spotify_cache["client"] is not None or _spotify_cache["user_playlists"] is not None:
_LOGGER.info("Manually clearing Spotify cache")
_spotify_cache["client"] = None
_spotify_cache["entity_id"] = None
_spotify_cache["user_playlists"] = None
return {"success": True, "message": "Cache cleared"}
else:
return {"success": False, "message": "Cache was already empty"}
@@ -1,6 +1,6 @@
search:
name: Search Spotify
description: Search Spotify for artists, albums, tracks, or playlists and return the Spotify URI. Uses exact match when available for artist searches. Leverages your existing Home Assistant Spotify integration - no additional authentication needed.
description: Search Spotify for artists, albums, tracks, or playlists and return the Spotify URI. Uses exact match when available. Leverages your existing Home Assistant Spotify integration - no additional authentication needed.
fields:
query:
name: Query
@@ -11,7 +11,7 @@ search:
text:
type:
name: Type
description: Type of content to search for. Artist search uses exact name matching to avoid personalized recommendations.
description: Type of content to search for. All search types use exact name matching when possible. Use 'user_playlist' to search only within your saved playlists.
required: false
default: "artist"
example: "artist"
@@ -22,7 +22,8 @@ search:
- "album"
- "track"
- "playlist"
- "user_playlist"
clear_cache:
name: Clear Cache
description: Clear the cached Spotify client. The integration caches the Spotify client reference for performance (15-50x faster searches). Use this service if you experience issues after removing or re-adding the Spotify integration. The cache automatically invalidates when the Spotify integration is reloaded.
description: Clear the cached Spotify client and user playlist data. The integration caches for performance (15-50x faster searches). Use this service after adding/removing playlists in Spotify or if you experience issues after removing or re-adding the Spotify integration. The cache automatically invalidates when the Spotify integration is reloaded.