"""Spotify lookup logic.""" import re from urllib.parse import urlparse SPOTIFY_ID_PATTERN = re.compile(r"^[a-zA-Z0-9]{22}$") def parse_spotify_album_id(query: str) -> str: """Extract a Spotify album ID from a URI, URL, or raw ID. Supported formats: - Spotify URI: spotify:album:5b7UrNnuckYDfCp6ZW0Sji - Spotify ID: 5b7UrNnuckYDfCp6ZW0Sji - Spotify URL: https://open.spotify.com/album/5b7UrNnuckYDfCp6ZW0Sji - Spotify URL w/ query string: https://open.spotify.com/album/5b7UrNnuckYDfCp6ZW0Sji?si=... Args: query: The raw query string containing a Spotify album identifier. Returns: The extracted Spotify album ID. Raises: ValueError: If the query does not contain a valid Spotify album identifier. """ query = query.strip() # Spotify URI: spotify:album: if query.startswith("spotify:album:"): album_id = query.split(":", 2)[2] if SPOTIFY_ID_PATTERN.match(album_id): return album_id raise ValueError(f"Invalid Spotify album ID in URI: {query}") # Spotify URL: https://open.spotify.com/album/[?...] if query.startswith("http://") or query.startswith("https://"): parsed = urlparse(query) path_parts = parsed.path.strip("/").split("/") if len(path_parts) == 2 and path_parts[0] == "album": album_id = path_parts[1] if SPOTIFY_ID_PATTERN.match(album_id): return album_id raise ValueError(f"Invalid Spotify album URL: {query}") # Raw Spotify ID if SPOTIFY_ID_PATTERN.match(query): return query raise ValueError(f"Could not extract Spotify album ID from query: {query}") def parse_spotify_artist_id(query: str) -> str: """Extract a Spotify artist ID from a URI, URL, or raw ID. Supported formats: - Spotify URI: spotify:artist:4QkSD9TRUnMtI8Fq1jXJJe - Spotify ID: 4QkSD9TRUnMtI8Fq1jXJJe - Spotify URL: https://open.spotify.com/artist/4QkSD9TRUnMtI8Fq1jXJJe - Spotify URL w/ query string: https://open.spotify.com/artist/4QkSD9TRUnMtI8Fq1jXJJe?si=... Args: query: The raw query string containing a Spotify artist identifier. Returns: The extracted Spotify artist ID. Raises: ValueError: If the query does not contain a valid Spotify artist identifier. """ query = query.strip() # Spotify URI: spotify:artist: if query.startswith("spotify:artist:"): artist_id = query.split(":", 2)[2] if SPOTIFY_ID_PATTERN.match(artist_id): return artist_id raise ValueError(f"Invalid Spotify artist ID in URI: {query}") # Spotify URL: https://open.spotify.com/artist/[?...] if query.startswith("http://") or query.startswith("https://"): parsed = urlparse(query) path_parts = parsed.path.strip("/").split("/") if len(path_parts) == 2 and path_parts[0] == "artist": artist_id = path_parts[1] if SPOTIFY_ID_PATTERN.match(artist_id): return artist_id raise ValueError(f"Invalid Spotify artist URL: {query}") # Raw Spotify ID if SPOTIFY_ID_PATTERN.match(query): return query raise ValueError(f"Could not extract Spotify artist ID from query: {query}")