| 1 |
"""Adds Beatport release and track search support to the autotagger""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import json |
| 6 |
import re |
| 7 |
from datetime import datetime, timedelta |
| 8 |
from typing import TYPE_CHECKING, Literal, overload |
| 9 |
|
| 10 |
import confuse |
| 11 |
from requests_oauthlib import OAuth1Session |
| 12 |
from requests_oauthlib.oauth1_session import ( |
| 13 |
TokenMissing, |
| 14 |
TokenRequestDenied, |
| 15 |
VerifierMissing, |
| 16 |
) |
| 17 |
|
| 18 |
import beets |
| 19 |
import beets.ui |
| 20 |
from beets import config |
| 21 |
from beets.autotag import AlbumInfo, TrackInfo |
| 22 |
from beets.exceptions import UserError |
| 23 |
from beets.metadata_plugins import MetadataSourcePlugin |
| 24 |
from beets.util import unique_list |
| 25 |
from beets.util.deprecation import deprecate_for_user |
| 26 |
|
| 27 |
if TYPE_CHECKING: |
| 28 |
from collections.abc import Iterable, Iterator, Sequence |
| 29 |
|
| 30 |
from beets.library import Item |
| 31 |
|
| 32 |
from ._typing import JSONDict |
| 33 |
|
| 34 |
AUTH_ERRORS = (TokenRequestDenied, TokenMissing, VerifierMissing) |
| 35 |
USER_AGENT = f"beets/{beets.__version__} +https://beets.io/" |
| 36 |
|
| 37 |
|
| 38 |
class BeatportAPIError(Exception): |
| 39 |
pass |
| 40 |
|
| 41 |
|
| 42 |
class BeatportClient: |
| 43 |
_api_base = "https://oauth-api.beatport.com" |
| 44 |
|
| 45 |
def __init__( |
| 46 |
self, |
| 47 |
c_key: str, |
| 48 |
c_secret: str, |
| 49 |
auth_key: str | None = None, |
| 50 |
auth_secret: str | None = None, |
| 51 |
) -> None: |
| 52 |
"""Initiate the client with OAuth information. |
| 53 |
|
| 54 |
For the initial authentication with the backend `auth_key` and |
| 55 |
`auth_secret` can be `None`. Use `get_authorize_url` and |
| 56 |
`get_access_token` to obtain them for subsequent uses of the API. |
| 57 |
|
| 58 |
:param c_key: OAuth1 client key |
| 59 |
:param c_secret: OAuth1 client secret |
| 60 |
:param auth_key: OAuth1 resource owner key |
| 61 |
:param auth_secret: OAuth1 resource owner secret |
| 62 |
""" |
| 63 |
self.api = OAuth1Session( |
| 64 |
client_key=c_key, |
| 65 |
client_secret=c_secret, |
| 66 |
resource_owner_key=auth_key, |
| 67 |
resource_owner_secret=auth_secret, |
| 68 |
callback_uri="oob", |
| 69 |
) |
| 70 |
self.api.headers = {"User-Agent": USER_AGENT} |
| 71 |
|
| 72 |
def get_authorize_url(self) -> str: |
| 73 |
"""Generate the URL for the user to authorize the application. |
| 74 |
|
| 75 |
Retrieves a request token from the Beatport API and returns the |
| 76 |
corresponding authorization URL on their end that the user has |
| 77 |
to visit. |
| 78 |
|
| 79 |
This is the first step of the initial authorization process with the |
| 80 |
API. Once the user has visited the URL, call |
| 81 |
:py:method:`get_access_token` with the displayed data to complete |
| 82 |
the process. |
| 83 |
|
| 84 |
:returns: Authorization URL for the user to visit |
| 85 |
:rtype: unicode |
| 86 |
""" |
| 87 |
self.api.fetch_request_token( |
| 88 |
self._make_url("/identity/1/oauth/request-token") |
| 89 |
) |
| 90 |
return self.api.authorization_url( |
| 91 |
self._make_url("/identity/1/oauth/authorize") |
| 92 |
) |
| 93 |
|
| 94 |
def get_access_token(self, auth_data: str) -> tuple[str, str]: |
| 95 |
"""Obtain the final access token and secret for the API. |
| 96 |
|
| 97 |
:param auth_data: URL-encoded authorization data as displayed at |
| 98 |
the authorization url (obtained via |
| 99 |
:py:meth:`get_authorize_url`) after signing in |
| 100 |
:returns: OAuth resource owner key and secret as unicode |
| 101 |
""" |
| 102 |
self.api.parse_authorization_response( |
| 103 |
f"https://beets.io/auth?{auth_data}" |
| 104 |
) |
| 105 |
access_data = self.api.fetch_access_token( |
| 106 |
self._make_url("/identity/1/oauth/access-token") |
| 107 |
) |
| 108 |
return access_data["oauth_token"], access_data["oauth_token_secret"] |
| 109 |
|
| 110 |
@overload |
| 111 |
def search( |
| 112 |
self, query: str, release_type: Literal["release"], details: bool = True |
| 113 |
) -> Iterator[BeatportRelease]: ... |
| 114 |
|
| 115 |
@overload |
| 116 |
def search( |
| 117 |
self, query: str, release_type: Literal["track"], details: bool = True |
| 118 |
) -> Iterator[BeatportTrack]: ... |
| 119 |
|
| 120 |
def search( |
| 121 |
self, |
| 122 |
query: str, |
| 123 |
release_type: Literal["release", "track"], |
| 124 |
details: bool = True, |
| 125 |
) -> Iterator[BeatportRelease | BeatportTrack]: |
| 126 |
"""Perform a search of the Beatport catalogue. |
| 127 |
|
| 128 |
:param query: Query string |
| 129 |
:param release_type: Type of releases to search for. |
| 130 |
:param details: Retrieve additional information about the |
| 131 |
search results. Currently this will fetch |
| 132 |
the tracklist for releases and do nothing for |
| 133 |
tracks |
| 134 |
:returns: Search results |
| 135 |
""" |
| 136 |
response = self._get( |
| 137 |
"catalog/3/search", |
| 138 |
query=query, |
| 139 |
perPage=5, |
| 140 |
facets=[f"fieldType:{release_type}"], |
| 141 |
) |
| 142 |
for item in response: |
| 143 |
if release_type == "release": |
| 144 |
release = BeatportRelease(item) |
| 145 |
if details: |
| 146 |
release.tracks = self.get_release_tracks(item["id"]) |
| 147 |
yield release |
| 148 |
elif release_type == "track": |
| 149 |
yield BeatportTrack(item) |
| 150 |
|
| 151 |
def get_release(self, beatport_id: str) -> BeatportRelease | None: |
| 152 |
"""Get information about a single release. |
| 153 |
|
| 154 |
:param beatport_id: Beatport ID of the release |
| 155 |
:returns: The matching release |
| 156 |
""" |
| 157 |
response = self._get("/catalog/3/releases", id=beatport_id) |
| 158 |
if response: |
| 159 |
release = BeatportRelease(response[0]) |
| 160 |
release.tracks = self.get_release_tracks(beatport_id) |
| 161 |
return release |
| 162 |
return None |
| 163 |
|
| 164 |
def get_release_tracks(self, beatport_id: str) -> list[BeatportTrack]: |
| 165 |
"""Get all tracks for a given release. |
| 166 |
|
| 167 |
:param beatport_id: Beatport ID of the release |
| 168 |
:returns: Tracks in the matching release |
| 169 |
""" |
| 170 |
response = self._get( |
| 171 |
"/catalog/3/tracks", releaseId=beatport_id, perPage=100 |
| 172 |
) |
| 173 |
return [BeatportTrack(t) for t in response] |
| 174 |
|
| 175 |
def get_track(self, beatport_id: str) -> BeatportTrack: |
| 176 |
"""Get information about a single track. |
| 177 |
|
| 178 |
:param beatport_id: Beatport ID of the track |
| 179 |
:returns: The matching track |
| 180 |
""" |
| 181 |
response = self._get("/catalog/3/tracks", id=beatport_id) |
| 182 |
return BeatportTrack(response[0]) |
| 183 |
|
| 184 |
def _make_url(self, endpoint: str) -> str: |
| 185 |
"""Get complete URL for a given API endpoint.""" |
| 186 |
if not endpoint.startswith("/"): |
| 187 |
endpoint = f"/{endpoint}" |
| 188 |
return f"{self._api_base}{endpoint}" |
| 189 |
|
| 190 |
def _get(self, endpoint: str, **kwargs) -> list[JSONDict]: |
| 191 |
"""Perform a GET request on a given API endpoint. |
| 192 |
|
| 193 |
Automatically extracts result data from the response and converts HTTP |
| 194 |
exceptions into :py:class:`BeatportAPIError` objects. |
| 195 |
""" |
| 196 |
try: |
| 197 |
response = self.api.get(self._make_url(endpoint), params=kwargs) |
| 198 |
except Exception as e: |
| 199 |
raise BeatportAPIError(f"Error connecting to Beatport API: {e}") |
| 200 |
if not response: |
| 201 |
raise BeatportAPIError( |
| 202 |
f"Error {response.status_code} for '{response.request.path_url}" |
| 203 |
) |
| 204 |
return response.json()["results"] |
| 205 |
|
| 206 |
|
| 207 |
class BeatportObject: |
| 208 |
beatport_id: str |
| 209 |
name: str |
| 210 |
|
| 211 |
release_date: datetime | None = None |
| 212 |
|
| 213 |
artists: list[tuple[str, str]] | None = None |
| 214 |
# tuple of artist id and artist name |
| 215 |
|
| 216 |
def __init__(self, data: JSONDict) -> None: |
| 217 |
self.beatport_id = str(data["id"]) # given as int in the response |
| 218 |
self.name = str(data["name"]) |
| 219 |
if "releaseDate" in data: |
| 220 |
self.release_date = datetime.strptime( |
| 221 |
data["releaseDate"], "%Y-%m-%d" |
| 222 |
) |
| 223 |
if "artists" in data: |
| 224 |
self.artists = [(x["id"], str(x["name"])) for x in data["artists"]] |
| 225 |
|
| 226 |
self.genres = unique_list( |
| 227 |
x["name"] |
| 228 |
for x in (*data.get("subGenres", []), *data.get("genres", [])) |
| 229 |
) |
| 230 |
|
| 231 |
def artists_str(self) -> str | None: |
| 232 |
if self.artists is not None: |
| 233 |
if len(self.artists) < 4: |
| 234 |
artist_str = ", ".join(x[1] for x in self.artists) |
| 235 |
else: |
| 236 |
artist_str = "Various Artists" |
| 237 |
else: |
| 238 |
artist_str = None |
| 239 |
|
| 240 |
return artist_str |
| 241 |
|
| 242 |
|
| 243 |
class BeatportRelease(BeatportObject): |
| 244 |
catalog_number: str | None |
| 245 |
label_name: str | None |
| 246 |
category: str | None |
| 247 |
url: str | None |
| 248 |
|
| 249 |
tracks: list[BeatportTrack] | None = None |
| 250 |
|
| 251 |
def __init__(self, data: JSONDict) -> None: |
| 252 |
super().__init__(data) |
| 253 |
|
| 254 |
self.catalog_number = data.get("catalogNumber") |
| 255 |
self.label_name = data.get("label", {}).get("name") |
| 256 |
self.category = data.get("category") |
| 257 |
|
| 258 |
if "slug" in data: |
| 259 |
self.url = ( |
| 260 |
f"https://beatport.com/release/{data['slug']}/{data['id']}" |
| 261 |
) |
| 262 |
|
| 263 |
def __str__(self) -> str: |
| 264 |
return ( |
| 265 |
"<BeatportRelease: " |
| 266 |
f"{self.artists_str()} - {self.name} ({self.catalog_number})>" |
| 267 |
) |
| 268 |
|
| 269 |
|
| 270 |
class BeatportTrack(BeatportObject): |
| 271 |
title: str | None |
| 272 |
mix_name: str | None |
| 273 |
length: timedelta |
| 274 |
url: str | None |
| 275 |
track_number: int | None |
| 276 |
bpm: str | None |
| 277 |
initial_key: str | None |
| 278 |
|
| 279 |
def __init__(self, data: JSONDict) -> None: |
| 280 |
super().__init__(data) |
| 281 |
if "title" in data: |
| 282 |
self.title = str(data["title"]) |
| 283 |
if "mixName" in data: |
| 284 |
self.mix_name = str(data["mixName"]) |
| 285 |
self.length = timedelta(milliseconds=data.get("lengthMs", 0) or 0) |
| 286 |
if not self.length: |
| 287 |
try: |
| 288 |
min_, sec = data.get("length", "0:0").split(":") |
| 289 |
self.length = timedelta(minutes=int(min_), seconds=int(sec)) |
| 290 |
except ValueError: |
| 291 |
pass |
| 292 |
if "slug" in data: |
| 293 |
self.url = f"https://beatport.com/track/{data['slug']}/{data['id']}" |
| 294 |
self.track_number = data.get("trackNumber") |
| 295 |
self.bpm = data.get("bpm") |
| 296 |
self.initial_key = str((data.get("key") or {}).get("shortName")) |
| 297 |
|
| 298 |
|
| 299 |
class BeatportPlugin(MetadataSourcePlugin): |
| 300 |
_client: BeatportClient | None = None |
| 301 |
|
| 302 |
def __init__(self) -> None: |
| 303 |
super().__init__() |
| 304 |
deprecate_for_user(self._log, "The 'beatport' plugin") |
| 305 |
self.config.add( |
| 306 |
{ |
| 307 |
"apikey": "57713c3906af6f5def151b33601389176b37b429", |
| 308 |
"apisecret": "b3fe08c93c80aefd749fe871a16cd2bb32e2b954", |
| 309 |
"tokenfile": "beatport_token.json", |
| 310 |
} |
| 311 |
) |
| 312 |
self.config["apikey"].redact = True |
| 313 |
self.config["apisecret"].redact = True |
| 314 |
self.setup() |
| 315 |
|
| 316 |
@property |
| 317 |
def client(self) -> BeatportClient: |
| 318 |
if self._client is None: |
| 319 |
raise ValueError( |
| 320 |
"Beatport client not initialized. Call setup() first." |
| 321 |
) |
| 322 |
return self._client |
| 323 |
|
| 324 |
def setup(self) -> None: |
| 325 |
c_key = self.config["apikey"].as_str() |
| 326 |
c_secret = self.config["apisecret"].as_str() |
| 327 |
|
| 328 |
# Get the OAuth token from a file or log in. |
| 329 |
try: |
| 330 |
with open(self._tokenfile()) as f: |
| 331 |
tokendata = json.load(f) |
| 332 |
except OSError: |
| 333 |
# No token yet. Generate one. |
| 334 |
token, secret = self.authenticate(c_key, c_secret) |
| 335 |
else: |
| 336 |
token = tokendata["token"] |
| 337 |
secret = tokendata["secret"] |
| 338 |
|
| 339 |
self._client = BeatportClient(c_key, c_secret, token, secret) |
| 340 |
|
| 341 |
def authenticate(self, c_key: str, c_secret: str) -> tuple[str, str]: |
| 342 |
# Get the link for the OAuth page. |
| 343 |
auth_client = BeatportClient(c_key, c_secret) |
| 344 |
try: |
| 345 |
url = auth_client.get_authorize_url() |
| 346 |
except AUTH_ERRORS as e: |
| 347 |
self._log.debug("authentication error: {}", e) |
| 348 |
raise UserError("communication with Beatport failed") |
| 349 |
|
| 350 |
beets.ui.print_("To authenticate with Beatport, visit:") |
| 351 |
beets.ui.print_(url) |
| 352 |
|
| 353 |
# Ask for the verifier data and validate it. |
| 354 |
data = beets.ui.input_("Enter the string displayed in your browser:") |
| 355 |
try: |
| 356 |
token, secret = auth_client.get_access_token(data) |
| 357 |
except AUTH_ERRORS as e: |
| 358 |
self._log.debug("authentication error: {}", e) |
| 359 |
raise UserError("Beatport token request failed") |
| 360 |
|
| 361 |
# Save the token for later use. |
| 362 |
self._log.debug("Beatport token {}, secret {}", token, secret) |
| 363 |
with open(self._tokenfile(), "w") as f: |
| 364 |
json.dump({"token": token, "secret": secret}, f) |
| 365 |
|
| 366 |
return token, secret |
| 367 |
|
| 368 |
def _tokenfile(self) -> str: |
| 369 |
"""Get the path to the JSON file for storing the OAuth token.""" |
| 370 |
return self.config["tokenfile"].get(confuse.Filename(in_app_dir=True)) |
| 371 |
|
| 372 |
def candidates( |
| 373 |
self, items: Sequence[Item], artist: str, album: str, va_likely: bool |
| 374 |
) -> Iterator[AlbumInfo]: |
| 375 |
if va_likely: |
| 376 |
query = album |
| 377 |
else: |
| 378 |
query = f"{artist} {album}" |
| 379 |
try: |
| 380 |
yield from self._get_releases(query) |
| 381 |
except BeatportAPIError as e: |
| 382 |
self._log.debug("API Error: {} (query: {})", e, query) |
| 383 |
return |
| 384 |
|
| 385 |
def item_candidates( |
| 386 |
self, item: Item, artist: str, title: str |
| 387 |
) -> Iterable[TrackInfo]: |
| 388 |
query = f"{artist} {title}" |
| 389 |
try: |
| 390 |
return self._get_tracks(query) |
| 391 |
except BeatportAPIError as e: |
| 392 |
self._log.debug("API Error: {} (query: {})", e, query) |
| 393 |
return [] |
| 394 |
|
| 395 |
def album_for_id(self, album_id: str) -> AlbumInfo | None: |
| 396 |
"""Fetches a release by its Beatport ID and returns an AlbumInfo object |
| 397 |
or None if the query is not a valid ID or release is not found. |
| 398 |
""" |
| 399 |
self._log.debug("Searching for release {}", album_id) |
| 400 |
|
| 401 |
if not (release_id := self._extract_id(album_id)): |
| 402 |
self._log.debug("Not a valid Beatport release ID.") |
| 403 |
return None |
| 404 |
|
| 405 |
release = self.client.get_release(release_id) |
| 406 |
if release: |
| 407 |
return self._get_album_info(release) |
| 408 |
return None |
| 409 |
|
| 410 |
def track_for_id(self, track_id: str) -> TrackInfo | None: |
| 411 |
"""Fetches a track by its Beatport ID and returns a TrackInfo object |
| 412 |
or None if the track is not a valid Beatport ID or track is not found. |
| 413 |
""" |
| 414 |
self._log.debug("Searching for track {}", track_id) |
| 415 |
# TODO: move to extractor |
| 416 |
match = re.search(r"(^|beatport\.com/track/.+/)(\d+)$", track_id) |
| 417 |
if not match: |
| 418 |
self._log.debug("Not a valid Beatport track ID.") |
| 419 |
return None |
| 420 |
bp_track = self.client.get_track(match.group(2)) |
| 421 |
if bp_track is not None: |
| 422 |
return self._get_track_info(bp_track) |
| 423 |
return None |
| 424 |
|
| 425 |
def _get_releases(self, query: str) -> Iterator[AlbumInfo]: |
| 426 |
"""Returns a list of AlbumInfo objects for a beatport search query.""" |
| 427 |
# Strip non-word characters from query. Things like "!" and "-" can |
| 428 |
# cause a query to return no results, even if they match the artist or |
| 429 |
# album title. Use `re.UNICODE` flag to avoid stripping non-english |
| 430 |
# word characters. |
| 431 |
query = re.sub(r"\W+", " ", query, flags=re.UNICODE) |
| 432 |
# Strip medium information from query, Things like "CD1" and "disk 1" |
| 433 |
# can also negate an otherwise positive result. |
| 434 |
query = re.sub(r"\b(CD|disc)\s*\d+", "", query, flags=re.I) |
| 435 |
for beatport_release in self.client.search(query, "release"): |
| 436 |
if beatport_release is None: |
| 437 |
continue |
| 438 |
yield self._get_album_info(beatport_release) |
| 439 |
|
| 440 |
def _get_album_info(self, release: BeatportRelease) -> AlbumInfo: |
| 441 |
"""Returns an AlbumInfo object for a Beatport Release object.""" |
| 442 |
va = release.artists is not None and len(release.artists) > 3 |
| 443 |
artist, artist_id = self._get_artist(release.artists) |
| 444 |
if va: |
| 445 |
artist = config["va_name"].as_str() |
| 446 |
tracks: list[TrackInfo] = [] |
| 447 |
if release.tracks is not None: |
| 448 |
tracks = [self._get_track_info(x) for x in release.tracks] |
| 449 |
|
| 450 |
release_date = release.release_date |
| 451 |
|
| 452 |
return AlbumInfo( |
| 453 |
album=release.name, |
| 454 |
album_id=release.beatport_id, |
| 455 |
beatport_album_id=release.beatport_id, |
| 456 |
artist=artist, |
| 457 |
artist_id=artist_id, |
| 458 |
tracks=tracks, |
| 459 |
albumtype=release.category, |
| 460 |
va=va, |
| 461 |
label=release.label_name, |
| 462 |
catalognum=release.catalog_number, |
| 463 |
media="Digital", |
| 464 |
data_source=self.data_source, |
| 465 |
data_url=release.url, |
| 466 |
genres=release.genres, |
| 467 |
year=release_date.year if release_date else None, |
| 468 |
month=release_date.month if release_date else None, |
| 469 |
day=release_date.day if release_date else None, |
| 470 |
) |
| 471 |
|
| 472 |
def _get_track_info(self, track: BeatportTrack) -> TrackInfo: |
| 473 |
"""Returns a TrackInfo object for a Beatport Track object.""" |
| 474 |
title = track.name |
| 475 |
if track.mix_name != "Original Mix": |
| 476 |
title += f" ({track.mix_name})" |
| 477 |
artist, artist_id = self._get_artist(track.artists) |
| 478 |
length = track.length.total_seconds() |
| 479 |
return TrackInfo( |
| 480 |
title=title, |
| 481 |
track_id=track.beatport_id, |
| 482 |
artist=artist, |
| 483 |
artist_id=artist_id, |
| 484 |
length=length, |
| 485 |
index=track.track_number, |
| 486 |
medium_index=track.track_number, |
| 487 |
data_source=self.data_source, |
| 488 |
data_url=track.url, |
| 489 |
bpm=track.bpm, |
| 490 |
initial_key=track.initial_key, |
| 491 |
genres=track.genres, |
| 492 |
) |
| 493 |
|
| 494 |
def _get_artist( |
| 495 |
self, artists: Iterable[tuple[str, str]] | None |
| 496 |
) -> tuple[str, str | None]: |
| 497 |
"""Returns an artist string (all artists) and an artist_id (the main |
| 498 |
artist) for a list of Beatport release or track artists. |
| 499 |
""" |
| 500 |
return self.get_artist(artists or [], id_key=0, name_key=1) # type: ignore[arg-type] |
| 501 |
|
| 502 |
def _get_tracks(self, query: str) -> list[TrackInfo]: |
| 503 |
"""Returns a list of TrackInfo objects for a Beatport query.""" |
| 504 |
bp_tracks = self.client.search(query, release_type="track") |
| 505 |
return [self._get_track_info(x) for x in bp_tracks] |