| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import re |
| 4 |
from dataclasses import dataclass, field |
| 5 |
from functools import cached_property |
| 6 |
from typing import TYPE_CHECKING, ClassVar |
| 7 |
|
| 8 |
from requests.auth import HTTPDigestAuth |
| 9 |
|
| 10 |
from beets import __version__, config |
| 11 |
from beets.exceptions import UserError |
| 12 |
from beets.plugins import BeetsPlugin |
| 13 |
from beets.ui import Subcommand |
| 14 |
|
| 15 |
from ._utils.musicbrainz import MusicBrainzAPI |
| 16 |
from ._utils.requests import BeetsHTTPError |
| 17 |
|
| 18 |
if TYPE_CHECKING: |
| 19 |
import optparse |
| 20 |
from collections.abc import Iterable, Iterator |
| 21 |
|
| 22 |
from requests import Response |
| 23 |
|
| 24 |
from beets.importer import ImportSession, ImportTask |
| 25 |
from beets.library import Album, Library |
| 26 |
|
| 27 |
from ._typing import JSONDict |
| 28 |
|
| 29 |
UUID_PAT = re.compile(r"^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$") |
| 30 |
|
| 31 |
|
| 32 |
@dataclass |
| 33 |
class MusicBrainzUserAPI(MusicBrainzAPI): |
| 34 |
"""MusicBrainz API client with user authentication. |
| 35 |
|
| 36 |
In order to retrieve private user collections and modify them, we need to |
| 37 |
authenticate the requests with the user's MusicBrainz credentials. |
| 38 |
|
| 39 |
See documentation for authentication details: |
| 40 |
https://musicbrainz.org/doc/MusicBrainz_API#Authentication |
| 41 |
|
| 42 |
Note that the documentation misleadingly states HTTP 'basic' authentication, |
| 43 |
and I had to reverse-engineer musicbrainzngs to discover that it actually |
| 44 |
uses HTTP 'digest' authentication. |
| 45 |
""" |
| 46 |
|
| 47 |
auth: HTTPDigestAuth = field(init=False) |
| 48 |
|
| 49 |
def __post_init__(self) -> None: |
| 50 |
super().__post_init__() |
| 51 |
config["musicbrainz"]["pass"].redact = True |
| 52 |
self.auth = HTTPDigestAuth( |
| 53 |
config["musicbrainz"]["user"].as_str(), |
| 54 |
config["musicbrainz"]["pass"].as_str(), |
| 55 |
) |
| 56 |
|
| 57 |
def request(self, *args, **kwargs) -> Response: |
| 58 |
"""Authenticate and include required client param in all requests.""" |
| 59 |
kwargs.setdefault("params", {}) |
| 60 |
kwargs["params"]["client"] = f"beets-{__version__}" |
| 61 |
kwargs["auth"] = self.auth |
| 62 |
return super().request(*args, **kwargs) |
| 63 |
|
| 64 |
def browse_collections(self) -> list[JSONDict]: |
| 65 |
"""Get all collections for the authenticated user.""" |
| 66 |
return self._browse("collection") |
| 67 |
|
| 68 |
|
| 69 |
@dataclass |
| 70 |
class MBCollection: |
| 71 |
"""Representation of a user's MusicBrainz collection. |
| 72 |
|
| 73 |
Provides convenient, chunked operations for retrieving releases and updating |
| 74 |
the collection via the MusicBrainz web API. Fetch and submission limits are |
| 75 |
controlled by class-level constants to avoid oversized requests. |
| 76 |
""" |
| 77 |
|
| 78 |
SUBMISSION_CHUNK_SIZE: ClassVar[int] = 200 |
| 79 |
FETCH_CHUNK_SIZE: ClassVar[int] = 100 |
| 80 |
|
| 81 |
data: JSONDict |
| 82 |
mb_api: MusicBrainzUserAPI |
| 83 |
|
| 84 |
@property |
| 85 |
def id(self) -> str: |
| 86 |
"""Unique identifier assigned to the collection by MusicBrainz.""" |
| 87 |
return self.data["id"] |
| 88 |
|
| 89 |
@property |
| 90 |
def release_count(self) -> int: |
| 91 |
"""Total number of releases recorded in the collection.""" |
| 92 |
return self.data["release_count"] |
| 93 |
|
| 94 |
@property |
| 95 |
def releases_url(self) -> str: |
| 96 |
"""Complete API endpoint URL for listing releases in this collection.""" |
| 97 |
return f"{self.mb_api.api_root}/collection/{self.id}/releases" |
| 98 |
|
| 99 |
@property |
| 100 |
def releases(self) -> list[JSONDict]: |
| 101 |
"""Retrieve all releases in the collection, fetched in successive pages. |
| 102 |
|
| 103 |
The fetch is performed in chunks and returns a flattened sequence of |
| 104 |
release records. |
| 105 |
""" |
| 106 |
offsets = list(range(0, self.release_count, self.FETCH_CHUNK_SIZE)) |
| 107 |
return [r for offset in offsets for r in self.get_releases(offset)] |
| 108 |
|
| 109 |
def get_releases(self, offset: int) -> list[JSONDict]: |
| 110 |
"""Fetch a single page of releases beginning at a given position.""" |
| 111 |
return self.mb_api.get_json( |
| 112 |
self.releases_url, |
| 113 |
params={"limit": self.FETCH_CHUNK_SIZE, "offset": offset}, |
| 114 |
)["releases"] |
| 115 |
|
| 116 |
@classmethod |
| 117 |
def get_id_chunks(cls, id_list: list[str]) -> Iterator[list[str]]: |
| 118 |
"""Yield successive sublists of identifiers sized for safe submission. |
| 119 |
|
| 120 |
Splits a long sequence of identifiers into batches that respect the |
| 121 |
service's submission limits to avoid oversized requests. |
| 122 |
""" |
| 123 |
for i in range(0, len(id_list), cls.SUBMISSION_CHUNK_SIZE): |
| 124 |
yield id_list[i : i + cls.SUBMISSION_CHUNK_SIZE] |
| 125 |
|
| 126 |
def add_releases(self, releases: list[str]) -> None: |
| 127 |
"""Add releases to the collection in batches.""" |
| 128 |
for chunk in self.get_id_chunks(releases): |
| 129 |
# Need to escape semicolons: https://github.com/psf/requests/issues/6990 |
| 130 |
self.mb_api.put(f"{self.releases_url}/{'%3B'.join(chunk)}") |
| 131 |
|
| 132 |
def remove_releases(self, releases: list[str]) -> None: |
| 133 |
"""Remove releases from the collection in chunks.""" |
| 134 |
for chunk in self.get_id_chunks(releases): |
| 135 |
# Need to escape semicolons: https://github.com/psf/requests/issues/6990 |
| 136 |
self.mb_api.delete(f"{self.releases_url}/{'%3B'.join(chunk)}") |
| 137 |
|
| 138 |
|
| 139 |
class MusicBrainzCollectionPlugin(BeetsPlugin): |
| 140 |
def __init__(self) -> None: |
| 141 |
super().__init__() |
| 142 |
self.config.add({"auto": False, "collection": "", "remove": False}) |
| 143 |
if self.config["auto"]: |
| 144 |
self.import_stages = [self.imported] |
| 145 |
|
| 146 |
@cached_property |
| 147 |
def mb_api(self) -> MusicBrainzUserAPI: |
| 148 |
return MusicBrainzUserAPI() |
| 149 |
|
| 150 |
@cached_property |
| 151 |
def collection(self) -> MBCollection: |
| 152 |
if not (collections := self.mb_api.browse_collections()): |
| 153 |
raise UserError("no collections exist for user") |
| 154 |
|
| 155 |
# Get all release collection IDs, avoiding event collections |
| 156 |
if not ( |
| 157 |
collection_by_id := { |
| 158 |
c["id"]: c for c in collections if c["entity_type"] == "release" |
| 159 |
} |
| 160 |
): |
| 161 |
raise UserError("No release collection found.") |
| 162 |
|
| 163 |
# Check that the collection exists so we can present a nice error |
| 164 |
if collection_id := self.config["collection"].as_str(): |
| 165 |
if not (collection := collection_by_id.get(collection_id)): |
| 166 |
raise UserError(f"invalid collection ID: {collection_id}") |
| 167 |
else: |
| 168 |
# No specified collection. Just return the first collection ID |
| 169 |
collection = next(iter(collection_by_id.values())) |
| 170 |
|
| 171 |
return MBCollection(collection, self.mb_api) |
| 172 |
|
| 173 |
def commands(self) -> list[Subcommand]: |
| 174 |
mbupdate = Subcommand("mbupdate", help="Update MusicBrainz collection") |
| 175 |
mbupdate.parser.add_option( |
| 176 |
"-r", |
| 177 |
"--remove", |
| 178 |
action="store_true", |
| 179 |
default=None, |
| 180 |
dest="remove", |
| 181 |
help="Remove albums not in beets library", |
| 182 |
) |
| 183 |
mbupdate.func = self.update_collection |
| 184 |
return [mbupdate] |
| 185 |
|
| 186 |
def update_collection( |
| 187 |
self, lib: Library, opts: optparse.Values, args: list[str] |
| 188 |
) -> None: |
| 189 |
self.config.set_args(opts) |
| 190 |
remove_missing = self.config["remove"].get(bool) |
| 191 |
self.update_album_list(lib, lib.albums(), remove_missing) |
| 192 |
|
| 193 |
def imported(self, session: ImportSession, task: ImportTask) -> None: |
| 194 |
"""Add each imported album to the collection.""" |
| 195 |
if task.is_album: |
| 196 |
self.update_album_list( |
| 197 |
session.lib, [task.album], remove_missing=False |
| 198 |
) |
| 199 |
|
| 200 |
def update_album_list( |
| 201 |
self, lib: Library, albums: Iterable[Album], remove_missing: bool |
| 202 |
) -> None: |
| 203 |
"""Update the MusicBrainz collection from a list of Beets albums""" |
| 204 |
try: |
| 205 |
collection = self.collection |
| 206 |
|
| 207 |
# Get a list of all the album IDs. |
| 208 |
album_ids = [ |
| 209 |
id_ for a in albums if UUID_PAT.match(id_ := a.mb_albumid) |
| 210 |
] |
| 211 |
|
| 212 |
# Submit to MusicBrainz. |
| 213 |
self._log.info( |
| 214 |
"Updating MusicBrainz collection {}...", collection.id |
| 215 |
) |
| 216 |
collection.add_releases(album_ids) |
| 217 |
if remove_missing: |
| 218 |
lib_ids = {x.mb_albumid for x in lib.albums()} |
| 219 |
albums_in_collection = {r["id"] for r in collection.releases} |
| 220 |
collection.remove_releases(list(albums_in_collection - lib_ids)) |
| 221 |
|
| 222 |
self._log.info("...MusicBrainz collection updated.") |
| 223 |
except BeetsHTTPError as exc: |
| 224 |
self._log.error("Failed to update MusicBrainz collection: {}", exc) |