| 1 |
"""Adds Listenbrainz support to Beets.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import datetime |
| 6 |
import json |
| 7 |
import time |
| 8 |
import zipfile |
| 9 |
from collections import Counter |
| 10 |
from typing import TYPE_CHECKING, ClassVar, Protocol, TypedDict |
| 11 |
|
| 12 |
import requests |
| 13 |
|
| 14 |
from beets import config, ui |
| 15 |
from beets.dbcore import types |
| 16 |
from beets.plugins import BeetsPlugin |
| 17 |
from beets.util import displayable_path, normpath, syspath |
| 18 |
|
| 19 |
from ._utils.musicbrainz import MusicBrainzAPIMixin |
| 20 |
from ._utils.playcount import update_play_counts |
| 21 |
from ._utils.requests import TimeoutAndRetrySession |
| 22 |
|
| 23 |
if TYPE_CHECKING: |
| 24 |
from collections.abc import Iterable |
| 25 |
from pathlib import Path |
| 26 |
|
| 27 |
from beets.library import Library |
| 28 |
|
| 29 |
from ._typing import JSONDict |
| 30 |
from ._utils.playcount import Track |
| 31 |
|
| 32 |
|
| 33 |
class LBImportCLIOpts(Protocol): |
| 34 |
export_file: str | None |
| 35 |
max_listens: int | None |
| 36 |
|
| 37 |
|
| 38 |
class Listen(TypedDict): |
| 39 |
listened_at: int |
| 40 |
track_metadata: TrackMetadata |
| 41 |
|
| 42 |
|
| 43 |
class TrackMetadata(TypedDict, total=False): |
| 44 |
artist_name: str |
| 45 |
track_name: str |
| 46 |
release_name: str | None |
| 47 |
additional_info: AdditionalInfo |
| 48 |
mbid_mapping: MbidMapping | None |
| 49 |
|
| 50 |
|
| 51 |
class AdditionalInfo(TypedDict, total=False): |
| 52 |
recording_mbid: str | None |
| 53 |
|
| 54 |
|
| 55 |
class MbidMapping(TypedDict, total=False): |
| 56 |
recording_mbid: str | None |
| 57 |
|
| 58 |
|
| 59 |
class ListenBrainzPlugin(MusicBrainzAPIMixin, BeetsPlugin): |
| 60 |
"""A Beets plugin for interacting with ListenBrainz.""" |
| 61 |
|
| 62 |
ROOT = "http://api.listenbrainz.org/1/" |
| 63 |
|
| 64 |
item_types: ClassVar[dict[str, types.Type]] = { |
| 65 |
"listenbrainz_play_count": types.INTEGER |
| 66 |
} |
| 67 |
|
| 68 |
def __init__(self) -> None: |
| 69 |
"""Initialize the plugin.""" |
| 70 |
super().__init__() |
| 71 |
self.token = self.config["token"].get() |
| 72 |
self.username = self.config["username"].get() |
| 73 |
self.session = TimeoutAndRetrySession() |
| 74 |
self.AUTH_HEADER = {"Authorization": f"Token {self.token}"} |
| 75 |
config["listenbrainz"]["token"].redact = True |
| 76 |
|
| 77 |
def commands(self) -> list[ui.Subcommand]: |
| 78 |
"""Add beet UI commands to interact with ListenBrainz.""" |
| 79 |
lbupdate_cmd = ui.Subcommand( |
| 80 |
"lbimport", help="Import ListenBrainz history" |
| 81 |
) |
| 82 |
lbupdate_cmd.parser.add_option( |
| 83 |
"-f", |
| 84 |
"--export-file", |
| 85 |
dest="export_file", |
| 86 |
metavar="PATH", |
| 87 |
default=None, |
| 88 |
help=( |
| 89 |
"path to a ListenBrainz data export .zip file" |
| 90 |
" (instead of fetching from the API)" |
| 91 |
), |
| 92 |
) |
| 93 |
lbupdate_cmd.parser.add_option( |
| 94 |
"--max", |
| 95 |
dest="max_listens", |
| 96 |
type="int", |
| 97 |
default=None, |
| 98 |
help=( |
| 99 |
"maximum number of listens to fetch via the API (default: all)." |
| 100 |
" This option does not apply when importing a file via" |
| 101 |
" -f/--export-file." |
| 102 |
), |
| 103 |
) |
| 104 |
|
| 105 |
def func(lib: Library, opts: LBImportCLIOpts, args: list[str]) -> None: |
| 106 |
self._lbupdate( |
| 107 |
lib, export_file=opts.export_file, max_listens=opts.max_listens |
| 108 |
) |
| 109 |
|
| 110 |
lbupdate_cmd.func = func |
| 111 |
return [lbupdate_cmd] |
| 112 |
|
| 113 |
def _lbupdate( |
| 114 |
self, |
| 115 |
lib: Library, |
| 116 |
export_file: str | None = None, |
| 117 |
max_listens: int | None = None, |
| 118 |
) -> None: |
| 119 |
"""Update play counts from ListenBrainz listening history.""" |
| 120 |
listens: list[Listen] | None |
| 121 |
if export_file is not None: |
| 122 |
self._log.info( |
| 123 |
"Importing ListenBrainz data from {}...", export_file |
| 124 |
) |
| 125 |
if max_listens is not None: |
| 126 |
self._log.warning( |
| 127 |
"Ignoring superfluous --max flag when importing from file." |
| 128 |
) |
| 129 |
listens = self.import_listenbrainz_data_export(export_file) |
| 130 |
else: |
| 131 |
self._log.info("Fetching ListenBrainz history...") |
| 132 |
listens = self.get_listens(max_total=max_listens) |
| 133 |
if listens is None: |
| 134 |
self._log.error("Failed to fetch listens from ListenBrainz.") |
| 135 |
return |
| 136 |
if not listens: |
| 137 |
self._log.info("No listens found.") |
| 138 |
return |
| 139 |
self._log.info("Found {} listens", len(listens)) |
| 140 |
tracks = self._aggregate_listens(self.get_tracks_from_listens(listens)) |
| 141 |
self._log.info("Aggregated into {} unique tracks", len(tracks)) |
| 142 |
found, unknown = update_play_counts( |
| 143 |
lib, tracks, self._log, "listenbrainz" |
| 144 |
) |
| 145 |
self._log.info("... done!") |
| 146 |
self._log.info("{} unknown play-counts", unknown) |
| 147 |
self._log.info("{} play-counts imported", found) |
| 148 |
|
| 149 |
@staticmethod |
| 150 |
def _aggregate_listens(tracks: Iterable[Track]) -> list[Track]: |
| 151 |
"""Aggregate individual listen events into per-track play counts. |
| 152 |
|
| 153 |
ListenBrainz returns individual listen events (each with playcount=1). |
| 154 |
We aggregate them by track identity so each unique track gets its total |
| 155 |
count, making the import idempotent. |
| 156 |
""" |
| 157 |
_agg_key = str | tuple[str, str, str] |
| 158 |
play_counts: Counter[_agg_key] = Counter() |
| 159 |
track_info: dict[_agg_key, Track] = {} |
| 160 |
for t in tracks: |
| 161 |
mbid = t.get("mbid") or "" |
| 162 |
artist = t["artist"] |
| 163 |
name = t["name"] |
| 164 |
album = t.get("album") or "" |
| 165 |
|
| 166 |
key: _agg_key = mbid if mbid else (artist, name, album) |
| 167 |
play_counts[key] += 1 |
| 168 |
if key not in track_info: |
| 169 |
track_info[key] = t |
| 170 |
|
| 171 |
return [ |
| 172 |
{**info, "playcount": play_counts[key]} |
| 173 |
for key, info in track_info.items() |
| 174 |
] |
| 175 |
|
| 176 |
def _make_request( |
| 177 |
self, url: str, params: JSONDict | None = None |
| 178 |
) -> JSONDict | None: |
| 179 |
"""Makes a request to the ListenBrainz API. |
| 180 |
|
| 181 |
Respects the X-RateLimit-* headers returned by the server: if the |
| 182 |
remaining quota drops to zero, sleeps until the window resets before |
| 183 |
returning, so the next call is guaranteed a fresh quota. |
| 184 |
""" |
| 185 |
try: |
| 186 |
response = self.session.get( |
| 187 |
url=url, headers=self.AUTH_HEADER, timeout=10, params=params |
| 188 |
) |
| 189 |
response.raise_for_status() |
| 190 |
remaining = response.headers.get("X-RateLimit-Remaining") |
| 191 |
reset_in = response.headers.get("X-RateLimit-Reset-In") |
| 192 |
if remaining is not None and int(remaining) == 0 and reset_in: |
| 193 |
self._log.debug( |
| 194 |
"ListenBrainz rate limit reached; sleeping {}s", reset_in |
| 195 |
) |
| 196 |
time.sleep(int(reset_in) + 1) |
| 197 |
return response.json() |
| 198 |
except requests.exceptions.RequestException as e: |
| 199 |
self._log.debug("Invalid Search Error: {}", e) |
| 200 |
return None |
| 201 |
|
| 202 |
def import_listenbrainz_data_export( |
| 203 |
self, export_file: str | Path |
| 204 |
) -> list[Listen]: |
| 205 |
"""Import ListenBrainz data from a .zip file.""" |
| 206 |
export_file = syspath(normpath(export_file)) |
| 207 |
|
| 208 |
all_listens = [] |
| 209 |
|
| 210 |
try: |
| 211 |
with zipfile.ZipFile(export_file, "r") as zip_file: |
| 212 |
for file_name in zip_file.namelist(): |
| 213 |
if file_name.startswith("listens/") and file_name.endswith( |
| 214 |
".jsonl" |
| 215 |
): |
| 216 |
self._log.info( |
| 217 |
"Reading listens from {}", |
| 218 |
displayable_path(file_name), |
| 219 |
) |
| 220 |
with zip_file.open(file_name) as file: |
| 221 |
for line in file: |
| 222 |
if not line.strip(): |
| 223 |
continue |
| 224 |
try: |
| 225 |
all_listens.append(json.loads(line)) |
| 226 |
except json.JSONDecodeError as err: |
| 227 |
self._log.error( |
| 228 |
"Invalid JSON in {}: {}", |
| 229 |
displayable_path(file_name), |
| 230 |
err, |
| 231 |
) |
| 232 |
except OSError as err: |
| 233 |
raise ui.UserError( |
| 234 |
f"unreadable export file {displayable_path(export_file)}: {err}" |
| 235 |
) from err |
| 236 |
return all_listens |
| 237 |
|
| 238 |
def get_listens( |
| 239 |
self, |
| 240 |
min_ts: int | None = None, |
| 241 |
max_ts: int | None = None, |
| 242 |
count: int | None = None, |
| 243 |
max_total: int | None = None, |
| 244 |
) -> list[Listen] | None: |
| 245 |
"""Gets the listening history of a given user from the ListenBrainz API. |
| 246 |
|
| 247 |
Paginates through all available listens using the max_ts parameter. |
| 248 |
|
| 249 |
Args: |
| 250 |
min_ts: History before this timestamp will not be returned. |
| 251 |
DO NOT USE WITH max_ts. |
| 252 |
max_ts: History after this timestamp will not be returned. |
| 253 |
DO NOT USE WITH min_ts. |
| 254 |
count: How many listens to return per page (max 1000). |
| 255 |
max_total: Stop after fetching this many listens in total. |
| 256 |
|
| 257 |
Returns: |
| 258 |
A list of listen info dictionaries, or None on API failure. |
| 259 |
""" |
| 260 |
if min_ts is not None and max_ts is not None: |
| 261 |
raise ValueError("min_ts and max_ts are mutually exclusive.") |
| 262 |
|
| 263 |
per_page = min(count or 1000, 1000) |
| 264 |
url = f"{self.ROOT}/user/{self.username}/listens" |
| 265 |
all_listens: list[Listen] = [] |
| 266 |
|
| 267 |
while True: |
| 268 |
if max_total is not None: |
| 269 |
remaining_needed = max_total - len(all_listens) |
| 270 |
if remaining_needed <= 0: |
| 271 |
break |
| 272 |
page_size = min(per_page, remaining_needed) |
| 273 |
else: |
| 274 |
page_size = per_page |
| 275 |
|
| 276 |
params = {"count": page_size} |
| 277 |
if max_ts is not None: |
| 278 |
params["max_ts"] = max_ts |
| 279 |
if min_ts is not None: |
| 280 |
params["min_ts"] = min_ts |
| 281 |
|
| 282 |
response = self._make_request(url, params) |
| 283 |
if response is None: |
| 284 |
if not all_listens: |
| 285 |
return None |
| 286 |
break |
| 287 |
|
| 288 |
listens = response["payload"]["listens"] |
| 289 |
if not listens: |
| 290 |
break |
| 291 |
|
| 292 |
all_listens.extend(listens) |
| 293 |
self._log.info("Fetched {} listens so far...", len(all_listens)) |
| 294 |
|
| 295 |
# If we got fewer than requested, we've reached the end |
| 296 |
if len(listens) < page_size: |
| 297 |
break |
| 298 |
|
| 299 |
# Paginate using the oldest listen's timestamp. |
| 300 |
# Subtract 1 to avoid re-fetching listens at the boundary. |
| 301 |
new_max_ts = listens[-1]["listened_at"] - 1 |
| 302 |
if max_ts is not None and new_max_ts >= max_ts: |
| 303 |
break |
| 304 |
max_ts = new_max_ts |
| 305 |
|
| 306 |
return all_listens |
| 307 |
|
| 308 |
def get_tracks_from_listens(self, listens: Iterable[Listen]) -> list[Track]: |
| 309 |
"""Returns a list of tracks from a list of listens.""" |
| 310 |
tracks: list[Track] = [] |
| 311 |
for track in listens: |
| 312 |
track_metadata = track["track_metadata"] |
| 313 |
if track_metadata.get("release_name") is None: |
| 314 |
continue |
| 315 |
additional_info = track_metadata.get("additional_info", {}) |
| 316 |
recording_mbid = additional_info.get("recording_mbid") |
| 317 |
if recording_mbid is None: |
| 318 |
mbid_mapping = track_metadata.get("mbid_mapping") |
| 319 |
if mbid_mapping is not None: |
| 320 |
recording_mbid = mbid_mapping.get("recording_mbid") |
| 321 |
tracks.append( |
| 322 |
{ |
| 323 |
"album": (track_metadata.get("release_name") or "").strip(), |
| 324 |
"name": (track_metadata.get("track_name") or "").strip(), |
| 325 |
"artist": (track_metadata.get("artist_name") or "").strip(), |
| 326 |
"mbid": recording_mbid, |
| 327 |
"playcount": 1, |
| 328 |
} |
| 329 |
) |
| 330 |
return tracks |
| 331 |
|
| 332 |
def get_mb_recording_id(self, track: JSONDict) -> str | None: |
| 333 |
"""Returns the MusicBrainz recording ID for a track.""" |
| 334 |
results = self.mb_api.search( |
| 335 |
"recording", |
| 336 |
{ |
| 337 |
"": track["track_metadata"].get("track_name"), |
| 338 |
"release": track["track_metadata"].get("release_name"), |
| 339 |
}, |
| 340 |
) |
| 341 |
return next((r["id"] for r in results), None) |
| 342 |
|
| 343 |
def get_playlists_createdfor(self, username: str) -> JSONDict | None: |
| 344 |
"""Returns a list of playlists created by a user.""" |
| 345 |
url = f"{self.ROOT}/user/{username}/playlists/createdfor" |
| 346 |
return self._make_request(url) |
| 347 |
|
| 348 |
def get_listenbrainz_playlists(self) -> list[JSONDict]: |
| 349 |
resp = self.get_playlists_createdfor(self.username) |
| 350 |
if not resp: |
| 351 |
return [] |
| 352 |
playlists = resp.get("playlists", []) |
| 353 |
listenbrainz_playlists = [] |
| 354 |
|
| 355 |
for playlist in playlists: |
| 356 |
playlist_info = playlist.get("playlist") |
| 357 |
if playlist_info.get("creator") == "listenbrainz": |
| 358 |
title = playlist_info.get("title") |
| 359 |
self._log.debug("Playlist title: {}", title) |
| 360 |
playlist_type = ( |
| 361 |
"Exploration" if "Exploration" in title else "Jams" |
| 362 |
) |
| 363 |
if "week of" in title: |
| 364 |
date_str = title.split("week of ")[1].split(" ")[0] |
| 365 |
date = datetime.datetime.strptime( |
| 366 |
date_str, "%Y-%m-%d" |
| 367 |
).date() |
| 368 |
else: |
| 369 |
continue |
| 370 |
identifier = playlist_info.get("identifier") |
| 371 |
id_ = identifier.split("/")[-1] |
| 372 |
listenbrainz_playlists.append( |
| 373 |
{"type": playlist_type, "date": date, "identifier": id_} |
| 374 |
) |
| 375 |
listenbrainz_playlists = sorted( |
| 376 |
listenbrainz_playlists, key=lambda x: x["type"] |
| 377 |
) |
| 378 |
listenbrainz_playlists = sorted( |
| 379 |
listenbrainz_playlists, key=lambda x: x["date"], reverse=True |
| 380 |
) |
| 381 |
for playlist in listenbrainz_playlists: |
| 382 |
self._log.debug("Playlist: {0[type]} - {0[date]}", playlist) |
| 383 |
return listenbrainz_playlists |
| 384 |
|
| 385 |
def get_playlist(self, identifier: str) -> JSONDict | None: |
| 386 |
"""Returns a playlist.""" |
| 387 |
url = f"{self.ROOT}/playlist/{identifier}" |
| 388 |
return self._make_request(url) |
| 389 |
|
| 390 |
def get_tracks_from_playlist(self, playlist: JSONDict) -> list[JSONDict]: |
| 391 |
"""This function returns a list of tracks in the playlist.""" |
| 392 |
tracks = [] |
| 393 |
for track in playlist.get("playlist", {}).get("track"): |
| 394 |
identifier = track.get("identifier") |
| 395 |
if isinstance(identifier, list): |
| 396 |
identifier = identifier[0] |
| 397 |
|
| 398 |
tracks.append( |
| 399 |
{ |
| 400 |
"artist": track.get("creator", "Unknown artist"), |
| 401 |
"identifier": identifier.split("/")[-1], |
| 402 |
"title": track.get("title"), |
| 403 |
} |
| 404 |
) |
| 405 |
return self.get_track_info(tracks) |
| 406 |
|
| 407 |
def get_track_info(self, tracks: Iterable[JSONDict]) -> list[JSONDict]: |
| 408 |
track_info = [] |
| 409 |
for track in tracks: |
| 410 |
identifier = track["identifier"] |
| 411 |
recording = self.mb_api.get_base_recording_with_releases(identifier) |
| 412 |
title = recording.get("title") |
| 413 |
if artist_credit := next(iter(recording["artist_credit"]), None): |
| 414 |
artist = artist_credit.get("artist", {}).get("name") |
| 415 |
else: |
| 416 |
artist = None |
| 417 |
if release := next(iter(recording["releases"]), None): |
| 418 |
album = release["title"] |
| 419 |
date = release.get("date") |
| 420 |
year = date.split("-")[0] if date else None |
| 421 |
else: |
| 422 |
album = None |
| 423 |
year = None |
| 424 |
track_info.append( |
| 425 |
{ |
| 426 |
"identifier": identifier, |
| 427 |
"title": title, |
| 428 |
"artist": artist, |
| 429 |
"album": album, |
| 430 |
"year": year, |
| 431 |
} |
| 432 |
) |
| 433 |
return track_info |
| 434 |
|
| 435 |
def get_weekly_playlist( |
| 436 |
self, playlist_type: str, most_recent: bool = True |
| 437 |
) -> list[JSONDict]: |
| 438 |
# Fetch all playlists |
| 439 |
playlists = self.get_listenbrainz_playlists() |
| 440 |
# Filter playlists by type |
| 441 |
filtered_playlists = [ |
| 442 |
p for p in playlists if p["type"] == playlist_type |
| 443 |
] |
| 444 |
# Sort playlists by date in descending order |
| 445 |
sorted_playlists = sorted( |
| 446 |
filtered_playlists, key=lambda x: x["date"], reverse=True |
| 447 |
) |
| 448 |
# Select the most recent or older playlist based on the most_recent flag |
| 449 |
selected_playlist = ( |
| 450 |
sorted_playlists[0] if most_recent else sorted_playlists[1] |
| 451 |
) |
| 452 |
self._log.debug( |
| 453 |
f"Selected playlist: {selected_playlist['type']} " |
| 454 |
f"- {selected_playlist['date']}" |
| 455 |
) |
| 456 |
# Fetch and return tracks from the selected playlist |
| 457 |
if (identifier := selected_playlist.get("identifier")) and ( |
| 458 |
playlist := self.get_playlist(identifier) |
| 459 |
): |
| 460 |
return self.get_tracks_from_playlist(playlist) |
| 461 |
return [] |