Debian Codegraph @

beetsplug/musicbrainz.py

raw
1 """Searches for albums in the MusicBrainz database."""
2
3 from __future__ import annotations
4
5 from collections import defaultdict
6 from contextlib import suppress
7 from functools import cached_property
8 from itertools import product
9 from typing import TYPE_CHECKING, Literal, TypedDict
10 from urllib.parse import urljoin
11
12 from confuse.exceptions import NotFoundError
13 from typing_extensions import NotRequired
14
15 from beets import config, plugins, util
16 from beets.autotag import AlbumInfo, TrackInfo
17 from beets.metadata_plugins import IDResponse, SearchApiMetadataSourcePlugin
18 from beets.util.deprecation import deprecate_for_user
19 from beets.util.id_extractors import extract_release_id
20
21 from ._utils.musicbrainz import MusicBrainzAPIMixin
22 from ._utils.requests import HTTPNotFoundError
23
24 if TYPE_CHECKING:
25 from collections.abc import Iterable, Sequence
26
27 from beets.library import Item
28 from beets.metadata_plugins import QueryType, SearchParams
29
30 from ._utils.musicbrainz import (
31 Alias,
32 ArtistCredit,
33 ArtistRelation,
34 LabelInfo,
35 Medium,
36 Recording,
37 Release,
38 ReleaseGroup,
39 UrlRelation,
40 WorkRelation,
41 )
42
43 VARIOUS_ARTISTS_ID = "89ad4ac3-39f7-470e-963a-56509c546377"
44
45 BASE_URL = "https://musicbrainz.org/"
46
47 FIELDS_TO_MB_KEYS = {
48 "barcode": "barcode",
49 "catalognum": "catno",
50 "country": "country",
51 "label": "label",
52 "media": "format",
53 "year": "date",
54 "tracks": "tracks",
55 "alias": "alias",
56 }
57
58 BROWSE_INCLUDES = [
59 "artist-credits",
60 "aliases",
61 "work-rels",
62 "artist-rels",
63 "recording-rels",
64 "release-rels",
65 ]
66 BROWSE_CHUNKSIZE = 100
67 BROWSE_MAXTRACKS = 500
68
69
70 UrlSource = Literal[
71 "discogs", "bandcamp", "spotify", "deezer", "tidal", "beatport"
72 ]
73
74
75 class ArtistInfo(TypedDict):
76 artist: str
77 artist_id: str
78 artist_sort: str
79 artist_credit: str
80 artists: list[str]
81 artists_ids: list[str]
82 artists_sort: list[str]
83 artists_credit: list[str]
84
85
86 class ReleaseGroupInfo(TypedDict):
87 albumtype: str | None
88 albumtypes: list[str]
89 releasegroup_id: str
90 release_group_title: str | None
91 releasegroupdisambig: str | None
92 original_year: int | None
93 original_month: int | None
94 original_day: int | None
95
96
97 class LabelInfoInfo(TypedDict):
98 label: str | None
99 catalognum: str | None
100
101
102 class ExternalIdsInfo(TypedDict):
103 discogs_album_id: NotRequired[str | None]
104 bandcamp_album_id: NotRequired[str | None]
105 spotify_album_id: NotRequired[str | None]
106 deezer_album_id: NotRequired[str | None]
107 tidal_album_id: NotRequired[str | None]
108 beatport_album_id: NotRequired[str | None]
109
110
111 class WorkRelationsInfo(TypedDict):
112 work: str | None
113 mb_workid: str | None
114 lyricists: list[str] | None
115 lyricists_ids: list[str] | None
116 composers: list[str] | None
117 composers_ids: list[str] | None
118 composer_sort: str | None
119
120
121 class ArtistRelationsInfo(TypedDict):
122 arrangers: list[str] | None
123 arrangers_ids: list[str] | None
124 remixers: list[str] | None
125 remixers_ids: list[str] | None
126
127
128 def _preferred_alias(
129 aliases: list[Alias], languages: list[str] | None = None
130 ) -> Alias | None:
131 """Select the most appropriate alias based on user preferences."""
132 if not aliases:
133 return None
134
135 # Get any ignored alias types and lower case them to prevent case issues
136 ignored_alias_types = {
137 a.lower() for a in config["import"]["ignored_alias_types"].as_str_seq()
138 }
139
140 # Search configured locales in order.
141 languages = languages or config["import"]["languages"].as_str_seq()
142
143 matches = (
144 al
145 for locale in languages
146 for al in aliases
147 # Find matching primary aliases for this locale that are not
148 # being ignored
149 if (
150 al["locale"] == locale
151 and al["primary"]
152 and (al["type"] or "").lower() not in ignored_alias_types
153 )
154 )
155 return next(matches, None)
156
157
158 def _key_with_preferred_alias(
159 obj: ReleaseGroup | Release | Recording, key: Literal["title"]
160 ) -> str:
161 alias = _preferred_alias(obj.get("aliases", []))
162 return alias["name"] if alias else obj[key]
163
164
165 def _preferred_release_event(release: Release) -> tuple[str | None, str | None]:
166 """Select the most relevant release country and date for matching.
167
168 Fall back to the default release event if a preferred event is not found.
169 """
170 preferred_countries = config["match"]["preferred"]["countries"].as_str_seq()
171
172 for country in preferred_countries:
173 for event in release.get("release_events", []):
174 if (area := event["area"]) and country in area["iso_3166_1_codes"]:
175 return country, event["date"]
176
177 return release.get("country"), release.get("date")
178
179
180 def _get_date(date_str: str) -> tuple[int | None, int | None, int | None]:
181 """Parse a partial `YYYY-MM-DD` string into numeric date parts.
182
183 Missing components are returned as `None`.
184 """
185 if not date_str:
186 return None, None, None
187
188 def _parse_part(part: str) -> int | None:
189 try:
190 return int(part)
191 except ValueError:
192 return None
193
194 parts = list(map(_parse_part, date_str.split("-")))
195
196 return (
197 parts[0] if len(parts) > 0 else None,
198 parts[1] if len(parts) > 1 else None,
199 parts[2] if len(parts) > 2 else None,
200 )
201
202
203 def _merge_pseudo_and_actual_album(
204 pseudo: AlbumInfo, actual: AlbumInfo
205 ) -> AlbumInfo:
206 """
207 Merges a pseudo release with its actual release.
208
209 This implementation is naive, it doesn't overwrite fields,
210 like status or ids.
211
212 According to the ticket PICARD-145, the main release id should be used.
213 But the ticket has been in limbo since over a decade now.
214 It also suggests the introduction of the tag `musicbrainz_pseudoreleaseid`,
215 but as of this field can't be found in any official Picard docs,
216 hence why we did not implement that for now.
217 """
218 merged = pseudo.copy()
219 from_actual = {
220 k: actual[k]
221 for k in [
222 "media",
223 "mediums",
224 "country",
225 "catalognum",
226 "year",
227 "month",
228 "day",
229 "original_year",
230 "original_month",
231 "original_day",
232 "label",
233 "barcode",
234 "asin",
235 "style",
236 "genres",
237 ]
238 }
239 merged.update(from_actual)
240 return merged
241
242
243 class MusicBrainzPlugin(
244 MusicBrainzAPIMixin, SearchApiMetadataSourcePlugin[IDResponse]
245 ):
246 @cached_property
247 def genres_field(self) -> Literal["genres", "tags"]:
248 choices: list[Literal["genre", "tag"]] = ["genre", "tag"]
249 choice = self.config["genres_tag"].as_choice(choices)
250 if choice == "genre":
251 return "genres"
252 return "tags"
253
254 @cached_property
255 def ignored_media(self) -> set[str]:
256 return set(config["match"]["ignored_media"].as_str_seq())
257
258 @cached_property
259 def ignore_data_tracks(self) -> bool:
260 return config["match"]["ignore_data_tracks"].get(bool)
261
262 @cached_property
263 def ignore_video_tracks(self) -> bool:
264 return config["match"]["ignore_video_tracks"].get(bool)
265
266 @cached_property
267 def aliases_as_credits(self) -> bool:
268 return self.config["aliases_as_credits"].get(bool)
269
270 def __init__(self) -> None:
271 """Set up the python-musicbrainz-ngs module according to settings
272 from the beets configuration. This should be called at startup.
273 """
274 super().__init__()
275 self.config.add(
276 {
277 "genres": False,
278 "genres_tag": "genre",
279 "external_ids": {
280 "discogs": False,
281 "bandcamp": False,
282 "spotify": False,
283 "deezer": False,
284 "tidal": False,
285 },
286 "extra_tags": [],
287 "aliases_as_credits": False,
288 }
289 )
290 # TODO: Remove in 3.0.0
291 with suppress(NotFoundError):
292 self.config["search_limit"] = self.config["match"][
293 "searchlimit"
294 ].get()
295 deprecate_for_user(
296 self._log,
297 "'musicbrainz.searchlimit' configuration option",
298 "'musicbrainz.search_limit'",
299 )
300
301 def _parse_artist_credits(
302 self, artist_credits: list[ArtistCredit]
303 ) -> ArtistInfo:
304 """Normalize MusicBrainz artist-credit data into tag-friendly fields.
305
306 MusicBrainz represents credits as a sequence of credited artists, each
307 with a display name and a `joinphrase` (for example `' & '`, `' feat.
308 '`, or `''`). This helper converts that structured representation into
309 both:
310
311 - Single string values suitable for common tags (concatenated names with
312 joinphrases preserved).
313 - Parallel lists that keep the per-artist granularity for callers that
314 need to reason about individual credited artists.
315
316 When available, a preferred alias is used for the canonical artist name,
317 sort name and the credit name.
318 """
319 artist_parts: list[str] = []
320 artist_sort_parts: list[str] = []
321 artist_credit_parts: list[str] = []
322 artists: list[str] = []
323 artists_sort: list[str] = []
324 artists_credit: list[str] = []
325 artists_ids: list[str] = []
326
327 for el in artist_credits:
328 artists_ids.append(el["artist"]["id"])
329 alias = _preferred_alias(el["artist"].get("aliases", []))
330 artist_object = alias or el["artist"]
331 credit_artist_object = (
332 alias if (alias and self.aliases_as_credits) else el
333 )
334
335 joinphrase = el["joinphrase"]
336 for name, parts, multi in (
337 (artist_object["name"], artist_parts, artists),
338 (artist_object["sort_name"], artist_sort_parts, artists_sort),
339 (
340 credit_artist_object["name"],
341 artist_credit_parts,
342 artists_credit,
343 ),
344 ):
345 parts.extend([name, joinphrase])
346 multi.append(name)
347
348 return {
349 "artist": "".join(artist_parts),
350 "artist_id": artists_ids[0],
351 "artist_sort": "".join(artist_sort_parts),
352 "artist_credit": "".join(artist_credit_parts),
353 "artists": artists,
354 "artists_ids": artists_ids,
355 "artists_sort": artists_sort,
356 "artists_credit": artists_credit,
357 }
358
359 @staticmethod
360 def _parse_work_relations(
361 relations: list[WorkRelation],
362 ) -> WorkRelationsInfo:
363 """Extract composer and lyricist credits from work relations.
364
365 Traverses performance-type relations to collect associated artist
366 credits, separating them into composers and lyricists along with
367 their MusicBrainz IDs and sort names.
368 """
369 lyricists: list[str] = []
370 lyricists_ids: list[str] = []
371 composers: list[str] = []
372 composers_ids: list[str] = []
373 composer_sort: list[str] = []
374
375 artist_relations = [
376 ar
377 for r in relations
378 if r["type"] == "performance"
379 for ar in r["work"].get("artist_relations", [])
380 ]
381 for artist_relation in artist_relations:
382 rel_type = artist_relation["type"]
383 if rel_type == "lyricist":
384 lyricists.append(artist_relation["artist"]["name"])
385 lyricists_ids.append(artist_relation["artist"]["id"])
386 elif rel_type == "composer":
387 composers.append(artist_relation["artist"]["name"])
388 composers_ids.append(artist_relation["artist"]["id"])
389 composer_sort.append(artist_relation["artist"]["sort_name"])
390
391 return {
392 # TODO: double-check if we should really use the last work here
393 "work": relations[-1]["work"]["title"] if relations else None,
394 "mb_workid": relations[-1]["work"]["id"] if relations else None,
395 "lyricists": lyricists or None,
396 "lyricists_ids": lyricists_ids or None,
397 "composers": composers or None,
398 "composers_ids": composers_ids or None,
399 "composer_sort": ", ".join(composer_sort) or None,
400 }
401
402 @staticmethod
403 def _parse_artist_relations(
404 relations: list[ArtistRelation],
405 ) -> ArtistRelationsInfo:
406 """Extract arranger and remixer credits from artist relations.
407
408 Traverses recording-level artist relations to collect associated artist
409 credits, separating them into arrangers and remixers along with their
410 MusicBrainz IDs.
411 """
412 arrangers: list[str] = []
413 arrangers_ids: list[str] = []
414 remixers: list[str] = []
415 remixers_ids: list[str] = []
416
417 for artist_relation in relations:
418 rel_type = artist_relation["type"]
419 if rel_type == "arranger":
420 arrangers.append(artist_relation["artist"]["name"])
421 arrangers_ids.append(artist_relation["artist"]["id"])
422 elif rel_type == "remixer":
423 remixers.append(artist_relation["artist"]["name"])
424 remixers_ids.append(artist_relation["artist"]["id"])
425
426 return {
427 "arrangers": arrangers or None,
428 "arrangers_ids": arrangers_ids or None,
429 "remixers": remixers or None,
430 "remixers_ids": remixers_ids or None,
431 }
432
433 def track_info(self, recording: Recording) -> TrackInfo:
434 """Build a `TrackInfo` object from a MusicBrainz recording payload.
435
436 This is the main translation layer between MusicBrainz's recording model
437 and beets' internal autotag representation. It gathers core identifying
438 metadata (title, MBIDs, URLs), timing information, and artist-credit
439 fields, then enriches the result with relationship-derived roles (such
440 as remixers and arrangers) and work-level credits (such as lyricists and
441 composers).
442 """
443 title = _key_with_preferred_alias(recording, key="title")
444
445 info = TrackInfo(
446 title=title,
447 track_id=recording["id"],
448 data_source=self.data_source,
449 data_url=urljoin(BASE_URL, f"recording/{recording['id']}"),
450 length=(
451 length / 1000.0 if (length := recording["length"]) else None
452 ),
453 trackdisambig=recording["disambiguation"] or None,
454 isrc=(
455 ";".join(isrcs) if (isrcs := recording.get("isrcs")) else None
456 ),
457 **self._parse_artist_credits(recording["artist_credit"]),
458 **self._parse_work_relations(recording.get("work_relations", [])),
459 **self._parse_artist_relations(
460 recording.get("artist_relations", [])
461 ),
462 )
463
464 # Supplementary fields provided by plugins
465 extra_trackdatas = plugins.send("mb_track_extract", data=recording)
466 for extra_trackdata in extra_trackdatas:
467 info.update(extra_trackdata)
468
469 return info
470
471 @staticmethod
472 def _parse_release_group(release_group: ReleaseGroup) -> ReleaseGroupInfo:
473 albumtype = None
474 albumtypes = []
475 if reltype := release_group["primary_type"]:
476 albumtype = reltype.lower()
477 albumtypes.append(albumtype)
478
479 year, month, day = _get_date(release_group["first_release_date"])
480 return ReleaseGroupInfo(
481 albumtype=albumtype,
482 albumtypes=[
483 *albumtypes,
484 *(st.lower() for st in release_group["secondary_types"]),
485 ],
486 releasegroup_id=release_group["id"],
487 release_group_title=_key_with_preferred_alias(
488 release_group, key="title"
489 ),
490 releasegroupdisambig=release_group["disambiguation"] or None,
491 original_year=year,
492 original_month=month,
493 original_day=day,
494 )
495
496 @staticmethod
497 def _parse_label_infos(label_infos: list[LabelInfo]) -> LabelInfoInfo:
498 catalognum = label = None
499 if label_infos:
500 label_info = label_infos[0]
501 catalognum = label_info["catalog_number"]
502 if (_label := label_info["label"]) and (
503 label_name := _label["name"]
504 ) != "[no label]":
505 label = label_name
506
507 return {"label": label, "catalognum": catalognum}
508
509 def _parse_genres(self, release: Release) -> list[str] | None:
510 if self.config["genres"] and (
511 genres := [
512 *release["release_group"][self.genres_field],
513 *release[self.genres_field],
514 ]
515 ):
516 count_by_genre: dict[str, int] = defaultdict(int)
517 for genre in genres:
518 count_by_genre[genre["name"]] += genre["count"]
519
520 return [
521 g
522 for g, _ in sorted(count_by_genre.items(), key=lambda g: -g[1])
523 ]
524
525 return None
526
527 def _parse_external_ids(
528 self, url_relations: list[UrlRelation]
529 ) -> ExternalIdsInfo:
530 """Extract configured external release ids from MusicBrainz URLs.
531
532 MusicBrainz releases can include `url_relations` pointing to third-party
533 sites (for example Bandcamp or Discogs). This helper filters those URL
534 relations to only the sources enabled in configuration, then derives a
535 stable external identifier from each matching URL.
536 """
537 external_ids = self.config["external_ids"].get()
538 wanted_sources: set[UrlSource] = {
539 site for site, wanted in external_ids.items() if wanted
540 }
541 url_by_source: dict[UrlSource, str] = {}
542 for source, url_relation in product(wanted_sources, url_relations):
543 if f"{source}.com" in (target := url_relation["url"]["resource"]):
544 url_by_source[source] = target
545 self._log.debug(
546 "Found link to {} release via MusicBrainz",
547 source.capitalize(),
548 )
549
550 return {
551 f"{source}_album_id": extract_release_id(source, url)
552 for source, url in url_by_source.items()
553 } # type: ignore[return-value]
554
555 def get_tracks_from_medium(self, medium: Medium) -> Iterable[TrackInfo]:
556 all_tracks = []
557 if pregap := medium.get("pregap"):
558 all_tracks.append(pregap)
559
560 all_tracks.extend(medium.get("tracks", []))
561
562 if not self.ignore_data_tracks:
563 all_tracks.extend(medium.get("data_tracks", []))
564
565 medium_data = {
566 "medium": medium["position"],
567 "medium_total": medium["track_count"],
568 "disctitle": medium["title"],
569 "media": medium["format"],
570 }
571 valid_tracks = [
572 t
573 for t in all_tracks
574 if (
575 # skip data tracks without titles
576 t["recording"]["title"] != "[data track]"
577 # and video tracks if we're configured to ignore them
578 and not (self.ignore_video_tracks and t["recording"]["video"])
579 )
580 ]
581 for track in valid_tracks:
582 # make a copy since we need to modify it with track-level overrides
583 recording = track["recording"].copy()
584 # Prefer track data, where present, over recording data.
585 recording["length"] = track["length"] or recording["length"]
586 recording["artist_credit"] = (
587 track["artist_credit"] or recording["artist_credit"]
588 )
589 if track["title"] and not _preferred_alias(recording["aliases"]):
590 recording["title"] = track["title"]
591
592 ti = self.track_info(recording)
593 ti.update(
594 medium_index=int(track["position"]),
595 release_track_id=track["id"],
596 track_alt=track["number"],
597 **medium_data,
598 )
599
600 yield ti
601
602 def _ensure_complete_recordings(self, release: Release) -> None:
603 """Patch a release's tracks with full recording data from the API.
604
605 The MusicBrainz API silently omits relation data for releases
606 exceeding a track threshold. This method detects that case and
607 re-fetches recordings in paginated chunks, then mutates the
608 release in-place so callers always see complete data.
609 """
610 track_count = sum(len(m.get("tracks", [])) for m in release["media"])
611 if track_count > BROWSE_MAXTRACKS:
612 self._log.debug("Album {} has too many tracks", release["id"])
613 recordings: list[Recording] = []
614 for i in range(0, track_count, BROWSE_CHUNKSIZE):
615 self._log.debug("Retrieving tracks starting at {}", i)
616 recordings.extend(
617 self.mb_api.browse_recordings(
618 release=release["id"],
619 limit=BROWSE_CHUNKSIZE,
620 includes=BROWSE_INCLUDES,
621 offset=i,
622 )
623 )
624 recording_by_id = {r["id"]: r for r in recordings}
625 for medium in release["media"]:
626 for track in medium["tracks"]:
627 track["recording"] = recording_by_id[
628 track["recording"]["id"]
629 ]
630
631 def album_info(self, release: Release) -> AlbumInfo:
632 """Takes a MusicBrainz release result dictionary and returns a beets
633 AlbumInfo object containing the interesting data about that release.
634 """
635 self._ensure_complete_recordings(release)
636
637 # Basic info.
638 valid_media = [
639 m for m in release["media"] if m["format"] not in self.ignored_media
640 ]
641 track_infos: list[TrackInfo] = []
642 for medium in valid_media:
643 track_infos.extend(self.get_tracks_from_medium(medium))
644
645 for index, track_info in enumerate(track_infos, 1):
646 track_info.index = index
647
648 release_title = _key_with_preferred_alias(release, key="title")
649 info = AlbumInfo(
650 **self._parse_artist_credits(release["artist_credit"]),
651 album=release_title,
652 album_id=release["id"],
653 tracks=track_infos,
654 media=(
655 medias.pop()
656 if len(medias := {t.media for t in track_infos}) == 1
657 else "Media"
658 ),
659 mediums=len(release["media"]),
660 data_source=self.data_source,
661 data_url=urljoin(BASE_URL, f"release/{release['id']}"),
662 barcode=release.get("barcode"),
663 genres=self._parse_genres(release),
664 script=release["text_representation"]["script"],
665 language=release["text_representation"]["language"],
666 asin=release["asin"],
667 albumstatus=release["status"],
668 albumdisambig=release["disambiguation"] or None,
669 **self._parse_release_group(release["release_group"]),
670 **self._parse_label_infos(release["label_info"]),
671 **self._parse_external_ids(release.get("url_relations", [])),
672 )
673 info.va = info.artist_id == VARIOUS_ARTISTS_ID
674 if info.va:
675 va_name = config["va_name"].as_str()
676 info.artist = va_name
677 info.artist_sort = va_name
678 info.artists = [va_name]
679 info.artists_sort = [va_name]
680 info.artist_credit = va_name
681 info.artists_credit = [va_name]
682
683 # Release events.
684 info.country, release_date = _preferred_release_event(release)
685 info.year, info.month, info.day = (
686 _get_date(release_date)
687 if release_date
688 else (info.original_year, info.original_month, info.original_day)
689 )
690
691 extra_albumdatas = plugins.send("mb_album_extract", data=release)
692 for extra_albumdata in extra_albumdatas:
693 info.update(extra_albumdata)
694
695 return info
696
697 @cached_property
698 def extra_mb_field_by_tag(self) -> dict[str, str]:
699 """Map configured extra tags to their MusicBrainz API field names.
700
701 Process user configuration to determine which additional MusicBrainz
702 fields should be included in search queries.
703 """
704 mb_field_by_tag = {
705 t: FIELDS_TO_MB_KEYS[t]
706 for t in self.config["extra_tags"].as_str_seq()
707 if t in FIELDS_TO_MB_KEYS
708 }
709 if mb_field_by_tag:
710 self._log.debug("Additional search terms: {}", mb_field_by_tag)
711
712 return mb_field_by_tag
713
714 def get_album_criteria(
715 self, items: Sequence[Item], artist: str, album: str, va_likely: bool
716 ) -> dict[str, str]:
717 criteria = {"release": album} | (
718 {"arid": VARIOUS_ARTISTS_ID} if va_likely else {"artist": artist}
719 )
720
721 for tag, mb_field in self.extra_mb_field_by_tag.items():
722 if tag == "tracks":
723 value = str(len(items))
724 elif tag == "alias":
725 value = album
726 else:
727 most_common, _ = util.plurality(i.get(tag) for i in items)
728 value = str(most_common)
729 if tag == "catalognum":
730 value = value.replace(" ", "")
731
732 criteria[mb_field] = value
733
734 return criteria
735
736 def get_search_query_with_filters(
737 self,
738 query_type: QueryType,
739 items: Sequence[Item],
740 artist: str,
741 name: str,
742 va_likely: bool,
743 ) -> tuple[str, dict[str, str]]:
744 """Build MusicBrainz criteria filters for album and recording search."""
745
746 if query_type == "album":
747 criteria = self.get_album_criteria(items, artist, name, va_likely)
748 else:
749 criteria = {"artist": artist, "recording": name, "alias": name}
750
751 return "", {
752 k: _v for k, v in criteria.items() if (_v := v.lower().strip())
753 }
754
755 def get_search_response(self, params: SearchParams) -> Sequence[IDResponse]:
756 """Search MusicBrainz and return release or recording result mappings."""
757
758 mb_entity: Literal["release", "recording"] = (
759 "release" if params.query_type == "album" else "recording"
760 )
761 return self.mb_api.search(
762 mb_entity, dict(params.filters), limit=params.limit
763 )
764
765 def album_for_id(self, album_id: str) -> AlbumInfo | None:
766 """Fetches an album by its MusicBrainz ID and returns an AlbumInfo
767 object or None if the album is not found. May raise a
768 MusicBrainzAPIError.
769 """
770 self._log.debug("Requesting MusicBrainz release {}", album_id)
771 if not (albumid := self._extract_id(album_id)):
772 self._log.debug("Invalid MBID ({}).", album_id)
773 return None
774
775 # A 404 error here is fine. e.g. re-importing a release that has
776 # been deleted on MusicBrainz.
777 try:
778 original_release = self.mb_api.get_release(albumid)
779 except HTTPNotFoundError:
780 self._log.debug("Release {} not found on MusicBrainz.", albumid)
781 return None
782
783 album = self.album_info(original_release)
784
785 if original_release["status"] == "Pseudo-Release":
786 linked_releases = (
787 rel
788 for rel in original_release.get("release_relations", [])
789 if (
790 rel["type"] == "transl-tracklisting"
791 and rel["direction"] == "backward"
792 )
793 )
794 if rel := next(linked_releases, None):
795 actual_release = self.mb_api.get_release(rel["release"]["id"])
796 album = _merge_pseudo_and_actual_album(
797 album, self.album_info(actual_release)
798 )
799
800 return album
801
802 def track_for_id(self, track_id: str) -> TrackInfo | None:
803 """Fetches a track by its MusicBrainz ID. Returns a TrackInfo object
804 or None if no track is found. May raise a MusicBrainzAPIError.
805 """
806 if not (trackid := self._extract_id(track_id)):
807 self._log.debug("Invalid MBID ({}).", track_id)
808 return None
809
810 with suppress(HTTPNotFoundError):
811 return self.track_info(self.mb_api.get_recording(trackid))
812
813 return None