Debian Codegraph @

beetsplug/discogs/__init__.py

raw
1 """Adds Discogs album search support to the autotagger. Requires the
2 python3-discogs-client library.
3 """
4
5 from __future__ import annotations
6
7 import http.client
8 import json
9 import os
10 import re
11 import socket
12 import time
13 import traceback
14 from functools import cache, cached_property
15 from itertools import groupby
16 from string import ascii_lowercase
17 from typing import TYPE_CHECKING
18
19 import confuse
20 import requests
21 from discogs_client import Client, Master, Release
22 from discogs_client.exceptions import DiscogsAPIError
23
24 import beets
25 import beets.ui
26 from beets import config, util
27 from beets.autotag import AlbumInfo, TrackInfo, string_dist
28 from beets.exceptions import UserError
29 from beets.metadata_plugins import IDResponse, SearchApiMetadataSourcePlugin
30
31 from .states import DISAMBIGUATION_RE, ArtistState, TracklistState
32
33 if TYPE_CHECKING:
34 from collections.abc import Callable, Iterator, Sequence
35
36 from beets.importer import ImportSession
37 from beets.library import Item
38 from beets.metadata_plugins import QueryType, SearchParams
39
40 from .types import AudioTrack, IndexTrack, ReleaseFormat, Track
41
42 USER_AGENT = f"beets/{beets.__version__} +https://beets.io/"
43 API_KEY = "rAzVUQYRaoFjeBjyWuWZ"
44 API_SECRET = "plxtUTqoCzwxZpqdPysCwGuBSmZNdZVy"
45
46
47 # Exceptions that discogs_client should really handle but does not.
48 CONNECTION_ERRORS = (
49 requests.exceptions.ConnectionError,
50 socket.error,
51 http.client.HTTPException,
52 ValueError, # JSON decoding raises a ValueError.
53 DiscogsAPIError,
54 )
55
56 TRACK_INDEX_RE = re.compile(
57 r"""
58 (.*?) # medium: everything before medium_index.
59 (\d*?) # medium_index: a number at the end of
60 # `position`, except if followed by a subtrack index.
61 # subtrack_index: can only be matched if medium
62 # or medium_index have been matched, and can be
63 (
64 (?<=\w)\.[\w]+ # a dot followed by a string (A.1, 2.A)
65 | (?<=\d)[A-Z]+ # a string that follows a number (1A, B2a)
66 )?
67 """,
68 re.VERBOSE,
69 )
70
71 FIELDS_TO_DISCOGS_KEYS = {
72 "barcode": "barcode",
73 "catalognum": "catno",
74 "country": "country",
75 "label": "label",
76 "media": "format",
77 "year": "year",
78 }
79
80
81 class DiscogsPlugin(SearchApiMetadataSourcePlugin[IDResponse]):
82 def __init__(self) -> None:
83 super().__init__()
84 self.config.add(
85 {
86 "apikey": API_KEY,
87 "apisecret": API_SECRET,
88 "tokenfile": "discogs_token.json",
89 "user_token": "",
90 "separator": ", ",
91 "index_tracks": False,
92 "append_style_genre": False,
93 "strip_disambiguation": True,
94 "featured_string": "Feat.",
95 "extra_tags": [],
96 "anv": {
97 "artist_credit": True,
98 "artist": False,
99 "album_artist": False,
100 },
101 }
102 )
103 self.config["apikey"].redact = True
104 self.config["apisecret"].redact = True
105 self.config["user_token"].redact = True
106 self.setup()
107
108 @cached_property
109 def extra_discogs_field_by_tag(self) -> dict[str, str]:
110 """Map configured extra tags to Discogs API search parameters.
111
112 Process user configuration to determine which additional Discogs
113 fields should be included in search queries.
114 """
115 field_by_tag = {
116 tag: FIELDS_TO_DISCOGS_KEYS[tag]
117 for tag in self.config["extra_tags"].as_str_seq()
118 if tag in FIELDS_TO_DISCOGS_KEYS
119 }
120 if field_by_tag:
121 self._log.debug(
122 "Discogs additional search filters from tags: {}", field_by_tag
123 )
124
125 return field_by_tag
126
127 def setup(self, session: ImportSession | None = None) -> None:
128 """Create the `discogs_client` field. Authenticate if necessary."""
129 c_key = self.config["apikey"].as_str()
130 c_secret = self.config["apisecret"].as_str()
131
132 # Try using a configured user token (bypassing OAuth login).
133 user_token = self.config["user_token"].as_str()
134 if user_token:
135 # The rate limit for authenticated users goes up to 60
136 # requests per minute.
137 self.discogs_client = Client(USER_AGENT, user_token=user_token)
138 return
139
140 # Get the OAuth token from a file or log in.
141 try:
142 with open(self._tokenfile()) as f:
143 tokendata = json.load(f)
144 except OSError:
145 # No token yet. Generate one.
146 token, secret = self.authenticate(c_key, c_secret)
147 else:
148 token = tokendata["token"]
149 secret = tokendata["secret"]
150
151 self.discogs_client = Client(USER_AGENT, c_key, c_secret, token, secret)
152
153 def reset_auth(self) -> None:
154 """Delete token file & redo the auth steps."""
155 os.remove(self._tokenfile())
156 self.setup()
157
158 def _tokenfile(self) -> str:
159 """Get the path to the JSON file for storing the OAuth token."""
160 return self.config["tokenfile"].get(confuse.Filename(in_app_dir=True))
161
162 def authenticate(self, c_key: str, c_secret: str) -> tuple[str, str]:
163 # Get the link for the OAuth page.
164 auth_client = Client(USER_AGENT, c_key, c_secret)
165 try:
166 _, _, url = auth_client.get_authorize_url()
167 except CONNECTION_ERRORS as e:
168 self._log.debug("connection error: {}", e)
169 raise UserError("communication with Discogs failed")
170
171 beets.ui.print_("To authenticate with Discogs, visit:")
172 beets.ui.print_(url)
173
174 # Ask for the code and validate it.
175 code = beets.ui.input_("Enter the code:")
176 try:
177 token, secret = auth_client.get_access_token(code)
178 except DiscogsAPIError:
179 raise UserError("Discogs authorization failed")
180 except CONNECTION_ERRORS as e:
181 self._log.debug("connection error: {}", e)
182 raise UserError("Discogs token request failed")
183
184 # Save the token for later use.
185 self._log.debug("Discogs token {}, secret {}", token, secret)
186 with open(self._tokenfile(), "w") as f:
187 json.dump({"token": token, "secret": secret}, f)
188
189 return token, secret
190
191 def get_track_from_album(
192 self, album_info: AlbumInfo, compare: Callable[[TrackInfo], float]
193 ) -> TrackInfo | None:
194 """Return the best matching track of the release."""
195 scores_and_tracks = [(compare(t), t) for t in album_info.tracks]
196 score, track_info = min(scores_and_tracks, key=lambda x: x[0])
197 if score > 0.3:
198 return None
199
200 track_info["artist"] = album_info.artist
201 track_info["artist_id"] = album_info.artist_id
202 track_info["album"] = album_info.album
203 return track_info
204
205 def item_candidates(
206 self, item: Item, artist: str, title: str
207 ) -> Iterator[TrackInfo]:
208 albums = self.candidates([item], artist, title, False)
209
210 def compare_func(track_info: TrackInfo) -> float:
211 return string_dist(track_info.title, title)
212
213 tracks = (self.get_track_from_album(a, compare_func) for a in albums)
214 return filter(None, tracks)
215
216 def album_for_id(self, album_id: str) -> AlbumInfo | None:
217 """Fetches an album by its Discogs ID and returns an AlbumInfo object
218 or None if the album is not found.
219 """
220 discogs_id = self._extract_id(album_id)
221
222 if not discogs_id:
223 return None
224
225 result = Release(self.discogs_client, {"id": discogs_id})
226 # Try to obtain title to verify that we indeed have a valid Release
227 try:
228 getattr(result, "title")
229 except DiscogsAPIError as e:
230 if e.status_code != 404:
231 self._log.debug(
232 "API Error: {} (query: {})", e, result.data["resource_url"]
233 )
234 if e.status_code == 401:
235 self.reset_auth()
236 return self.album_for_id(album_id)
237 return None
238 except CONNECTION_ERRORS:
239 self._log.debug("Connection error in album lookup", exc_info=True)
240 return None
241 return self.get_album_info(result)
242
243 def track_for_id(self, track_id: str) -> TrackInfo | None:
244 if album := self.album_for_id(track_id):
245 for track in album.tracks:
246 if track.track_id == track_id:
247 return track
248 return None
249
250 def get_search_query_with_filters(
251 self,
252 query_type: QueryType,
253 items: Sequence[Item],
254 artist: str,
255 name: str,
256 va_likely: bool,
257 ) -> tuple[str, dict[str, str]]:
258 """Build a Discogs release query and fixed release-type filter.
259
260 The query is normalized to improve hit rates for punctuation-heavy album
261 names and medium suffixes that can reduce recall.
262 """
263
264 query = f"{artist} {name}" if va_likely else name
265 # Strip non-word characters from query. Things like "!" and "-" can
266 # cause a query to return no results, even if they match the artist or
267 # album title. Use `re.UNICODE` flag to avoid stripping non-english
268 # word characters.
269 query = re.sub(r"(?u)\W+", " ", query)
270 # Strip medium information from query, Things like "CD1" and "disk 1"
271 # can also negate an otherwise positive result.
272 query = re.sub(r"(?i)\b(CD|disc|vinyl)\s*\d+", "", query)
273
274 filters: dict[str, str] = {"type": "release"}
275
276 if not items:
277 return query, filters
278
279 for tag, api_field in self.extra_discogs_field_by_tag.items():
280 most_common, _count = util.plurality(
281 item.get(tag) for item in items
282 )
283 if most_common is None:
284 continue
285
286 value = str(most_common)
287 if tag == "catalognum":
288 value = value.replace(" ", "")
289
290 filters[api_field] = value
291
292 return query, filters
293
294 def get_search_response(self, params: SearchParams) -> Sequence[IDResponse]:
295 """Search Discogs releases and return raw result mappings with IDs."""
296
297 def search() -> list[IDResponse]:
298 results = self.discogs_client.search(params.query, **params.filters)
299 results.per_page = params.limit
300 return [r.data for r in results.page(1)]
301
302 try:
303 return search()
304 except json.JSONDecodeError:
305 self._log.debug(
306 "Discogs returned an invalid JSON search response; retrying"
307 )
308 return search()
309
310 @cache
311 def get_master_year(self, master_id: str) -> int | None:
312 """Fetches a master release given its Discogs ID and returns its year
313 or None if the master release is not found.
314 """
315 self._log.debug("Getting master release {}", master_id)
316 result = Master(self.discogs_client, {"id": master_id})
317
318 try:
319 return result.fetch("year")
320 except DiscogsAPIError as e:
321 if e.status_code != 404:
322 self._log.debug(
323 "API Error: {} (query: {})", e, result.data["resource_url"]
324 )
325 if e.status_code == 401:
326 self.reset_auth()
327 return self.get_master_year(master_id)
328 return None
329 except CONNECTION_ERRORS:
330 self._log.debug(
331 "Connection error in master release lookup", exc_info=True
332 )
333 return None
334
335 @staticmethod
336 def get_media_and_albumtype(
337 formats: list[ReleaseFormat] | None,
338 ) -> tuple[str | None, str | None]:
339 media = albumtype = None
340 if formats and (first_format := formats[0]):
341 if descriptions := first_format["descriptions"]:
342 albumtype = ", ".join(descriptions)
343 media = first_format["name"]
344
345 return media, albumtype
346
347 def get_album_info(self, result: Release) -> AlbumInfo | None:
348 """Returns an AlbumInfo object for a discogs Release object."""
349 # Explicitly reload the `Release` fields, as they might not be yet
350 # present if the result is from a `discogs_client.search()`.
351 if not result.data.get("artists"):
352 try:
353 result.refresh()
354 except CONNECTION_ERRORS:
355 self._log.debug(
356 "Connection error in release lookup: {0}", result
357 )
358 return None
359
360 artist_data = [a.data for a in result.artists]
361 # Information for the album artist
362 albumartist = ArtistState.from_config(
363 self.config, artist_data, for_album_artist=True
364 )
365
366 album = re.sub(r" +", " ", result.title)
367 album_id = result.data["id"]
368 # Use `.data` to access the tracklist directly instead of the
369 # convenient `.tracklist` property, which will strip out useful artist
370 # information and leave us with skeleton `Artist` objects that will
371 # each make an API call just to get the same data back.
372 tracks = self.get_tracks(
373 result.data["tracklist"],
374 ArtistState.from_config(self.config, artist_data),
375 )
376
377 # Extract information for the optional AlbumInfo fields, if possible.
378 va = albumartist.artist == config["va_name"].as_str()
379 year = result.data.get("year")
380 mediums = [t["medium"] for t in tracks]
381 country = result.data.get("country")
382 data_url = result.data.get("uri")
383 # we swap genre and style since discogs genres are more general and
384 # styles more specific
385 styles: list[str] = result.data.get("genres") or []
386 genres: list[str] = result.data.get("styles") or []
387
388 if self.config["append_style_genre"]:
389 genres.extend(styles)
390
391 discogs_albumid = self._extract_id(result.data.get("uri"))
392
393 # Extract information for the optional AlbumInfo fields that are
394 # contained on nested discogs fields.
395 media, albumtype = self.get_media_and_albumtype(
396 result.data.get("formats")
397 )
398
399 label = catalogno = labelid = None
400 if result.data.get("labels"):
401 label = self.strip_disambiguation(
402 result.data["labels"][0].get("name")
403 )
404 catalogno = result.data["labels"][0].get("catno")
405 labelid = result.data["labels"][0].get("id")
406
407 cover_art_url = self.select_cover_art(result)
408
409 # Additional cleanups
410 # (catalog number, media, disambiguation).
411 if catalogno == "none":
412 catalogno = None
413 # Explicitly set the `media` for the tracks, since it is expected by
414 # `autotag.apply_metadata`, and set `medium_total`.
415 for track in tracks:
416 track.media = media
417 track.medium_total = mediums.count(track.medium)
418 # Discogs does not have track IDs. Invent our own IDs as proposed
419 # in #2336.
420 track.track_id = f"{album_id}-{track.track_alt}"
421 track.data_url = data_url
422 track.data_source = "Discogs"
423
424 # Retrieve master release id (returns None if there isn't one).
425 master_id = result.data.get("master_id")
426 # Assume `original_year` is equal to `year` for releases without
427 # a master release, otherwise fetch the master release.
428 original_year = self.get_master_year(master_id) if master_id else year
429
430 return AlbumInfo(
431 album=album,
432 album_id=album_id,
433 **albumartist.info, # Unpacks values to satisfy the keyword arguments
434 tracks=tracks,
435 albumtype=albumtype,
436 va=va,
437 year=year,
438 label=label,
439 mediums=len(set(mediums)),
440 releasegroup_id=master_id,
441 catalognum=catalogno,
442 country=country,
443 style=(
444 self.config["separator"].as_str().join(sorted(styles)) or None
445 ),
446 genres=sorted(genres),
447 media=media,
448 original_year=original_year,
449 data_source=self.data_source,
450 data_url=data_url,
451 discogs_albumid=discogs_albumid,
452 discogs_labelid=labelid,
453 discogs_artistid=albumartist.artist_id,
454 cover_art_url=cover_art_url,
455 )
456
457 def select_cover_art(self, result: Release) -> str | None:
458 """Returns the best candidate image, if any, from a Discogs `Release` object."""
459 if result.data.get("images") and len(result.data.get("images")) > 0:
460 # The first image in this list appears to be the one displayed first
461 # on the release page - even if it is not flagged as `type: "primary"` - and
462 # so it is the best candidate for the cover art.
463 return result.data.get("images")[0].get("uri")
464
465 return None
466
467 def get_tracks(
468 self, tracklist: list[Track], albumartistinfo: ArtistState
469 ) -> list[TrackInfo]:
470 """Returns a list of TrackInfo objects for a discogs tracklist."""
471 try:
472 clean_tracklist: list[Track] = self._coalesce_tracks(tracklist)
473 except Exception as exc:
474 # FIXME: this is an extra precaution for making sure there are no
475 # side effects after #2222. It should be removed after further
476 # testing.
477 self._log.debug("{}", traceback.format_exc())
478 self._log.error("uncaught exception in _coalesce_tracks: {}", exc)
479 clean_tracklist = tracklist
480 t = TracklistState.build(self, clean_tracklist, albumartistinfo)
481 # Fix up medium and medium_index for each track. Discogs position is
482 # unreliable, but tracks are in order.
483 medium = None
484 medium_count, index_count, side_count = 0, 0, 0
485 sides_per_medium = 1
486
487 # If a medium has two sides (ie. vinyl or cassette), each pair of
488 # consecutive sides should belong to the same medium.
489 if all([medium is not None for medium in t.mediums]):
490 m = sorted(
491 {medium.lower() if medium else "" for medium in t.mediums}
492 )
493 # If all track.medium are single consecutive letters, assume it is
494 # a 2-sided medium.
495 if "".join(m) in ascii_lowercase:
496 sides_per_medium = 2
497
498 for i, track in enumerate(t.tracks):
499 # Handle special case where a different medium does not indicate a
500 # new disc, when there is no medium_index and the ordinal of medium
501 # is not sequential. For example, I, II, III, IV, V. Assume these
502 # are the track index, not the medium.
503 # side_count is the number of mediums or medium sides (in the case
504 # of two-sided mediums) that were seen before.
505 medium_str = t.mediums[i]
506 medium_index = t.medium_indices[i]
507 medium_is_index = (
508 medium_str
509 and not medium_index
510 and (
511 len(medium_str) != 1
512 or
513 # Not within standard incremental medium values (A, B, C, ...).
514 ord(medium_str) - 64 != side_count + 1
515 )
516 )
517
518 if not medium_is_index and medium != medium_str:
519 side_count += 1
520 if sides_per_medium == 2:
521 if side_count % sides_per_medium:
522 # Two-sided medium changed. Reset index_count.
523 index_count = 0
524 medium_count += 1
525 else:
526 # Medium changed. Reset index_count.
527 medium_count += 1
528 index_count = 0
529 medium = medium_str
530
531 index_count += 1
532 medium_count = 1 if medium_count == 0 else medium_count
533 track.medium, track.medium_index = medium_count, index_count
534
535 # Get `disctitle` from Discogs index tracks. Assume that an index track
536 # before the first track of each medium is a disc title.
537 for track in t.tracks:
538 if track.medium_index == 1:
539 if track.index in t.index_tracks:
540 disctitle = t.index_tracks[track.index]
541 else:
542 disctitle = None
543 track.disctitle = disctitle
544
545 return t.tracks
546
547 def _subtrack_position(self, track: Track) -> str | None:
548 """Identify the physical position containing a flat audio subtrack."""
549 if track["type_"] == "track":
550 medium, medium_index, subindex = self.get_track_index(
551 track["position"]
552 )
553 if subindex:
554 return f"{medium or ''}{medium_index or ''}"
555 return None
556
557 def _coalesce_tracks(self, raw_tracklist: list[Track]) -> list[Track]:
558 """Normalize each Discogs tracklist entry by its declared kind."""
559 tracklist: list[Track] = []
560 for position, tracks in groupby(
561 raw_tracklist, key=self._subtrack_position
562 ):
563 if position is not None:
564 subtracks = [
565 track for track in tracks if track["type_"] == "track"
566 ]
567 tracklist.append(self._merge_subtracks(subtracks))
568 continue
569
570 for track in tracks:
571 if track["type_"] in {"track", "heading"}:
572 tracklist.append(track)
573 elif track["type_"] == "index":
574 tracklist.extend(self._coalesce_index_track(track))
575
576 return tracklist
577
578 @staticmethod
579 def _merge_subtracks(subtracks: list[AudioTrack]) -> AudioTrack:
580 """Combine flat Discogs subtracks representing one physical track."""
581 merged_track = subtracks[0].copy()
582 merged_track["title"] = " / ".join(
583 subtrack["title"] for subtrack in subtracks
584 )
585 return merged_track
586
587 def _coalesce_index_track(
588 self, index_track: IndexTrack
589 ) -> list[AudioTrack]:
590 """Convert an index container into its physical audio tracks."""
591 subtracks = index_track["sub_tracks"]
592 if not subtracks:
593 raise ValueError("Discogs index track does not contain subtracks")
594
595 medium, medium_index, subindex = self.get_track_index(
596 subtracks[0]["position"]
597 )
598
599 # Subindexed children are logical pieces contained in one physical
600 # track. Keep the index track's metadata and discard the child entries.
601 if subindex:
602 merged_track: AudioTrack = {
603 "type_": "track",
604 "position": f"{medium or ''}{medium_index or ''}",
605 "title": index_track["title"],
606 "duration": index_track["duration"],
607 }
608 if artists := index_track.get("artists"):
609 merged_track["artists"] = artists
610 if extraartists := index_track.get("extraartists"):
611 merged_track["extraartists"] = extraartists
612 return [merged_track]
613
614 # Children without subindices are separate physical tracks grouped
615 # under a musical work. Discard the index while retaining its context.
616 artists = index_track.get("artists")
617 title_prefix = (
618 f"{index_track['title']}: " if self.config["index_tracks"] else ""
619 )
620 tracks: list[AudioTrack] = []
621 for subtrack in subtracks:
622 track = subtrack.copy()
623 if artists and not track.get("artists"):
624 track["artists"] = artists
625 if title_prefix:
626 track["title"] = f"{title_prefix}{track['title']}"
627 tracks.append(track)
628 return tracks
629
630 def strip_disambiguation(self, text: str) -> str:
631 """Removes discogs specific disambiguations from a string.
632 Turns 'Label Name (5)' to 'Label Name' or 'Artist (1) & Another Artist (2)'
633 to 'Artist & Another Artist'. Does nothing if strip_disambiguation is False."""
634 if not self.config["strip_disambiguation"]:
635 return text
636 return DISAMBIGUATION_RE.sub("", text)
637
638 def get_track_info(
639 self,
640 track: AudioTrack,
641 index: int,
642 divisions: list[str],
643 albumartistinfo: ArtistState,
644 ) -> tuple[TrackInfo, str | None, str | None]:
645 """Returns a TrackInfo object for a discogs track."""
646
647 title = track["title"]
648 if self.config["index_tracks"]:
649 prefix = ", ".join(divisions)
650 if prefix:
651 title = f"{prefix}: {title}"
652 track_id = None
653 medium, medium_index, _ = self.get_track_index(track["position"])
654
655 length = self.get_track_length(track["duration"])
656 # If artists are found on the track, we will use those instead
657 artistinfo = ArtistState.from_config(
658 self.config,
659 [
660 *(track.get("artists") or albumartistinfo.raw_artists),
661 *track.get("extraartists", []),
662 ],
663 )
664
665 return (
666 TrackInfo(
667 title=title,
668 track_id=track_id,
669 **artistinfo.info,
670 length=length,
671 index=index,
672 ),
673 medium,
674 medium_index,
675 )
676
677 @staticmethod
678 def get_track_index(
679 position: str,
680 ) -> tuple[str | None, str | None, str | None]:
681 """Returns the medium, medium index and subtrack index for a discogs
682 track position."""
683 # Match the standard Discogs positions (12.2.9), which can have several
684 # forms (1, 1-1, A1, A1.1, A1a, ...).
685 medium = index = subindex = None
686 if match := TRACK_INDEX_RE.fullmatch(position.upper()):
687 medium, index, subindex = match.groups()
688
689 if subindex and subindex.startswith("."):
690 subindex = subindex[1:]
691
692 return medium or None, index or None, subindex or None
693
694 def get_track_length(self, duration: str) -> int | None:
695 """Returns the track length in seconds for a discogs duration."""
696 try:
697 length = time.strptime(duration, "%M:%S")
698 except ValueError:
699 return None
700 return length.tm_min * 60 + length.tm_sec