| 1 |
"""Adds Spotify release and track search support to the autotagger. |
| 2 |
|
| 3 |
Also includes Spotify playlist construction. |
| 4 |
""" |
| 5 |
|
| 6 |
from __future__ import annotations |
| 7 |
|
| 8 |
import base64 |
| 9 |
import collections |
| 10 |
import json |
| 11 |
import re |
| 12 |
import threading |
| 13 |
import time |
| 14 |
import webbrowser |
| 15 |
from http import HTTPStatus |
| 16 |
from typing import TYPE_CHECKING, Any, ClassVar, Literal, Protocol, TypedDict |
| 17 |
|
| 18 |
import confuse |
| 19 |
import requests |
| 20 |
|
| 21 |
from beets import ui |
| 22 |
from beets.autotag import AlbumInfo, TrackInfo |
| 23 |
from beets.dbcore import types |
| 24 |
from beets.exceptions import UserError |
| 25 |
from beets.library import Library |
| 26 |
from beets.metadata_plugins import IDResponse, SearchApiMetadataSourcePlugin |
| 27 |
from beets.util import chunks |
| 28 |
|
| 29 |
if TYPE_CHECKING: |
| 30 |
from collections.abc import Iterable, Mapping, Sequence |
| 31 |
|
| 32 |
from beets.library import Item, Library |
| 33 |
from beets.metadata_plugins import QueryType, SearchParams |
| 34 |
from beetsplug._typing import JSONDict |
| 35 |
|
| 36 |
DEFAULT_WAITING_TIME = 5 |
| 37 |
|
| 38 |
|
| 39 |
class SpotifyCLIOpts(Protocol): |
| 40 |
mode: str | None |
| 41 |
show_failures: bool | None |
| 42 |
|
| 43 |
|
| 44 |
class SpotifySyncCLIOpts(Protocol): |
| 45 |
force_refetch: bool |
| 46 |
|
| 47 |
|
| 48 |
class TrackDetails(TypedDict): |
| 49 |
"""Popularity and external IDs returned by the /v1/tracks batch endpoint.""" |
| 50 |
|
| 51 |
spotify_track_popularity: int | None |
| 52 |
isrc: str | None |
| 53 |
ean: str | None |
| 54 |
upc: str | None |
| 55 |
|
| 56 |
|
| 57 |
class AudioFeatures(TypedDict, total=False): |
| 58 |
"""Audio feature fields returned by the /v1/audio-features endpoint.""" |
| 59 |
|
| 60 |
id: str |
| 61 |
acousticness: float |
| 62 |
danceability: float |
| 63 |
energy: float |
| 64 |
instrumentalness: float |
| 65 |
key: int |
| 66 |
liveness: float |
| 67 |
loudness: float |
| 68 |
mode: int |
| 69 |
speechiness: float |
| 70 |
tempo: float |
| 71 |
time_signature: int |
| 72 |
valence: float |
| 73 |
|
| 74 |
|
| 75 |
class SearchResponseAlbums(IDResponse): |
| 76 |
"""A response returned by the Spotify API. |
| 77 |
|
| 78 |
We only use items and disregard the pagination information. i.e. |
| 79 |
res["albums"]["items"][0]. |
| 80 |
|
| 81 |
There are more fields in the response, but we only type the ones we |
| 82 |
currently use. |
| 83 |
|
| 84 |
see https://developer.spotify.com/documentation/web-api/reference/search |
| 85 |
|
| 86 |
""" |
| 87 |
|
| 88 |
album_type: str |
| 89 |
available_markets: Sequence[str] |
| 90 |
name: str |
| 91 |
|
| 92 |
|
| 93 |
class SearchResponseTracks(IDResponse): |
| 94 |
"""A track response returned by the Spotify API.""" |
| 95 |
|
| 96 |
album: SearchResponseAlbums |
| 97 |
available_markets: Sequence[str] |
| 98 |
popularity: int |
| 99 |
name: str |
| 100 |
|
| 101 |
|
| 102 |
class APIError(Exception): |
| 103 |
pass |
| 104 |
|
| 105 |
|
| 106 |
class AudioFeaturesUnavailableError(Exception): |
| 107 |
"""Raised when audio features API returns 403 (deprecated).""" |
| 108 |
|
| 109 |
|
| 110 |
class SpotifyPlugin( |
| 111 |
SearchApiMetadataSourcePlugin[SearchResponseAlbums | SearchResponseTracks] |
| 112 |
): |
| 113 |
item_types: ClassVar[dict[str, types.Type]] = { |
| 114 |
"spotify_track_popularity": types.INTEGER, |
| 115 |
"spotify_acousticness": types.FLOAT, |
| 116 |
"spotify_danceability": types.FLOAT, |
| 117 |
"spotify_energy": types.FLOAT, |
| 118 |
"spotify_instrumentalness": types.FLOAT, |
| 119 |
"spotify_key": types.FLOAT, |
| 120 |
"spotify_liveness": types.FLOAT, |
| 121 |
"spotify_loudness": types.FLOAT, |
| 122 |
"spotify_mode": types.INTEGER, |
| 123 |
"spotify_speechiness": types.FLOAT, |
| 124 |
"spotify_tempo": types.FLOAT, |
| 125 |
"spotify_time_signature": types.INTEGER, |
| 126 |
"spotify_valence": types.FLOAT, |
| 127 |
"spotify_updated": types.DATE, |
| 128 |
} |
| 129 |
|
| 130 |
# Base URLs for the Spotify API |
| 131 |
# Documentation: https://developer.spotify.com/web-api |
| 132 |
oauth_token_url = "https://accounts.spotify.com/api/token" |
| 133 |
open_track_url = "https://open.spotify.com/track/" |
| 134 |
search_url = "https://api.spotify.com/v1/search" |
| 135 |
album_url = "https://api.spotify.com/v1/albums/" |
| 136 |
track_url = "https://api.spotify.com/v1/tracks" |
| 137 |
audio_features_url = "https://api.spotify.com/v1/audio-features" |
| 138 |
|
| 139 |
spotify_audio_features: ClassVar[dict[str, str]] = { |
| 140 |
"acousticness": "spotify_acousticness", |
| 141 |
"danceability": "spotify_danceability", |
| 142 |
"energy": "spotify_energy", |
| 143 |
"instrumentalness": "spotify_instrumentalness", |
| 144 |
"key": "spotify_key", |
| 145 |
"liveness": "spotify_liveness", |
| 146 |
"loudness": "spotify_loudness", |
| 147 |
"mode": "spotify_mode", |
| 148 |
"speechiness": "spotify_speechiness", |
| 149 |
"tempo": "spotify_tempo", |
| 150 |
"time_signature": "spotify_time_signature", |
| 151 |
"valence": "spotify_valence", |
| 152 |
} |
| 153 |
|
| 154 |
def __init__(self) -> None: |
| 155 |
super().__init__() |
| 156 |
self.config.add( |
| 157 |
{ |
| 158 |
"mode": "list", |
| 159 |
"tiebreak": "popularity", |
| 160 |
"show_failures": False, |
| 161 |
"region_filter": None, |
| 162 |
"regex": [], |
| 163 |
"client_id": "4e414367a1d14c75a5c5129a627fcab8", |
| 164 |
"client_secret": "4a9b5b7848e54e118a7523b1c7c3e1e5", |
| 165 |
"tokenfile": "spotify_token.json", |
| 166 |
} |
| 167 |
) |
| 168 |
self.config["client_id"].redact = True |
| 169 |
self.config["client_secret"].redact = True |
| 170 |
|
| 171 |
self.audio_features_available = ( |
| 172 |
True # Track if audio features API is available |
| 173 |
) |
| 174 |
self._audio_features_lock = ( |
| 175 |
threading.Lock() |
| 176 |
) # Protects audio_features_available |
| 177 |
self.setup() |
| 178 |
|
| 179 |
def setup(self) -> None: |
| 180 |
"""Retrieve previously saved OAuth token or generate a new one.""" |
| 181 |
|
| 182 |
try: |
| 183 |
with open(self._tokenfile()) as f: |
| 184 |
token_data = json.load(f) |
| 185 |
except OSError: |
| 186 |
self._authenticate() |
| 187 |
else: |
| 188 |
self.access_token = token_data["access_token"] |
| 189 |
|
| 190 |
def _tokenfile(self) -> str: |
| 191 |
"""Get the path to the JSON file for storing the OAuth token.""" |
| 192 |
return self.config["tokenfile"].get(confuse.Filename(in_app_dir=True)) |
| 193 |
|
| 194 |
def _authenticate(self) -> None: |
| 195 |
"""Request an access token via the Client Credentials Flow: https://developer.spotify.com/documentation/general/guides/authorization-guide/#client-credentials-flow""" |
| 196 |
c_id = self.config["client_id"].as_str() |
| 197 |
c_secret = self.config["client_secret"].as_str() |
| 198 |
|
| 199 |
headers = { |
| 200 |
"Authorization": ( |
| 201 |
"Basic" |
| 202 |
f" {base64.b64encode(f'{c_id}:{c_secret}'.encode()).decode()}" |
| 203 |
) |
| 204 |
} |
| 205 |
response = requests.post( |
| 206 |
self.oauth_token_url, |
| 207 |
data={"grant_type": "client_credentials"}, |
| 208 |
headers=headers, |
| 209 |
timeout=10, |
| 210 |
) |
| 211 |
try: |
| 212 |
response.raise_for_status() |
| 213 |
except requests.exceptions.HTTPError as e: |
| 214 |
raise UserError( |
| 215 |
f"Spotify authorization failed: {e}\n{response.text}" |
| 216 |
) |
| 217 |
self.access_token = response.json()["access_token"] |
| 218 |
|
| 219 |
# Save the token for later use. |
| 220 |
self._log.debug("{0.data_source} access token: {0.access_token}", self) |
| 221 |
with open(self._tokenfile(), "w") as f: |
| 222 |
json.dump({"access_token": self.access_token}, f) |
| 223 |
|
| 224 |
def _handle_response( |
| 225 |
self, |
| 226 |
method: Literal["get", "post", "put", "delete"], |
| 227 |
url: str, |
| 228 |
params: Any = None, |
| 229 |
retry_count: int = 0, |
| 230 |
max_retries: int = 3, |
| 231 |
) -> JSONDict: |
| 232 |
"""Send a request, reauthenticating if necessary. |
| 233 |
|
| 234 |
:param method: HTTP method to use for the request. |
| 235 |
:param url: URL for the new :class:`Request` object. |
| 236 |
:param dict params: (optional) list of tuples or bytes to send |
| 237 |
in the query string for the :class:`Request`. |
| 238 |
|
| 239 |
""" |
| 240 |
|
| 241 |
if retry_count > max_retries: |
| 242 |
raise APIError("Maximum retries reached.") |
| 243 |
|
| 244 |
try: |
| 245 |
response = requests.request( |
| 246 |
method, |
| 247 |
url, |
| 248 |
headers={"Authorization": f"Bearer {self.access_token}"}, |
| 249 |
params=params, |
| 250 |
timeout=10, |
| 251 |
) |
| 252 |
response.raise_for_status() |
| 253 |
return response.json() |
| 254 |
except requests.exceptions.ReadTimeout: |
| 255 |
self._log.error("ReadTimeout.") |
| 256 |
raise APIError("Request timed out.") |
| 257 |
except requests.exceptions.ConnectionError as e: |
| 258 |
self._log.error("Network error: {}", e) |
| 259 |
raise APIError("Network error.") |
| 260 |
except requests.exceptions.RequestException as e: |
| 261 |
if e.response is None: |
| 262 |
self._log.error("Request failed: {}", e) |
| 263 |
raise APIError("Request failed.") |
| 264 |
if e.response.status_code == 401: |
| 265 |
self._log.debug( |
| 266 |
"{.data_source} access token has expired. Reauthenticating.", |
| 267 |
self, |
| 268 |
) |
| 269 |
self._authenticate() |
| 270 |
return self._handle_response( |
| 271 |
method, url, params=params, retry_count=retry_count + 1 |
| 272 |
) |
| 273 |
if e.response.status_code == 404: |
| 274 |
raise APIError( |
| 275 |
f"API Error: {e.response.status_code}\n" |
| 276 |
f"URL: {url}\nparams: {params}" |
| 277 |
) |
| 278 |
if e.response.status_code == 403: |
| 279 |
# Check if this is the audio features endpoint |
| 280 |
if url.startswith(self.audio_features_url): |
| 281 |
raise AudioFeaturesUnavailableError( |
| 282 |
"Audio features API returned 403 " |
| 283 |
"(deprecated or unavailable)" |
| 284 |
) |
| 285 |
raise APIError( |
| 286 |
f"API Error: {e.response.status_code}\n" |
| 287 |
f"URL: {url}\nparams: {params}" |
| 288 |
) |
| 289 |
if e.response.status_code == 429: |
| 290 |
seconds = e.response.headers.get( |
| 291 |
"Retry-After", DEFAULT_WAITING_TIME |
| 292 |
) |
| 293 |
self._log.debug( |
| 294 |
"Too many API requests. Retrying after {} seconds.", seconds |
| 295 |
) |
| 296 |
time.sleep(int(seconds) + 1) |
| 297 |
return self._handle_response( |
| 298 |
method, url, params=params, retry_count=retry_count + 1 |
| 299 |
) |
| 300 |
if e.response.status_code == 503: |
| 301 |
self._log.debug( |
| 302 |
"Service Unavailable. Retrying after {} seconds.", |
| 303 |
DEFAULT_WAITING_TIME, |
| 304 |
) |
| 305 |
time.sleep(DEFAULT_WAITING_TIME + 1) |
| 306 |
return self._handle_response( |
| 307 |
method, url, params=params, retry_count=retry_count + 1 |
| 308 |
) |
| 309 |
if e.response.status_code == 502: |
| 310 |
self._log.error("Bad Gateway.") |
| 311 |
raise APIError("Bad Gateway.") |
| 312 |
if e.response is not None: |
| 313 |
raise APIError( |
| 314 |
f"{self.data_source} API error:\n" |
| 315 |
f"{e.response.text}\n" |
| 316 |
f"URL:\n{url}\nparams:\n{params}" |
| 317 |
) |
| 318 |
self._log.error("Request failed. Error: {}", e) |
| 319 |
raise APIError("Request failed.") |
| 320 |
|
| 321 |
def _multi_artist_credit( |
| 322 |
self, artists: Iterable[dict[str | int, str]] |
| 323 |
) -> tuple[list[str], list[str]]: |
| 324 |
"""Given a list of artist dictionaries, accumulate data into a pair |
| 325 |
of lists: the first being the artist names, and the second being the |
| 326 |
artist IDs. |
| 327 |
""" |
| 328 |
artist_names = [] |
| 329 |
artist_ids = [] |
| 330 |
for artist in artists: |
| 331 |
artist_names.append(artist["name"]) |
| 332 |
artist_ids.append(artist["id"]) |
| 333 |
return artist_names, artist_ids |
| 334 |
|
| 335 |
def album_for_id(self, album_id: str) -> AlbumInfo | None: |
| 336 |
"""Fetch an album by its Spotify ID or URL and return an |
| 337 |
AlbumInfo object or None if the album is not found. |
| 338 |
|
| 339 |
:param str album_id: Spotify ID or URL for the album |
| 340 |
|
| 341 |
:returns: AlbumInfo object for album |
| 342 |
:rtype: beets.autotag.hooks.AlbumInfo or None |
| 343 |
|
| 344 |
""" |
| 345 |
if not (spotify_id := self._extract_id(album_id)): |
| 346 |
return None |
| 347 |
|
| 348 |
album_data = self._handle_response( |
| 349 |
"get", f"{self.album_url}{spotify_id}" |
| 350 |
) |
| 351 |
if album_data["name"] == "": |
| 352 |
self._log.debug("Album removed from Spotify: {}", album_id) |
| 353 |
return None |
| 354 |
artists_names, artists_ids = self._multi_artist_credit( |
| 355 |
album_data["artists"] |
| 356 |
) |
| 357 |
artist = ", ".join(artists_names) |
| 358 |
|
| 359 |
date_parts = [ |
| 360 |
int(part) for part in album_data["release_date"].split("-") |
| 361 |
] |
| 362 |
|
| 363 |
release_date_precision = album_data["release_date_precision"] |
| 364 |
if release_date_precision == "day": |
| 365 |
year, month, day = date_parts |
| 366 |
elif release_date_precision == "month": |
| 367 |
year, month = date_parts |
| 368 |
day = None |
| 369 |
elif release_date_precision == "year": |
| 370 |
year = date_parts[0] |
| 371 |
month = None |
| 372 |
day = None |
| 373 |
else: |
| 374 |
raise UserError( |
| 375 |
"Invalid `release_date_precision` returned " |
| 376 |
f"by {self.data_source} API: '{release_date_precision}'" |
| 377 |
) |
| 378 |
|
| 379 |
tracks_data = album_data["tracks"] |
| 380 |
tracks_items = tracks_data["items"] |
| 381 |
while tracks_data["next"]: |
| 382 |
tracks_data = self._handle_response("get", tracks_data["next"]) |
| 383 |
tracks_items.extend(tracks_data["items"]) |
| 384 |
|
| 385 |
tracks = [] |
| 386 |
medium_totals: dict[int | None, int] = collections.defaultdict(int) |
| 387 |
for i, track_data in enumerate(tracks_items, start=1): |
| 388 |
track = self._get_track(track_data) |
| 389 |
track.index = i |
| 390 |
medium_totals[track.medium] += 1 |
| 391 |
tracks.append(track) |
| 392 |
for track in tracks: |
| 393 |
track.medium_total = medium_totals[track.medium] |
| 394 |
|
| 395 |
return AlbumInfo( |
| 396 |
album=album_data["name"], |
| 397 |
album_id=spotify_id, |
| 398 |
spotify_album_id=spotify_id, |
| 399 |
artist=artist, |
| 400 |
artist_id=artists_ids[0] if len(artists_ids) > 0 else None, |
| 401 |
spotify_artist_id=artists_ids[0] if len(artists_ids) > 0 else None, |
| 402 |
artists=artists_names, |
| 403 |
artists_ids=artists_ids, |
| 404 |
tracks=tracks, |
| 405 |
albumtype=album_data["album_type"], |
| 406 |
va=len(album_data["artists"]) == 1 |
| 407 |
and artist.lower() == "various artists", |
| 408 |
year=year, |
| 409 |
month=month, |
| 410 |
day=day, |
| 411 |
label=album_data.get("label"), |
| 412 |
mediums=max(filter(None, medium_totals.keys())), |
| 413 |
data_source=self.data_source, |
| 414 |
data_url=album_data["external_urls"]["spotify"], |
| 415 |
) |
| 416 |
|
| 417 |
def _get_track(self, track_data: JSONDict) -> TrackInfo: |
| 418 |
"""Convert a Spotify track object dict to a TrackInfo object. |
| 419 |
|
| 420 |
:param track_data: Simplified track object |
| 421 |
(https://developer.spotify.com/documentation/web-api/reference/object-model/#track-object-simplified) |
| 422 |
|
| 423 |
:returns: TrackInfo object for track |
| 424 |
|
| 425 |
""" |
| 426 |
artists_names, artists_ids = self._multi_artist_credit( |
| 427 |
track_data["artists"] |
| 428 |
) |
| 429 |
artist = ", ".join(artists_names) |
| 430 |
|
| 431 |
# Get album information for spotify tracks |
| 432 |
try: |
| 433 |
album = track_data["album"]["name"] |
| 434 |
except (KeyError, TypeError): |
| 435 |
album = None |
| 436 |
return TrackInfo( |
| 437 |
title=track_data["name"], |
| 438 |
track_id=track_data["id"], |
| 439 |
spotify_track_id=track_data["id"], |
| 440 |
artist=artist, |
| 441 |
album=album, |
| 442 |
artist_id=artists_ids[0] if len(artists_ids) > 0 else None, |
| 443 |
spotify_artist_id=artists_ids[0] if len(artists_ids) > 0 else None, |
| 444 |
artists=artists_names, |
| 445 |
artists_ids=artists_ids, |
| 446 |
length=track_data["duration_ms"] / 1000, |
| 447 |
index=track_data["track_number"], |
| 448 |
medium=track_data["disc_number"], |
| 449 |
medium_index=track_data["track_number"], |
| 450 |
data_source=self.data_source, |
| 451 |
data_url=track_data["external_urls"]["spotify"], |
| 452 |
) |
| 453 |
|
| 454 |
def track_for_id(self, track_id: str) -> TrackInfo | None: |
| 455 |
"""Fetch a track by its Spotify ID or URL. |
| 456 |
|
| 457 |
Returns a TrackInfo object or None if the track is not found. |
| 458 |
|
| 459 |
""" |
| 460 |
|
| 461 |
if not (spotify_id := self._extract_id(track_id)): |
| 462 |
self._log.debug("Invalid Spotify ID: {}", track_id) |
| 463 |
return None |
| 464 |
|
| 465 |
if not ( |
| 466 |
track_data := self._handle_response( |
| 467 |
"get", f"{self.track_url}/{spotify_id}" |
| 468 |
) |
| 469 |
): |
| 470 |
self._log.debug("Track not found: {}", track_id) |
| 471 |
return None |
| 472 |
|
| 473 |
track = self._get_track(track_data) |
| 474 |
|
| 475 |
# Get album's tracks to set `track.index` (position on the entire |
| 476 |
# release) and `track.medium_total` (total number of tracks on |
| 477 |
# the track's disc). |
| 478 |
album_data = self._handle_response( |
| 479 |
"get", f"{self.album_url}{track_data['album']['id']}" |
| 480 |
) |
| 481 |
medium_total = 0 |
| 482 |
for i, track_data in enumerate(album_data["tracks"]["items"], start=1): |
| 483 |
if track_data["disc_number"] == track.medium: |
| 484 |
medium_total += 1 |
| 485 |
if track_data["id"] == track.track_id: |
| 486 |
track.index = i |
| 487 |
track.medium_total = medium_total |
| 488 |
return track |
| 489 |
|
| 490 |
def get_search_query_with_filters( |
| 491 |
self, |
| 492 |
query_type: QueryType, |
| 493 |
items: Sequence[Item], |
| 494 |
artist: str, |
| 495 |
name: str, |
| 496 |
va_likely: bool, |
| 497 |
) -> tuple[str, dict[str, str]]: |
| 498 |
query = f'album:"{name}"' if query_type == "album" else name |
| 499 |
if query_type == "track" or not va_likely: |
| 500 |
query += f' artist:"{artist}"' |
| 501 |
|
| 502 |
return query, {} |
| 503 |
|
| 504 |
def get_search_response( |
| 505 |
self, params: SearchParams |
| 506 |
) -> Sequence[SearchResponseAlbums | SearchResponseTracks]: |
| 507 |
"""Search Spotify and return raw album or track result items. |
| 508 |
|
| 509 |
Unauthorized responses trigger one token refresh attempt before the |
| 510 |
method gives up and falls back to an empty result set. |
| 511 |
""" |
| 512 |
for _ in range(2): |
| 513 |
response = requests.get( |
| 514 |
self.search_url, |
| 515 |
headers={"Authorization": f"Bearer {self.access_token}"}, |
| 516 |
params={ |
| 517 |
**params.filters, |
| 518 |
"q": params.query.replace('"', "'"), |
| 519 |
"type": params.query_type, |
| 520 |
"limit": str(params.limit), |
| 521 |
}, |
| 522 |
timeout=10, |
| 523 |
) |
| 524 |
try: |
| 525 |
response.raise_for_status() |
| 526 |
except requests.exceptions.HTTPError: |
| 527 |
if response.status_code == HTTPStatus.UNAUTHORIZED: |
| 528 |
self._authenticate() |
| 529 |
continue |
| 530 |
raise |
| 531 |
|
| 532 |
return ( |
| 533 |
response.json() |
| 534 |
.get(f"{params.query_type}s", {}) |
| 535 |
.get("items", []) |
| 536 |
) |
| 537 |
|
| 538 |
return () |
| 539 |
|
| 540 |
def commands(self) -> list[ui.Subcommand]: |
| 541 |
# autotagger import command |
| 542 |
def queries( |
| 543 |
lib: Library, opts: SpotifyCLIOpts, args: list[str] |
| 544 |
) -> None: |
| 545 |
success = self._parse_opts(opts) |
| 546 |
if success: |
| 547 |
results = self._match_library_tracks(lib, args) |
| 548 |
self._output_match_results(results) |
| 549 |
|
| 550 |
spotify_cmd = ui.Subcommand( |
| 551 |
"spotify", help=f"build a {self.data_source} playlist" |
| 552 |
) |
| 553 |
spotify_cmd.parser.add_option( |
| 554 |
"-m", |
| 555 |
"--mode", |
| 556 |
action="store", |
| 557 |
help=( |
| 558 |
f'"open" to open {self.data_source} with playlist, ' |
| 559 |
'"list" to print (default)' |
| 560 |
), |
| 561 |
) |
| 562 |
spotify_cmd.parser.add_option( |
| 563 |
"-f", |
| 564 |
"--show-failures", |
| 565 |
action="store_true", |
| 566 |
dest="show_failures", |
| 567 |
help=f"list tracks that did not match a {self.data_source} ID", |
| 568 |
) |
| 569 |
spotify_cmd.func = queries |
| 570 |
|
| 571 |
# spotifysync command |
| 572 |
sync_cmd = ui.Subcommand( |
| 573 |
"spotifysync", help="fetch track attributes from Spotify" |
| 574 |
) |
| 575 |
sync_cmd.parser.add_option( |
| 576 |
"-f", |
| 577 |
"--force", |
| 578 |
dest="force_refetch", |
| 579 |
action="store_true", |
| 580 |
default=False, |
| 581 |
help="re-download data when already present", |
| 582 |
) |
| 583 |
|
| 584 |
def func( |
| 585 |
lib: Library, opts: SpotifySyncCLIOpts, args: list[str] |
| 586 |
) -> None: |
| 587 |
items = lib.items(args) |
| 588 |
self._fetch_info(lib, items, ui.should_write(), opts.force_refetch) |
| 589 |
|
| 590 |
sync_cmd.func = func |
| 591 |
return [spotify_cmd, sync_cmd] |
| 592 |
|
| 593 |
def _parse_opts(self, opts: SpotifyCLIOpts) -> bool: |
| 594 |
if opts.mode: |
| 595 |
self.config["mode"].set(opts.mode) |
| 596 |
|
| 597 |
if opts.show_failures: |
| 598 |
self.config["show_failures"].set(True) |
| 599 |
|
| 600 |
if self.config["mode"].get() not in ["list", "open"]: |
| 601 |
self._log.warning( |
| 602 |
"{} is not a valid mode", self.config["mode"].get() |
| 603 |
) |
| 604 |
return False |
| 605 |
|
| 606 |
self.opts = opts |
| 607 |
return True |
| 608 |
|
| 609 |
def _match_library_tracks( |
| 610 |
self, library: Library, keywords: Sequence[str] |
| 611 |
) -> list[SearchResponseAlbums | SearchResponseTracks] | None: |
| 612 |
"""Get simplified track object dicts for library tracks. |
| 613 |
|
| 614 |
Matches tracks based on the specified ``keywords``. |
| 615 |
|
| 616 |
:param library: beets library object to query. |
| 617 |
:param keywords: Query to match library items against. |
| 618 |
|
| 619 |
:returns: List of simplified track object dicts for library |
| 620 |
items matching the specified query. |
| 621 |
|
| 622 |
""" |
| 623 |
results = [] |
| 624 |
failures = [] |
| 625 |
|
| 626 |
items = library.items(keywords) |
| 627 |
|
| 628 |
if not items: |
| 629 |
self._log.debug( |
| 630 |
"Your beets query returned no items, skipping {.data_source}.", |
| 631 |
self, |
| 632 |
) |
| 633 |
return None |
| 634 |
|
| 635 |
self._log.info("Processing {} tracks...", len(items)) |
| 636 |
|
| 637 |
for item in items: |
| 638 |
# Apply regex transformations if provided |
| 639 |
for regex in self.config["regex"].get(): |
| 640 |
if ( |
| 641 |
not regex["field"] |
| 642 |
or not regex["search"] |
| 643 |
or not regex["replace"] |
| 644 |
): |
| 645 |
continue |
| 646 |
|
| 647 |
value = item[regex["field"]] |
| 648 |
item[regex["field"]] = re.sub( |
| 649 |
regex["search"], regex["replace"], value |
| 650 |
) |
| 651 |
|
| 652 |
artist = item["artist"] or item["albumartist"] |
| 653 |
album = item["album"] |
| 654 |
query_string = item["title"] |
| 655 |
|
| 656 |
# Query the Web API for each track, look for the items' JSON data |
| 657 |
query = query_string |
| 658 |
if artist: |
| 659 |
query += f" artist:'{artist}'" |
| 660 |
if album: |
| 661 |
query += f" album:'{album}'" |
| 662 |
|
| 663 |
response_data_tracks = self._search_api("track", query, {}) |
| 664 |
if not response_data_tracks: |
| 665 |
failures.append(query) |
| 666 |
continue |
| 667 |
|
| 668 |
# Apply market filter if requested |
| 669 |
region_filter: str = self.config["region_filter"].get() |
| 670 |
if region_filter: |
| 671 |
response_data_tracks = [ |
| 672 |
track_data |
| 673 |
for track_data in response_data_tracks |
| 674 |
if region_filter in track_data["available_markets"] |
| 675 |
] |
| 676 |
|
| 677 |
if ( |
| 678 |
len(response_data_tracks) == 1 |
| 679 |
or self.config["tiebreak"].get() == "first" |
| 680 |
): |
| 681 |
self._log.debug( |
| 682 |
"{.data_source} track(s) found, count: {}", |
| 683 |
self, |
| 684 |
len(response_data_tracks), |
| 685 |
) |
| 686 |
chosen_result = response_data_tracks[0] |
| 687 |
else: |
| 688 |
# Use the popularity filter |
| 689 |
self._log.debug( |
| 690 |
"Most popular track chosen, count: {}", |
| 691 |
len(response_data_tracks), |
| 692 |
) |
| 693 |
chosen_result = max( |
| 694 |
response_data_tracks, |
| 695 |
key=lambda x: x[ |
| 696 |
# We are sure this is a track response! |
| 697 |
"popularity" # type: ignore[typeddict-item] |
| 698 |
], |
| 699 |
) |
| 700 |
results.append(chosen_result) |
| 701 |
|
| 702 |
failure_count = len(failures) |
| 703 |
if failure_count > 0: |
| 704 |
if self.config["show_failures"].get(): |
| 705 |
self._log.info( |
| 706 |
"{} track(s) did not match a {.data_source} ID:", |
| 707 |
failure_count, |
| 708 |
self, |
| 709 |
) |
| 710 |
for track in failures: |
| 711 |
self._log.info("track: {}", track) |
| 712 |
self._log.info("") |
| 713 |
else: |
| 714 |
self._log.warning( |
| 715 |
"{} track(s) did not match a {.data_source} ID:\n" |
| 716 |
"use --show-failures to display", |
| 717 |
failure_count, |
| 718 |
self, |
| 719 |
) |
| 720 |
|
| 721 |
return results |
| 722 |
|
| 723 |
def _output_match_results( |
| 724 |
self, results: Sequence[Mapping[str, Any]] | None |
| 725 |
) -> None: |
| 726 |
"""Open a playlist or print Spotify URLs. |
| 727 |
|
| 728 |
Uses the provided track object dicts. |
| 729 |
|
| 730 |
:param list[dict] results: List of simplified track object dicts |
| 731 |
(https://developer.spotify.com/documentation/web-api/ |
| 732 |
reference/object-model/#track-object-simplified) |
| 733 |
|
| 734 |
""" |
| 735 |
if results: |
| 736 |
spotify_ids = [track_data["id"] for track_data in results] |
| 737 |
if self.config["mode"].get() == "open": |
| 738 |
self._log.info( |
| 739 |
"Attempting to open {.data_source} with playlist", self |
| 740 |
) |
| 741 |
spotify_url = ( |
| 742 |
f"spotify:trackset:Playlist:{','.join(spotify_ids)}" |
| 743 |
) |
| 744 |
webbrowser.open(spotify_url) |
| 745 |
else: |
| 746 |
for spotify_id in spotify_ids: |
| 747 |
print(f"{self.open_track_url}{spotify_id}") |
| 748 |
else: |
| 749 |
self._log.warning( |
| 750 |
"No {.data_source} tracks found from beets query", self |
| 751 |
) |
| 752 |
|
| 753 |
def _disable_audio_features(self) -> None: |
| 754 |
"""Disable audio features globally and warn only once.""" |
| 755 |
should_log = False |
| 756 |
with self._audio_features_lock: |
| 757 |
if self.audio_features_available: |
| 758 |
self.audio_features_available = False |
| 759 |
should_log = True |
| 760 |
if should_log: |
| 761 |
self._log.warning( |
| 762 |
"Audio features API is unavailable (403 error). " |
| 763 |
"Skipping audio features for remaining tracks." |
| 764 |
) |
| 765 |
|
| 766 |
def get_track_details_by_id( |
| 767 |
self, track_ids: Sequence[str] |
| 768 |
) -> dict[str, TrackDetails]: |
| 769 |
"""Fetch popularity and external IDs in batches of 50 tracks.""" |
| 770 |
if not track_ids: |
| 771 |
return {} |
| 772 |
|
| 773 |
details_by_id: dict[str, TrackDetails] = {} |
| 774 |
for chunk in chunks(track_ids, 50): |
| 775 |
track_data = self._handle_response( |
| 776 |
"get", self.track_url, params={"ids": ",".join(chunk)} |
| 777 |
) |
| 778 |
|
| 779 |
for idx, track in enumerate(track_data.get("tracks", [])): |
| 780 |
if track is None: |
| 781 |
continue |
| 782 |
|
| 783 |
external_ids = track.get("external_ids", {}) |
| 784 |
track_id = track.get("id") or chunk[idx] |
| 785 |
details_by_id[track_id] = TrackDetails( |
| 786 |
spotify_track_popularity=track.get("popularity"), |
| 787 |
isrc=external_ids.get("isrc"), |
| 788 |
ean=external_ids.get("ean"), |
| 789 |
upc=external_ids.get("upc"), |
| 790 |
) |
| 791 |
|
| 792 |
return details_by_id |
| 793 |
|
| 794 |
def track_audio_features_batch( |
| 795 |
self, track_ids: Sequence[str] |
| 796 |
) -> dict[str, AudioFeatures]: |
| 797 |
"""Fetch track audio features in batches of 100 tracks.""" |
| 798 |
if not track_ids: |
| 799 |
return {} |
| 800 |
|
| 801 |
with self._audio_features_lock: |
| 802 |
if not self.audio_features_available: |
| 803 |
return {} |
| 804 |
|
| 805 |
features_by_id: dict[str, AudioFeatures] = {} |
| 806 |
for chunk in chunks(track_ids, 100): |
| 807 |
try: |
| 808 |
features_data = self._handle_response( |
| 809 |
"get", |
| 810 |
self.audio_features_url, |
| 811 |
params={"ids": ",".join(chunk)}, |
| 812 |
) |
| 813 |
except AudioFeaturesUnavailableError: |
| 814 |
self._disable_audio_features() |
| 815 |
break |
| 816 |
except APIError as e: |
| 817 |
self._log.debug("Spotify API error: {}", e) |
| 818 |
continue |
| 819 |
|
| 820 |
for idx, feature_data in enumerate( |
| 821 |
features_data.get("audio_features", []) |
| 822 |
): |
| 823 |
if feature_data: |
| 824 |
track_id = feature_data.get("id") or chunk[idx] |
| 825 |
features_by_id[track_id] = feature_data |
| 826 |
|
| 827 |
return features_by_id |
| 828 |
|
| 829 |
def _fetch_info( |
| 830 |
self, lib: Library, items: Sequence[Item], write: bool, force: bool |
| 831 |
) -> None: |
| 832 |
"""Obtain track information from Spotify.""" |
| 833 |
|
| 834 |
self._log.debug("Total {} tracks", len(items)) |
| 835 |
|
| 836 |
items_to_update: list[tuple[Item, str]] = [] |
| 837 |
|
| 838 |
for index, item in enumerate(items, start=1): |
| 839 |
self._log.info( |
| 840 |
"Processing {}/{} tracks - {} ", index, len(items), item |
| 841 |
) |
| 842 |
# If we're not forcing re-downloading for all tracks, check |
| 843 |
# whether the popularity data is already present |
| 844 |
if not force: |
| 845 |
if "spotify_track_popularity" in item: |
| 846 |
self._log.debug("Popularity already present for: {}", item) |
| 847 |
continue |
| 848 |
try: |
| 849 |
spotify_track_id = item.spotify_track_id |
| 850 |
except AttributeError: |
| 851 |
self._log.debug("No track_id present for: {}", item) |
| 852 |
continue |
| 853 |
|
| 854 |
items_to_update.append((item, spotify_track_id)) |
| 855 |
|
| 856 |
if not items_to_update: |
| 857 |
return |
| 858 |
|
| 859 |
unique_track_ids = list( |
| 860 |
dict.fromkeys(track_id for _, track_id in items_to_update) |
| 861 |
) |
| 862 |
track_details_by_id = self.get_track_details_by_id(unique_track_ids) |
| 863 |
audio_features_by_id = self.track_audio_features_batch(unique_track_ids) |
| 864 |
|
| 865 |
for item, spotify_track_id in items_to_update: |
| 866 |
if track_details := track_details_by_id.get(spotify_track_id): |
| 867 |
item.update(track_details) |
| 868 |
|
| 869 |
if self.audio_features_available: |
| 870 |
audio_features = audio_features_by_id.get(spotify_track_id) |
| 871 |
if audio_features is None: |
| 872 |
self._log.info("No audio features found for: {}", item) |
| 873 |
else: |
| 874 |
for feature, value in audio_features.items(): |
| 875 |
if feature in self.spotify_audio_features: |
| 876 |
item[self.spotify_audio_features[feature]] = value |
| 877 |
|
| 878 |
item["spotify_updated"] = time.time() |
| 879 |
if write: |
| 880 |
item.try_write() |
| 881 |
|
| 882 |
with lib.transaction(): |
| 883 |
for item, _ in items_to_update: |
| 884 |
item.store() |
| 885 |
|
| 886 |
def track_info( |
| 887 |
self, track_id: str |
| 888 |
) -> tuple[int | None, str | None, str | None, str | None]: |
| 889 |
"""Fetch a track's popularity and external IDs using its Spotify ID.""" |
| 890 |
track_data = self._handle_response( |
| 891 |
"get", f"{self.track_url}/{track_id}" |
| 892 |
) |
| 893 |
external_ids = track_data.get("external_ids", {}) |
| 894 |
popularity = track_data.get("popularity") |
| 895 |
self._log.debug( |
| 896 |
"track_popularity: {} and track_isrc: {}", |
| 897 |
popularity, |
| 898 |
external_ids.get("isrc"), |
| 899 |
) |
| 900 |
return ( |
| 901 |
popularity, |
| 902 |
external_ids.get("isrc"), |
| 903 |
external_ids.get("ean"), |
| 904 |
external_ids.get("upc"), |
| 905 |
) |
| 906 |
|
| 907 |
def track_audio_features(self, track_id: str) -> JSONDict | None: |
| 908 |
"""Fetch track audio features by its Spotify ID. |
| 909 |
|
| 910 |
Thread-safe: avoids redundant API calls and logs the 403 warning only |
| 911 |
once. |
| 912 |
|
| 913 |
""" |
| 914 |
# Fast path: if we've already detected unavailability, skip the call. |
| 915 |
with self._audio_features_lock: |
| 916 |
if not self.audio_features_available: |
| 917 |
return None |
| 918 |
|
| 919 |
try: |
| 920 |
return self._handle_response( |
| 921 |
"get", f"{self.audio_features_url}/{track_id}" |
| 922 |
) |
| 923 |
except AudioFeaturesUnavailableError: |
| 924 |
self._disable_audio_features() |
| 925 |
return None |
| 926 |
except APIError as e: |
| 927 |
self._log.debug("Spotify API error: {}", e) |
| 928 |
return None |