Skip to content

Commit

Permalink
handle spotify web URLs as well
Browse files Browse the repository at this point in the history
This automatically converts spotify web URLs (e.g.
https://open.spotify.com/track/XXX) to spotify URIs.

Signed-off-by: Casey Callendrello <[email protected]>
  • Loading branch information
squeed committed Apr 4, 2023
1 parent d8816cd commit 3fe1944
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
4 changes: 4 additions & 0 deletions custom_components/spotcast/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
get_random_playlist_from_category,
get_search_results,
is_valid_uri,
url_to_spotify_uri,
)

from .spotcast_controller import SpotcastController
Expand Down Expand Up @@ -206,6 +207,9 @@ def start_casting(call: ha_core.ServiceCall):
# remove ? from badly formatted URI
uri = uri.split("?")[0]

if uri.startswith("https"):
uri = url_to_spotify_uri(uri)

if not is_valid_uri(uri):
_LOGGER.error("Invalid URI provided, aborting casting")
return
Expand Down
24 changes: 23 additions & 1 deletion custom_components/spotcast/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import asyncio
import logging
import requests
import urllib
import urllib.parse
import difflib
import random
from functools import partial, wraps
Expand Down Expand Up @@ -171,6 +171,28 @@ def get_random_playlist_from_category(spotify_client:spotipy.Spotify, category:s

return chosen['uri']


def url_to_spotify_uri(url: str) -> str:
"""
Convert a spotify web url (e.g. https://open.spotify.com/track/XXXX) to
a spotify-style URI (spotify:track:XXXX). Returns None on error.
"""

o: urllib.parse.ParseResult
try:
o = urllib.parse.urlparse(url)
except ValueError:
return None

if o.hostname != "open.spotify.com":
return None

path = o.path.split("/")
if len(path) != 3:
return None

return f'spotify:{path[1]}:{path[2]}'

def is_valid_uri(uri: str) -> bool:

# list of possible types
Expand Down

0 comments on commit 3fe1944

Please sign in to comment.