Refactor MetadataSourcePlugin._get_id()

and put to use in Spotify plugin.

- Make _get_id() a staticmethod usable from outside a metadata source plugin.
- id_regex now has to be passed as an argument instead of assuming it is
  accessible via an instance variable (self.id_regex).
- In the Spotify plugin, import spotify_id_regex from util.id_extractors
This commit is contained in:
J0J0 Todos 2023-01-11 09:18:40 +01:00
parent 0175a9aed8
commit 284180ec75
2 changed files with 14 additions and 13 deletions

View file

@ -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

View file

@ -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(