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