| 1 |
"""Fetches album art.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import os |
| 6 |
import re |
| 7 |
from abc import ABC, abstractmethod |
| 8 |
from collections import OrderedDict |
| 9 |
from contextlib import closing |
| 10 |
from enum import Enum |
| 11 |
from functools import cached_property |
| 12 |
from typing import TYPE_CHECKING, Any, AnyStr, ClassVar, Literal, Protocol |
| 13 |
|
| 14 |
import confuse |
| 15 |
import requests |
| 16 |
from mediafile import image_mime_type |
| 17 |
|
| 18 |
from beets import config, importer, plugins, ui, util |
| 19 |
from beets.exceptions import UserError |
| 20 |
from beets.util import bytestring_path, get_temp_filename, sorted_walk, syspath |
| 21 |
from beets.util.artresizer import ArtResizer |
| 22 |
from beets.util.color import colorize |
| 23 |
from beets.util.config import UnknownPairError, sanitize_pairs |
| 24 |
|
| 25 |
if TYPE_CHECKING: |
| 26 |
from collections.abc import Iterable, Iterator, Sequence |
| 27 |
|
| 28 |
from beets.importer import ImportSession, ImportTask |
| 29 |
from beets.library import Album, Library |
| 30 |
from beets.logging import BeetsLogger as Logger |
| 31 |
|
| 32 |
|
| 33 |
class FetchArtCLIOpts(Protocol): |
| 34 |
force: bool |
| 35 |
quiet: bool |
| 36 |
|
| 37 |
|
| 38 |
try: |
| 39 |
from bs4 import BeautifulSoup, Tag |
| 40 |
|
| 41 |
HAS_BEAUTIFUL_SOUP = True |
| 42 |
except ImportError: |
| 43 |
HAS_BEAUTIFUL_SOUP = False |
| 44 |
|
| 45 |
|
| 46 |
CONTENT_TYPES = { |
| 47 |
"image/jpeg": [b"jpg", b"jpeg"], |
| 48 |
"image/png": [b"png"], |
| 49 |
"image/webp": [b"webp"], |
| 50 |
} |
| 51 |
IMAGE_EXTENSIONS = [ext for exts in CONTENT_TYPES.values() for ext in exts] |
| 52 |
|
| 53 |
|
| 54 |
class ImageAction(Enum): |
| 55 |
"""Indicates whether an image is useable or requires post-processing.""" |
| 56 |
|
| 57 |
BAD = 0 |
| 58 |
EXACT = 1 |
| 59 |
DOWNSCALE = 2 |
| 60 |
DOWNSIZE = 3 |
| 61 |
DEINTERLACE = 4 |
| 62 |
REFORMAT = 5 |
| 63 |
|
| 64 |
|
| 65 |
class MetadataMatch(Enum): |
| 66 |
"""Indicates whether a `Candidate` matches the search criteria exactly.""" |
| 67 |
|
| 68 |
EXACT = 0 |
| 69 |
FALLBACK = 1 |
| 70 |
|
| 71 |
|
| 72 |
SourceLocation = Literal["local", "remote"] |
| 73 |
|
| 74 |
|
| 75 |
class Candidate: |
| 76 |
"""Holds information about a matching artwork, deals with validation of |
| 77 |
dimension restrictions and resizing. |
| 78 |
""" |
| 79 |
|
| 80 |
def __init__( |
| 81 |
self, |
| 82 |
log: Logger, |
| 83 |
source_name: str, |
| 84 |
path: bytes | None = None, |
| 85 |
url: str | None = None, |
| 86 |
match: MetadataMatch | None = None, |
| 87 |
size: tuple[int, int] | None = None, |
| 88 |
) -> None: |
| 89 |
self._log = log |
| 90 |
self.path = path |
| 91 |
self.url = url |
| 92 |
self.source_name = source_name |
| 93 |
self._check: ImageAction | None = None |
| 94 |
self.match = match |
| 95 |
self.size = size |
| 96 |
|
| 97 |
def _validate( |
| 98 |
self, |
| 99 |
plugin: FetchArtPlugin, |
| 100 |
skip_check_for: Sequence[ImageAction] | None = None, |
| 101 |
) -> ImageAction: |
| 102 |
"""Determine whether the candidate artwork is valid based on |
| 103 |
its dimensions (width and ratio). |
| 104 |
|
| 105 |
`skip_check_for` is a check or list of checks to skip. This is used to |
| 106 |
avoid redundant checks when the candidate has already been |
| 107 |
validated for a particular operation without changing |
| 108 |
plugin configuration. |
| 109 |
|
| 110 |
Return `ImageAction.BAD` if the file is unusable. |
| 111 |
Return `ImageAction.EXACT` if the file is usable as-is. |
| 112 |
Return `ImageAction.DOWNSCALE` if the file must be rescaled. |
| 113 |
Return `ImageAction.DOWNSIZE` if the file must be resized, and possibly |
| 114 |
also rescaled. |
| 115 |
Return `ImageAction.DEINTERLACE` if the file must be deinterlaced. |
| 116 |
Return `ImageAction.REFORMAT` if the file has to be converted. |
| 117 |
""" |
| 118 |
if not self.path: |
| 119 |
return ImageAction.BAD |
| 120 |
|
| 121 |
if not ( |
| 122 |
plugin.enforce_ratio |
| 123 |
or plugin.minwidth |
| 124 |
or plugin.maxwidth |
| 125 |
or plugin.max_filesize |
| 126 |
or plugin.deinterlace |
| 127 |
or plugin.cover_format |
| 128 |
): |
| 129 |
return ImageAction.EXACT |
| 130 |
|
| 131 |
# get_size returns None if no local imaging backend is available |
| 132 |
if not self.size: |
| 133 |
self.size = ArtResizer.shared.get_size(self.path) |
| 134 |
self._log.debug("image size: {.size}", self) |
| 135 |
|
| 136 |
if not self.size: |
| 137 |
self._log.warning( |
| 138 |
"Could not get size of image (please see " |
| 139 |
"documentation for dependencies). " |
| 140 |
"The configuration options `minwidth`, " |
| 141 |
"`enforce_ratio` and `max_filesize` " |
| 142 |
"may be violated." |
| 143 |
) |
| 144 |
return ImageAction.EXACT |
| 145 |
|
| 146 |
short_edge = min(self.size) |
| 147 |
long_edge = max(self.size) |
| 148 |
|
| 149 |
# Check minimum dimension. |
| 150 |
if plugin.minwidth and self.size[0] < plugin.minwidth: |
| 151 |
self._log.debug( |
| 152 |
"image too small ({} < {.minwidth})", self.size[0], plugin |
| 153 |
) |
| 154 |
return ImageAction.BAD |
| 155 |
|
| 156 |
# Check aspect ratio. |
| 157 |
edge_diff = long_edge - short_edge |
| 158 |
if plugin.enforce_ratio: |
| 159 |
if plugin.margin_px: |
| 160 |
if edge_diff > plugin.margin_px: |
| 161 |
self._log.debug( |
| 162 |
"image is not close enough to being " |
| 163 |
"square, ({} - {} > {.margin_px})", |
| 164 |
long_edge, |
| 165 |
short_edge, |
| 166 |
plugin, |
| 167 |
) |
| 168 |
return ImageAction.BAD |
| 169 |
elif plugin.margin_percent: |
| 170 |
margin_px = plugin.margin_percent * long_edge |
| 171 |
if edge_diff > margin_px: |
| 172 |
self._log.debug( |
| 173 |
"image is not close enough to being " |
| 174 |
"square, ({} - {} > {})", |
| 175 |
long_edge, |
| 176 |
short_edge, |
| 177 |
margin_px, |
| 178 |
) |
| 179 |
return ImageAction.BAD |
| 180 |
elif edge_diff: |
| 181 |
# also reached for margin_px == 0 and margin_percent == 0.0 |
| 182 |
self._log.debug( |
| 183 |
"image is not square ({} != {})", self.size[0], self.size[1] |
| 184 |
) |
| 185 |
return ImageAction.BAD |
| 186 |
|
| 187 |
# Check maximum dimension. |
| 188 |
downscale = False |
| 189 |
if plugin.maxwidth and self.size[0] > plugin.maxwidth: |
| 190 |
self._log.debug( |
| 191 |
"image needs rescaling ({} > {.maxwidth})", self.size[0], plugin |
| 192 |
) |
| 193 |
downscale = True |
| 194 |
|
| 195 |
# Check filesize. |
| 196 |
downsize = False |
| 197 |
if plugin.max_filesize: |
| 198 |
filesize = os.stat(syspath(self.path)).st_size |
| 199 |
if filesize > plugin.max_filesize: |
| 200 |
self._log.debug( |
| 201 |
"image needs resizing ({}B > {.max_filesize}B)", |
| 202 |
filesize, |
| 203 |
plugin, |
| 204 |
) |
| 205 |
downsize = True |
| 206 |
|
| 207 |
# Check image format |
| 208 |
reformat = False |
| 209 |
if plugin.cover_format: |
| 210 |
fmt = ArtResizer.shared.get_format(self.path) |
| 211 |
reformat = fmt != plugin.cover_format |
| 212 |
if reformat: |
| 213 |
self._log.debug( |
| 214 |
"image needs reformatting: {} -> {.cover_format}", |
| 215 |
fmt, |
| 216 |
plugin, |
| 217 |
) |
| 218 |
|
| 219 |
skip_check_for = skip_check_for or [] |
| 220 |
|
| 221 |
if downscale and (ImageAction.DOWNSCALE not in skip_check_for): |
| 222 |
return ImageAction.DOWNSCALE |
| 223 |
if reformat and (ImageAction.REFORMAT not in skip_check_for): |
| 224 |
return ImageAction.REFORMAT |
| 225 |
if plugin.deinterlace and ( |
| 226 |
ImageAction.DEINTERLACE not in skip_check_for |
| 227 |
): |
| 228 |
return ImageAction.DEINTERLACE |
| 229 |
if downsize and (ImageAction.DOWNSIZE not in skip_check_for): |
| 230 |
return ImageAction.DOWNSIZE |
| 231 |
return ImageAction.EXACT |
| 232 |
|
| 233 |
def validate( |
| 234 |
self, |
| 235 |
plugin: FetchArtPlugin, |
| 236 |
skip_check_for: Sequence[ImageAction] | None = None, |
| 237 |
) -> ImageAction: |
| 238 |
self._check = self._validate(plugin, skip_check_for) |
| 239 |
return self._check |
| 240 |
|
| 241 |
def resize(self, plugin: FetchArtPlugin) -> None: |
| 242 |
"""Resize the candidate artwork according to the plugin's |
| 243 |
configuration until it is valid or no further resizing is |
| 244 |
possible. |
| 245 |
""" |
| 246 |
# validate the candidate in case it hasn't been done yet |
| 247 |
current_check = self.validate(plugin) |
| 248 |
checks_performed = [] |
| 249 |
|
| 250 |
# we don't want to resize the image if it's valid or bad |
| 251 |
while current_check not in [ImageAction.BAD, ImageAction.EXACT]: |
| 252 |
self._resize(plugin, current_check) |
| 253 |
checks_performed.append(current_check) |
| 254 |
current_check = self.validate( |
| 255 |
plugin, skip_check_for=checks_performed |
| 256 |
) |
| 257 |
|
| 258 |
def _resize( |
| 259 |
self, plugin: FetchArtPlugin, check: ImageAction | None = None |
| 260 |
) -> None: |
| 261 |
"""Resize the candidate artwork according to the plugin's |
| 262 |
configuration and the specified check. |
| 263 |
""" |
| 264 |
# This must only be called when _validate returned something other than |
| 265 |
# ImageAction.Bad or ImageAction.EXACT; then path and size are known. |
| 266 |
assert self.path is not None |
| 267 |
assert self.size is not None |
| 268 |
|
| 269 |
if check == ImageAction.DOWNSCALE: |
| 270 |
self.path = ArtResizer.shared.resize( |
| 271 |
plugin.maxwidth, |
| 272 |
self.path, |
| 273 |
quality=plugin.quality, |
| 274 |
max_filesize=plugin.max_filesize, |
| 275 |
) |
| 276 |
elif check == ImageAction.DOWNSIZE: |
| 277 |
# dimensions are correct, so maxwidth is set to maximum dimension |
| 278 |
self.path = ArtResizer.shared.resize( |
| 279 |
max(self.size), |
| 280 |
self.path, |
| 281 |
quality=plugin.quality, |
| 282 |
max_filesize=plugin.max_filesize, |
| 283 |
) |
| 284 |
elif check == ImageAction.DEINTERLACE: |
| 285 |
self.path = ArtResizer.shared.deinterlace(self.path) |
| 286 |
elif check == ImageAction.REFORMAT: |
| 287 |
self.path = ArtResizer.shared.reformat( |
| 288 |
self.path, |
| 289 |
# TODO: fix this gnarly logic to remove the need for type ignore |
| 290 |
plugin.cover_format, # type: ignore[arg-type] |
| 291 |
deinterlaced=plugin.deinterlace, |
| 292 |
) |
| 293 |
|
| 294 |
|
| 295 |
def _logged_get(log: Logger, *args, **kwargs) -> requests.Response: |
| 296 |
"""Like `requests.get`, but logs the effective URL to the specified |
| 297 |
`log` at the `DEBUG` level. |
| 298 |
|
| 299 |
Use the optional `message` parameter to specify what to log before |
| 300 |
the URL. By default, the string is "getting URL". |
| 301 |
|
| 302 |
Also sets the User-Agent header to indicate beets. |
| 303 |
""" |
| 304 |
# Use some arguments with the `send` call but most with the |
| 305 |
# `Request` construction. This is a cheap, magic-filled way to |
| 306 |
# emulate `requests.get` or, more pertinently, |
| 307 |
# `requests.Session.request`. |
| 308 |
req_kwargs = kwargs |
| 309 |
send_kwargs = {} |
| 310 |
for arg in ("stream", "verify", "proxies", "cert", "timeout"): |
| 311 |
if arg in kwargs: |
| 312 |
send_kwargs[arg] = req_kwargs.pop(arg) |
| 313 |
if "timeout" not in send_kwargs: |
| 314 |
send_kwargs["timeout"] = 10 |
| 315 |
|
| 316 |
# Our special logging message parameter. |
| 317 |
if "message" in kwargs: |
| 318 |
message = kwargs.pop("message") |
| 319 |
else: |
| 320 |
message = "getting URL" |
| 321 |
|
| 322 |
req = requests.Request("GET", *args, **req_kwargs) |
| 323 |
|
| 324 |
with requests.Session() as s: |
| 325 |
s.headers = {"User-Agent": "beets"} |
| 326 |
prepped = s.prepare_request(req) |
| 327 |
settings = s.merge_environment_settings( |
| 328 |
prepped.url, {}, None, None, None |
| 329 |
) |
| 330 |
log.debug("{}: {.url}", message, prepped) |
| 331 |
merged_kwargs: dict[Any, Any] = {**send_kwargs, **settings} |
| 332 |
return s.send(prepped, **merged_kwargs) |
| 333 |
|
| 334 |
|
| 335 |
class RequestMixin: |
| 336 |
"""Adds a Requests wrapper to the class that uses the logger, which |
| 337 |
must be named `self._log`. |
| 338 |
""" |
| 339 |
|
| 340 |
_log: Logger |
| 341 |
|
| 342 |
def request(self, *args, **kwargs) -> requests.Response: |
| 343 |
"""Like `requests.get`, but uses the logger `self._log`. |
| 344 |
|
| 345 |
See also `_logged_get`. |
| 346 |
""" |
| 347 |
return _logged_get(self._log, *args, **kwargs) |
| 348 |
|
| 349 |
|
| 350 |
# ART SOURCES ################################################################ |
| 351 |
|
| 352 |
|
| 353 |
class ArtSource(RequestMixin, ABC): |
| 354 |
# Specify whether this source fetches local or remote images |
| 355 |
LOC: ClassVar[SourceLocation] |
| 356 |
# A list of methods to match metadata, sorted by descending accuracy |
| 357 |
VALID_MATCHING_CRITERIA: ClassVar[list[str]] = ["default"] |
| 358 |
# A human-readable name for the art source |
| 359 |
NAME: ClassVar[str] |
| 360 |
# The key to select the art source in the config. This value will also be |
| 361 |
# stored in the database. |
| 362 |
ID: ClassVar[str] |
| 363 |
|
| 364 |
def __init__( |
| 365 |
self, |
| 366 |
log: Logger, |
| 367 |
config: confuse.ConfigView, |
| 368 |
match_by: list[str] | None = None, |
| 369 |
) -> None: |
| 370 |
self._log = log |
| 371 |
self._config = config |
| 372 |
self.match_by = match_by or self.VALID_MATCHING_CRITERIA |
| 373 |
|
| 374 |
@cached_property |
| 375 |
def description(self) -> str: |
| 376 |
return f"{self.ID}[{', '.join(self.match_by)}]" |
| 377 |
|
| 378 |
@staticmethod |
| 379 |
def add_default_config(config: confuse.ConfigView) -> None: |
| 380 |
pass |
| 381 |
|
| 382 |
@classmethod |
| 383 |
def available(cls, log: Logger, config: confuse.ConfigView) -> bool: |
| 384 |
"""Return whether or not all dependencies are met and the art source is |
| 385 |
in fact usable. |
| 386 |
""" |
| 387 |
return True |
| 388 |
|
| 389 |
@abstractmethod |
| 390 |
def get( |
| 391 |
self, |
| 392 |
album: Album, |
| 393 |
plugin: FetchArtPlugin, |
| 394 |
paths: Sequence[bytes] | None, |
| 395 |
) -> Iterator[Candidate]: |
| 396 |
pass |
| 397 |
|
| 398 |
def _candidate(self, **kwargs) -> Candidate: |
| 399 |
return Candidate(source_name=self.ID, log=self._log, **kwargs) |
| 400 |
|
| 401 |
@abstractmethod |
| 402 |
def fetch_image(self, candidate: Candidate, plugin: FetchArtPlugin) -> None: |
| 403 |
"""Fetch the image to a temporary file if it is not already available |
| 404 |
as a local file. |
| 405 |
|
| 406 |
After calling this, `Candidate.path` is set to the image path if |
| 407 |
successful, or to `None` otherwise. |
| 408 |
""" |
| 409 |
|
| 410 |
def cleanup(self, candidate: Candidate) -> None: |
| 411 |
pass |
| 412 |
|
| 413 |
|
| 414 |
class LocalArtSource(ArtSource): |
| 415 |
LOC = "local" |
| 416 |
|
| 417 |
def fetch_image(self, candidate: Candidate, plugin: FetchArtPlugin) -> None: |
| 418 |
pass |
| 419 |
|
| 420 |
|
| 421 |
class RemoteArtSource(ArtSource): |
| 422 |
LOC = "remote" |
| 423 |
|
| 424 |
def fetch_image(self, candidate: Candidate, plugin: FetchArtPlugin) -> None: |
| 425 |
"""Downloads an image from a URL and checks whether it seems to |
| 426 |
actually be an image. |
| 427 |
""" |
| 428 |
# This must only be called for candidates that were returned by |
| 429 |
# self.get, which are expected to have a url and no path (because they |
| 430 |
# haven't been downloaded yet). |
| 431 |
assert candidate.path is None |
| 432 |
assert candidate.url is not None |
| 433 |
|
| 434 |
if plugin.maxwidth: |
| 435 |
candidate.url = ArtResizer.shared.proxy_url( |
| 436 |
plugin.maxwidth, candidate.url |
| 437 |
) |
| 438 |
try: |
| 439 |
with closing( |
| 440 |
self.request( |
| 441 |
candidate.url, stream=True, message="downloading image" |
| 442 |
) |
| 443 |
) as resp: |
| 444 |
ct = resp.headers.get("Content-Type", None) |
| 445 |
|
| 446 |
# Download the image to a temporary file. As some servers |
| 447 |
# (notably fanart.tv) have proven to return wrong Content-Types |
| 448 |
# when images were uploaded with a bad file extension, do not |
| 449 |
# rely on it. Instead validate the type using the file magic |
| 450 |
# and only then determine the extension. |
| 451 |
data = resp.iter_content(chunk_size=1024) |
| 452 |
header = b"" |
| 453 |
for chunk in data: |
| 454 |
header += chunk |
| 455 |
if len(header) >= 32: |
| 456 |
# The imghdr module will only read 32 bytes, and our |
| 457 |
# own additions in mediafile even less. |
| 458 |
break |
| 459 |
else: |
| 460 |
# server didn't return enough data, i.e. corrupt image |
| 461 |
return |
| 462 |
|
| 463 |
real_ct = image_mime_type(header) |
| 464 |
if real_ct is None: |
| 465 |
# detection by file magic failed, fall back to the |
| 466 |
# server-supplied Content-Type |
| 467 |
# Is our type detection failsafe enough to drop this? |
| 468 |
real_ct = ct |
| 469 |
|
| 470 |
if real_ct not in CONTENT_TYPES: |
| 471 |
self._log.debug( |
| 472 |
"not a supported image: {}", |
| 473 |
real_ct or "unknown content type", |
| 474 |
) |
| 475 |
return |
| 476 |
|
| 477 |
ext = b"." + CONTENT_TYPES[real_ct][0] |
| 478 |
|
| 479 |
if real_ct != ct: |
| 480 |
self._log.warning( |
| 481 |
"Server specified {}, but returned a " |
| 482 |
"{} image. Correcting the extension " |
| 483 |
"to {}", |
| 484 |
ct, |
| 485 |
real_ct, |
| 486 |
ext, |
| 487 |
) |
| 488 |
|
| 489 |
filename = get_temp_filename(__name__, suffix=ext.decode()) |
| 490 |
with open(filename, "wb") as fh: |
| 491 |
# write the first already loaded part of the image |
| 492 |
fh.write(header) |
| 493 |
# download the remaining part of the image |
| 494 |
for chunk in data: |
| 495 |
fh.write(chunk) |
| 496 |
self._log.debug( |
| 497 |
"downloaded art to: {}", util.displayable_path(filename) |
| 498 |
) |
| 499 |
candidate.path = util.bytestring_path(filename) |
| 500 |
return |
| 501 |
|
| 502 |
except (OSError, requests.RequestException, TypeError) as exc: |
| 503 |
# Handling TypeError works around a urllib3 bug: |
| 504 |
# https://github.com/shazow/urllib3/issues/556 |
| 505 |
self._log.debug("error fetching art: {}", exc) |
| 506 |
return |
| 507 |
|
| 508 |
def cleanup(self, candidate: Candidate) -> None: |
| 509 |
if candidate.path: |
| 510 |
try: |
| 511 |
util.remove(path=candidate.path) |
| 512 |
except util.FilesystemError as exc: |
| 513 |
self._log.debug("error cleaning up tmp art: {}", exc) |
| 514 |
|
| 515 |
|
| 516 |
class CoverArtArchive(RemoteArtSource): |
| 517 |
NAME = "Cover Art Archive" |
| 518 |
ID = "coverart" |
| 519 |
VALID_MATCHING_CRITERIA: ClassVar[list[str]] = ["release", "releasegroup"] |
| 520 |
VALID_THUMBNAIL_SIZES: ClassVar[list[int]] = [250, 500, 1200] |
| 521 |
LEGACY_THUMBNAIL_NAMES: ClassVar[dict[str, str]] = { |
| 522 |
"250": "small", |
| 523 |
"500": "large", |
| 524 |
} |
| 525 |
|
| 526 |
URL = "https://coverartarchive.org/release/{mbid}" |
| 527 |
GROUP_URL = "https://coverartarchive.org/release-group/{mbid}" |
| 528 |
|
| 529 |
def get( |
| 530 |
self, |
| 531 |
album: Album, |
| 532 |
plugin: FetchArtPlugin, |
| 533 |
paths: Sequence[bytes] | None, |
| 534 |
) -> Iterator[Candidate]: |
| 535 |
"""Return the Cover Art Archive and Cover Art Archive release |
| 536 |
group URLs using album MusicBrainz release ID and release group |
| 537 |
ID. |
| 538 |
""" |
| 539 |
|
| 540 |
def get_image_urls( |
| 541 |
url: str, preferred_width: str | None = None |
| 542 |
) -> Iterator[str]: |
| 543 |
try: |
| 544 |
response = self.request(url) |
| 545 |
except requests.RequestException: |
| 546 |
self._log.debug("{.NAME}: error receiving response", self) |
| 547 |
return |
| 548 |
|
| 549 |
try: |
| 550 |
data = response.json() |
| 551 |
except ValueError: |
| 552 |
self._log.debug( |
| 553 |
"{.NAME}: error loading response: {.text}", self, response |
| 554 |
) |
| 555 |
return |
| 556 |
|
| 557 |
for item in data.get("images", []): |
| 558 |
try: |
| 559 |
if "Front" not in item["types"]: |
| 560 |
continue |
| 561 |
|
| 562 |
# If there is a pre-sized thumbnail of the desired size |
| 563 |
# we select it. Otherwise, we return the raw image. |
| 564 |
image_url: str = item["image"] |
| 565 |
if preferred_width is not None: |
| 566 |
if isinstance(item.get("thumbnails"), dict): |
| 567 |
image_url = item["thumbnails"].get( |
| 568 |
preferred_width, |
| 569 |
item["thumbnails"].get( |
| 570 |
self.LEGACY_THUMBNAIL_NAMES.get( |
| 571 |
preferred_width |
| 572 |
), |
| 573 |
image_url, |
| 574 |
), |
| 575 |
) |
| 576 |
yield image_url |
| 577 |
except KeyError: |
| 578 |
pass |
| 579 |
|
| 580 |
release_url = self.URL.format(mbid=album.mb_albumid) |
| 581 |
release_group_url = self.GROUP_URL.format(mbid=album.mb_releasegroupid) |
| 582 |
|
| 583 |
# Cover Art Archive API offers pre-resized thumbnails at several sizes. |
| 584 |
# If the maxwidth config matches one of the already available sizes |
| 585 |
# fetch it directly instead of fetching the full sized image and |
| 586 |
# resizing it. |
| 587 |
preferred_width = None |
| 588 |
if plugin.maxwidth in self.VALID_THUMBNAIL_SIZES: |
| 589 |
preferred_width = str(plugin.maxwidth) |
| 590 |
|
| 591 |
if "release" in self.match_by and album.mb_albumid: |
| 592 |
for url in get_image_urls(release_url, preferred_width): |
| 593 |
yield self._candidate(url=url, match=MetadataMatch.EXACT) |
| 594 |
|
| 595 |
if "releasegroup" in self.match_by and album.mb_releasegroupid: |
| 596 |
for url in get_image_urls(release_group_url, preferred_width): |
| 597 |
yield self._candidate(url=url, match=MetadataMatch.FALLBACK) |
| 598 |
|
| 599 |
|
| 600 |
class Amazon(RemoteArtSource): |
| 601 |
NAME = "Amazon" |
| 602 |
ID = "amazon" |
| 603 |
URL = "https://images.amazon.com/images/P/{}.{:02d}.LZZZZZZZ.jpg" |
| 604 |
INDICES = (1, 2) |
| 605 |
|
| 606 |
def get( |
| 607 |
self, |
| 608 |
album: Album, |
| 609 |
plugin: FetchArtPlugin, |
| 610 |
paths: Sequence[bytes] | None, |
| 611 |
) -> Iterator[Candidate]: |
| 612 |
"""Generate URLs using Amazon ID (ASIN) string.""" |
| 613 |
if album.asin: |
| 614 |
for index in self.INDICES: |
| 615 |
yield self._candidate( |
| 616 |
url=self.URL.format(album.asin, index), |
| 617 |
match=MetadataMatch.EXACT, |
| 618 |
) |
| 619 |
|
| 620 |
|
| 621 |
class AlbumArtOrg(RemoteArtSource): |
| 622 |
NAME = "AlbumArt.org scraper" |
| 623 |
ID = "albumart" |
| 624 |
URL = "https://www.albumart.org/index_detail.php" |
| 625 |
PAT = r'href\s*=\s*"([^>"]*)"[^>]*title\s*=\s*"View larger image"' |
| 626 |
|
| 627 |
def get( |
| 628 |
self, |
| 629 |
album: Album, |
| 630 |
plugin: FetchArtPlugin, |
| 631 |
paths: Sequence[bytes] | None, |
| 632 |
) -> Iterator[Any]: |
| 633 |
"""Return art URL from AlbumArt.org using album ASIN.""" |
| 634 |
if not album.asin: |
| 635 |
return |
| 636 |
# Get the page from albumart.org. |
| 637 |
try: |
| 638 |
resp = self.request(self.URL, params={"asin": album.asin}) |
| 639 |
self._log.debug("scraped art URL: {.url}", resp) |
| 640 |
except requests.RequestException: |
| 641 |
self._log.debug("error scraping art page") |
| 642 |
return |
| 643 |
|
| 644 |
# Search the page for the image URL. |
| 645 |
m = re.search(self.PAT, resp.text) |
| 646 |
if m: |
| 647 |
image_url = m.group(1) |
| 648 |
yield self._candidate(url=image_url, match=MetadataMatch.EXACT) |
| 649 |
else: |
| 650 |
self._log.debug("no image found on page") |
| 651 |
|
| 652 |
|
| 653 |
class GoogleImages(RemoteArtSource): |
| 654 |
NAME = "Google Images" |
| 655 |
ID = "google" |
| 656 |
URL = "https://www.googleapis.com/customsearch/v1" |
| 657 |
|
| 658 |
def __init__(self, *args, **kwargs) -> None: |
| 659 |
super().__init__(*args, **kwargs) |
| 660 |
self.key = (self._config["google_key"].get(),) |
| 661 |
self.cx = (self._config["google_engine"].get(),) |
| 662 |
|
| 663 |
@staticmethod |
| 664 |
def add_default_config(config: confuse.ConfigView) -> None: |
| 665 |
config.add( |
| 666 |
{ |
| 667 |
"google_key": None, |
| 668 |
"google_engine": "001442825323518660753:hrh5ch1gjzm", |
| 669 |
} |
| 670 |
) |
| 671 |
config["google_key"].redact = True |
| 672 |
config["google_engine"].redact = True |
| 673 |
|
| 674 |
@classmethod |
| 675 |
def available(cls, log: Logger, config: confuse.ConfigView) -> bool: |
| 676 |
has_key = bool(config["google_key"].get()) |
| 677 |
if not has_key: |
| 678 |
log.debug("google: Disabling art source due to missing key") |
| 679 |
return has_key |
| 680 |
|
| 681 |
def get( |
| 682 |
self, |
| 683 |
album: Album, |
| 684 |
plugin: FetchArtPlugin, |
| 685 |
paths: Sequence[bytes] | None, |
| 686 |
) -> Iterator[Candidate]: |
| 687 |
"""Return art URL from google custom search engine |
| 688 |
given an album title and interpreter. |
| 689 |
""" |
| 690 |
if not (album.albumartist and album.album): |
| 691 |
return |
| 692 |
search_string = f"{album.albumartist},{album.album}".encode() |
| 693 |
|
| 694 |
try: |
| 695 |
response = self.request( |
| 696 |
self.URL, |
| 697 |
params={ |
| 698 |
"key": self.key, |
| 699 |
"cx": self.cx, |
| 700 |
"q": search_string, |
| 701 |
"searchType": "image", |
| 702 |
}, |
| 703 |
) |
| 704 |
except requests.RequestException: |
| 705 |
self._log.debug("google: error receiving response") |
| 706 |
return |
| 707 |
|
| 708 |
# Get results using JSON. |
| 709 |
try: |
| 710 |
data = response.json() |
| 711 |
except ValueError: |
| 712 |
self._log.debug("google: error loading response: {.text}", response) |
| 713 |
return |
| 714 |
|
| 715 |
if "error" in data: |
| 716 |
reason = data["error"]["errors"][0]["reason"] |
| 717 |
self._log.debug("google fetchart error: {}", reason) |
| 718 |
return |
| 719 |
|
| 720 |
if "items" in data.keys(): |
| 721 |
for item in data["items"]: |
| 722 |
yield self._candidate( |
| 723 |
url=item["link"], match=MetadataMatch.EXACT |
| 724 |
) |
| 725 |
|
| 726 |
|
| 727 |
class FanartTV(RemoteArtSource): |
| 728 |
"""Art from fanart.tv requested using their API""" |
| 729 |
|
| 730 |
NAME = "fanart.tv" |
| 731 |
ID = "fanarttv" |
| 732 |
API_URL = "https://webservice.fanart.tv/v3/" |
| 733 |
API_ALBUMS = f"{API_URL}music/albums/" |
| 734 |
PROJECT_KEY = "61a7d0ab4e67162b7a0c7c35915cd48e" |
| 735 |
|
| 736 |
def __init__(self, *args, **kwargs) -> None: |
| 737 |
super().__init__(*args, **kwargs) |
| 738 |
self.client_key = self._config["fanarttv_key"].get() |
| 739 |
|
| 740 |
@staticmethod |
| 741 |
def add_default_config(config: confuse.ConfigView) -> None: |
| 742 |
config.add({"fanarttv_key": None}) |
| 743 |
config["fanarttv_key"].redact = True |
| 744 |
|
| 745 |
def get( |
| 746 |
self, |
| 747 |
album: Album, |
| 748 |
plugin: FetchArtPlugin, |
| 749 |
paths: Sequence[bytes] | None, |
| 750 |
) -> Iterator[Candidate]: |
| 751 |
if not album.mb_releasegroupid: |
| 752 |
return |
| 753 |
|
| 754 |
try: |
| 755 |
response = self.request( |
| 756 |
f"{self.API_ALBUMS}{album.mb_releasegroupid}", |
| 757 |
headers={ |
| 758 |
"api-key": self.PROJECT_KEY, |
| 759 |
"client-key": self.client_key, |
| 760 |
}, |
| 761 |
) |
| 762 |
except requests.RequestException: |
| 763 |
self._log.debug("fanart.tv: error receiving response") |
| 764 |
return |
| 765 |
|
| 766 |
try: |
| 767 |
data = response.json() |
| 768 |
except ValueError: |
| 769 |
self._log.debug( |
| 770 |
"fanart.tv: error loading response: {.text}", response |
| 771 |
) |
| 772 |
return |
| 773 |
|
| 774 |
if "status" in data and data["status"] == "error": |
| 775 |
if "not found" in data["error message"].lower(): |
| 776 |
self._log.debug("fanart.tv: no image found") |
| 777 |
elif "api key" in data["error message"].lower(): |
| 778 |
self._log.warning( |
| 779 |
"fanart.tv: Invalid API key given, please " |
| 780 |
"enter a valid one in your config file." |
| 781 |
) |
| 782 |
else: |
| 783 |
self._log.debug( |
| 784 |
"fanart.tv: error on request: {}", data["error message"] |
| 785 |
) |
| 786 |
return |
| 787 |
|
| 788 |
matches = [] |
| 789 |
# can there be more than one releasegroupid per response? |
| 790 |
for mbid, art in data.get("albums", {}).items(): |
| 791 |
# there might be more art referenced, e.g. cdart, and an albumcover |
| 792 |
# might not be present, even if the request was successful |
| 793 |
if album.mb_releasegroupid == mbid and "albumcover" in art: |
| 794 |
matches.extend(art["albumcover"]) |
| 795 |
# can this actually occur? |
| 796 |
else: |
| 797 |
self._log.debug( |
| 798 |
"fanart.tv: unexpected mb_releasegroupid in response!" |
| 799 |
) |
| 800 |
|
| 801 |
matches.sort(key=lambda x: int(x["likes"]), reverse=True) |
| 802 |
for item in matches: |
| 803 |
# fanart.tv has a strict size requirement for album art to be |
| 804 |
# uploaded |
| 805 |
yield self._candidate( |
| 806 |
url=item["url"], match=MetadataMatch.EXACT, size=(1000, 1000) |
| 807 |
) |
| 808 |
|
| 809 |
|
| 810 |
class ITunesStore(RemoteArtSource): |
| 811 |
NAME = "iTunes Store" |
| 812 |
ID = "itunes" |
| 813 |
API_URL = "https://itunes.apple.com/search" |
| 814 |
|
| 815 |
def get( |
| 816 |
self, |
| 817 |
album: Album, |
| 818 |
plugin: FetchArtPlugin, |
| 819 |
paths: Sequence[bytes] | None, |
| 820 |
) -> Iterator[Candidate]: |
| 821 |
"""Return art URL from iTunes Store given an album title.""" |
| 822 |
if not (album.albumartist and album.album): |
| 823 |
return |
| 824 |
|
| 825 |
payload = { |
| 826 |
"term": f"{album.albumartist} {album.album}", |
| 827 |
"entity": "album", |
| 828 |
"media": "music", |
| 829 |
"limit": 200, |
| 830 |
} |
| 831 |
try: |
| 832 |
r = self.request(self.API_URL, params=payload) |
| 833 |
r.raise_for_status() |
| 834 |
except requests.RequestException as e: |
| 835 |
self._log.debug("iTunes search failed: {}", e) |
| 836 |
return |
| 837 |
|
| 838 |
try: |
| 839 |
candidates = r.json()["results"] |
| 840 |
except ValueError as e: |
| 841 |
self._log.debug("Could not decode json response: {}", e) |
| 842 |
return |
| 843 |
except KeyError as e: |
| 844 |
self._log.debug( |
| 845 |
"{} not found in json. Fields are {} ", e, list(r.json().keys()) |
| 846 |
) |
| 847 |
return |
| 848 |
|
| 849 |
if not candidates: |
| 850 |
self._log.debug( |
| 851 |
"iTunes search for {!r} got no results", payload["term"] |
| 852 |
) |
| 853 |
return |
| 854 |
|
| 855 |
if self._config["high_resolution"]: |
| 856 |
image_suffix = "100000x100000-999" |
| 857 |
else: |
| 858 |
image_suffix = "1200x1200bb" |
| 859 |
|
| 860 |
for c in candidates: |
| 861 |
try: |
| 862 |
if ( |
| 863 |
c["artistName"] == album.albumartist |
| 864 |
and c["collectionName"] == album.album |
| 865 |
): |
| 866 |
art_url = c["artworkUrl100"] |
| 867 |
art_url = art_url.replace("100x100bb", image_suffix) |
| 868 |
yield self._candidate( |
| 869 |
url=art_url, match=MetadataMatch.EXACT |
| 870 |
) |
| 871 |
except KeyError as e: |
| 872 |
self._log.debug( |
| 873 |
"Malformed itunes candidate: {} not found in {}", |
| 874 |
e, |
| 875 |
list(c.keys()), |
| 876 |
) |
| 877 |
|
| 878 |
try: |
| 879 |
fallback_art_url = candidates[0]["artworkUrl100"] |
| 880 |
fallback_art_url = fallback_art_url.replace( |
| 881 |
"100x100bb", image_suffix |
| 882 |
) |
| 883 |
yield self._candidate( |
| 884 |
url=fallback_art_url, match=MetadataMatch.FALLBACK |
| 885 |
) |
| 886 |
except KeyError as e: |
| 887 |
self._log.debug( |
| 888 |
"Malformed itunes candidate: {} not found in {}", |
| 889 |
e, |
| 890 |
list(c.keys()), |
| 891 |
) |
| 892 |
|
| 893 |
|
| 894 |
class Wikipedia(RemoteArtSource): |
| 895 |
NAME = "Wikipedia (queried through DBpedia)" |
| 896 |
ID = "wikipedia" |
| 897 |
DBPEDIA_URL = "https://dbpedia.org/sparql" |
| 898 |
WIKIPEDIA_URL = "https://en.wikipedia.org/w/api.php" |
| 899 |
SPARQL_QUERY = """PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> |
| 900 |
PREFIX dbpprop: <http://dbpedia.org/property/> |
| 901 |
PREFIX owl: <http://dbpedia.org/ontology/> |
| 902 |
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> |
| 903 |
PREFIX foaf: <http://xmlns.com/foaf/0.1/> |
| 904 |
|
| 905 |
SELECT DISTINCT ?pageId ?coverFilename WHERE {{ |
| 906 |
?subject owl:wikiPageID ?pageId . |
| 907 |
?subject dbpprop:name ?name . |
| 908 |
?subject rdfs:label ?label . |
| 909 |
{{ ?subject dbpprop:artist ?artist }} |
| 910 |
UNION |
| 911 |
{{ ?subject owl:artist ?artist }} |
| 912 |
{{ ?artist foaf:name "{artist}"@en }} |
| 913 |
UNION |
| 914 |
{{ ?artist dbpprop:name "{artist}"@en }} |
| 915 |
?subject rdf:type <http://dbpedia.org/ontology/Album> . |
| 916 |
?subject dbpprop:cover ?coverFilename . |
| 917 |
FILTER ( regex(?name, "{album}", "i") ) |
| 918 |
}} |
| 919 |
Limit 1""" |
| 920 |
|
| 921 |
def get( |
| 922 |
self, |
| 923 |
album: Album, |
| 924 |
plugin: FetchArtPlugin, |
| 925 |
paths: Sequence[bytes] | None, |
| 926 |
) -> Iterator[Candidate]: |
| 927 |
if not (album.albumartist and album.album): |
| 928 |
return |
| 929 |
|
| 930 |
# Find the name of the cover art filename on DBpedia |
| 931 |
cover_filename, page_id = None, None |
| 932 |
|
| 933 |
try: |
| 934 |
dbpedia_response = self.request( |
| 935 |
self.DBPEDIA_URL, |
| 936 |
params={ |
| 937 |
"format": "application/sparql-results+json", |
| 938 |
"timeout": 2500, |
| 939 |
"query": self.SPARQL_QUERY.format( |
| 940 |
artist=album.albumartist.title(), album=album.album |
| 941 |
), |
| 942 |
}, |
| 943 |
headers={"content-type": "application/json"}, |
| 944 |
) |
| 945 |
except requests.RequestException: |
| 946 |
self._log.debug("dbpedia: error receiving response") |
| 947 |
return |
| 948 |
|
| 949 |
try: |
| 950 |
data = dbpedia_response.json() |
| 951 |
results = data["results"]["bindings"] |
| 952 |
if results: |
| 953 |
cover_filename = f"File:{results[0]['coverFilename']['value']}" |
| 954 |
page_id = results[0]["pageId"]["value"] |
| 955 |
else: |
| 956 |
self._log.debug("wikipedia: album not found on dbpedia") |
| 957 |
except (ValueError, KeyError, IndexError): |
| 958 |
self._log.debug( |
| 959 |
"wikipedia: error scraping dbpedia response: {.text}", |
| 960 |
dbpedia_response, |
| 961 |
) |
| 962 |
|
| 963 |
# Ensure we have a filename before attempting to query wikipedia |
| 964 |
if not (cover_filename and page_id): |
| 965 |
return |
| 966 |
|
| 967 |
# DBPedia sometimes provides an incomplete cover_filename, indicated |
| 968 |
# by the filename having a space before the extension, e.g., 'foo .bar' |
| 969 |
# An additional Wikipedia call can help to find the real filename. |
| 970 |
# This may be removed once the DBPedia issue is resolved, see: |
| 971 |
# https://github.com/dbpedia/extraction-framework/issues/396 |
| 972 |
if " ." in cover_filename and "." not in cover_filename.split(" .")[-1]: |
| 973 |
self._log.debug( |
| 974 |
"wikipedia: dbpedia provided incomplete cover_filename" |
| 975 |
) |
| 976 |
lpart, rpart = cover_filename.rsplit(" .", 1) |
| 977 |
|
| 978 |
# Query all the images in the page |
| 979 |
try: |
| 980 |
wikipedia_response = self.request( |
| 981 |
self.WIKIPEDIA_URL, |
| 982 |
params={ |
| 983 |
"format": "json", |
| 984 |
"action": "query", |
| 985 |
"continue": "", |
| 986 |
"prop": "images", |
| 987 |
"pageids": page_id, |
| 988 |
}, |
| 989 |
headers={"content-type": "application/json"}, |
| 990 |
) |
| 991 |
except requests.RequestException: |
| 992 |
self._log.debug("wikipedia: error receiving response") |
| 993 |
return |
| 994 |
|
| 995 |
# Try to see if one of the images on the pages matches our |
| 996 |
# incomplete cover_filename |
| 997 |
try: |
| 998 |
data = wikipedia_response.json() |
| 999 |
results = data["query"]["pages"][page_id]["images"] |
| 1000 |
for result in results: |
| 1001 |
if re.match( |
| 1002 |
rf"{re.escape(lpart)}.*?\.{re.escape(rpart)}", |
| 1003 |
result["title"], |
| 1004 |
): |
| 1005 |
cover_filename = result["title"] |
| 1006 |
break |
| 1007 |
except (ValueError, KeyError): |
| 1008 |
self._log.debug( |
| 1009 |
"wikipedia: failed to retrieve a cover_filename" |
| 1010 |
) |
| 1011 |
return |
| 1012 |
|
| 1013 |
# Find the absolute url of the cover art on Wikipedia |
| 1014 |
try: |
| 1015 |
wikipedia_response = self.request( |
| 1016 |
self.WIKIPEDIA_URL, |
| 1017 |
params={ |
| 1018 |
"format": "json", |
| 1019 |
"action": "query", |
| 1020 |
"continue": "", |
| 1021 |
"prop": "imageinfo", |
| 1022 |
"iiprop": "url", |
| 1023 |
"titles": cover_filename.encode("utf-8"), |
| 1024 |
}, |
| 1025 |
headers={"content-type": "application/json"}, |
| 1026 |
) |
| 1027 |
except requests.RequestException: |
| 1028 |
self._log.debug("wikipedia: error receiving response") |
| 1029 |
return |
| 1030 |
|
| 1031 |
try: |
| 1032 |
data = wikipedia_response.json() |
| 1033 |
results = data["query"]["pages"] |
| 1034 |
for _, result in results.items(): |
| 1035 |
image_url = result["imageinfo"][0]["url"] |
| 1036 |
yield self._candidate(url=image_url, match=MetadataMatch.EXACT) |
| 1037 |
except (ValueError, KeyError, IndexError): |
| 1038 |
self._log.debug("wikipedia: error scraping imageinfo") |
| 1039 |
return |
| 1040 |
|
| 1041 |
|
| 1042 |
class FileSystem(LocalArtSource): |
| 1043 |
NAME = "Filesystem" |
| 1044 |
ID = "filesystem" |
| 1045 |
|
| 1046 |
@staticmethod |
| 1047 |
def filename_priority( |
| 1048 |
filename: AnyStr, cover_names: Sequence[AnyStr] |
| 1049 |
) -> list[int]: |
| 1050 |
"""Sort order for image names. |
| 1051 |
|
| 1052 |
Return indexes of cover names found in the image filename. This |
| 1053 |
means that images with lower-numbered and more keywords will have |
| 1054 |
higher priority. |
| 1055 |
""" |
| 1056 |
return [idx for (idx, x) in enumerate(cover_names) if x in filename] |
| 1057 |
|
| 1058 |
def get( |
| 1059 |
self, |
| 1060 |
album: Album, |
| 1061 |
plugin: FetchArtPlugin, |
| 1062 |
paths: Sequence[bytes] | None, |
| 1063 |
) -> Iterator[Candidate]: |
| 1064 |
"""Look for album art files in the specified directories.""" |
| 1065 |
if not paths: |
| 1066 |
return |
| 1067 |
cover_names = list(map(util.bytestring_path, plugin.cover_names)) |
| 1068 |
cover_names_str = b"|".join(cover_names) |
| 1069 |
cover_pat = rb"".join([rb"(\b|_)(", cover_names_str, rb")(\b|_)"]) |
| 1070 |
|
| 1071 |
for path in paths: |
| 1072 |
if not os.path.isdir(syspath(path)): |
| 1073 |
continue |
| 1074 |
|
| 1075 |
# Find all files that look like images in the directory. |
| 1076 |
images = [] |
| 1077 |
ignore = list(map(os.fsencode, config["ignore"].as_str_seq())) |
| 1078 |
ignore_hidden = config["ignore_hidden"].get(bool) |
| 1079 |
for _, _, files in sorted_walk( |
| 1080 |
path, ignore=ignore, ignore_hidden=ignore_hidden |
| 1081 |
): |
| 1082 |
for fn in files: |
| 1083 |
fn = bytestring_path(fn) |
| 1084 |
for ext in IMAGE_EXTENSIONS: |
| 1085 |
if fn.lower().endswith(b"." + ext) and os.path.isfile( |
| 1086 |
syspath(os.path.join(path, fn)) |
| 1087 |
): |
| 1088 |
images.append(fn) |
| 1089 |
|
| 1090 |
# Look for "preferred" filenames. |
| 1091 |
images = sorted( |
| 1092 |
images, key=lambda x: self.filename_priority(x, cover_names) |
| 1093 |
) |
| 1094 |
remaining = [] |
| 1095 |
for fn in images: |
| 1096 |
if re.search(cover_pat, os.path.splitext(fn)[0], re.I): |
| 1097 |
self._log.debug( |
| 1098 |
"using well-named art file {}", |
| 1099 |
util.displayable_path(fn), |
| 1100 |
) |
| 1101 |
yield self._candidate( |
| 1102 |
path=os.path.join(path, fn), match=MetadataMatch.EXACT |
| 1103 |
) |
| 1104 |
else: |
| 1105 |
remaining.append(fn) |
| 1106 |
|
| 1107 |
# Fall back to a configured image. |
| 1108 |
if plugin.fallback: |
| 1109 |
self._log.debug( |
| 1110 |
"using fallback art file {}", |
| 1111 |
util.displayable_path(plugin.fallback), |
| 1112 |
) |
| 1113 |
yield self._candidate( |
| 1114 |
path=plugin.fallback, match=MetadataMatch.FALLBACK |
| 1115 |
) |
| 1116 |
|
| 1117 |
# Fall back to any image in the folder. |
| 1118 |
if remaining and not plugin.cautious: |
| 1119 |
self._log.debug( |
| 1120 |
"using fallback art file {}", |
| 1121 |
util.displayable_path(remaining[0]), |
| 1122 |
) |
| 1123 |
yield self._candidate( |
| 1124 |
path=os.path.join(path, remaining[0]), |
| 1125 |
match=MetadataMatch.FALLBACK, |
| 1126 |
) |
| 1127 |
|
| 1128 |
|
| 1129 |
class LastFM(RemoteArtSource): |
| 1130 |
NAME = "Last.fm" |
| 1131 |
ID = "lastfm" |
| 1132 |
|
| 1133 |
# Sizes in priority order. |
| 1134 |
SIZES: ClassVar[dict[str, tuple[int, int]]] = OrderedDict( |
| 1135 |
[ |
| 1136 |
("mega", (300, 300)), |
| 1137 |
("extralarge", (300, 300)), |
| 1138 |
("large", (174, 174)), |
| 1139 |
("medium", (64, 64)), |
| 1140 |
("small", (34, 34)), |
| 1141 |
] |
| 1142 |
) |
| 1143 |
|
| 1144 |
API_URL = "https://ws.audioscrobbler.com/2.0" |
| 1145 |
|
| 1146 |
def __init__(self, *args, **kwargs) -> None: |
| 1147 |
super().__init__(*args, **kwargs) |
| 1148 |
self.key = (self._config["lastfm_key"].get(),) |
| 1149 |
|
| 1150 |
@staticmethod |
| 1151 |
def add_default_config(config: confuse.ConfigView) -> None: |
| 1152 |
config.add({"lastfm_key": None}) |
| 1153 |
config["lastfm_key"].redact = True |
| 1154 |
|
| 1155 |
@classmethod |
| 1156 |
def available(cls, log: Logger, config: confuse.ConfigView) -> bool: |
| 1157 |
has_key = bool(config["lastfm_key"].get()) |
| 1158 |
if not has_key: |
| 1159 |
log.debug("lastfm: Disabling art source due to missing key") |
| 1160 |
return has_key |
| 1161 |
|
| 1162 |
def get( |
| 1163 |
self, |
| 1164 |
album: Album, |
| 1165 |
plugin: FetchArtPlugin, |
| 1166 |
paths: Sequence[bytes] | None, |
| 1167 |
) -> Iterator[Candidate]: |
| 1168 |
if not album.mb_albumid: |
| 1169 |
return |
| 1170 |
|
| 1171 |
try: |
| 1172 |
response = self.request( |
| 1173 |
self.API_URL, |
| 1174 |
params={ |
| 1175 |
"method": "album.getinfo", |
| 1176 |
"api_key": self.key, |
| 1177 |
"mbid": album.mb_albumid, |
| 1178 |
"format": "json", |
| 1179 |
}, |
| 1180 |
) |
| 1181 |
except requests.RequestException: |
| 1182 |
self._log.debug("lastfm: error receiving response") |
| 1183 |
return |
| 1184 |
|
| 1185 |
try: |
| 1186 |
data = response.json() |
| 1187 |
|
| 1188 |
if "error" in data: |
| 1189 |
if data["error"] == 6: |
| 1190 |
self._log.debug( |
| 1191 |
"lastfm: no results for {.mb_albumid}", album |
| 1192 |
) |
| 1193 |
else: |
| 1194 |
self._log.error( |
| 1195 |
"lastfm: failed to get album info: {} ({})", |
| 1196 |
data["message"], |
| 1197 |
data["error"], |
| 1198 |
) |
| 1199 |
else: |
| 1200 |
images = { |
| 1201 |
image["size"]: image["#text"] |
| 1202 |
for image in data["album"]["image"] |
| 1203 |
} |
| 1204 |
|
| 1205 |
# Provide candidates in order of size. |
| 1206 |
for size in self.SIZES.keys(): |
| 1207 |
if size in images: |
| 1208 |
yield self._candidate( |
| 1209 |
url=images[size], size=self.SIZES[size] |
| 1210 |
) |
| 1211 |
except ValueError: |
| 1212 |
self._log.debug("lastfm: error loading response: {.text}", response) |
| 1213 |
return |
| 1214 |
|
| 1215 |
|
| 1216 |
class Spotify(RemoteArtSource): |
| 1217 |
NAME = "Spotify" |
| 1218 |
ID = "spotify" |
| 1219 |
|
| 1220 |
SPOTIFY_ALBUM_URL = "https://open.spotify.com/album/" |
| 1221 |
|
| 1222 |
@classmethod |
| 1223 |
def available(cls, log: Logger, config: confuse.ConfigView) -> bool: |
| 1224 |
if not HAS_BEAUTIFUL_SOUP: |
| 1225 |
log.debug( |
| 1226 |
"To use Spotify as an album art source, " |
| 1227 |
"you must install the beautifulsoup4 module. See " |
| 1228 |
"the documentation for further details." |
| 1229 |
) |
| 1230 |
return HAS_BEAUTIFUL_SOUP |
| 1231 |
|
| 1232 |
def get( |
| 1233 |
self, |
| 1234 |
album: Album, |
| 1235 |
plugin: FetchArtPlugin, |
| 1236 |
paths: Sequence[bytes] | None, |
| 1237 |
) -> Iterator[Candidate]: |
| 1238 |
try: |
| 1239 |
url = f"{self.SPOTIFY_ALBUM_URL}{album.items().get().spotify_album_id}" # type: ignore[union-attr] |
| 1240 |
except AttributeError: |
| 1241 |
self._log.debug("Fetchart: no Spotify album ID found") |
| 1242 |
return |
| 1243 |
|
| 1244 |
try: |
| 1245 |
response = requests.get(url, timeout=10) |
| 1246 |
response.raise_for_status() |
| 1247 |
except requests.RequestException as e: |
| 1248 |
self._log.debug("Error: {!s}", e) |
| 1249 |
return |
| 1250 |
|
| 1251 |
try: |
| 1252 |
html = response.text |
| 1253 |
soup = BeautifulSoup(html, "html.parser") |
| 1254 |
except ValueError: |
| 1255 |
self._log.debug( |
| 1256 |
"Spotify: error loading response: {.text}", response |
| 1257 |
) |
| 1258 |
return |
| 1259 |
|
| 1260 |
tag = soup.find("meta", attrs={"property": "og:image"}) |
| 1261 |
if tag is None or not isinstance(tag, Tag): |
| 1262 |
self._log.debug( |
| 1263 |
"Spotify: Unexpected response, og:image tag missing" |
| 1264 |
) |
| 1265 |
return |
| 1266 |
|
| 1267 |
image_url = tag["content"] |
| 1268 |
yield self._candidate(url=image_url, match=MetadataMatch.EXACT) |
| 1269 |
|
| 1270 |
|
| 1271 |
class CoverArtUrl(RemoteArtSource): |
| 1272 |
# This source is intended to be used with a plugin that sets the |
| 1273 |
# cover_art_url field on albums or tracks. Users can also manually update |
| 1274 |
# the cover_art_url field using the "set" command. This source will then |
| 1275 |
# use that URL to fetch the image. |
| 1276 |
|
| 1277 |
NAME = "Cover Art URL" |
| 1278 |
ID = "cover_art_url" |
| 1279 |
|
| 1280 |
def get( |
| 1281 |
self, |
| 1282 |
album: Album, |
| 1283 |
plugin: FetchArtPlugin, |
| 1284 |
paths: Sequence[bytes] | None, |
| 1285 |
) -> Iterator[Candidate]: |
| 1286 |
image_url = None |
| 1287 |
try: |
| 1288 |
# look for cover_art_url on album or first track |
| 1289 |
if album.get("cover_art_url"): |
| 1290 |
image_url = album.cover_art_url |
| 1291 |
else: |
| 1292 |
image_url = album.items().get().cover_art_url # type: ignore[union-attr] |
| 1293 |
self._log.debug("Cover art URL {} found for {}", image_url, album) |
| 1294 |
except (AttributeError, TypeError): |
| 1295 |
self._log.debug("Cover art URL not found for {}", album) |
| 1296 |
return |
| 1297 |
if image_url: |
| 1298 |
yield self._candidate(url=image_url, match=MetadataMatch.EXACT) |
| 1299 |
else: |
| 1300 |
self._log.debug("Cover art URL not found for {}", album) |
| 1301 |
return |
| 1302 |
|
| 1303 |
|
| 1304 |
# All art sources. The order they will be tried in is specified by the config. |
| 1305 |
ART_SOURCES: set[type[ArtSource]] = { |
| 1306 |
FileSystem, |
| 1307 |
CoverArtArchive, |
| 1308 |
ITunesStore, |
| 1309 |
AlbumArtOrg, |
| 1310 |
Amazon, |
| 1311 |
Wikipedia, |
| 1312 |
GoogleImages, |
| 1313 |
FanartTV, |
| 1314 |
LastFM, |
| 1315 |
Spotify, |
| 1316 |
CoverArtUrl, |
| 1317 |
} |
| 1318 |
|
| 1319 |
|
| 1320 |
# PLUGIN LOGIC ############################################################### |
| 1321 |
|
| 1322 |
|
| 1323 |
class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): |
| 1324 |
PAT_PX = r"(0|[1-9][0-9]*)px" |
| 1325 |
PAT_PERCENT = r"(100(\.00?)?|[1-9]?[0-9](\.[0-9]{1,2})?)%" |
| 1326 |
|
| 1327 |
def __init__(self) -> None: |
| 1328 |
super().__init__() |
| 1329 |
|
| 1330 |
# Holds candidates corresponding to downloaded images between |
| 1331 |
# fetching them and placing them in the filesystem. |
| 1332 |
self.art_candidates: dict[ImportTask, Candidate] = {} |
| 1333 |
|
| 1334 |
self.config.add( |
| 1335 |
{ |
| 1336 |
"auto": True, |
| 1337 |
"fetch_for_asis": False, |
| 1338 |
"minwidth": 0, |
| 1339 |
"maxwidth": 0, |
| 1340 |
"quality": 0, |
| 1341 |
"max_filesize": 0, |
| 1342 |
"enforce_ratio": False, |
| 1343 |
"cautious": False, |
| 1344 |
"cover_names": ["cover", "front", "art", "album", "folder"], |
| 1345 |
"fallback": None, |
| 1346 |
"sources": [ |
| 1347 |
"filesystem", |
| 1348 |
"coverart", |
| 1349 |
"itunes", |
| 1350 |
"amazon", |
| 1351 |
"albumart", |
| 1352 |
"cover_art_url", |
| 1353 |
], |
| 1354 |
"store_source": False, |
| 1355 |
"high_resolution": False, |
| 1356 |
"deinterlace": False, |
| 1357 |
"cover_format": None, |
| 1358 |
} |
| 1359 |
) |
| 1360 |
for source in ART_SOURCES: |
| 1361 |
source.add_default_config(self.config) |
| 1362 |
|
| 1363 |
self.minwidth = self.config["minwidth"].get(int) |
| 1364 |
self.maxwidth = self.config["maxwidth"].get(int) |
| 1365 |
self.max_filesize = self.config["max_filesize"].get(int) |
| 1366 |
self.quality = self.config["quality"].get(int) |
| 1367 |
|
| 1368 |
# allow both pixel and percentage-based margin specifications |
| 1369 |
self.enforce_ratio = self.config["enforce_ratio"].get( |
| 1370 |
confuse.OneOf[bool | str]( |
| 1371 |
[ |
| 1372 |
bool, |
| 1373 |
confuse.String(pattern=self.PAT_PX), |
| 1374 |
confuse.String(pattern=self.PAT_PERCENT), |
| 1375 |
] |
| 1376 |
) |
| 1377 |
) |
| 1378 |
self.margin_px = None |
| 1379 |
self.margin_percent = None |
| 1380 |
self.deinterlace = self.config["deinterlace"].get(bool) |
| 1381 |
if isinstance(self.enforce_ratio, str): |
| 1382 |
if self.enforce_ratio[-1] == "%": |
| 1383 |
self.margin_percent = float(self.enforce_ratio[:-1]) / 100 |
| 1384 |
elif self.enforce_ratio[-2:] == "px": |
| 1385 |
self.margin_px = int(self.enforce_ratio[:-2]) |
| 1386 |
else: |
| 1387 |
# shouldn't happen |
| 1388 |
raise confuse.ConfigValueError() |
| 1389 |
self.enforce_ratio = True |
| 1390 |
|
| 1391 |
cover_names = self.config["cover_names"].as_str_seq() |
| 1392 |
self.cover_names = list(map(util.bytestring_path, cover_names)) |
| 1393 |
self.cautious = self.config["cautious"].get(bool) |
| 1394 |
self.fallback = self.config["fallback"].get( |
| 1395 |
confuse.Optional(confuse.Filename()) |
| 1396 |
) |
| 1397 |
self.store_source = self.config["store_source"].get(bool) |
| 1398 |
|
| 1399 |
self.cover_format = self.config["cover_format"].get( |
| 1400 |
confuse.Optional(str) |
| 1401 |
) |
| 1402 |
|
| 1403 |
if self.config["auto"]: |
| 1404 |
# Enable two import hooks when fetching is enabled. |
| 1405 |
self.import_stages = [self.fetch_art] |
| 1406 |
self.register_listener("import_task_files", self.assign_art) |
| 1407 |
|
| 1408 |
sources = self._get_sources() |
| 1409 |
|
| 1410 |
if "remote_priority" in self.config: |
| 1411 |
self._log.warning( |
| 1412 |
"The `fetch_art.remote_priority` configuration option has " |
| 1413 |
"been deprecated. Instead, place `filesystem` at the end of " |
| 1414 |
"your `sources` list." |
| 1415 |
) |
| 1416 |
if self.config["remote_priority"].get(bool): |
| 1417 |
fs = [] |
| 1418 |
others = [] |
| 1419 |
for s, c in sources: |
| 1420 |
if s == "filesystem": |
| 1421 |
fs.append((s, c)) |
| 1422 |
else: |
| 1423 |
others.append((s, c)) |
| 1424 |
sources = others + fs |
| 1425 |
|
| 1426 |
sources_by_name = {s_cls.ID: s_cls for s_cls in ART_SOURCES} |
| 1427 |
|
| 1428 |
self.sources = [ |
| 1429 |
sources_by_name[s](self._log, self.config, match_by=[c]) |
| 1430 |
for s, c in sources |
| 1431 |
] |
| 1432 |
|
| 1433 |
def _get_sources(self) -> list[tuple[str, str]]: |
| 1434 |
available_sources = [ |
| 1435 |
(s_cls.ID, c) |
| 1436 |
for s_cls in ART_SOURCES |
| 1437 |
if s_cls.available(self._log, self.config) |
| 1438 |
for c in s_cls.VALID_MATCHING_CRITERIA |
| 1439 |
] |
| 1440 |
|
| 1441 |
if isinstance(self.config["sources"].get(), str): |
| 1442 |
cfg_sources = [(self.config["sources"].get(), "*")] |
| 1443 |
else: |
| 1444 |
cfg_sources = self.config["sources"].as_pairs(default_value="*") |
| 1445 |
|
| 1446 |
try: |
| 1447 |
sources = sanitize_pairs( |
| 1448 |
cfg_sources, available_sources, raise_on_unknown=True |
| 1449 |
) |
| 1450 |
|
| 1451 |
if len(sources) == 0: |
| 1452 |
raise UserError("fetchart: no sources defined in config") |
| 1453 |
|
| 1454 |
return sources |
| 1455 |
except UnknownPairError as e: |
| 1456 |
raise UserError(e) |
| 1457 |
|
| 1458 |
@cached_property |
| 1459 |
def fetch_for_asis(self) -> bool: |
| 1460 |
return self.config["fetch_for_asis"].get(bool) |
| 1461 |
|
| 1462 |
@staticmethod |
| 1463 |
def _is_source_file_removal_enabled() -> bool: |
| 1464 |
return config["import"]["delete"].get(bool) or config["import"][ |
| 1465 |
"move" |
| 1466 |
].get(bool) |
| 1467 |
|
| 1468 |
def _is_candidate_fallback(self, candidate: Candidate) -> bool: |
| 1469 |
try: |
| 1470 |
return ( |
| 1471 |
candidate.path is not None |
| 1472 |
and self.fallback is not None |
| 1473 |
and os.path.samefile(candidate.path, self.fallback) |
| 1474 |
) |
| 1475 |
except OSError: |
| 1476 |
return False |
| 1477 |
|
| 1478 |
# Asynchronous; after music is added to the library. |
| 1479 |
def fetch_art(self, session: ImportSession, task: ImportTask) -> None: |
| 1480 |
"""Find art for the album being imported.""" |
| 1481 |
if task.is_album: # Only fetch art for full albums. |
| 1482 |
if task.album.artpath and os.path.isfile( |
| 1483 |
syspath(task.album.artpath) |
| 1484 |
): |
| 1485 |
# Album already has art (probably a re-import); skip it. |
| 1486 |
return |
| 1487 |
if task.choice_flag == importer.Action.ASIS: |
| 1488 |
# For as-is imports, don't search Web sources for art, |
| 1489 |
# unless fetch_for_asis is set |
| 1490 |
local = not self.fetch_for_asis |
| 1491 |
elif task.choice_flag in ( |
| 1492 |
importer.Action.APPLY, |
| 1493 |
importer.Action.RETAG, |
| 1494 |
): |
| 1495 |
# Search everywhere for art. |
| 1496 |
local = False |
| 1497 |
else: |
| 1498 |
# For any other choices (e.g., TRACKS), do nothing. |
| 1499 |
return |
| 1500 |
|
| 1501 |
candidate = self.art_for_album(task.album, task.paths, local) |
| 1502 |
|
| 1503 |
if candidate: |
| 1504 |
self.art_candidates[task] = candidate |
| 1505 |
|
| 1506 |
def _set_art( |
| 1507 |
self, album: Album, candidate: Candidate, delete: bool = False |
| 1508 |
) -> bool: |
| 1509 |
"""Set album art from candidate. Returns True on success, False on |
| 1510 |
failure (e.g. permission errors when writing the art file). |
| 1511 |
""" |
| 1512 |
try: |
| 1513 |
album.set_art(candidate.path, delete) # type: ignore[arg-type] |
| 1514 |
except OSError as exc: |
| 1515 |
self._log.warning( |
| 1516 |
"fetchart: could not write art for {0.albumartist} - " |
| 1517 |
"{0.album}: {1}", |
| 1518 |
album, |
| 1519 |
exc, |
| 1520 |
) |
| 1521 |
return False |
| 1522 |
if self.store_source: |
| 1523 |
# store the source of the chosen artwork in a flexible field |
| 1524 |
self._log.debug( |
| 1525 |
"Storing art_source for {0.albumartist} - {0.album}", album |
| 1526 |
) |
| 1527 |
album.art_source = candidate.source_name |
| 1528 |
album.store() |
| 1529 |
return True |
| 1530 |
|
| 1531 |
# Synchronous; after music files are put in place. |
| 1532 |
def assign_art(self, session: ImportSession, task: ImportTask) -> None: |
| 1533 |
"""Place the discovered art in the filesystem.""" |
| 1534 |
if task in self.art_candidates: |
| 1535 |
candidate = self.art_candidates.pop(task) |
| 1536 |
removal_enabled = self._is_source_file_removal_enabled() |
| 1537 |
|
| 1538 |
self._set_art(task.album, candidate, not removal_enabled) |
| 1539 |
|
| 1540 |
if ( |
| 1541 |
removal_enabled |
| 1542 |
and not self._is_candidate_fallback(candidate) |
| 1543 |
and (path := candidate.path) |
| 1544 |
): |
| 1545 |
task.prune(path) |
| 1546 |
|
| 1547 |
# Manual album art fetching. |
| 1548 |
def commands(self) -> list[ui.Subcommand]: |
| 1549 |
cmd = ui.Subcommand("fetchart", help="download album art") |
| 1550 |
cmd.parser.add_option( |
| 1551 |
"-f", |
| 1552 |
"--force", |
| 1553 |
dest="force", |
| 1554 |
action="store_true", |
| 1555 |
default=False, |
| 1556 |
help="re-download art when already present", |
| 1557 |
) |
| 1558 |
cmd.parser.add_option( |
| 1559 |
"-q", |
| 1560 |
"--quiet", |
| 1561 |
dest="quiet", |
| 1562 |
action="store_true", |
| 1563 |
default=False, |
| 1564 |
help="quiet mode: do not output albums that already have artwork", |
| 1565 |
) |
| 1566 |
|
| 1567 |
def func(lib: Library, opts: FetchArtCLIOpts, args: list[str]) -> None: |
| 1568 |
self.batch_fetch_art(lib, lib.albums(args), opts.force, opts.quiet) |
| 1569 |
|
| 1570 |
cmd.func = func |
| 1571 |
return [cmd] |
| 1572 |
|
| 1573 |
# Utilities converted from functions to methods on logging overhaul |
| 1574 |
|
| 1575 |
def art_for_album( |
| 1576 |
self, |
| 1577 |
album: Album, |
| 1578 |
paths: Sequence[bytes] | None, |
| 1579 |
local_only: bool = False, |
| 1580 |
) -> Candidate | None: |
| 1581 |
"""Given an Album object, returns a path to downloaded art for the |
| 1582 |
album (or None if no art is found). If `maxwidth`, then images are |
| 1583 |
resized to this maximum pixel size. If `quality` then resized images |
| 1584 |
are saved at the specified quality level. If `local_only`, then only |
| 1585 |
local image files from the filesystem are returned; no network |
| 1586 |
requests are made. |
| 1587 |
""" |
| 1588 |
out = None |
| 1589 |
|
| 1590 |
for source in self.sources: |
| 1591 |
if source.LOC == "local" or not local_only: |
| 1592 |
self._log.debug( |
| 1593 |
"trying source {0.description}" |
| 1594 |
" for album {1.albumartist} - {1.album}", |
| 1595 |
source, |
| 1596 |
album, |
| 1597 |
) |
| 1598 |
# URLs might be invalid at this point, or the image may not |
| 1599 |
# fulfill the requirements |
| 1600 |
for candidate in source.get(album, self, paths): |
| 1601 |
source.fetch_image(candidate, self) |
| 1602 |
if candidate.validate(self) != ImageAction.BAD: |
| 1603 |
out = candidate |
| 1604 |
assert out.path is not None # help mypy |
| 1605 |
self._log.debug( |
| 1606 |
"using {.LOC} image {.path}", source, out |
| 1607 |
) |
| 1608 |
break |
| 1609 |
# Remove temporary files for invalid candidates. |
| 1610 |
source.cleanup(candidate) |
| 1611 |
if out: |
| 1612 |
break |
| 1613 |
|
| 1614 |
if out: |
| 1615 |
out.resize(self) |
| 1616 |
|
| 1617 |
return out |
| 1618 |
|
| 1619 |
def batch_fetch_art( |
| 1620 |
self, lib: Library, albums: Iterable[Album], force: bool, quiet: bool |
| 1621 |
) -> None: |
| 1622 |
"""Fetch album art for each of the albums. This implements the manual |
| 1623 |
fetchart CLI command. |
| 1624 |
""" |
| 1625 |
for album in albums: |
| 1626 |
if ( |
| 1627 |
album.artpath |
| 1628 |
and not force |
| 1629 |
and os.path.isfile(syspath(album.artpath)) |
| 1630 |
): |
| 1631 |
if not quiet: |
| 1632 |
message = colorize("text_highlight_minor", "has album art") |
| 1633 |
ui.print_(f"{album}: {message}") |
| 1634 |
else: |
| 1635 |
# In ordinary invocations, look for images on the |
| 1636 |
# filesystem. When forcing, however, always go to the Web |
| 1637 |
# sources. |
| 1638 |
local_paths = None if force else [album.path] |
| 1639 |
|
| 1640 |
candidate = self.art_for_album(album, local_paths) |
| 1641 |
if candidate: |
| 1642 |
if self._set_art(album, candidate): |
| 1643 |
message = colorize("text_success", "found album art") |
| 1644 |
else: |
| 1645 |
message = colorize( |
| 1646 |
"text_error", "error writing album art" |
| 1647 |
) |
| 1648 |
else: |
| 1649 |
message = colorize("text_error", "no art found") |
| 1650 |
ui.print_(f"{album}: {message}") |