diff --git a/beets/plugins.py b/beets/plugins.py index c14d7b423..8974cb117 100644 --- a/beets/plugins.py +++ b/beets/plugins.py @@ -705,22 +705,27 @@ class MetadataSourcePlugin(metaclass=abc.ABCMeta): return artist_string, artist_id - def _get_id(self, url_type, id_): + @staticmethod + def _get_id(url_type, id_, id_regex): """Parse an ID from its URL if necessary. :param url_type: Type of URL. Either 'album' or 'track'. :type url_type: str :param id_: Album/track ID or URL. :type id_: str + :param id_regex: A dictionary containing a regular expression + extracting an ID from an URL (if it's not an ID already) in + 'pattern' and the number of the match group in 'match_group'. + :type id_regex: dict :return: Album/track ID. :rtype: str """ - self._log.debug( - "Searching {} for {} '{}'", self.data_source, url_type, id_ + log.debug( + "Extracting {} ID from '{}'", url_type, id_ ) - match = re.search(self.id_regex['pattern'].format(url_type), str(id_)) + match = re.search(id_regex['pattern'].format(url_type), str(id_)) if match: - id_ = match.group(self.id_regex['match_group']) + id_ = match.group(id_regex['match_group']) if id_: return id_ return None diff --git a/beetsplug/spotify.py b/beetsplug/spotify.py index 393e9c50a..026b9da1c 100644 --- a/beetsplug/spotify.py +++ b/beetsplug/spotify.py @@ -32,6 +32,7 @@ from beets.autotag.hooks import AlbumInfo, TrackInfo from beets.dbcore import types from beets.library import DateType from beets.plugins import BeetsPlugin, MetadataSourcePlugin +from beets.util.id_extractors import spotify_id_regex DEFAULT_WAITING_TIME = 5 @@ -69,12 +70,7 @@ class SpotifyPlugin(MetadataSourcePlugin, BeetsPlugin): track_url = 'https://api.spotify.com/v1/tracks/' audio_features_url = 'https://api.spotify.com/v1/audio-features/' - # Spotify IDs consist of 22 alphanumeric characters - # (zero-left-padded base62 representation of randomly generated UUID4) - id_regex = { - 'pattern': r'(^|open\.spotify\.com/{}/)([0-9A-Za-z]{{22}})', - 'match_group': 2, - } + id_regex = spotify_id_regex spotify_audio_features = { 'acousticness': 'spotify_acousticness', @@ -216,7 +212,7 @@ class SpotifyPlugin(MetadataSourcePlugin, BeetsPlugin): :return: AlbumInfo object for album :rtype: beets.autotag.hooks.AlbumInfo or None """ - spotify_id = self._get_id('album', album_id) + spotify_id = self._get_id('album', album_id, self.id_regex) if spotify_id is None: return None @@ -330,7 +326,7 @@ class SpotifyPlugin(MetadataSourcePlugin, BeetsPlugin): :rtype: beets.autotag.hooks.TrackInfo or None """ if track_data is None: - spotify_id = self._get_id('track', track_id) + spotify_id = self._get_id('track', track_id, self.id_regex) if spotify_id is None: return None track_data = self._handle_response(