| 1 |
"""Adds Deezer release and track search support to the autotagger""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import collections |
| 6 |
import time |
| 7 |
from typing import TYPE_CHECKING, ClassVar |
| 8 |
|
| 9 |
import requests |
| 10 |
|
| 11 |
from beets import config, ui |
| 12 |
from beets.autotag import AlbumInfo, TrackInfo |
| 13 |
from beets.dbcore import types |
| 14 |
from beets.exceptions import UserError |
| 15 |
from beets.importer.tasks import SINGLE_ARTIST_THRESH |
| 16 |
from beets.metadata_plugins import IDResponse, SearchApiMetadataSourcePlugin |
| 17 |
|
| 18 |
VARIOUS_ARTISTS_ID = 5080 |
| 19 |
|
| 20 |
if TYPE_CHECKING: |
| 21 |
import optparse |
| 22 |
from collections.abc import Sequence |
| 23 |
|
| 24 |
from beets.library import Item, Library |
| 25 |
from beets.metadata_plugins import QueryType, SearchParams |
| 26 |
|
| 27 |
from ._typing import JSONDict |
| 28 |
|
| 29 |
|
| 30 |
class DeezerPlugin(SearchApiMetadataSourcePlugin[IDResponse]): |
| 31 |
item_types: ClassVar[dict[str, types.Type]] = { |
| 32 |
"deezer_track_rank": types.INTEGER, |
| 33 |
"deezer_track_id": types.INTEGER, |
| 34 |
"deezer_updated": types.DATE, |
| 35 |
} |
| 36 |
# Base URLs for the Deezer API |
| 37 |
# Documentation: https://developers.deezer.com/api/ |
| 38 |
search_url = "https://api.deezer.com/search/" |
| 39 |
album_url = "https://api.deezer.com/album/" |
| 40 |
track_url = "https://api.deezer.com/track/" |
| 41 |
|
| 42 |
def __init__(self) -> None: |
| 43 |
super().__init__() |
| 44 |
|
| 45 |
def commands(self) -> list[ui.Subcommand]: |
| 46 |
"""Add beet UI commands to interact with Deezer.""" |
| 47 |
deezer_update_cmd = ui.Subcommand( |
| 48 |
"deezerupdate", help=f"Update {self.data_source} rank" |
| 49 |
) |
| 50 |
|
| 51 |
def func(lib: Library, opts: optparse.Values, args: list[str]) -> None: |
| 52 |
items = lib.items(args) |
| 53 |
self.deezerupdate(list(items), ui.should_write()) |
| 54 |
|
| 55 |
deezer_update_cmd.func = func |
| 56 |
|
| 57 |
return [deezer_update_cmd] |
| 58 |
|
| 59 |
def album_for_id(self, album_id: str) -> AlbumInfo | None: |
| 60 |
"""Fetch an album by its Deezer ID or URL.""" |
| 61 |
if not (deezer_id := self._extract_id(album_id)): |
| 62 |
return None |
| 63 |
|
| 64 |
album_url = f"{self.album_url}{deezer_id}" |
| 65 |
if not (album_data := self.fetch_data(album_url)): |
| 66 |
return None |
| 67 |
|
| 68 |
contributors = album_data.get("contributors") |
| 69 |
if contributors is not None: |
| 70 |
artist, artist_id = self.get_artist(contributors) |
| 71 |
else: |
| 72 |
artist, artist_id = None, None |
| 73 |
|
| 74 |
release_date = album_data["release_date"] |
| 75 |
date_parts = [int(part) for part in release_date.split("-")] |
| 76 |
num_date_parts = len(date_parts) |
| 77 |
|
| 78 |
if num_date_parts == 3: |
| 79 |
year, month, day = date_parts |
| 80 |
elif num_date_parts == 2: |
| 81 |
year, month = date_parts |
| 82 |
day = None |
| 83 |
elif num_date_parts == 1: |
| 84 |
year = date_parts[0] |
| 85 |
month = None |
| 86 |
day = None |
| 87 |
else: |
| 88 |
raise UserError( |
| 89 |
f"Invalid `release_date` returned by {self.data_source} API: " |
| 90 |
f"{release_date!r}" |
| 91 |
) |
| 92 |
tracks_obj = self.fetch_data(f"{self.album_url}{deezer_id}/tracks") |
| 93 |
if tracks_obj is None: |
| 94 |
return None |
| 95 |
try: |
| 96 |
tracks_data = tracks_obj["data"] |
| 97 |
except KeyError: |
| 98 |
self._log.debug("Error fetching album tracks for {}", deezer_id) |
| 99 |
tracks_data = None |
| 100 |
if not tracks_data: |
| 101 |
return None |
| 102 |
while "next" in tracks_obj: |
| 103 |
tracks_obj = requests.get(tracks_obj["next"], timeout=10).json() |
| 104 |
tracks_data.extend(tracks_obj["data"]) |
| 105 |
|
| 106 |
tracks = [] |
| 107 |
medium_totals: dict[int | None, int] = collections.defaultdict(int) |
| 108 |
for i, track_data in enumerate(tracks_data, start=1): |
| 109 |
track = self._get_track(track_data) |
| 110 |
track.index = i |
| 111 |
medium_totals[track.medium] += 1 |
| 112 |
tracks.append(track) |
| 113 |
for track in tracks: |
| 114 |
track.medium_total = medium_totals[track.medium] |
| 115 |
|
| 116 |
album_artist_id = str(album_data["artist"]["id"]) |
| 117 |
# Deezer assigns some compilations a single "main" artist instead of |
| 118 |
# the Various Artists entity, leaving them undetected. Treat a release |
| 119 |
# as VA when its album artist performs on fewer tracks than the |
| 120 |
# importer's own single-artist plurality threshold. |
| 121 |
is_va = album_artist_id == str(VARIOUS_ARTISTS_ID) or ( |
| 122 |
sum(t.artist_id == album_artist_id for t in tracks) |
| 123 |
< len(tracks) * SINGLE_ARTIST_THRESH |
| 124 |
) |
| 125 |
if is_va: |
| 126 |
va_name = config["va_name"].as_str() |
| 127 |
artist = va_name |
| 128 |
|
| 129 |
return AlbumInfo( |
| 130 |
album=album_data["title"], |
| 131 |
album_id=deezer_id, |
| 132 |
deezer_album_id=deezer_id, |
| 133 |
artist=artist, |
| 134 |
artist_credit=( |
| 135 |
artist if is_va else self.get_artist([album_data["artist"]])[0] |
| 136 |
), |
| 137 |
artist_id=str(artist_id), |
| 138 |
tracks=tracks, |
| 139 |
albumtype=album_data["record_type"], |
| 140 |
va=is_va, |
| 141 |
year=year, |
| 142 |
month=month, |
| 143 |
day=day, |
| 144 |
label=album_data["label"], |
| 145 |
mediums=max(filter(None, medium_totals.keys())), |
| 146 |
data_source=self.data_source, |
| 147 |
data_url=album_data["link"], |
| 148 |
cover_art_url=album_data.get("cover_xl"), |
| 149 |
) |
| 150 |
|
| 151 |
def track_for_id(self, track_id: str) -> TrackInfo | None: |
| 152 |
"""Fetch a track by its Deezer ID or URL and return a |
| 153 |
TrackInfo object or None if the track is not found. |
| 154 |
|
| 155 |
:param track_id: (Optional) Deezer ID or URL for the track. Either |
| 156 |
``track_id`` or ``track_data`` must be provided. |
| 157 |
|
| 158 |
""" |
| 159 |
if not (deezer_id := self._extract_id(track_id)): |
| 160 |
self._log.debug("Invalid Deezer track_id: {}", track_id) |
| 161 |
return None |
| 162 |
|
| 163 |
if not (track_data := self.fetch_data(f"{self.track_url}{deezer_id}")): |
| 164 |
self._log.debug("Track not found: {}", track_id) |
| 165 |
return None |
| 166 |
|
| 167 |
track = self._get_track(track_data) |
| 168 |
|
| 169 |
# Get album's tracks to set `track.index` (position on the entire |
| 170 |
# release) and `track.medium_total` (total number of tracks on |
| 171 |
# the track's disc). |
| 172 |
if not ( |
| 173 |
album_tracks_obj := self.fetch_data( |
| 174 |
f"{self.album_url}{track_data['album']['id']}/tracks" |
| 175 |
) |
| 176 |
): |
| 177 |
return None |
| 178 |
|
| 179 |
try: |
| 180 |
album_tracks_data = album_tracks_obj["data"] |
| 181 |
except KeyError: |
| 182 |
self._log.debug( |
| 183 |
"Error fetching album tracks for {}", track_data["album"]["id"] |
| 184 |
) |
| 185 |
return None |
| 186 |
medium_total = 0 |
| 187 |
for i, track_data in enumerate(album_tracks_data, start=1): |
| 188 |
if track_data["disk_number"] == track.medium: |
| 189 |
medium_total += 1 |
| 190 |
if track_data["id"] == track.track_id: |
| 191 |
track.index = i |
| 192 |
track.medium_total = medium_total |
| 193 |
return track |
| 194 |
|
| 195 |
def _get_track(self, track_data: JSONDict) -> TrackInfo: |
| 196 |
"""Convert a Deezer track object dict to a TrackInfo object. |
| 197 |
|
| 198 |
:param track_data: Deezer Track object dict |
| 199 |
""" |
| 200 |
contributors = track_data.get("contributors") |
| 201 |
if contributors is None and (artist_data := track_data.get("artist")): |
| 202 |
contributors = [artist_data] |
| 203 |
if contributors is not None: |
| 204 |
artist, artist_id = self.get_artist(contributors) |
| 205 |
else: |
| 206 |
artist, artist_id = None, None |
| 207 |
return TrackInfo( |
| 208 |
title=track_data["title"], |
| 209 |
track_id=track_data["id"], |
| 210 |
deezer_track_id=track_data["id"], |
| 211 |
isrc=track_data.get("isrc"), |
| 212 |
artist=artist, |
| 213 |
artist_id=str(artist_id) if artist_id is not None else None, |
| 214 |
length=track_data["duration"], |
| 215 |
index=track_data.get("track_position"), |
| 216 |
medium=track_data.get("disk_number"), |
| 217 |
deezer_track_rank=track_data.get("rank"), |
| 218 |
medium_index=track_data.get("track_position"), |
| 219 |
data_source=self.data_source, |
| 220 |
data_url=track_data["link"], |
| 221 |
deezer_updated=time.time(), |
| 222 |
) |
| 223 |
|
| 224 |
def get_search_query_with_filters( |
| 225 |
self, |
| 226 |
query_type: QueryType, |
| 227 |
items: Sequence[Item], |
| 228 |
artist: str, |
| 229 |
name: str, |
| 230 |
va_likely: bool, |
| 231 |
) -> tuple[str, dict[str, str]]: |
| 232 |
if query_type == "album": |
| 233 |
query = f'album:"{name}"' |
| 234 |
if not va_likely: |
| 235 |
query += f' artist:"{artist}"' |
| 236 |
else: |
| 237 |
# Deezer drops unquoted free text as soon as the query carries any |
| 238 |
# field:"value" filter, so `<title> artist:"<artist>"` degenerated |
| 239 |
# into "every track by this artist", truncated to `search_limit`. |
| 240 |
# The wanted track routinely fell outside that window. Filtering on |
| 241 |
# the title instead is no better, because `artist:` is fuzzy enough |
| 242 |
# to match unrelated artists ("Pan Da Punk" for "Daft Punk"), so the |
| 243 |
# two filters can intersect to nothing even for a well-tagged file. |
| 244 |
# Plain free text lets Deezer's own relevance ranking do the work. |
| 245 |
query = f"{name} {artist}".strip() |
| 246 |
|
| 247 |
return query, {} |
| 248 |
|
| 249 |
def get_search_response(self, params: SearchParams) -> list[IDResponse]: |
| 250 |
"""Search Deezer and return the raw result payload entries.""" |
| 251 |
|
| 252 |
response = requests.get( |
| 253 |
f"{self.search_url}{params.query_type}", |
| 254 |
params={ |
| 255 |
**params.filters, |
| 256 |
"q": params.query, |
| 257 |
"limit": str(params.limit), |
| 258 |
}, |
| 259 |
timeout=10, |
| 260 |
) |
| 261 |
response.raise_for_status() |
| 262 |
return response.json()["data"] |
| 263 |
|
| 264 |
def deezerupdate(self, items: Sequence[Item], write: bool) -> None: |
| 265 |
"""Obtain rank information from Deezer.""" |
| 266 |
for index, item in enumerate(items, start=1): |
| 267 |
self._log.info( |
| 268 |
"Processing {}/{} tracks - {} ", index, len(items), item |
| 269 |
) |
| 270 |
try: |
| 271 |
deezer_track_id = item.deezer_track_id |
| 272 |
except AttributeError: |
| 273 |
self._log.debug("No deezer_track_id present for: {}", item) |
| 274 |
continue |
| 275 |
try: |
| 276 |
track = self.fetch_data(f"{self.track_url}{deezer_track_id}") |
| 277 |
except Exception as e: |
| 278 |
self._log.debug("Invalid Deezer track_id: {}", e) |
| 279 |
continue |
| 280 |
else: |
| 281 |
if track and (rank := track.get("rank") is not None): |
| 282 |
self._log.debug( |
| 283 |
"Deezer track: {} has {} rank", deezer_track_id, rank |
| 284 |
) |
| 285 |
item.deezer_track_rank = int(rank) |
| 286 |
item.store() |
| 287 |
item.deezer_updated = time.time() |
| 288 |
if write: |
| 289 |
item.try_write() |
| 290 |
|
| 291 |
def fetch_data(self, url: str) -> JSONDict | None: |
| 292 |
try: |
| 293 |
response = requests.get(url, timeout=10) |
| 294 |
response.raise_for_status() |
| 295 |
data = response.json() |
| 296 |
except requests.exceptions.RequestException as e: |
| 297 |
self._log.error("Error fetching data from {}\n Error: {}", url, e) |
| 298 |
return None |
| 299 |
if "error" in data: |
| 300 |
self._log.debug("Deezer API error: {}", data["error"]["message"]) |
| 301 |
return None |
| 302 |
return data |