From ea334bd977ee8ed0cdbd627b7e9564dd08dd43f7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=A0ar=C5=ABnas=20Nejus?= Date: Thu, 18 Jun 2026 01:36:18 +0100 Subject: [PATCH 01/23] Move AttrDict under beets.util --- beets/autotag/__init__.py | 3 +-- beets/autotag/hooks.py | 53 ++------------------------------------ beets/util/__init__.py | 45 ++++++++++++++++++++++++++++++++ test/autotag/test_hooks.py | 2 +- 4 files changed, 49 insertions(+), 54 deletions(-) diff --git a/beets/autotag/__init__.py b/beets/autotag/__init__.py index bdb2ee903..6cd193ad6 100644 --- a/beets/autotag/__init__.py +++ b/beets/autotag/__init__.py @@ -8,7 +8,7 @@ from importlib import import_module from beets.util.deprecation import deprecate_for_maintainers, deprecate_imports from .distance import Distance, distance, string_dist, track_distance -from .hooks import AlbumInfo, AttrDict, Info, TrackInfo, correct_list_fields +from .hooks import AlbumInfo, Info, TrackInfo, correct_list_fields from .match import ( AlbumMatch, Match, @@ -34,7 +34,6 @@ def __getattr__(name: str): __all__ = [ "AlbumInfo", "AlbumMatch", - "AttrDict", "Distance", "Info", "Match", diff --git a/beets/autotag/hooks.py b/beets/autotag/hooks.py index 4a771e238..ceba6f6bf 100644 --- a/beets/autotag/hooks.py +++ b/beets/autotag/hooks.py @@ -4,20 +4,16 @@ from __future__ import annotations from copy import deepcopy from functools import cached_property -from typing import Any, ClassVar, TypeVar - -from typing_extensions import Self +from typing import Any, ClassVar from beets import config, logging -from beets.util import cached_classproperty, unique_list +from beets.util import AttrDict, cached_classproperty, unique_list from beets.util.deprecation import ( ALBUM_LEGACY_TO_LIST_FIELD, ITEM_LEGACY_TO_LIST_FIELD, deprecate_for_maintainers, ) -V = TypeVar("V") - JSONDict = dict[str, Any] log = logging.getLogger("beets") @@ -87,51 +83,6 @@ def correct_list_fields(input_data: JSONDict) -> JSONDict: # Classes used to represent candidate options. -class AttrDict(dict[str, V]): - """Mapping enabling attribute-style access to stored metadata values.""" - - def copy(self) -> Self: - """Return a detached copy preserving subclass-specific behavior.""" - return deepcopy(self) - - def __getattribute__(self, attr: str) -> V: - # Intercept cached_property failures so an AttributeError raised - # inside the property body is not masked by __getattr__ fallback. - # Reuse the original traceback so the wrapped RuntimeError still - # points at the real failing line, but suppress the printed cause - # block to keep CLI tracebacks readable. See #6558 (and #6503 / - # #6506 for the same masking pattern with different metadata - # providers). - try: - return super().__getattribute__(attr) - except AttributeError as exc: - if not attr.startswith("__"): - for klass in type(self).__mro__: - descr = klass.__dict__.get(attr) - if descr is None: - continue - if isinstance(descr, cached_property): - raise RuntimeError( - f"{type(self).__name__}.{attr} failed: {exc}" - ).with_traceback(exc.__traceback__) from None - break - raise - - def __getattr__(self, attr: str) -> V: - if attr in self: - return self[attr] - - raise AttributeError( - f"'{self.__class__.__name__}' object has no attribute '{attr}'" - ) - - def __setattr__(self, key: str, value: V) -> None: - self.__setitem__(key, value) - - def __hash__(self) -> int: # type: ignore[override] - return id(self) - - class Info(AttrDict[Any]): """Container for metadata about a musical entity.""" diff --git a/beets/util/__init__.py b/beets/util/__init__.py index 5606d502b..12a638778 100644 --- a/beets/util/__init__.py +++ b/beets/util/__init__.py @@ -1206,3 +1206,48 @@ def chunks(lst: Sequence[T], n: int) -> Iterator[list[T]]: """Yield successive n-sized chunks from lst.""" for i in range(0, len(lst), n): yield list(lst[i : i + n]) + + +class AttrDict(dict[str, T]): + """Mapping enabling attribute-style access to stored metadata values.""" + + def copy(self) -> Self: + """Return a detached copy preserving subclass-specific behavior.""" + return deepcopy(self) + + def __getattribute__(self, attr: str) -> T: + # Intercept cached_property failures so an AttributeError raised + # inside the property body is not masked by __getattr__ fallback. + # Reuse the original traceback so the wrapped RuntimeError still + # points at the real failing line, but suppress the printed cause + # block to keep CLI tracebacks readable. See #6558 (and #6503 / + # #6506 for the same masking pattern with different metadata + # providers). + try: + return super().__getattribute__(attr) + except AttributeError as exc: + if not attr.startswith("__"): + for klass in type(self).__mro__: + descr = klass.__dict__.get(attr) + if descr is None: + continue + if isinstance(descr, cached_property): + raise RuntimeError( + f"{type(self).__name__}.{attr} failed: {exc}" + ).with_traceback(exc.__traceback__) from None + break + raise + + def __getattr__(self, attr: str) -> T: + if attr in self: + return self[attr] + + raise AttributeError( + f"'{self.__class__.__name__}' object has no attribute '{attr}'" + ) + + def __setattr__(self, key: str, value: T) -> None: + self.__setitem__(key, value) + + def __hash__(self) -> int: # type: ignore[override] + return id(self) diff --git a/test/autotag/test_hooks.py b/test/autotag/test_hooks.py index 0c3e78aa0..c58523ab7 100644 --- a/test/autotag/test_hooks.py +++ b/test/autotag/test_hooks.py @@ -9,7 +9,6 @@ import pytest from beets.autotag import ( AlbumInfo, AlbumMatch, - AttrDict, Distance, TrackInfo, TrackMatch, @@ -17,6 +16,7 @@ from beets.autotag import ( ) from beets.library import Item from beets.test.helper import BeetsTestCase +from beets.util import AttrDict str_field_deprecation = pytest.warns( DeprecationWarning, match="The 'genre' field is deprecated" From 1d1a2930480e99a9c9713c495b8ba34a01966c3a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=A0ar=C5=ABnas=20Nejus?= Date: Thu, 18 Jun 2026 01:58:48 +0100 Subject: [PATCH 02/23] Exclude AttrDict move from git blame --- .git-blame-ignore-revs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs index a7a59c7de..5bfd34f5e 100644 --- a/.git-blame-ignore-revs +++ b/.git-blame-ignore-revs @@ -271,3 +271,5 @@ d24c0d341ec6074c343cd8054083fe358da8fa14 b2f52ac12443c102712b735e456fd07a6525786b # Return Path from TestHelper.create_mediafile_fixture bb66b0c378e9bf7d97622a1582d93c4dfcf20fdd +# Move AttrDict under beets.util +ea334bd977ee8ed0cdbd627b7e9564dd08dd43f7 From 97904e7e16218f298e0d283e409060d762336253 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=A0ar=C5=ABnas=20Nejus?= Date: Thu, 18 Jun 2026 01:55:43 +0100 Subject: [PATCH 03/23] Refactor autotag to use Source abstraction Introduce Source class to encapsulate metadata extraction logic, replacing scattered `get_most_common_tags` calls throughout codebase. - Add Source class in importer.tasks with artist, name, and metadata - Simplify `distance()` to accept Source.data instead of items list - Update display functions to use Source objects - Cache Source creation with @cached_property on ImportTask This centralizes metadata handling and reduces coupling between autotag and library modules. --- beets/autotag/__init__.py | 2 + beets/autotag/distance.py | 72 +++++++++++----------- beets/autotag/match.py | 60 +++++++----------- beets/autotag/source.py | 57 +++++++++++++++++ beets/importer/tasks.py | 35 +++++------ beets/ui/commands/import_/display.py | 27 +++++---- beets/ui/commands/import_/session.py | 91 ++++++++++------------------ beets/util/__init__.py | 22 +++---- beetsplug/bench.py | 5 +- beetsplug/ihate.py | 13 +--- beetsplug/mbpseudo.py | 9 ++- test/autotag/test_distance.py | 8 ++- test/autotag/test_match.py | 17 ++++-- test/test_util.py | 7 +-- test/ui/commands/test_import.py | 25 +++++--- 15 files changed, 233 insertions(+), 217 deletions(-) create mode 100644 beets/autotag/source.py diff --git a/beets/autotag/__init__.py b/beets/autotag/__init__.py index 6cd193ad6..dc3d1a62f 100644 --- a/beets/autotag/__init__.py +++ b/beets/autotag/__init__.py @@ -19,6 +19,7 @@ from .match import ( tag_album, tag_item, ) +from .source import Source def __getattr__(name: str): @@ -39,6 +40,7 @@ __all__ = [ "Match", "Proposal", "Recommendation", + "Source", "TrackInfo", "TrackMatch", "assign_items", diff --git a/beets/autotag/distance.py b/beets/autotag/distance.py index ba6d7939b..03c4afe53 100644 --- a/beets/autotag/distance.py +++ b/beets/autotag/distance.py @@ -9,13 +9,14 @@ from jellyfish import levenshtein_distance from unidecode import unidecode from beets import config, metadata_plugins -from beets.util import as_string, cached_classproperty, get_most_common_tags +from beets.util import as_string, cached_classproperty from beets.util.color import colorize if TYPE_CHECKING: from collections.abc import Iterator, KeysView, Sequence from beets.library import Item + from beets.util import AttrDict from beets.util.color import ColorName from .hooks import AlbumInfo, TrackInfo @@ -427,28 +428,27 @@ def track_distance( def distance( - items: Sequence[Item], + original: AttrDict[Any], album_info: AlbumInfo, item_info_pairs: list[tuple[Item, TrackInfo]], + unmatched_count: int, ) -> Distance: - """Determines how "significant" an album metadata change would be. - Returns a Distance object. `album_info` is an AlbumInfo object - reflecting the album to be compared. `items` is a sequence of all - Item objects that will be matched (order is not important). - `mapping` is a dictionary mapping Items to TrackInfo objects; the - keys are a subset of `items` and the values are a subset of - `album_info.tracks`. - """ - likelies, _ = get_most_common_tags(items) + """Determine how "significant" an album metadata change would be. + Returns a Distance object. + `original` is an AttrDict with the original album metadata. + `album_info` is an AlbumInfo object reflecting the album to be compared. + `item_info_pairs` is a list with matched (Item, TrackInfo) pairs. + `unmatched_count` is the number of unmatched tracks on the release. + """ dist = Distance() # Artist, if not various. if not album_info.va: - dist.add_string("artist", likelies["artist"], album_info.artist) + dist.add_string("artist", original.artist, album_info.artist) # Album. - dist.add_string("album", likelies["album"], album_info.album) + dist.add_string("album", original.album, album_info.album) preferred_config = config["match"]["preferred"] # Current or preferred media. @@ -461,29 +461,29 @@ def distance( if options: dist.add_priority("media", album_info.media, options) # Current media. - elif likelies["media"]: - dist.add_equality("media", album_info.media, likelies["media"]) + elif original.media: + dist.add_equality("media", album_info.media, original.media) # Mediums. - if likelies["disctotal"] and album_info.mediums: - dist.add_number("mediums", likelies["disctotal"], album_info.mediums) + if original.disctotal and album_info.mediums: + dist.add_number("mediums", original.disctotal, album_info.mediums) # Prefer earliest release. if album_info.year and preferred_config["original_year"]: # Assume 1889 (earliest first gramophone discs) if we don't know the # original year. - original = album_info.original_year or 1889 - diff = abs(album_info.year - original) - diff_max = abs(datetime.date.today().year - original) + original_year = album_info.original_year or 1889 + diff = abs(album_info.year - original_year) + diff_max = abs(datetime.date.today().year - original_year) dist.add_ratio("year", diff, diff_max) # Year. - elif likelies["year"] and album_info.year: - if likelies["year"] in (album_info.year, album_info.original_year): + elif original.year and album_info.year: + if original.year in (album_info.year, album_info.original_year): # No penalty for matching release or original year. dist.add("year", 0.0) elif album_info.original_year: # Prefer matchest closest to the release year. - diff = abs(likelies["year"] - album_info.year) + diff = abs(original.year - album_info.year) diff_max = abs( datetime.date.today().year - album_info.original_year ) @@ -498,30 +498,28 @@ def distance( if album_info.country and options: dist.add_priority("country", album_info.country, options) # Country. - elif likelies["country"] and album_info.country: - dist.add_string("country", likelies["country"], album_info.country) + elif original.country and album_info.country: + dist.add_string("country", original.country, album_info.country) # Label. - if likelies["label"] and album_info.label: - dist.add_string("label", likelies["label"], album_info.label) + if original.label and album_info.label: + dist.add_string("label", original.label, album_info.label) # Catalog number. - if likelies["catalognum"] and album_info.catalognum: + if original.catalognum and album_info.catalognum: dist.add_string( - "catalognum", likelies["catalognum"], album_info.catalognum + "catalognum", original.catalognum, album_info.catalognum ) # Disambiguation. - if likelies["albumdisambig"] and album_info.albumdisambig: + if original.albumdisambig and album_info.albumdisambig: dist.add_string( - "albumdisambig", likelies["albumdisambig"], album_info.albumdisambig + "albumdisambig", original.albumdisambig, album_info.albumdisambig ) # Album ID. - if likelies["mb_albumid"]: - dist.add_equality( - "album_id", likelies["mb_albumid"], album_info.album_id - ) + if original.mb_albumid: + dist.add_equality("album_id", original.mb_albumid, album_info.album_id) # Tracks. dist.tracks = {} @@ -534,9 +532,9 @@ def distance( dist.add("missing_tracks", 1.0) # Unmatched tracks. - for _ in range(len(items) - len(item_info_pairs)): + for _ in range(unmatched_count): dist.add("unmatched_tracks", 1.0) - dist.add_data_source(likelies["data_source"], album_info.data_source) + dist.add_data_source(original.data_source, album_info.data_source) return dist diff --git a/beets/autotag/match.py b/beets/autotag/match.py index a4775f352..d90dfd4b7 100644 --- a/beets/autotag/match.py +++ b/beets/autotag/match.py @@ -13,13 +13,13 @@ import lap import numpy as np from beets import config, logging, metadata_plugins, plugins -from beets.util import get_most_common_tags from .distance import VA_ARTISTS, distance, track_distance if TYPE_CHECKING: from collections.abc import Iterable, Sequence + from beets.autotag import Source from beets.library import Album, Item from .distance import Distance @@ -329,7 +329,7 @@ def _sort_candidates(candidates: Iterable[AnyMatch]) -> Sequence[AnyMatch]: def _add_candidate( - items: Sequence[Item], results: Candidates[AlbumMatch], info: AlbumInfo + source: Source, results: Candidates[AlbumMatch], info: AlbumInfo ): """Given a candidate AlbumInfo object, attempt to add the candidate to the output dictionary of AlbumMatch objects. This involves @@ -360,11 +360,11 @@ def _add_candidate( # Find mapping between the items and the track info. item_info_pairs, extra_items, extra_tracks = assign_items( - items, info.tracks + source.items, info.tracks ) # Get the change distance. - dist = distance(items, info, item_info_pairs) + dist = distance(source.data, info, item_info_pairs, len(extra_items)) # Skip matches with ignored penalties. penalties = [key for key, _ in dist] @@ -381,16 +381,12 @@ def _add_candidate( def tag_album( - items, + source: Source, search_artist: str | None = None, search_name: str | None = None, search_ids: list[str] = [], -) -> tuple[str, str, Proposal]: - """Return a tuple of the current artist name, the current album - name, and a `Proposal` containing `AlbumMatch` candidates. - - The artist and album are the most common values of these fields - among `items`. +) -> Proposal: + """Return `Proposal` containing `AlbumMatch` candidates. The `AlbumMatch` objects are generated by searching the metadata backends. By default, the metadata of the items is used for the @@ -404,10 +400,7 @@ def tag_album( candidates. """ # Get current metadata. - likelies, consensus = get_most_common_tags(items) - cur_artist: str = likelies["artist"] - cur_album: str = likelies["album"] - log.debug("Tagging {} - {}", cur_artist, cur_album) + log.debug("Tagging {}", source.desc) # The output result, keys are (data_source, album_id) pairs, values are # AlbumMatch objects. @@ -417,15 +410,13 @@ def tag_album( if search_ids: log.debug("Searching for album IDs: {}", ", ".join(search_ids)) for _info in metadata_plugins.albums_for_ids(search_ids): - _add_candidate(items, candidates, _info) + _add_candidate(source, candidates, _info) # Use existing metadata or text search. else: # Try search based on current ID. - for info in match_by_id( - likelies["mb_albumid"], consensus["mb_albumid"] - ): - _add_candidate(items, candidates, info) + for info in match_by_id(source.id, source.id_consensus): + _add_candidate(source, candidates, info) rec = _recommendation(list(candidates.values())) log.debug("Album ID match recommendation is {}", rec) @@ -435,41 +426,33 @@ def tag_album( # matches. if rec == Recommendation.strong: log.debug("ID match.") - return ( - cur_artist, - cur_album, - Proposal(list(candidates.values()), rec), - ) + return Proposal(list(candidates.values()), rec) # Search terms. if not (search_artist and search_name): # No explicit search terms -- use current metadata. - search_artist, search_name = cur_artist, cur_album + search_artist, search_name = source.artist, source.name log.debug("Search terms: {} - {}", search_artist, search_name) # Is this album likely to be a "various artist" release? - va_likely = ( - (not consensus["artist"]) - or (search_artist.lower() in VA_ARTISTS) - or any(item.comp for item in items) - ) + va_likely = source.va_likely or (search_artist.lower() in VA_ARTISTS) log.debug("Album might be VA: {}", va_likely) # Get the results from the data sources. for matched_candidate in metadata_plugins.candidates( - items, search_artist, search_name, va_likely + source.items, search_artist, search_name, va_likely ): - _add_candidate(items, candidates, matched_candidate) + _add_candidate(source, candidates, matched_candidate) log.debug("Evaluating {} candidates.", len(candidates)) # Sort and get the recommendation. candidates_sorted = _sort_candidates(candidates.values()) rec = _recommendation(candidates_sorted) - return cur_artist, cur_album, Proposal(candidates_sorted, rec) + return Proposal(candidates_sorted, rec) def tag_item( - item, + source: Source, search_artist: str | None = None, search_name: str | None = None, search_ids: list[str] | None = None, @@ -486,8 +469,9 @@ def tag_item( candidates: Candidates[TrackMatch] = {} rec: Recommendation | None = None + item = source.items[0] # First, try matching by the external source ID. - trackids = search_ids or [t for t in [item.mb_trackid] if t] + trackids = search_ids or [t for t in [source.id] if t] if trackids: log.debug("Searching for track IDs: {}", ", ".join(trackids)) for info in metadata_plugins.tracks_for_ids(trackids): @@ -508,8 +492,8 @@ def tag_item( return Proposal([], Recommendation.none) # Search terms. - search_artist = search_artist or item.artist - search_name = search_name or item.title + search_artist = search_artist or source.artist + search_name = search_name or source.name log.debug("Item search terms: {} - {}", search_artist, search_name) # Get and evaluate candidate metadata. diff --git a/beets/autotag/source.py b/beets/autotag/source.py new file mode 100644 index 000000000..4f1b222e2 --- /dev/null +++ b/beets/autotag/source.py @@ -0,0 +1,57 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Literal, NamedTuple + +from beets.util import AttrDict, get_most_common_tags + +if TYPE_CHECKING: + from collections.abc import Sequence + + from beets.library import Item + + +class Source(NamedTuple): + type: Literal["album", "track"] + artist: str + name: str + data: AttrDict[Any] + items: Sequence[Item] + id: str + id_consensus: bool + + @property + def desc(self) -> str: + return f"{self.artist} - {self.name}" + + @property + def va_likely(self) -> bool: + return len({i.artist for i in self.items}) > 1 or any( + i.comp for i in self.items + ) + + @classmethod + def from_items(cls, items: Sequence[Item]) -> Source: + """Create a Source object from a list of items.""" + likelies = get_most_common_tags(items) + return cls( + type="album", + artist=likelies["artist"], + name=likelies["album"], + data=AttrDict(likelies), + items=items, + id=likelies["mb_albumid"], + id_consensus=len({i.mb_albumid for i in items}) == 1, + ) + + @classmethod + def from_item(cls, item: Item) -> Source: + """Create a Source object from an item.""" + return cls( + type="track", + artist=item.artist, + name=item.title, + data=AttrDict(item), + items=[item], + id=item.mb_trackid, + id_consensus=True, + ) diff --git a/beets/importer/tasks.py b/beets/importer/tasks.py index 6b9cda5f6..832c29272 100644 --- a/beets/importer/tasks.py +++ b/beets/importer/tasks.py @@ -7,13 +7,14 @@ import shutil import time from collections import defaultdict from collections.abc import Callable +from functools import cached_property from tempfile import mkdtemp from typing import TYPE_CHECKING, Any, AnyStr import mediafile from beets import config, library, plugins, util -from beets.autotag import AlbumMatch, tag_album, tag_item +from beets.autotag import AlbumMatch, Source, tag_album, tag_item from beets.dbcore.query import PathQuery from beets.util import extension from beets.util.extension import remux_mpeglayer3_wav @@ -239,8 +240,6 @@ class ImportTask(BaseImportTask): album: library.Album # Keep track of the current task item - cur_album: str | None = None - cur_artist: str | None = None candidates: Sequence[AlbumMatch | TrackMatch] | None = None rec: Recommendation | None = None duplicate_action: DuplicateAction | None = None @@ -251,6 +250,10 @@ class ImportTask(BaseImportTask): _upgrade_superseded: list[library.Item] | None = None _upgrade_old_albums: list[int] | None = None + @cached_property + def source(self) -> Source: + return Source.from_items(self.items) + def __init__( self, toppath: util.PathBytes | None, @@ -317,8 +320,7 @@ class ImportTask(BaseImportTask): or APPLY (in which case the data comes from the choice). """ if self.choice_flag in (Action.ASIS, Action.RETAG): - likelies, _ = util.get_most_common_tags(self.items) - return likelies + return self.source.data.copy() if self.choice_flag is Action.APPLY and self.match: return self.match.info.copy() assert False @@ -553,8 +555,8 @@ class ImportTask(BaseImportTask): If User-specified ``search_ids`` list is not empty, the lookup is restricted to only those IDs. """ - self.cur_artist, self.cur_album, (self.candidates, self.rec) = ( - tag_album(self.items, search_ids=search_ids) + self.candidates, self.rec = tag_album( + self.source, search_ids=search_ids ) def find_duplicates(self, lib: library.Library) -> list[library.Album]: @@ -853,6 +855,10 @@ class ImportTask(BaseImportTask): class SingletonImportTask(ImportTask): """ImportTask for a single track that is not associated to an album.""" + @cached_property + def source(self) -> Source: + return Source.from_item(self.item) + def __init__( self, toppath: util.PathBytes | None, item: library.Item ) -> None: @@ -861,19 +867,6 @@ class SingletonImportTask(ImportTask): self.is_album = False self.paths = [item.path] - def chosen_info(self) -> dict[str, Any]: - """Return a dictionary of metadata about the current choice. - May only be called when the choice flag is ASIS or RETAG - (in which case the data comes from the files' current metadata) - or APPLY (in which case the data comes from the choice). - """ - assert self.choice_flag in (Action.ASIS, Action.RETAG, Action.APPLY) - if self.choice_flag in (Action.ASIS, Action.RETAG): - return dict(self.item) - if self.choice_flag is Action.APPLY and self.match: - return self.match.info.copy() - assert False - def imported_items(self) -> list[library.Item]: return [self.item] @@ -900,7 +893,7 @@ class SingletonImportTask(ImportTask): plugins.send("item_imported", lib=lib, item=item) def lookup_candidates(self, search_ids: list[str]) -> None: - self.candidates, self.rec = tag_item(self.item, search_ids=search_ids) + self.candidates, self.rec = tag_item(self.source, search_ids=search_ids) def find_duplicates(self, lib: library.Library) -> list[library.Item]: # type: ignore[override] # Need splitting Singleton and Album tasks into separate classes """Return a list of items from `lib` that have the same artist diff --git a/beets/ui/commands/import_/display.py b/beets/ui/commands/import_/display.py index e28ec01be..370cc2926 100644 --- a/beets/ui/commands/import_/display.py +++ b/beets/ui/commands/import_/display.py @@ -17,7 +17,7 @@ from beets.util.units import human_seconds_short if TYPE_CHECKING: import confuse - from beets.autotag import AlbumMatch, Match, TrackMatch + from beets.autotag import AlbumMatch, Match, Source, TrackMatch from beets.library.models import Item from beets.util.color import ColorName @@ -32,8 +32,8 @@ class ChangeRepresentation: TrackMatch object, accordingly. """ - cur_artist: str - cur_name: str + original_artist: str + original_name: str match: Match @cached_property @@ -99,7 +99,10 @@ class ChangeRepresentation: and artist name. """ # Artist. - artist_l, artist_r = self.cur_artist or "", self.match.info.artist or "" + artist_l, artist_r = ( + self.original_artist, + self.match.info.artist or "", + ) if artist_r == VARIOUS_ARTISTS: # Hide artists for VA releases. artist_l, artist_r = "", "" @@ -112,10 +115,10 @@ class ChangeRepresentation: else: ui.print_(f"{self.indent_detail}*", "Artist:", artist_r) - if self.cur_name: + if self.original_name: type_ = self.match.type - name_l, name_r = self.cur_name or "", self.match.info.name - if self.cur_name != self.match.info.name != VARIOUS_ARTISTS: + name_l, name_r = self.original_name, self.match.info.name + if self.original_name != self.match.info.name != VARIOUS_ARTISTS: name_l, name_r = colordiff(name_l, name_r) left = Side(f"{self.changed_prefix} {type_}: ", name_l, "") right = Side("", name_r, "") @@ -361,12 +364,12 @@ class TrackChange(ChangeRepresentation): match: TrackMatch -def show_change(cur_artist: str, cur_album: str, match: AlbumMatch) -> None: +def show_change(source: Source, match: AlbumMatch) -> None: """Print out a representation of the changes that will be made if an album's tags are changed according to `match`, which must be an AlbumMatch object. """ - change = AlbumChange(cur_artist, cur_album, match) + change = AlbumChange(source.artist, source.name, match) # Print the match header. change.show_match_header() @@ -378,11 +381,11 @@ def show_change(cur_artist: str, cur_album: str, match: AlbumMatch) -> None: change.show_match_tracks() -def show_item_change(item: Item, match: TrackMatch) -> None: - """Print out the change that would occur by tagging `item` with the +def show_item_change(source: Source, match: TrackMatch) -> None: + """Print out the change that would occur by tagging a track with the metadata from `match`, a TrackMatch object. """ - change = TrackChange(item.artist, item.title, match) + change = TrackChange(source.artist, source.name, match) # Print the match header. change.show_match_header() # Print the match details. diff --git a/beets/ui/commands/import_/session.py b/beets/ui/commands/import_/session.py index 4e2fe48ad..354469a27 100644 --- a/beets/ui/commands/import_/session.py +++ b/beets/ui/commands/import_/session.py @@ -13,7 +13,7 @@ from beets.autotag import ( tag_album, tag_item, ) -from beets.importer import DuplicateAction +from beets.importer import DuplicateAction, SingletonImportTask from beets.library import Album from beets.util import PromptChoice, displayable_path from beets.util.color import colorize @@ -22,6 +22,8 @@ from beets.util.units import human_bytes, human_seconds_short from .display import show_change, show_item_change if TYPE_CHECKING: + from beets.autotag import Source + from beets.importer import ImportSession, ImportTask from beets.library import AnyLibModel, Item # Global logger. @@ -64,7 +66,7 @@ class TerminalImportSession(importer.ImportSession): action = _summary_judgment(task.rec) if action == importer.Action.APPLY: match = task.candidates[0] - show_change(task.cur_artist, task.cur_album, match) + show_change(task.source, match) return match if action is not None: return action @@ -77,13 +79,7 @@ class TerminalImportSession(importer.ImportSession): # `PromptChoice`. choices = self._get_choices(task) choice = choose_candidate( - task.candidates, - False, - task.rec, - task.cur_artist, - task.cur_album, - itemcount=len(task.items), - choices=choices, + task.candidates, task.rec, task.source, choices=choices ) # Basic choices that require no more action here. @@ -121,7 +117,7 @@ class TerminalImportSession(importer.ImportSession): action = _summary_judgment(task.rec) if action == importer.Action.APPLY: match = candidates[0] - show_item_change(task.item, match) + show_item_change(task.source, match) return match if action is not None: return action @@ -130,7 +126,7 @@ class TerminalImportSession(importer.ImportSession): # Ask for a choice. choices = self._get_choices(task) choice = choose_candidate( - candidates, True, rec, item=task.item, choices=choices + candidates, rec, task.source, choices=choices ) if choice in (importer.Action.SKIP, importer.Action.ASIS): @@ -164,10 +160,7 @@ class TerminalImportSession(importer.ImportSession): that's already in the library. """ is_album = task.is_album - log.warning( - "This {} is already in the library!", - ("album" if is_album else "item"), - ) + log.warning("This {.source.type} is already in the library!", task) if config["import"]["quiet"]: # In quiet mode, don't prompt -- just skip. @@ -360,23 +353,14 @@ def _summary_judgment(rec: Recommendation) -> importer.Action | None: return action -def choose_candidate( - candidates, - singleton, - rec, - cur_artist=None, - cur_album=None, - item=None, - itemcount=None, - choices=[], -): - """Given a sorted list of candidates, ask the user for a selection - of which candidate to use. Applies to both full albums and - singletons (tracks). Candidates are either AlbumMatch or TrackMatch - objects depending on `singleton`. for albums, `cur_artist`, - `cur_album`, and `itemcount` must be provided. For singletons, - `item` must be provided. +def choose_candidate(candidates, rec, source: Source, choices=[]): + """Ask the user for a selection of which candidate to use. + Applies to both full albums and singletons (tracks). Candidates are either + AlbumMatch or TrackMatch objects. + + `rec` is the autotagging recommendation for the candidates. + `source` is the Source object describing the item or album being imported. `choices` is a list of `PromptChoice`s to be used in each prompt. Returns one of the following: @@ -384,23 +368,18 @@ def choose_candidate( * a candidate (an AlbumMatch/TrackMatch object) * a chosen `PromptChoice` from `choices` """ - # Sanity check. - if singleton: - assert item is not None - else: - assert cur_artist is not None - assert cur_album is not None - # Build helper variables for the prompt choices. choice_opts = tuple(c.long for c in choices) choice_actions = {c.short: c for c in choices} # Zero candidates. if not candidates: - if singleton: + if source.type == "track": ui.print_("No matching recordings found.") else: - ui.print_(f"No matching release found for {itemcount} tracks.") + ui.print_( + f"No matching release found for {len(source.items)} tracks." + ) ui.print_( "For help, see: " "https://beets.readthedocs.org/en/latest/faq.html#nomatch" @@ -423,11 +402,7 @@ def choose_candidate( if not bypass_candidates: # Display list of candidates. ui.print_("") - ui.print_( - f"Finding tags for {'track' if singleton else 'album'} " - f'"{item.artist if singleton else cur_artist} -' - f' {item.title if singleton else cur_album}".' - ) + ui.print_(f'Finding tags for {source.type} "{source.desc}".') ui.print_(" Candidates:") for i, match in enumerate(candidates): @@ -471,10 +446,10 @@ def choose_candidate( bypass_candidates = False # Show what we're about to do. - if singleton: - show_item_change(item, match) + if source.type == "track": + show_item_change(source, match) else: - show_change(cur_artist, cur_album, match) + show_change(source, match) # Exact match => tag automatically if we're not in timid mode. if rec == Recommendation.strong and not config["import"]["timid"]: @@ -500,33 +475,29 @@ def choose_candidate( return choice_actions[sel] -def manual_search(session, task): +def manual_search(session: ImportSession, task: ImportTask) -> Proposal: """Get a new `Proposal` using manual search criteria. Input either an artist and album (for full albums) or artist and track name (for singletons) for manual search. """ artist = ui.input_("Artist:").strip() - name = ui.input_("Album:" if task.is_album else "Track:").strip() + name = ui.input_(f"{task.source.type.capitalize()}:").strip() - if task.is_album: - _, _, prop = tag_album(task.items, artist, name) - return prop - return tag_item(task.item, artist, name) + method = tag_item if isinstance(task, SingletonImportTask) else tag_album + return method(task.source, artist, name) -def manual_id(session, task): +def manual_id(session: ImportSession, task: ImportTask) -> Proposal: """Get a new `Proposal` using a manually-entered ID. Input an ID, either for an album ("release") or a track ("recording"). """ - prompt = f"Enter {'release' if task.is_album else 'recording'} ID:" + prompt = f"Enter {task.source.type} ID:" search_id = ui.input_(prompt).strip() - if task.is_album: - _, _, prop = tag_album(task.items, search_ids=search_id.split()) - return prop - return tag_item(task.item, search_ids=search_id.split()) + method = tag_item if isinstance(task, SingletonImportTask) else tag_album + return method(task.source, search_ids=search_id.split()) def abort_action(session, task): diff --git a/beets/util/__init__.py b/beets/util/__init__.py index 12a638778..e1f104b28 100644 --- a/beets/util/__init__.py +++ b/beets/util/__init__.py @@ -18,8 +18,9 @@ import unicodedata from collections import Counter from collections.abc import Sequence from contextlib import suppress +from copy import deepcopy from enum import Enum -from functools import cache +from functools import cache, cached_property from importlib import import_module from multiprocessing.pool import ThreadPool from pathlib import Path @@ -36,6 +37,7 @@ from typing import ( cast, ) +from typing_extensions import Self from unidecode import unidecode import beets @@ -809,18 +811,11 @@ def plurality(objs: Iterable[T]) -> tuple[T, int]: return c.most_common(1)[0] -def get_most_common_tags( - items: Sequence[Item], -) -> tuple[dict[str, Any], dict[str, Any]]: - """Extract the likely current metadata for an album given a list of its - items. Return two dictionaries: - - The most common value for each field. - - Whether each field's value was unanimous (values are booleans). - """ +def get_most_common_tags(items: Sequence[Item]) -> dict[str, Any]: + """Extract the most common value for each field given a list of items.""" assert items # Must be nonempty. likelies = {} - consensus = {} fields = [ "artist", "album", @@ -838,14 +833,13 @@ def get_most_common_tags( ] for field in fields: values = [item.get(field) for item in items if item] - likelies[field], freq = plurality(values) - consensus[field] = freq == len(values) + likelies[field], _ = plurality(values) # If there's an album artist consensus, use this for the artist. - if consensus["albumartist"] and likelies["albumartist"]: + if len({i.albumartist for i in items}) == 1 and likelies["albumartist"]: likelies["artist"] = likelies["albumartist"] - return likelies, consensus + return likelies # stdout and stderr as bytes diff --git a/beetsplug/bench.py b/beetsplug/bench.py index 3beca7928..8553357a5 100644 --- a/beetsplug/bench.py +++ b/beetsplug/bench.py @@ -4,7 +4,7 @@ import cProfile import timeit from beets import importer, plugins, ui -from beets.autotag import tag_album +from beets.autotag import Source, tag_album from beets.plugins import BeetsPlugin from beets.util.pathformats import PF_KEY_DEFAULT from beetsplug._utils import vfs @@ -63,7 +63,8 @@ def match_benchmark(lib, prof, query=None, album_id=None): # Run the match. def _run_match(): - tag_album(items, search_ids=[album_id]) + source = Source.from_items(items) + tag_album(source, search_ids=[album_id]) if prof: cProfile.runctx( diff --git a/beetsplug/ihate.py b/beetsplug/ihate.py index b0da0661d..96aefe03c 100644 --- a/beetsplug/ihate.py +++ b/beetsplug/ihate.py @@ -8,15 +8,6 @@ __author__ = "baobab@heresiarch.info" __version__ = "2.0" -def summary(task): - """Given an ImportTask, produce a short string identifying the - object. - """ - if task.is_album: - return f"{task.cur_artist} - {task.cur_album}" - return f"{task.item.artist} - {task.item.title}" - - class IHatePlugin(BeetsPlugin): def __init__(self): super().__init__() @@ -48,10 +39,10 @@ class IHatePlugin(BeetsPlugin): self._log.debug("processing your hate") if self.do_i_hate_this(task, skip_queries): task.choice_flag = Action.SKIP - self._log.info("skipped: {}", summary(task)) + self._log.info("skipped: {}", task.source.desc) return if self.do_i_hate_this(task, warn_queries): - self._log.info("you may hate this: {}", summary(task)) + self._log.info("you may hate this: {}", task.source.desc) else: self._log.debug("nothing to do") else: diff --git a/beetsplug/mbpseudo.py b/beetsplug/mbpseudo.py index 9581c788c..a468b9205 100644 --- a/beetsplug/mbpseudo.py +++ b/beetsplug/mbpseudo.py @@ -11,7 +11,7 @@ import mediafile from typing_extensions import override from beets import config -from beets.autotag import AlbumInfo, assign_items, distance +from beets.autotag import AlbumInfo, Source, assign_items, distance from beets.plugins import find_plugins from beets.util.id_extractors import extract_release_id from beetsplug.musicbrainz import ( @@ -303,7 +303,12 @@ class PseudoAlbumInfo(AlbumInfo): def _compute_distance(self, items: Sequence[Item]) -> Distance: mapping, _, _ = assign_items(items, self.tracks) - return distance(items, self, mapping) + return distance( + Source.from_items(items).data, + self, + mapping, + len(items) - len(mapping), + ) def use_pseudo_as_ref(self): self.__dict__["_pseudo_source"] = True diff --git a/test/autotag/test_distance.py b/test/autotag/test_distance.py index 03c2513c7..16da2f483 100644 --- a/test/autotag/test_distance.py +++ b/test/autotag/test_distance.py @@ -5,6 +5,7 @@ import pytest from beets.autotag import ( AlbumInfo, Distance, + Source, TrackInfo, distance, string_dist, @@ -187,7 +188,12 @@ class TestAlbumDistance: @pytest.fixture def get_dist(self, items): def inner(info: AlbumInfo): - return distance(items, info, list(zip(items, info.tracks))) + return distance( + Source.from_items(items).data, + info, + list(zip(items, info.tracks)), + len(items) - len(info.tracks), + ) return inner diff --git a/test/autotag/test_match.py b/test/autotag/test_match.py index 302df212f..402db620b 100644 --- a/test/autotag/test_match.py +++ b/test/autotag/test_match.py @@ -5,6 +5,7 @@ import pytest from beets import metadata_plugins from beets.autotag import ( AlbumInfo, + Source, TrackInfo, assign_items, tag_album, @@ -167,21 +168,29 @@ class TestTagMultipleDataSources: assert set(sources) == {"Discogs", "Deezer"} def test_search_album_ids(self, shared_album_id): - _, _, proposal = tag_album([Item()], search_ids=[shared_album_id]) + source = Source.from_items([Item()]) + + proposal = tag_album(source, search_ids=[shared_album_id]) self.check_proposal(proposal) def test_search_album_current_id(self, shared_album_id): - _, _, proposal = tag_album([Item(mb_albumid=shared_album_id)]) + source = Source.from_items([Item(mb_albumid=shared_album_id)]) + + proposal = tag_album(source) self.check_proposal(proposal) def test_search_track_ids(self, shared_track_id): - proposal = tag_item(Item(), search_ids=[shared_track_id]) + source = Source.from_item(Item()) + + proposal = tag_item(source, search_ids=[shared_track_id]) self.check_proposal(proposal) def test_search_track_current_id(self, shared_track_id): - proposal = tag_item(Item(mb_trackid=shared_track_id)) + source = Source.from_item(Item(mb_trackid=shared_track_id)) + + proposal = tag_item(source) self.check_proposal(proposal) diff --git a/test/test_util.py b/test/test_util.py index dbde9ef24..64b0f8497 100644 --- a/test/test_util.py +++ b/test/test_util.py @@ -230,7 +230,7 @@ class TestPlurality: Item(albumartist="aartist", label="label 3", album="another album"), ] - likelies, consensus = util.get_most_common_tags(items) + likelies = util.get_most_common_tags(items) assert likelies["albumartist"] == "aartist" assert likelies["album"] == "album" @@ -239,11 +239,6 @@ class TestPlurality: assert likelies["label"] == "label 1" assert likelies["year"] == 0 - assert consensus["year"] - assert consensus["albumartist"] - assert not consensus["album"] - assert not consensus["label"] - class HelperTest(unittest.TestCase): def test_ancestry_works_on_file(self): diff --git a/test/ui/commands/test_import.py b/test/ui/commands/test_import.py index dabf8a1a6..5f0a143b6 100644 --- a/test/ui/commands/test_import.py +++ b/test/ui/commands/test_import.py @@ -5,7 +5,7 @@ from unittest.mock import Mock, patch import pytest from beets import config, library -from beets.autotag import AlbumInfo, AlbumMatch, TrackInfo, distance +from beets.autotag import AlbumInfo, AlbumMatch, Source, TrackInfo, distance from beets.exceptions import UserError from beets.test import _common from beets.test.helper import BeetsTestCase, IOMixin @@ -60,11 +60,17 @@ class ShowChangeTestCase(IOMixin, BeetsTestCase): def _show_change(self): """Return an unicode string representing the changes""" long_name = f"a{' very' * 10} long name" + album = "another album" + albumartist = f"another artist with {long_name}" + + def make_item(**kwargs): + return _common.item(album=album, albumartist=albumartist, **kwargs) + items = [ - _common.item(track=1, title="first title"), - _common.item(track=2, title="", path=b"/path/to/file.mp3"), - _common.item(track=3, title="caf\xe9"), - _common.item(track=4, title=f"title with {long_name}"), + make_item(track=1, title="first title"), + make_item(track=2, title="", path=b"/path/to/file.mp3"), + make_item(track=3, title="caf\xe9"), + make_item(track=4, title=f"title with {long_name}"), ] info = AlbumInfo( album="caf\xe9", @@ -81,12 +87,13 @@ class ShowChangeTestCase(IOMixin, BeetsTestCase): item_info_pairs = list(zip(items, info.tracks)) self.config["ui"]["color"] = False self.config["import"]["detail"] = True - change_dist = distance(items, info, item_info_pairs) + source = Source.from_items(items) + change_dist = distance( + source.data, info, item_info_pairs, len(items) - len(info.tracks) + ) change_dist._penalties = {"album": [0.1], "artist": [0.1]} show_change( - f"another artist with {long_name}", - "another album", - AlbumMatch(change_dist, info, dict(item_info_pairs)), + source, AlbumMatch(change_dist, info, dict(item_info_pairs)) ) return self.io.getoutput() From 649135c0f5728660e2bd2c0b20e9764c07c63735 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=A0ar=C5=ABnas=20Nejus?= Date: Wed, 3 Jun 2026 19:19:55 +0100 Subject: [PATCH 04/23] Ignore Match move commit --- .git-blame-ignore-revs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs index 5bfd34f5e..a954074c3 100644 --- a/.git-blame-ignore-revs +++ b/.git-blame-ignore-revs @@ -191,6 +191,8 @@ adfb73b66dba0fc799880af176ef6f9ac0a7ee68 6493d4dd018e08eb5d16d5381ebff47deea98bb1 # Import everything from parent beets.autotag 29580d2f00eb02f1ce77ebe3e1435804f7252ba1 +# Move Match classes to beets.autotag.match +fd46e5b7738a3e11ef01e6fa8dc6fb8e0c7c82ec # Add setup fixture to TestHelper 7bad226c33c2d48b5102cff213c67f16eeb09a7b # Fix mbcollection tests From 4e2e70f2fbaadd3f1fcaea0acbf85820a72287f5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=A0ar=C5=ABnas=20Nejus?= Date: Fri, 17 Jul 2026 09:55:47 +0100 Subject: [PATCH 05/23] Define a container for Likelies --- beets/autotag/distance.py | 6 +++--- beets/autotag/source.py | 16 ++++++++-------- beets/util/__init__.py | 22 ++++++++++++++++++++-- 3 files changed, 31 insertions(+), 13 deletions(-) diff --git a/beets/autotag/distance.py b/beets/autotag/distance.py index 03c4afe53..7c762de0c 100644 --- a/beets/autotag/distance.py +++ b/beets/autotag/distance.py @@ -16,7 +16,7 @@ if TYPE_CHECKING: from collections.abc import Iterator, KeysView, Sequence from beets.library import Item - from beets.util import AttrDict + from beets.util import Likelies from beets.util.color import ColorName from .hooks import AlbumInfo, TrackInfo @@ -428,7 +428,7 @@ def track_distance( def distance( - original: AttrDict[Any], + original: Likelies, album_info: AlbumInfo, item_info_pairs: list[tuple[Item, TrackInfo]], unmatched_count: int, @@ -436,7 +436,7 @@ def distance( """Determine how "significant" an album metadata change would be. Returns a Distance object. - `original` is an AttrDict with the original album metadata. + `original` contains original album metadata. `album_info` is an AlbumInfo object reflecting the album to be compared. `item_info_pairs` is a list with matched (Item, TrackInfo) pairs. `unmatched_count` is the number of unmatched tracks on the release. diff --git a/beets/autotag/source.py b/beets/autotag/source.py index 4f1b222e2..08cd1c186 100644 --- a/beets/autotag/source.py +++ b/beets/autotag/source.py @@ -1,8 +1,8 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Any, Literal, NamedTuple +from typing import TYPE_CHECKING, Literal, NamedTuple -from beets.util import AttrDict, get_most_common_tags +from beets.util import Likelies, get_most_common_tags if TYPE_CHECKING: from collections.abc import Sequence @@ -14,7 +14,7 @@ class Source(NamedTuple): type: Literal["album", "track"] artist: str name: str - data: AttrDict[Any] + data: Likelies items: Sequence[Item] id: str id_consensus: bool @@ -35,11 +35,11 @@ class Source(NamedTuple): likelies = get_most_common_tags(items) return cls( type="album", - artist=likelies["artist"], - name=likelies["album"], - data=AttrDict(likelies), + artist=likelies.artist, + name=likelies.album, + data=likelies, items=items, - id=likelies["mb_albumid"], + id=likelies.mb_albumid, id_consensus=len({i.mb_albumid for i in items}) == 1, ) @@ -50,7 +50,7 @@ class Source(NamedTuple): type="track", artist=item.artist, name=item.title, - data=AttrDict(item), + data=Likelies(item), items=[item], id=item.mb_trackid, id_consensus=True, diff --git a/beets/util/__init__.py b/beets/util/__init__.py index e1f104b28..159fbc3fd 100644 --- a/beets/util/__init__.py +++ b/beets/util/__init__.py @@ -811,7 +811,7 @@ def plurality(objs: Iterable[T]) -> tuple[T, int]: return c.most_common(1)[0] -def get_most_common_tags(items: Sequence[Item]) -> dict[str, Any]: +def get_most_common_tags(items: Sequence[Item]) -> Likelies: """Extract the most common value for each field given a list of items.""" assert items # Must be nonempty. @@ -839,7 +839,7 @@ def get_most_common_tags(items: Sequence[Item]) -> dict[str, Any]: if len({i.albumartist for i in items}) == 1 and likelies["albumartist"]: likelies["artist"] = likelies["albumartist"] - return likelies + return Likelies(likelies) # stdout and stderr as bytes @@ -1245,3 +1245,21 @@ class AttrDict(dict[str, T]): def __hash__(self) -> int: # type: ignore[override] return id(self) + + +class Likelies(AttrDict[Any]): + """A dictionary of the most common tags in a list of items.""" + + artist: str + album: str + albumartist: str + year: int + disctotal: int + mb_albumid: str + label: str + barcode: str + catalognum: str + country: str + media: str + albumdisambig: str + data_source: str From c19b6b42d82651a0f03b35c899007fb3794e7cfb Mon Sep 17 00:00:00 2001 From: Alok Saboo Date: Wed, 5 Aug 2026 08:47:26 -0400 Subject: [PATCH 06/23] add interactive upgrade option --- beets/importer/actions.py | 8 +------- beets/test/helper.py | 11 +++++++++++ docs/changelog.rst | 4 +++- docs/guides/tagger.rst | 9 +++++++-- docs/reference/config.rst | 4 ++-- test/test_importer.py | 10 ++++++++++ test/ui/test_ui_importer.py | 10 ++++++++++ 7 files changed, 44 insertions(+), 12 deletions(-) diff --git a/beets/importer/actions.py b/beets/importer/actions.py index c184e9330..1a4b07a69 100644 --- a/beets/importer/actions.py +++ b/beets/importer/actions.py @@ -34,10 +34,7 @@ class DuplicateAction(str, Enum): @classmethod def strict_options(cls) -> list[str]: - return [ - d.text - for d in set(cls) - {DuplicateAction.ASK, DuplicateAction.UPGRADE} - ] + return [d.text for d in cls if d is not DuplicateAction.ASK] @classmethod def choices(cls) -> dict[str, str]: @@ -48,7 +45,4 @@ class DuplicateAction(str, Enum): REMOVE = "r", "Remove old" KEEP = "k", "Keep all" ASK = "a", "Ask" - # Config-only: not offered in the interactive `ask` prompt (see - # `strict_options`). Resolved to SKIP or applied per-track by - # `beets.importer.stages._resolve_duplicates`. UPGRADE = "u", "Upgrade" diff --git a/beets/test/helper.py b/beets/test/helper.py index 44a0ab1b9..ffd623eb8 100644 --- a/beets/test/helper.py +++ b/beets/test/helper.py @@ -688,6 +688,7 @@ class TerminalImportSessionFixture(TerminalImportSession): self.io = kwargs.pop("io") super().__init__(*args, **kwargs) self._choices = [] + self._duplicate_actions = [] default_choice = importer.Action.APPLY @@ -697,6 +698,16 @@ class TerminalImportSessionFixture(TerminalImportSession): def clear_choices(self) -> None: self._choices = [] + def add_duplicate_action(self, action: importer.DuplicateAction) -> None: + self._duplicate_actions.append(action) + + def _get_duplicate_action_from_user( + self, task: importer.ImportTask, found_duplicates: list[Any] + ) -> str: + if self._duplicate_actions: + self.io.addinput(self._duplicate_actions.pop(0).value) + return super()._get_duplicate_action_from_user(task, found_duplicates) + def choose_match( self, task: importer.ImportTask ) -> AlbumMatch | importer.Action: diff --git a/docs/changelog.rst b/docs/changelog.rst index 0983c9b08..1bea07a6d 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -14,7 +14,9 @@ New features - :ref:`duplicate_action`: Add an ``upgrade`` option that replaces individual duplicate tracks only if the new copy has a higher bitrate, adds any genuinely - new tracks, and keeps the album together rather than splitting it. :bug:`4471` + new tracks, and keeps the album together rather than splitting it. The option + is available both through configuration and from the interactive duplicate + prompt. :bug:`4471` Bug fixes ~~~~~~~~~ diff --git a/docs/guides/tagger.rst b/docs/guides/tagger.rst index 832437807..f7a507a7f 100644 --- a/docs/guides/tagger.rst +++ b/docs/guides/tagger.rst @@ -232,10 +232,10 @@ one you're importing, you may see a prompt like this: :: This album is already in the library! - [S]kip new, Keep all, Remove old, Merge all? + [S]kip new, Merge all, Remove old, Keep all, Upgrade? Beets wants to keep you safe from duplicates, which can be a real pain, so you -have four choices in this situation. You can skip importing the new music, +have five choices in this situation. You can skip importing the new music, choosing to keep the stuff you already have in your library; you can keep both the old and the new music; you can remove the existing music and choose the new stuff; or you can merge all the new and old tracks into a single album. If you @@ -249,6 +249,11 @@ that's missing some tracks and then want to import the remaining songs. The importer will ask you the same questions as it would if you were importing all tracks at once. +If you choose "upgrade", beets compares each new track with its existing +counterpart and replaces the old track only when the new one has a higher +bitrate. New tracks without an existing counterpart are still added, while the +rest of the existing album remains untouched. + If you choose to keep two identically-named albums, beets can avoid storing both in the same directory. See :ref:`aunique` for details. diff --git a/docs/reference/config.rst b/docs/reference/config.rst index 6f1a4e1fb..944d2d991 100644 --- a/docs/reference/config.rst +++ b/docs/reference/config.rst @@ -847,8 +847,8 @@ that same album rather than a new one. If the import matches more than one existing album (e.g. two differently-encoded copies of the same release already in the library), only the album it overlaps with the most is upgraded; every other candidate album is left completely untouched, since a track can only ever -be added to one album. Unlike the other options, "upgrade" is config-only and is -not offered when ``duplicate_action`` is ``ask``. +be added to one album. When ``duplicate_action`` is ``ask``, "upgrade" is one of +the available interactive choices. .. _duplicate_verbose_prompt: diff --git a/test/test_importer.py b/test/test_importer.py index a82490056..772353579 100644 --- a/test/test_importer.py +++ b/test/test_importer.py @@ -1318,6 +1318,16 @@ def bitrate_overrides(bitrates_by_title): DUP_KEYS = ["artist", "title"] +def test_duplicate_action_prompt_options(): + assert importer.DuplicateAction.strict_options() == [ + "Skip new", + "Merge all", + "Remove old", + "Keep all", + "Upgrade", + ] + + class ResolveUpgradeTest(unittest.TestCase): """Unit tests for `resolve_upgrade`, the per-track decision algorithm behind `duplicate_action: upgrade`. diff --git a/test/ui/test_ui_importer.py b/test/ui/test_ui_importer.py index da3b20a75..77904b596 100644 --- a/test/ui/test_ui_importer.py +++ b/test/ui/test_ui_importer.py @@ -4,6 +4,7 @@ test_importer module. But here the test importer inherits from ``TerminalImportSession``. So we test this class, too. """ +from beets import importer from beets.test.helper import TerminalImportMixin from test import test_importer @@ -54,3 +55,12 @@ class GlobalGroupAlbumsImportTest( TerminalImportMixin, test_importer.GlobalGroupAlbumsImportTest ): pass + + +class TestImportDuplicateAlbumUpgrade( + TerminalImportMixin, test_importer.TestImportDuplicateAlbumUpgrade +): + def setup_beets(self): + super().setup_beets() + self.config["import"]["duplicate_action"] = "ask" + self.importer.add_duplicate_action(importer.DuplicateAction.UPGRADE) From 1ddc95f7a66ad31ac6dc43fcb265b6765691889d Mon Sep 17 00:00:00 2001 From: Alok Saboo Date: Wed, 5 Aug 2026 09:05:51 -0400 Subject: [PATCH 07/23] address copilot comments --- beets/test/helper.py | 1 + docs/reference/config.rst | 2 +- test/ui/test_ui_importer.py | 2 ++ 3 files changed, 4 insertions(+), 1 deletion(-) diff --git a/beets/test/helper.py b/beets/test/helper.py index 9f72bad00..377b0ea9f 100644 --- a/beets/test/helper.py +++ b/beets/test/helper.py @@ -693,6 +693,7 @@ class TerminalImportSessionFixture(TerminalImportSession): def clear_choices(self) -> None: self._choices = [] + self._duplicate_actions = [] def add_duplicate_action(self, action: importer.DuplicateAction) -> None: self._duplicate_actions.append(action) diff --git a/docs/reference/config.rst b/docs/reference/config.rst index 944d2d991..fe046a100 100644 --- a/docs/reference/config.rst +++ b/docs/reference/config.rst @@ -868,7 +868,7 @@ is applied, which would, considering the default, look like this: New: 2 items, MP3, 320kbps, 7:18, 17.1 MiB Artist Name - Album Name - First Track Title Artist Name - Album Name - Second Track Title - [S]kip new, Keep all, Remove old, Merge all? + [S]kip new, Merge all, Remove old, Keep all, Upgrade? Default: ``no``. diff --git a/test/ui/test_ui_importer.py b/test/ui/test_ui_importer.py index 77904b596..bfe3c6b90 100644 --- a/test/ui/test_ui_importer.py +++ b/test/ui/test_ui_importer.py @@ -63,4 +63,6 @@ class TestImportDuplicateAlbumUpgrade( def setup_beets(self): super().setup_beets() self.config["import"]["duplicate_action"] = "ask" + self.importer.add_duplicate_action(importer.DuplicateAction.KEEP) + self.importer.clear_choices() self.importer.add_duplicate_action(importer.DuplicateAction.UPGRADE) From e9d6c996baae1b393a0d5afd54d9e93acea87755 Mon Sep 17 00:00:00 2001 From: Alok Saboo Date: Wed, 5 Aug 2026 14:46:04 -0400 Subject: [PATCH 08/23] remove dead code --- test/ui/test_ui_importer.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/test/ui/test_ui_importer.py b/test/ui/test_ui_importer.py index bfe3c6b90..77904b596 100644 --- a/test/ui/test_ui_importer.py +++ b/test/ui/test_ui_importer.py @@ -63,6 +63,4 @@ class TestImportDuplicateAlbumUpgrade( def setup_beets(self): super().setup_beets() self.config["import"]["duplicate_action"] = "ask" - self.importer.add_duplicate_action(importer.DuplicateAction.KEEP) - self.importer.clear_choices() self.importer.add_duplicate_action(importer.DuplicateAction.UPGRADE) From 58bd7ede4cc2eebe7c0d8980c413137e0823d69a Mon Sep 17 00:00:00 2001 From: Sanjay Santhanam <51058514+Sanjays2402@users.noreply.github.com> Date: Fri, 24 Jul 2026 17:41:52 -0700 Subject: [PATCH 09/23] fix: skip metadata source search when query and filters are empty Items with no artist or title tags produce a search with an empty query and no filters. The request was still sent to the metadata source API, and MusicBrainz answers it with a 400 Bad Request, which was logged with a traceback once per affected file during an import. Return no candidates instead of issuing a request that cannot match anything. --- beets/metadata_plugins.py | 7 +++++++ docs/changelog.rst | 4 ++++ test/test_metadata_plugins.py | 8 ++++++++ 3 files changed, 19 insertions(+) diff --git a/beets/metadata_plugins.py b/beets/metadata_plugins.py index e116d1d52..6d285fe80 100644 --- a/beets/metadata_plugins.py +++ b/beets/metadata_plugins.py @@ -412,6 +412,13 @@ class SearchApiMetadataSourcePlugin( if self.config["search_query_ascii"].get(): query = unidecode.unidecode(query) + if not query and not filters: + # Items without usable metadata produce an empty search request, + # which APIs reject (e.g. MusicBrainz answers with a 400). Report + # no candidates instead of making a doomed request. + self._log.debug("Skipping search with empty query and filters") + return () + limit = self.config["search_limit"].get(int) params = SearchParams(query_type, query, filters, limit) diff --git a/docs/changelog.rst b/docs/changelog.rst index 4d98aa214..2f8f5618d 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -156,6 +156,10 @@ Bug fixes valid date/time string" error instead of crashing with an uncaught ``KeyError``. A ``|`` was being accepted as a relative-date unit due to a regular expression character-class typo. +- Metadata source searches with neither a query nor any filters (for example + items with no artist and title tags) no longer hit the API, which rejected + them with an error such as MusicBrainz' ``400 Bad Request``. Such searches + now report no candidates instead. :bug:`6862` .. For plugin developers diff --git a/test/test_metadata_plugins.py b/test/test_metadata_plugins.py index 8f57ddbd9..4d677989f 100644 --- a/test/test_metadata_plugins.py +++ b/test/test_metadata_plugins.py @@ -127,6 +127,14 @@ class TestSearchApiMetadataSourcePlugin(PluginMixin): with pytest.raises(ValueError, match="Search failure"): search_plugin._search_api("track", "query", {}) + def test_search_api_skips_request_without_query_and_filters( + self, config, search_plugin + ): + """Empty searches are rejected by APIs, so do not send them.""" + config["raise_on_error"] = True + + assert search_plugin._search_api("track", "", {}) == () + def test_albums_for_ids_calls_each_plugin_once(monkeypatch): start_workers = Event() From 6fff0532d6192841abccb2c9662896692f457c54 Mon Sep 17 00:00:00 2001 From: Sanjay Santhanam <51058514+Sanjays2402@users.noreply.github.com> Date: Thu, 30 Jul 2026 05:38:48 -0700 Subject: [PATCH 10/23] docs: scope changelog entry to SearchApiMetadataSourcePlugin plugins --- docs/changelog.rst | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 2f8f5618d..da23937d9 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -156,10 +156,12 @@ Bug fixes valid date/time string" error instead of crashing with an uncaught ``KeyError``. A ``|`` was being accepted as a relative-date unit due to a regular expression character-class typo. -- Metadata source searches with neither a query nor any filters (for example - items with no artist and title tags) no longer hit the API, which rejected - them with an error such as MusicBrainz' ``400 Bad Request``. Such searches - now report no candidates instead. :bug:`6862` +- Plugins built on ``SearchApiMetadataSourcePlugin`` (:doc:`plugins/musicbrainz`, + :doc:`plugins/spotify`, :doc:`plugins/deezer` and :doc:`plugins/discogs`) no + longer send a search request when both the query text and the filters are + empty, as happens for items with no artist and title tags. Such a request + cannot match anything and MusicBrainz rejects it with ``400 Bad Request``; + these searches now report no candidates instead. :bug:`6862` .. For plugin developers From 0ab54bd44efb5c687ea7d4cf430440b276db93e0 Mon Sep 17 00:00:00 2001 From: Sanjay Santhanam <51058514+Sanjays2402@users.noreply.github.com> Date: Sun, 2 Aug 2026 02:02:42 -0700 Subject: [PATCH 11/23] Simplify empty-search comment and shorten changelog entry --- beets/metadata_plugins.py | 3 --- docs/changelog.rst | 4 +--- 2 files changed, 1 insertion(+), 6 deletions(-) diff --git a/beets/metadata_plugins.py b/beets/metadata_plugins.py index 6d285fe80..124d4ab4e 100644 --- a/beets/metadata_plugins.py +++ b/beets/metadata_plugins.py @@ -413,9 +413,6 @@ class SearchApiMetadataSourcePlugin( query = unidecode.unidecode(query) if not query and not filters: - # Items without usable metadata produce an empty search request, - # which APIs reject (e.g. MusicBrainz answers with a 400). Report - # no candidates instead of making a doomed request. self._log.debug("Skipping search with empty query and filters") return () diff --git a/docs/changelog.rst b/docs/changelog.rst index da23937d9..0a9183203 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -159,9 +159,7 @@ Bug fixes - Plugins built on ``SearchApiMetadataSourcePlugin`` (:doc:`plugins/musicbrainz`, :doc:`plugins/spotify`, :doc:`plugins/deezer` and :doc:`plugins/discogs`) no longer send a search request when both the query text and the filters are - empty, as happens for items with no artist and title tags. Such a request - cannot match anything and MusicBrainz rejects it with ``400 Bad Request``; - these searches now report no candidates instead. :bug:`6862` + empty. :bug:`6862` .. For plugin developers From 4596bd21d241070537da2a994950600a8c4366b5 Mon Sep 17 00:00:00 2001 From: Sanjay Santhanam <51058514+Sanjays2402@users.noreply.github.com> Date: Thu, 6 Aug 2026 10:06:50 -0700 Subject: [PATCH 12/23] docs: reformat changelog entry with docstrfmt --- docs/changelog.rst | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 0a9183203..bc6961f95 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -156,10 +156,10 @@ Bug fixes valid date/time string" error instead of crashing with an uncaught ``KeyError``. A ``|`` was being accepted as a relative-date unit due to a regular expression character-class typo. -- Plugins built on ``SearchApiMetadataSourcePlugin`` (:doc:`plugins/musicbrainz`, - :doc:`plugins/spotify`, :doc:`plugins/deezer` and :doc:`plugins/discogs`) no - longer send a search request when both the query text and the filters are - empty. :bug:`6862` +- Plugins built on ``SearchApiMetadataSourcePlugin`` + (:doc:`plugins/musicbrainz`, :doc:`plugins/spotify`, :doc:`plugins/deezer` and + :doc:`plugins/discogs`) no longer send a search request when both the query + text and the filters are empty. :bug:`6862` .. For plugin developers From f6b7e1f76105a4cade4a41e549fc9004981f1e01 Mon Sep 17 00:00:00 2001 From: NoDancing Date: Tue, 4 Aug 2026 22:45:47 -0700 Subject: [PATCH 13/23] tidal: Normalize copyright text into a concise label name _parse_label() used to store Tidal's raw copyright info as the label name. Add _normalize_label(), a helper that strips leading markers, years, legal entities, and boilerplate clauses. Fixes #6796 --- beetsplug/tidal/__init__.py | 45 ++++++++++++++++++++++++++++++++++++- docs/changelog.rst | 4 ++++ test/plugins/test_tidal.py | 39 ++++++++++++++++++++++++++++---- 3 files changed, 83 insertions(+), 5 deletions(-) diff --git a/beetsplug/tidal/__init__.py b/beetsplug/tidal/__init__.py index d16a8ca40..06d8b2dec 100644 --- a/beetsplug/tidal/__init__.py +++ b/beetsplug/tidal/__init__.py @@ -392,6 +392,49 @@ class TidalPlugin(MetadataSourcePlugin): tidal_updated=time.time(), ) + # Leading marker & year + _LEADING_MARKER_RE = re.compile( + r"^\s*(?:©|℗|\(C\)|\(P\))\s*", re.IGNORECASE + ) + _LEADING_YEAR_RE = re.compile(r"^\s*\d{4}\s*") + + # Matches ", a" + _CORPORATE_RE = re.compile(r",\s+a\s+", re.IGNORECASE) + + # Matches "under exclusive license to" + _LICENSE_TO_RE = re.compile( + r"\bunder\s+exclusive\s+licen[cs]e\s+to\s+", re.IGNORECASE + ) + + # inc, llc, ltd, co suffixes + _TRAILING_SUFFIX_RE = re.compile( + r",?\s+(?:Inc|LLC|Ltd|Co)\.?$", re.IGNORECASE + ) + + # For the United States... + _TERRITORIAL_RE = re.compile( + r"\s+for\s+the\s+United\s+States\s+and\s+", re.IGNORECASE + ) + + @staticmethod + def _normalize_label(text: str) -> str: + """Removes leading copyright markers, years, and trims corporate boilerplate + from Tidal copyright text. + """ + text = TidalPlugin._LEADING_MARKER_RE.sub("", text, count=1) + text = TidalPlugin._LEADING_YEAR_RE.sub("", text, count=1) + + if match := TidalPlugin._CORPORATE_RE.search(text): + text = text[: match.start()] + + if match := TidalPlugin._LICENSE_TO_RE.search(text): + text = text[match.end() :] + + if match := TidalPlugin._TERRITORIAL_RE.search(text): + text = text[: match.start()] + + return TidalPlugin._TRAILING_SUFFIX_RE.sub("", text) + @staticmethod def _parse_artwork_url( album: TidalAlbum, artwork_by_id: dict[str, TidalArtwork] @@ -487,7 +530,7 @@ class TidalPlugin(MetadataSourcePlugin): @staticmethod def _parse_label(attributes: MediaAttributes) -> str | None: if copyright_ := attributes.get("copyright"): - return copyright_["text"] + return TidalPlugin._normalize_label(copyright_["text"]) return None @staticmethod diff --git a/docs/changelog.rst b/docs/changelog.rst index 4d98aa214..ac4b5a48c 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -50,6 +50,10 @@ Bug fixes relevance order and truncated to ``search_limit``. For artists with more releases than that window, the track being imported was never among the candidates offered. +- :doc:`plugins/tidal`: The ``label`` field no longer stores Tidal's raw + copyright/rights-statement text verbatim. It's now normalized to a concise + label name, stripping copyright markers, years, and corporate, licensing, and + territorial boilerplate. Affects both album and track metadata. :bug:`6796` .. For plugin developers diff --git a/test/plugins/test_tidal.py b/test/plugins/test_tidal.py index a3682c512..82b511e0b 100644 --- a/test/plugins/test_tidal.py +++ b/test/plugins/test_tidal.py @@ -747,14 +747,45 @@ class TestStaticHelpers: @pytest.mark.parametrize( "attrs, expected", - [ - ({"copyright": {"text": "(P) 2024 Tidal"}}, "(P) 2024 Tidal"), - ({}, None), - ], + [({"copyright": {"text": "(P) 2024 Tidal"}}, "Tidal"), ({}, None)], ) def test_parse_label(self, attrs, expected): assert TidalPlugin._parse_label(attrs) == expected + @pytest.mark.parametrize( + "text, expected", + [ + # marker prefixes + ("© 2017 Blackened Recordings", "Blackened Recordings"), + ("(C) 2019 Ghosteen Ltd", "Ghosteen"), + ("(P) 2007 Century Media Records Ltd.", "Century Media Records"), + ("℗ 2024 Tidal", "Tidal"), + # plain label name + ("Lightning Bolt", "Lightning Bolt"), + # under exclusive license to + ( + "Kim Gordon under exclusive license to Matador Records", + "Matador Records", + ), + # issue #6796's own examples, verbatim — cover the corporate-relationship + # clause, the territorial split, and the bare trailing suffix + ( + "© 2011 Motown Records, a Division of UMG Recordings, Inc.", + "Motown Records", + ), + ( + ( + "© 2019 Atlantic Recording Corporation for the United States and " + "WEA International Inc. for the world outside of the United States" + ), + "Atlantic Recording Corporation", + ), + ("(P) 1992 Zomba Recording LLC", "Zomba Recording"), + ], + ) + def test_normalize_label(self, text, expected): + assert TidalPlugin._normalize_label(text) == expected + @pytest.mark.parametrize( "attrs, expected", [ From f387d5bb4ad72281dfcfb9e4a696583493fdcdd1 Mon Sep 17 00:00:00 2001 From: NoDancing Date: Wed, 5 Aug 2026 10:31:59 -0700 Subject: [PATCH 14/23] tidal: rewrite _normalize_label without regex per review Replace the regex-based function with string methods, per review feedback. Also fixes a potential bug with the order of the license-to and the corporate-relationship clause. Verified against the same copyright samples as the previous implementation, output is identical. --- beetsplug/tidal/__init__.py | 76 +++++++++++++++++++------------------ 1 file changed, 40 insertions(+), 36 deletions(-) diff --git a/beetsplug/tidal/__init__.py b/beetsplug/tidal/__init__.py index 06d8b2dec..1a7091ef5 100644 --- a/beetsplug/tidal/__init__.py +++ b/beetsplug/tidal/__init__.py @@ -392,48 +392,52 @@ class TidalPlugin(MetadataSourcePlugin): tidal_updated=time.time(), ) - # Leading marker & year - _LEADING_MARKER_RE = re.compile( - r"^\s*(?:©|℗|\(C\)|\(P\))\s*", re.IGNORECASE - ) - _LEADING_YEAR_RE = re.compile(r"^\s*\d{4}\s*") - - # Matches ", a" - _CORPORATE_RE = re.compile(r",\s+a\s+", re.IGNORECASE) - - # Matches "under exclusive license to" - _LICENSE_TO_RE = re.compile( - r"\bunder\s+exclusive\s+licen[cs]e\s+to\s+", re.IGNORECASE - ) - - # inc, llc, ltd, co suffixes - _TRAILING_SUFFIX_RE = re.compile( - r",?\s+(?:Inc|LLC|Ltd|Co)\.?$", re.IGNORECASE - ) - - # For the United States... - _TERRITORIAL_RE = re.compile( - r"\s+for\s+the\s+United\s+States\s+and\s+", re.IGNORECASE - ) - @staticmethod def _normalize_label(text: str) -> str: - """Removes leading copyright markers, years, and trims corporate boilerplate - from Tidal copyright text. - """ - text = TidalPlugin._LEADING_MARKER_RE.sub("", text, count=1) - text = TidalPlugin._LEADING_YEAR_RE.sub("", text, count=1) + """Normalize label from Tidal copyright text by stripping markers/years + and known corporate/licensing/territorial boilerplate.""" + text = text.strip() - if match := TidalPlugin._CORPORATE_RE.search(text): - text = text[: match.start()] + # Leading copyright markers + for marker in ("©", "℗", "(C)", "(P)", "(c)", "(p)"): + if text.startswith(marker): + text = text[len(marker) :].strip() + break - if match := TidalPlugin._LICENSE_TO_RE.search(text): - text = text[match.end() :] + # Leading year + first, _, rest = text.partition(" ") + if len(first) == 4 and first.isdigit(): + text = rest.lstrip() - if match := TidalPlugin._TERRITORIAL_RE.search(text): - text = text[: match.start()] + # "under exclusive license to" + phrase = "under exclusive license to" + phrase_alt = "under exclusive licence to" - return TidalPlugin._TRAILING_SUFFIX_RE.sub("", text) + lower = text.lower() + for p in (phrase, phrase_alt): + if p in lower: + idx = lower.index(p) + text = text[idx + len(p) :] + break + + # ", a " + lower = text.lower() + if ", a " in lower: + text = text[: lower.index(", a ")] + + # Territorial boilerplate + phrase = " for the united states and " + lower = text.lower() + if phrase in lower: + text = text[: lower.index(phrase)] + + # Trailing company suffixes + for suffix in (" inc.", " inc", " llc", " ltd.", " ltd", " co.", " co"): + if text.lower().endswith(suffix): + text = text[: -len(suffix)].rstrip(", ") + break + + return text.strip() @staticmethod def _parse_artwork_url( From 7c139ab987f5164ad7d6f7f65f857b613b3a9062 Mon Sep 17 00:00:00 2001 From: NoDancing Date: Wed, 5 Aug 2026 12:20:44 -0700 Subject: [PATCH 15/23] tidal: rewrite _normalize_label with regex, using apply_transforms Return _normalize_label to regex-based logic, per review. Uses the apply_transforms method that was previously in lyrics.py, now moved to new module beetsplug/_utis/func.py. --- beetsplug/_utils/func.py | 13 +++++++ beetsplug/lyrics.py | 12 ++----- beetsplug/tidal/__init__.py | 69 +++++++++++++------------------------ 3 files changed, 39 insertions(+), 55 deletions(-) create mode 100644 beetsplug/_utils/func.py diff --git a/beetsplug/_utils/func.py b/beetsplug/_utils/func.py new file mode 100644 index 000000000..4907702d3 --- /dev/null +++ b/beetsplug/_utils/func.py @@ -0,0 +1,13 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from collections.abc import Callable, Iterable + + +def apply_transforms(text: str, methods: Iterable[Callable[[str], str]]) -> str: + for method in methods: + text = method(text) + + return text diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index c9e5c529d..4f10e4f70 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -28,6 +28,7 @@ from beets.library import Item, parse_query_string from beets.util.config import sanitize_choices from beets.util.lyrics import INSTRUMENTAL_LYRICS, Lyrics +from ._utils.func import apply_transforms from ._utils.requests import ( HTTPNotFoundError, RequestHandler, @@ -35,7 +36,7 @@ from ._utils.requests import ( ) if TYPE_CHECKING: - from collections.abc import Callable, Iterable, Iterator + from collections.abc import Iterable, Iterator import confuse @@ -51,8 +52,6 @@ if TYPE_CHECKING: TranslatorAPI, ) - HtmlTransformer = Callable[[str], str] - class CaptchaError(requests.exceptions.HTTPError): def __init__(self, *args, **kwargs) -> None: @@ -441,13 +440,6 @@ class MusiXmatch(Backend): return Lyrics(lyrics, self.__class__.name, url) -def apply_transforms(html: str, methods: Iterable[HtmlTransformer]) -> str: - for method in methods: - html = method(html) - - return html - - class Html: collapse_space = partial(re.compile(r"(^| ) +", re.M).sub, r"\1") expand_br = partial(re.compile(r"\s*]*>\s*", re.I).sub, "\n") diff --git a/beetsplug/tidal/__init__.py b/beetsplug/tidal/__init__.py index 1a7091ef5..581bde62c 100644 --- a/beetsplug/tidal/__init__.py +++ b/beetsplug/tidal/__init__.py @@ -4,7 +4,7 @@ import itertools import os import re import time -from functools import cached_property +from functools import cached_property, partial from typing import TYPE_CHECKING, ClassVar, Literal, overload import confuse @@ -15,6 +15,7 @@ from beets.dbcore import types from beets.exceptions import UserError from beets.logging import getLogger from beets.metadata_plugins import MetadataSourcePlugin +from beetsplug._utils.func import apply_transforms from .api import TidalAPI @@ -40,6 +41,19 @@ if TYPE_CHECKING: log = getLogger("beets.tidal") +_remove_leading = partial( + re.compile(r"^(?:(?:©|℗|\([cp]\)) *)?(?:\d{4} +)?", re.IGNORECASE).sub, "" +) +_remove_license = partial( + re.compile(r".* under exclusive licen[sc]e to ", re.IGNORECASE).sub, "" +) +_remove_trailing_clause = partial( + re.compile(r"(?:, a| for the united states and) .*", re.IGNORECASE).sub, "" +) +_remove_legal_suffix = partial( + re.compile(r",? (?:inc|llc|ltd|co)\.?$", re.IGNORECASE).sub, "" +) + class TidalPlugin(MetadataSourcePlugin): item_types: ClassVar[dict[str, types.Type]] = { @@ -394,50 +408,15 @@ class TidalPlugin(MetadataSourcePlugin): @staticmethod def _normalize_label(text: str) -> str: - """Normalize label from Tidal copyright text by stripping markers/years - and known corporate/licensing/territorial boilerplate.""" - text = text.strip() - - # Leading copyright markers - for marker in ("©", "℗", "(C)", "(P)", "(c)", "(p)"): - if text.startswith(marker): - text = text[len(marker) :].strip() - break - - # Leading year - first, _, rest = text.partition(" ") - if len(first) == 4 and first.isdigit(): - text = rest.lstrip() - - # "under exclusive license to" - phrase = "under exclusive license to" - phrase_alt = "under exclusive licence to" - - lower = text.lower() - for p in (phrase, phrase_alt): - if p in lower: - idx = lower.index(p) - text = text[idx + len(p) :] - break - - # ", a " - lower = text.lower() - if ", a " in lower: - text = text[: lower.index(", a ")] - - # Territorial boilerplate - phrase = " for the united states and " - lower = text.lower() - if phrase in lower: - text = text[: lower.index(phrase)] - - # Trailing company suffixes - for suffix in (" inc.", " inc", " llc", " ltd.", " ltd", " co.", " co"): - if text.lower().endswith(suffix): - text = text[: -len(suffix)].rstrip(", ") - break - - return text.strip() + return apply_transforms( + text, + [ + _remove_leading, + _remove_license, + _remove_trailing_clause, + _remove_legal_suffix, + ], + ) @staticmethod def _parse_artwork_url( From ecff1e72154a061af47b481bed44fea062086d18 Mon Sep 17 00:00:00 2001 From: NoDancing Date: Thu, 6 Aug 2026 19:46:10 -0700 Subject: [PATCH 16/23] tidal: rework _normalize_label into a single regex Replace the apply_transforms based pipeline with a single compiled regex, per review. --- beetsplug/_utils/func.py | 13 ------------- beetsplug/lyrics.py | 12 ++++++++++-- beetsplug/tidal/__init__.py | 38 ++++++++++++++++--------------------- 3 files changed, 26 insertions(+), 37 deletions(-) delete mode 100644 beetsplug/_utils/func.py diff --git a/beetsplug/_utils/func.py b/beetsplug/_utils/func.py deleted file mode 100644 index 4907702d3..000000000 --- a/beetsplug/_utils/func.py +++ /dev/null @@ -1,13 +0,0 @@ -from __future__ import annotations - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from collections.abc import Callable, Iterable - - -def apply_transforms(text: str, methods: Iterable[Callable[[str], str]]) -> str: - for method in methods: - text = method(text) - - return text diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 4f10e4f70..c9e5c529d 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -28,7 +28,6 @@ from beets.library import Item, parse_query_string from beets.util.config import sanitize_choices from beets.util.lyrics import INSTRUMENTAL_LYRICS, Lyrics -from ._utils.func import apply_transforms from ._utils.requests import ( HTTPNotFoundError, RequestHandler, @@ -36,7 +35,7 @@ from ._utils.requests import ( ) if TYPE_CHECKING: - from collections.abc import Iterable, Iterator + from collections.abc import Callable, Iterable, Iterator import confuse @@ -52,6 +51,8 @@ if TYPE_CHECKING: TranslatorAPI, ) + HtmlTransformer = Callable[[str], str] + class CaptchaError(requests.exceptions.HTTPError): def __init__(self, *args, **kwargs) -> None: @@ -440,6 +441,13 @@ class MusiXmatch(Backend): return Lyrics(lyrics, self.__class__.name, url) +def apply_transforms(html: str, methods: Iterable[HtmlTransformer]) -> str: + for method in methods: + html = method(html) + + return html + + class Html: collapse_space = partial(re.compile(r"(^| ) +", re.M).sub, r"\1") expand_br = partial(re.compile(r"\s*]*>\s*", re.I).sub, "\n") diff --git a/beetsplug/tidal/__init__.py b/beetsplug/tidal/__init__.py index 581bde62c..de41c59ac 100644 --- a/beetsplug/tidal/__init__.py +++ b/beetsplug/tidal/__init__.py @@ -4,7 +4,7 @@ import itertools import os import re import time -from functools import cached_property, partial +from functools import cached_property from typing import TYPE_CHECKING, ClassVar, Literal, overload import confuse @@ -15,7 +15,6 @@ from beets.dbcore import types from beets.exceptions import UserError from beets.logging import getLogger from beets.metadata_plugins import MetadataSourcePlugin -from beetsplug._utils.func import apply_transforms from .api import TidalAPI @@ -41,17 +40,17 @@ if TYPE_CHECKING: log = getLogger("beets.tidal") -_remove_leading = partial( - re.compile(r"^(?:(?:©|℗|\([cp]\)) *)?(?:\d{4} +)?", re.IGNORECASE).sub, "" -) -_remove_license = partial( - re.compile(r".* under exclusive licen[sc]e to ", re.IGNORECASE).sub, "" -) -_remove_trailing_clause = partial( - re.compile(r"(?:, a| for the united states and) .*", re.IGNORECASE).sub, "" -) -_remove_legal_suffix = partial( - re.compile(r",? (?:inc|llc|ltd|co)\.?$", re.IGNORECASE).sub, "" +_normalize_label_re = re.compile( + r""" + ^(?:.*(?:©|℗|\([cp]\))\s*)? # optional text through last marker + (?:\d{4}\s+)? # optional year + (?:.*?\ under\ exclusive\ licen[sc]e\ to\ )? # optional license prefix + (.*?) # text to keep + (?:,?\ (?:inc|llc|ltd|co)\.?)? # optional legal suffix + (?:,\ a\ .*)? # optional corporate clause + (?:,?\ for\ the\ united\ states\ and\ .*)? # optional territorial clause + $""", + re.IGNORECASE | re.VERBOSE, ) @@ -408,15 +407,10 @@ class TidalPlugin(MetadataSourcePlugin): @staticmethod def _normalize_label(text: str) -> str: - return apply_transforms( - text, - [ - _remove_leading, - _remove_license, - _remove_trailing_clause, - _remove_legal_suffix, - ], - ) + """Reduce a raw copyright string to a concise label name.""" + if match := _normalize_label_re.match(text): + return match.group(1) + return text @staticmethod def _parse_artwork_url( From 80b8c847795fe1b913aad32e4ef56d1f7ac8b8c6 Mon Sep 17 00:00:00 2001 From: Sean Cohan Date: Mon, 10 Aug 2026 16:05:08 -0700 Subject: [PATCH 17/23] tidal: comment formatting/alignment, per review MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Šarūnas Nejus --- beetsplug/tidal/__init__.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/beetsplug/tidal/__init__.py b/beetsplug/tidal/__init__.py index de41c59ac..1b6594427 100644 --- a/beetsplug/tidal/__init__.py +++ b/beetsplug/tidal/__init__.py @@ -42,13 +42,13 @@ log = getLogger("beets.tidal") _normalize_label_re = re.compile( r""" - ^(?:.*(?:©|℗|\([cp]\))\s*)? # optional text through last marker - (?:\d{4}\s+)? # optional year - (?:.*?\ under\ exclusive\ licen[sc]e\ to\ )? # optional license prefix - (.*?) # text to keep - (?:,?\ (?:inc|llc|ltd|co)\.?)? # optional legal suffix - (?:,\ a\ .*)? # optional corporate clause - (?:,?\ for\ the\ united\ states\ and\ .*)? # optional territorial clause + ^(?:.*(?:©|℗|\([cp]\))\s*)? # optional copyright marker + (?:\d{4}\s+)? # optional year + (?:.*?\ under\ exclusive\ licence\ to\ )? # optional license prefix + (.*?) # text to keep + (?:,?\ (?:inc|llc|ltd|co)\.?)? # optional legal suffix + (?:,\ a\ .*)? # optional corporate clause + (?:,?\ for\ the\ united\ states\ and\ .*)? # optional territorial clause $""", re.IGNORECASE | re.VERBOSE, ) From 5187fb31d9e6cae5e35c20c1437e961291909a2d Mon Sep 17 00:00:00 2001 From: NoDancing Date: Mon, 10 Aug 2026 16:16:05 -0700 Subject: [PATCH 18/23] tidal: restore licen[sc]e option lost in formatting --- beetsplug/tidal/__init__.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/beetsplug/tidal/__init__.py b/beetsplug/tidal/__init__.py index 1b6594427..173668a5d 100644 --- a/beetsplug/tidal/__init__.py +++ b/beetsplug/tidal/__init__.py @@ -42,13 +42,13 @@ log = getLogger("beets.tidal") _normalize_label_re = re.compile( r""" - ^(?:.*(?:©|℗|\([cp]\))\s*)? # optional copyright marker - (?:\d{4}\s+)? # optional year - (?:.*?\ under\ exclusive\ licence\ to\ )? # optional license prefix - (.*?) # text to keep - (?:,?\ (?:inc|llc|ltd|co)\.?)? # optional legal suffix - (?:,\ a\ .*)? # optional corporate clause - (?:,?\ for\ the\ united\ states\ and\ .*)? # optional territorial clause + ^(?:.*(?:©|℗|\([cp]\))\s*)? # optional copyright marker + (?:\d{4}\s+)? # optional year + (?:.*?\ under\ exclusive\ licen[sc]e\ to\ )? # optional license prefix + (.*?) # text to keep + (?:,?\ (?:inc|llc|ltd|co)\.?)? # optional legal suffix + (?:,\ a\ .*)? # optional corporate clause + (?:,?\ for\ the\ united\ states\ and\ .*)? # optional territorial clause $""", re.IGNORECASE | re.VERBOSE, ) From afd07ce5d3bfe882229fbf8b850eb6fd04957ed4 Mon Sep 17 00:00:00 2001 From: Trey Turner Date: Wed, 5 Aug 2026 17:16:13 -0500 Subject: [PATCH 19/23] fix(discogs): retry malformed search responses --- beetsplug/discogs/__init__.py | 16 ++++++++++++--- docs/changelog.rst | 2 ++ test/plugins/test_discogs.py | 38 +++++++++++++++++++++++++++++++++++ 3 files changed, 53 insertions(+), 3 deletions(-) diff --git a/beetsplug/discogs/__init__.py b/beetsplug/discogs/__init__.py index e21929c58..bb62a0a96 100644 --- a/beetsplug/discogs/__init__.py +++ b/beetsplug/discogs/__init__.py @@ -292,9 +292,19 @@ class DiscogsPlugin(SearchApiMetadataSourcePlugin[IDResponse]): def get_search_response(self, params: SearchParams) -> Sequence[IDResponse]: """Search Discogs releases and return raw result mappings with IDs.""" - results = self.discogs_client.search(params.query, **params.filters) - results.per_page = params.limit - return [r.data for r in results.page(1)] + + def search() -> list[IDResponse]: + results = self.discogs_client.search(params.query, **params.filters) + results.per_page = params.limit + return [r.data for r in results.page(1)] + + try: + return search() + except json.JSONDecodeError: + self._log.debug( + "Discogs returned an invalid JSON search response; retrying" + ) + return search() @cache def get_master_year(self, master_id: str) -> int | None: diff --git a/docs/changelog.rst b/docs/changelog.rst index ac4b5a48c..abf2b71c4 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -54,6 +54,8 @@ Bug fixes copyright/rights-statement text verbatim. It's now normalized to a concise label name, stripping copyright markers, years, and corporate, licensing, and territorial boilerplate. Affects both album and track metadata. :bug:`6796` +- :doc:`plugins/discogs`: Retry a search once when Discogs returns an invalid + JSON response instead of immediately discarding all Discogs candidates. .. For plugin developers diff --git a/test/plugins/test_discogs.py b/test/plugins/test_discogs.py index e0b40772f..dc42d1942 100644 --- a/test/plugins/test_discogs.py +++ b/test/plugins/test_discogs.py @@ -2,13 +2,16 @@ from __future__ import annotations +import json from typing import TYPE_CHECKING, Any +from unittest.mock import MagicMock import pytest from discogs_client import Client, Release from beets import config from beets.library import Item +from beets.metadata_plugins import SearchParams from beets.test.helper import TestHelper from beetsplug.discogs import ArtistState, DiscogsPlugin @@ -498,6 +501,41 @@ class TestDGSearchQuery(TestHelper): config["discogs"]["extra_tags"] = [] +class TestDGSearchResponse(DiscogsTestMixin): + @staticmethod + def _decode_error(): + return json.JSONDecodeError("Expecting value", "", 0) + + @pytest.fixture + def params(self): + return SearchParams("album", "Album", {"type": "release"}, 5) + + @pytest.fixture + def client(self, plugin): + plugin.discogs_client = MagicMock() + return plugin.discogs_client + + def test_retries_invalid_json_response(self, plugin, client, params): + result = MagicMock(data={"id": 123}) + results = client.search.return_value + results.page.side_effect = [self._decode_error(), [result]] + + assert plugin.get_search_response(params) == [{"id": 123}] + assert client.search.call_count == 2 + assert results.page.call_count == 2 + assert results.per_page == params.limit + + def test_raises_after_invalid_json_retry(self, plugin, client, params): + results = client.search.return_value + results.page.side_effect = [self._decode_error(), self._decode_error()] + + with pytest.raises(json.JSONDecodeError): + plugin.get_search_response(params) + + assert client.search.call_count == 2 + assert results.page.call_count == 2 + + class TestAnv: @pytest.fixture def album_info(self, monkeypatch, anv_config): From d97d78f83065c3dae2d695d2ececfed14a48249b Mon Sep 17 00:00:00 2001 From: Cohen Karnell <7363269+ckarnell@users.noreply.github.com> Date: Fri, 14 Aug 2026 12:02:07 -0400 Subject: [PATCH 20/23] Fix KeyError in Deezer track conversion when artist is missing _get_track resolved the artist with track_data.get('contributors', [track_data['artist']]), whose default is evaluated eagerly, so track_data['artist'] raises KeyError whenever the artist key is absent, even when contributors is present. Guard the fallback the same way album_for_id already does. Fixes #4339. --- beetsplug/deezer.py | 12 ++++++++---- docs/changelog.rst | 5 +++++ test/plugins/test_deezer.py | 33 +++++++++++++++++++++++++++++++++ 3 files changed, 46 insertions(+), 4 deletions(-) diff --git a/beetsplug/deezer.py b/beetsplug/deezer.py index 6ea172631..629c87bd4 100644 --- a/beetsplug/deezer.py +++ b/beetsplug/deezer.py @@ -187,16 +187,20 @@ class DeezerPlugin(SearchApiMetadataSourcePlugin[IDResponse]): :param track_data: Deezer Track object dict """ - artist, artist_id = self.get_artist( - track_data.get("contributors", [track_data["artist"]]) - ) + 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), + 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"), diff --git a/docs/changelog.rst b/docs/changelog.rst index e75ac5ca0..7a92d72e2 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -56,6 +56,11 @@ Bug fixes copyright/rights-statement text verbatim. It's now normalized to a concise label name, stripping copyright markers, years, and corporate, licensing, and territorial boilerplate. Affects both album and track metadata. :bug:`6796` +- :doc:`plugins/deezer`: Track conversion no longer assumes the API sends both + ``contributors`` and ``artist``. The fallback to ``artist`` was evaluated even + when ``contributors`` was present, so a track payload without ``artist`` + raised ``KeyError``. Albums were already guarded; this fixes the remaining + call site. :bug:`4339` .. For plugin developers diff --git a/test/plugins/test_deezer.py b/test/plugins/test_deezer.py index e62514824..fb5cffaa6 100644 --- a/test/plugins/test_deezer.py +++ b/test/plugins/test_deezer.py @@ -39,3 +39,36 @@ class TestSearchQuery: ) assert query == 'album:"Album"' + + +class TestGetTrack: + def track_data(self, **fields): + return { + "id": 1, + "title": "Title", + "duration": 100, + "link": "https://www.deezer.com/track/1", + **fields, + } + + def test_uses_contributors_when_artist_is_missing(self, plugin): + track = plugin._get_track( + self.track_data(contributors=[{"id": 2, "name": "Artist"}]) + ) + + assert track.artist == "Artist" + assert track.artist_id == "2" + + def test_falls_back_to_artist_without_contributors(self, plugin): + track = plugin._get_track( + self.track_data(artist={"id": 2, "name": "Artist"}) + ) + + assert track.artist == "Artist" + assert track.artist_id == "2" + + def test_tolerates_missing_artist_and_contributors(self, plugin): + track = plugin._get_track(self.track_data()) + + assert track.artist is None + assert track.artist_id is None From 127a2d8914a0a859d6c6ba6b9108d90f02fc0d11 Mon Sep 17 00:00:00 2001 From: Sanjay Santhanam <51058514+Sanjays2402@users.noreply.github.com> Date: Sat, 15 Aug 2026 16:59:28 -0700 Subject: [PATCH 21/23] docs: keep changelog entry under unreleased --- docs/changelog.rst | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 620a3f5e0..82dfc4c14 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -54,6 +54,10 @@ Bug fixes copyright/rights-statement text verbatim. It's now normalized to a concise label name, stripping copyright markers, years, and corporate, licensing, and territorial boilerplate. Affects both album and track metadata. :bug:`6796` +- Plugins built on ``SearchApiMetadataSourcePlugin`` + (:doc:`plugins/musicbrainz`, :doc:`plugins/spotify`, :doc:`plugins/deezer` and + :doc:`plugins/discogs`) no longer send a search request when both the query + text and the filters are empty. :bug:`6862` .. For plugin developers @@ -160,10 +164,6 @@ Bug fixes valid date/time string" error instead of crashing with an uncaught ``KeyError``. A ``|`` was being accepted as a relative-date unit due to a regular expression character-class typo. -- Plugins built on ``SearchApiMetadataSourcePlugin`` - (:doc:`plugins/musicbrainz`, :doc:`plugins/spotify`, :doc:`plugins/deezer` and - :doc:`plugins/discogs`) no longer send a search request when both the query - text and the filters are empty. :bug:`6862` .. For plugin developers From 9b16f67af1c656691a10de2bb0d6831661fe08ca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=A0ar=C5=ABnas=20Nejus?= Date: Tue, 4 Aug 2026 01:31:35 +0100 Subject: [PATCH 22/23] Remove bluelet in favor of using asyncio in bpd plugin --- beets/util/bluelet.py | 651 -------------------------------------- beetsplug/bpd/__init__.py | 172 +++++----- docs/changelog.rst | 8 +- test/plugins/test_bpd.py | 27 +- 4 files changed, 112 insertions(+), 746 deletions(-) delete mode 100644 beets/util/bluelet.py diff --git a/beets/util/bluelet.py b/beets/util/bluelet.py deleted file mode 100644 index b4a5aa7b1..000000000 --- a/beets/util/bluelet.py +++ /dev/null @@ -1,651 +0,0 @@ -"""Extremely simple pure-Python implementation of coroutine-style -asynchronous socket I/O. Inspired by, but inferior to, Eventlet. -Bluelet can also be thought of as a less-terrible replacement for -asyncore. - -Bluelet: easy concurrency without all the messy parallelism. -""" - -import collections -import errno -import select -import socket -import sys -import time -import traceback -import types - -# Basic events used for thread scheduling. - - -class Event: - """Just a base class identifying Bluelet events. An event is an - object yielded from a Bluelet thread coroutine to suspend operation - and communicate with the scheduler. - """ - - -class WaitableEvent(Event): - """A waitable event is one encapsulating an action that can be - waited for using a select() call. That is, it's an event with an - associated file descriptor. - """ - - def waitables(self): - """Return "waitable" objects to pass to select(). Should return - three iterables for input readiness, output readiness, and - exceptional conditions (i.e., the three lists passed to - select()). - """ - return (), (), () - - def fire(self): - """Called when an associated file descriptor becomes ready - (i.e., is returned from a select() call). - """ - - -class ValueEvent(Event): - """An event that does nothing but return a fixed value.""" - - def __init__(self, value): - self.value = value - - -class ExceptionEvent(Event): - """Raise an exception at the yield point. Used internally.""" - - def __init__(self, exc_info): - self.exc_info = exc_info - - -class SpawnEvent(Event): - """Add a new coroutine thread to the scheduler.""" - - def __init__(self, coro): - self.spawned = coro - - -class JoinEvent(Event): - """Suspend the thread until the specified child thread has - completed. - """ - - def __init__(self, child): - self.child = child - - -class KillEvent(Event): - """Unschedule a child thread.""" - - def __init__(self, child): - self.child = child - - -class DelegationEvent(Event): - """Suspend execution of the current thread, start a new thread and, - once the child thread finished, return control to the parent - thread. - """ - - def __init__(self, coro): - self.spawned = coro - - -class ReturnEvent(Event): - """Return a value the current thread's delegator at the point of - delegation. Ends the current (delegate) thread. - """ - - def __init__(self, value): - self.value = value - - -class SleepEvent(WaitableEvent): - """Suspend the thread for a given duration.""" - - def __init__(self, duration): - self.wakeup_time = time.time() + duration - - def time_left(self): - return max(self.wakeup_time - time.time(), 0.0) - - -class ReadEvent(WaitableEvent): - """Reads from a file-like object.""" - - def __init__(self, fd, bufsize): - self.fd = fd - self.bufsize = bufsize - - def waitables(self): - return (self.fd,), (), () - - def fire(self): - return self.fd.read(self.bufsize) - - -class WriteEvent(WaitableEvent): - """Writes to a file-like object.""" - - def __init__(self, fd, data): - self.fd = fd - self.data = data - - def waitable(self): - return (), (self.fd,), () - - def fire(self): - self.fd.write(self.data) - - -# Core logic for executing and scheduling threads. - - -def _event_select(events): - """Perform a select() over all the Events provided, returning the - ones ready to be fired. Only WaitableEvents (including SleepEvents) - matter here; all other events are ignored (and thus postponed). - """ - # Gather waitables and wakeup times. - waitable_to_event = {} - rlist, wlist, xlist = [], [], [] - earliest_wakeup = None - for event in events: - if isinstance(event, SleepEvent): - if not earliest_wakeup: - earliest_wakeup = event.wakeup_time - else: - earliest_wakeup = min(earliest_wakeup, event.wakeup_time) - elif isinstance(event, WaitableEvent): - r, w, x = event.waitables() - rlist += r - wlist += w - xlist += x - for waitable in r: - waitable_to_event[("r", waitable)] = event - for waitable in w: - waitable_to_event[("w", waitable)] = event - for waitable in x: - waitable_to_event[("x", waitable)] = event - - # If we have a any sleeping threads, determine how long to sleep. - if earliest_wakeup: - timeout = max(earliest_wakeup - time.time(), 0.0) - else: - timeout = None - - # Perform select() if we have any waitables. - if rlist or wlist or xlist: - rready, wready, xready = select.select(rlist, wlist, xlist, timeout) - else: - rready, wready, xready = (), (), () - if timeout: - time.sleep(timeout) - - # Gather ready events corresponding to the ready waitables. - ready_events = set() - for ready in rready: - ready_events.add(waitable_to_event[("r", ready)]) - for ready in wready: - ready_events.add(waitable_to_event[("w", ready)]) - for ready in xready: - ready_events.add(waitable_to_event[("x", ready)]) - - # Gather any finished sleeps. - for event in events: - if isinstance(event, SleepEvent) and event.time_left() == 0.0: - ready_events.add(event) - - return ready_events - - -class ThreadError(Exception): - def __init__(self, coro, exc_info): - self.coro = coro - self.exc_info = exc_info - - def reraise(self): - raise self.exc_info[1].with_traceback(self.exc_info[2]) - - -SUSPENDED = Event() # Special sentinel placeholder for suspended threads. - - -class Delegated(Event): - """Placeholder indicating that a thread has delegated execution to a - different thread. - """ - - def __init__(self, child): - self.child = child - - -def run(root_coro): - """Schedules a coroutine, running it to completion. This - encapsulates the Bluelet scheduler, which the root coroutine can - add to by spawning new coroutines. - """ - # The "threads" dictionary keeps track of all the currently- - # executing and suspended coroutines. It maps coroutines to their - # currently "blocking" event. The event value may be SUSPENDED if - # the coroutine is waiting on some other condition: namely, a - # delegated coroutine or a joined coroutine. In this case, the - # coroutine should *also* appear as a value in one of the below - # dictionaries `delegators` or `joiners`. - threads = {root_coro: ValueEvent(None)} - - # Maps child coroutines to delegating parents. - delegators = {} - - # Maps child coroutines to joining (exit-waiting) parents. - joiners = collections.defaultdict(list) - - def complete_thread(coro, return_value): - """Remove a coroutine from the scheduling pool, awaking - delegators and joiners as necessary and returning the specified - value to any delegating parent. - """ - del threads[coro] - - # Resume delegator. - if coro in delegators: - threads[delegators[coro]] = ValueEvent(return_value) - del delegators[coro] - - # Resume joiners. - if coro in joiners: - for parent in joiners[coro]: - threads[parent] = ValueEvent(None) - del joiners[coro] - - def advance_thread(coro, value, is_exc=False): - """After an event is fired, run a given coroutine associated with - it in the threads dict until it yields again. If the coroutine - exits, then the thread is removed from the pool. If the coroutine - raises an exception, it is reraised in a ThreadError. If - is_exc is True, then the value must be an exc_info tuple and the - exception is thrown into the coroutine. - """ - try: - if is_exc: - next_event = coro.throw(*value) - else: - next_event = coro.send(value) - except StopIteration: - # Thread is done. - complete_thread(coro, None) - except BaseException: - # Thread raised some other exception. - del threads[coro] - raise ThreadError(coro, sys.exc_info()) - else: - if isinstance(next_event, types.GeneratorType): - # Automatically invoke sub-coroutines. (Shorthand for - # explicit bluelet.call().) - next_event = DelegationEvent(next_event) - threads[coro] = next_event - - def kill_thread(coro): - """Unschedule this thread and its (recursive) delegates.""" - # Collect all coroutines in the delegation stack. - coros = [coro] - while isinstance(threads[coro], Delegated): - coro = threads[coro].child - coros.append(coro) - - # Complete each coroutine from the top to the bottom of the - # stack. - for coro in reversed(coros): - complete_thread(coro, None) - - # Continue advancing threads until root thread exits. - exit_te = None - while threads: - try: - # Look for events that can be run immediately. Continue - # running immediate events until nothing is ready. - while True: - have_ready = False - for coro, event in list(threads.items()): - if isinstance(event, SpawnEvent): - threads[event.spawned] = ValueEvent(None) # Spawn. - advance_thread(coro, None) - have_ready = True - elif isinstance(event, ValueEvent): - advance_thread(coro, event.value) - have_ready = True - elif isinstance(event, ExceptionEvent): - advance_thread(coro, event.exc_info, True) - have_ready = True - elif isinstance(event, DelegationEvent): - threads[coro] = Delegated(event.spawned) # Suspend. - threads[event.spawned] = ValueEvent(None) # Spawn. - delegators[event.spawned] = coro - have_ready = True - elif isinstance(event, ReturnEvent): - # Thread is done. - complete_thread(coro, event.value) - have_ready = True - elif isinstance(event, JoinEvent): - threads[coro] = SUSPENDED # Suspend. - joiners[event.child].append(coro) - have_ready = True - elif isinstance(event, KillEvent): - threads[coro] = ValueEvent(None) - kill_thread(event.child) - have_ready = True - - # Only start the select when nothing else is ready. - if not have_ready: - break - - # Wait and fire. - event2coro = {v: k for k, v in threads.items()} - for event in _event_select(threads.values()): - # Run the IO operation, but catch socket errors. - try: - value = event.fire() - except OSError as exc: - if ( - isinstance(exc.args, tuple) - and exc.args[0] == errno.EPIPE - ): - # Broken pipe. Remote host disconnected. - pass - elif ( - isinstance(exc.args, tuple) - and exc.args[0] == errno.ECONNRESET - ): - # Connection was reset by peer. - pass - else: - traceback.print_exc() - # Abort the coroutine. - threads[event2coro[event]] = ReturnEvent(None) - else: - advance_thread(event2coro[event], value) - - except ThreadError as te: - # Exception raised from inside a thread. - event = ExceptionEvent(te.exc_info) - if te.coro in delegators: - # The thread is a delegate. Raise exception in its - # delegator. - threads[delegators[te.coro]] = event - del delegators[te.coro] - else: - # The thread is root-level. Raise in client code. - exit_te = te - break - - except BaseException: - # For instance, KeyboardInterrupt during select(). Raise - # into root thread and terminate others. - threads = {root_coro: ExceptionEvent(sys.exc_info())} - - # If any threads still remain, kill them. - for coro in threads: - coro.close() - - # If we're exiting with an exception, raise it in the client. - if exit_te: - exit_te.reraise() - - -# Sockets and their associated events. - - -class SocketClosedError(Exception): - pass - - -class Listener: - """A socket wrapper object for listening sockets.""" - - def __init__(self, host, port): - """Create a listening socket on the given hostname and port.""" - self._closed = False - self.host = host - self.port = port - self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - self.sock.bind((host, port)) - self.sock.listen(5) - - def accept(self): - """An event that waits for a connection on the listening socket. - When a connection is made, the event returns a Connection - object. - """ - if self._closed: - raise SocketClosedError() - return AcceptEvent(self) - - def close(self): - """Immediately close the listening socket. (Not an event.)""" - self._closed = True - self.sock.close() - - -class Connection: - """A socket wrapper object for connected sockets.""" - - def __init__(self, sock, addr): - self.sock = sock - self.addr = addr - self._buf = b"" - self._closed = False - - def close(self): - """Close the connection.""" - self._closed = True - self.sock.close() - - def recv(self, size): - """Read at most size bytes of data from the socket.""" - if self._closed: - raise SocketClosedError() - - if self._buf: - # We already have data read previously. - out = self._buf[:size] - self._buf = self._buf[size:] - return ValueEvent(out) - return ReceiveEvent(self, size) - - def send(self, data): - """Sends data on the socket, returning the number of bytes - successfully sent. - """ - if self._closed: - raise SocketClosedError() - return SendEvent(self, data) - - def sendall(self, data): - """Send all of data on the socket.""" - if self._closed: - raise SocketClosedError() - return SendEvent(self, data, True) - - def readline(self, terminator=b"\n", bufsize=1024): - """Reads a line (delimited by terminator) from the socket.""" - if self._closed: - raise SocketClosedError() - - while True: - if terminator in self._buf: - line, self._buf = self._buf.split(terminator, 1) - line += terminator - yield ReturnEvent(line) - break - data = yield ReceiveEvent(self, bufsize) - if data: - self._buf += data - else: - line = self._buf - self._buf = b"" - yield ReturnEvent(line) - break - - -class AcceptEvent(WaitableEvent): - """An event for Listener objects (listening sockets) that suspends - execution until the socket gets a connection. - """ - - def __init__(self, listener): - self.listener = listener - - def waitables(self): - return (self.listener.sock,), (), () - - def fire(self): - sock, addr = self.listener.sock.accept() - return Connection(sock, addr) - - -class ReceiveEvent(WaitableEvent): - """An event for Connection objects (connected sockets) for - asynchronously reading data. - """ - - def __init__(self, conn, bufsize): - self.conn = conn - self.bufsize = bufsize - - def waitables(self): - return (self.conn.sock,), (), () - - def fire(self): - return self.conn.sock.recv(self.bufsize) - - -class SendEvent(WaitableEvent): - """An event for Connection objects (connected sockets) for - asynchronously writing data. - """ - - def __init__(self, conn, data, sendall=False): - self.conn = conn - self.data = data - self.sendall = sendall - - def waitables(self): - return (), (self.conn.sock,), () - - def fire(self): - if self.sendall: - return self.conn.sock.sendall(self.data) - return self.conn.sock.send(self.data) - - -# Public interface for threads; each returns an event object that -# can immediately be "yield"ed. - - -def null(): - """Event: yield to the scheduler without doing anything special.""" - return ValueEvent(None) - - -def spawn(coro): - """Event: add another coroutine to the scheduler. Both the parent - and child coroutines run concurrently. - """ - if not isinstance(coro, types.GeneratorType): - raise ValueError(f"{coro} is not a coroutine") - return SpawnEvent(coro) - - -def call(coro): - """Event: delegate to another coroutine. The current coroutine - is resumed once the sub-coroutine finishes. If the sub-coroutine - returns a value using end(), then this event returns that value. - """ - if not isinstance(coro, types.GeneratorType): - raise ValueError(f"{coro} is not a coroutine") - return DelegationEvent(coro) - - -def end(value=None): - """Event: ends the coroutine and returns a value to its - delegator. - """ - return ReturnEvent(value) - - -def read(fd, bufsize=None): - """Event: read from a file descriptor asynchronously.""" - if bufsize is None: - # Read all. - def reader(): - buf = [] - while True: - data = yield read(fd, 1024) - if not data: - break - buf.append(data) - yield ReturnEvent("".join(buf)) - - return DelegationEvent(reader()) - - return ReadEvent(fd, bufsize) - - -def write(fd, data): - """Event: write to a file descriptor asynchronously.""" - return WriteEvent(fd, data) - - -def connect(host, port): - """Event: connect to a network address and return a Connection - object for communicating on the socket. - """ - addr = (host, port) - sock = socket.create_connection(addr) - return ValueEvent(Connection(sock, addr)) - - -def sleep(duration): - """Event: suspend the thread for ``duration`` seconds.""" - return SleepEvent(duration) - - -def join(coro): - """Suspend the thread until another, previously `spawn`ed thread - completes. - """ - return JoinEvent(coro) - - -def kill(coro): - """Halt the execution of a different `spawn`ed thread.""" - return KillEvent(coro) - - -# Convenience function for running socket servers. - - -def server(host, port, func): - """A coroutine that runs a network server. Host and port specify the - listening address. func should be a coroutine that takes a single - parameter, a Connection object. The coroutine is invoked for every - incoming connection on the listening socket. - """ - - def handler(conn): - try: - yield func(conn) - finally: - conn.close() - - listener = Listener(host, port) - try: - while True: - conn = yield listener.accept() - yield spawn(handler(conn)) - except KeyboardInterrupt: - pass - finally: - listener.close() diff --git a/beetsplug/bpd/__init__.py b/beetsplug/bpd/__init__.py index aa98f0c7a..0af635798 100644 --- a/beetsplug/bpd/__init__.py +++ b/beetsplug/bpd/__init__.py @@ -3,6 +3,9 @@ Beets library. Attempts to implement a compatible protocol to allow use of the wide range of MPD clients. """ +from __future__ import annotations + +import asyncio import inspect import math import random @@ -20,7 +23,7 @@ from beets import dbcore from beets.exceptions import UserError from beets.library import Item from beets.plugins import BeetsPlugin -from beets.util import as_string, bluelet +from beets.util import as_string from beetsplug._utils import vfs if TYPE_CHECKING: @@ -220,6 +223,7 @@ class BaseServer: # Current connections self.connections = set() + self._notification_tasks: set[asyncio.Task[None]] = set() # Object for random numbers generation self.random_obj = random.Random() @@ -230,34 +234,42 @@ class BaseServer: def disconnect(self, conn): """Client has disconnected; clean up residual state.""" - self.connections.remove(conn) + self.connections.discard(conn) def run(self): """Block and start listening for connections from clients. An interrupt (^C) closes the server. """ + asyncio.run(self._run()) + + async def _run(self) -> None: + """Serve MPD and control connections in one event loop.""" self.startup_time = time.time() - def start(): - yield bluelet.spawn( - bluelet.server( - self.ctrl_host, - self.ctrl_port, - ControlConnection.handler(self), + async with await asyncio.start_server( + ControlConnection.handler(self), + self.ctrl_host, + self.ctrl_port, + family=socket.AF_INET, + ) as control_server: + async with await asyncio.start_server( + MPDConnection.handler(self), + self.host, + self.port, + family=socket.AF_INET, + ) as mpd_server: + await asyncio.gather( + control_server.serve_forever(), mpd_server.serve_forever() ) - ) - yield bluelet.server( - self.host, self.port, MPDConnection.handler(self) - ) - bluelet.run(start()) - - def dispatch_events(self): + def dispatch_events(self) -> None: """If any clients have idle events ready, send them.""" # We need a copy of `self.connections` here since clients might # disconnect once we try and send to them, changing `self.connections`. for conn in list(self.connections): - yield bluelet.spawn(conn.send_notifications()) + task = asyncio.create_task(conn.send_notifications()) + self._notification_tasks.add(task) + task.add_done_callback(self._notification_tasks.discard) def _ctrl_send(self, message): """Send some data over the control socket. @@ -738,39 +750,46 @@ class BaseServer: class Connection: """A connection between a client and the server.""" - def __init__(self, server, sock): - """Create a new connection for the accepted socket `client`.""" + def __init__(self, server, reader, writer): + """Create a new connection for the accepted client streams.""" self.server = server - self.sock = sock - self.address = ":".join(map(str, sock.sock.getpeername())) + self.reader = reader + self.writer = writer + peername = writer.get_extra_info("peername") + self.address = ":".join(map(str, peername)) if peername else "" def debug(self, message, kind=" "): """Log a debug message about this connection.""" self.server._log.debug("{}[{.address}]: {}", kind, self, message) - def run(self): - pass + async def run(self) -> None: + raise NotImplementedError - def send(self, lines): - """Send lines, which which is either a single string or an + async def send(self, lines) -> None: + """Send lines, which is either a single string or an iterable consisting of strings, to the client. A newline is - added after every string. Returns a Bluelet event that sends - the data. + added after every string. """ if isinstance(lines, str): lines = [lines] out = NEWLINE.join(lines) + NEWLINE for line in out.split(NEWLINE)[:-1]: self.debug(line, kind=">") - if isinstance(out, str): - out = out.encode("utf-8") - return self.sock.sendall(out) + self.writer.write(out.encode("utf-8")) + await self.writer.drain() @classmethod def handler(cls, server): - def _handle(sock): + async def _handle(reader, writer): """Creates a new `Connection` and runs it.""" - return cls(server, sock).run() + try: + await cls(server, reader, writer).run() + finally: + writer.close() + try: + await writer.wait_closed() + except ConnectionError: + pass return _handle @@ -778,24 +797,23 @@ class Connection: class MPDConnection(Connection): """A connection that receives commands from an MPD-compatible client.""" - def __init__(self, server, sock): + def __init__(self, server, reader, writer): """Create a new connection for the accepted socket `client`.""" - super().__init__(server, sock) + super().__init__(server, reader, writer) self.authenticated = False self.notifications = set() self.idle_subscriptions = set() - def do_command(self, command): - """A coroutine that runs the given command and sends an - appropriate response.""" + async def do_command(self, command) -> None: + """Run the given command and send an appropriate response.""" try: - yield bluelet.call(command.run(self)) + await command.run(self) except BPDError as e: # Send the error. - yield self.send(e.response()) + await self.send(e.response()) else: # Send success code. - yield self.send(RESP_OK) + await self.send(RESP_OK) def disconnect(self): """The connection has closed for any reason.""" @@ -806,37 +824,37 @@ class MPDConnection(Connection): """Queue up an event for sending to this client.""" self.notifications.add(event) - def send_notifications(self, force_close_idle=False): + async def send_notifications(self, force_close_idle=False) -> None: """Send the client any queued events now.""" pending = self.notifications.intersection(self.idle_subscriptions) try: for event in pending: - yield self.send(f"changed: {event}") + await self.send(f"changed: {event}") if pending or force_close_idle: self.idle_subscriptions = set() self.notifications = self.notifications.difference(pending) - yield self.send(RESP_OK) - except bluelet.SocketClosedError: + await self.send(RESP_OK) + except ConnectionError: self.disconnect() # Client disappeared. - def run(self): + async def run(self) -> None: """Send a greeting to the client and begin processing commands as they arrive. """ self.debug("connected", kind="*") self.server.connect(self) - yield self.send(HELLO) + await self.send(HELLO) clist = None # Initially, no command list is being constructed. while True: - line = yield self.sock.readline() + line = await self.reader.readline() if not line: self.disconnect() # Client disappeared. break line = line.strip() if not line: err = BPDError(ERROR_UNKNOWN, "No command given") - yield self.send(err.response()) + await self.send(err.response()) self.disconnect() # Client sent a blank line. break line = line.decode("utf8") # MPD protocol uses UTF-8. @@ -846,12 +864,13 @@ class MPDConnection(Connection): if self.idle_subscriptions: # The connection is in idle mode. if line == "noidle": - yield bluelet.call(self.send_notifications(True)) + await self.send_notifications(True) else: err = BPDError( ERROR_UNKNOWN, f"Got command while idle: {line}" ) - yield self.send(err.response()) + await self.send(err.response()) + self.disconnect() break continue if line == "noidle": @@ -861,9 +880,9 @@ class MPDConnection(Connection): if clist is not None: # Command list already opened. if line == CLIST_END: - yield bluelet.call(self.do_command(clist)) + await self.do_command(clist) clist = None # Clear the command list. - yield bluelet.call(self.server.dispatch_events()) + self.server.dispatch_events() else: clist.append(Command(line)) @@ -874,33 +893,32 @@ class MPDConnection(Connection): else: # Ordinary command. try: - yield bluelet.call(self.do_command(Command(line))) + await self.do_command(Command(line)) except BPDCloseError: # Command indicates that the conn should close. - self.sock.close() self.disconnect() # Client explicitly closed. return except BPDIdleError as e: self.idle_subscriptions = e.subsystems self.debug(f"awaiting: {' '.join(e.subsystems)}", kind="z") - yield bluelet.call(self.server.dispatch_events()) + self.server.dispatch_events() class ControlConnection(Connection): """A connection used to control BPD for debugging and internal events.""" - def __init__(self, server, sock): + def __init__(self, server, reader, writer): """Create a new connection for the accepted socket `client`.""" - super().__init__(server, sock) + super().__init__(server, reader, writer) def debug(self, message, kind=" "): self.server._log.debug("CTRL {}[{.address}]: {}", kind, self, message) - def run(self): + async def run(self) -> None: """Listen for control commands and delegate to `ctrl_*` methods.""" self.debug("connected", kind="*") while True: - line = yield self.sock.readline() + line = await self.reader.readline() if not line: break # Client disappeared. line = line.strip() @@ -912,33 +930,33 @@ class ControlConnection(Connection): command = Command(line) try: func = command.delegate("ctrl_", self) - yield bluelet.call(func(*command.args)) + await func(*command.args) except (AttributeError, TypeError) as e: - yield self.send(f"ERROR: {e.args[0]}") + await self.send(f"ERROR: {e.args[0]}") except Exception: - yield self.send( + await self.send( ["ERROR: server error", traceback.format_exc().rstrip()] ) - def ctrl_play_finished(self): + async def ctrl_play_finished(self) -> None: """Callback from the player signalling a song finished playing.""" - yield bluelet.call(self.server.dispatch_events()) + self.server.dispatch_events() - def ctrl_profile(self): + async def ctrl_profile(self) -> None: """Memory profiling for debugging.""" from guppy import hpy heap = hpy().heap() - yield self.send(heap) + await self.send(str(heap)) - def ctrl_nickname(self, oldlabel, newlabel): + async def ctrl_nickname(self, oldlabel, newlabel) -> None: """Rename a client in the log messages.""" for c in self.server.connections: if c.address == oldlabel: c.address = newlabel break else: - yield self.send(f"ERROR: no such client: {oldlabel}") + await self.send(f"ERROR: no such client: {oldlabel}") class Command: @@ -997,10 +1015,8 @@ class Command: return func - def run(self, conn): - """A coroutine that executes the command on the given - connection. - """ + async def run(self, conn) -> None: + """Execute the command on the given connection.""" try: # `conn` is an extra argument to all cmd handlers. func = self.delegate("cmd_", conn.server, extra_args=1) @@ -1022,13 +1038,13 @@ class Command: results = func(*args) if results: for data in results: - yield conn.send(data) + await conn.send(data) except BPDError as e: # An exposed error. Set the command name and then let # the Connection handle it. e.cmd_name = self.name - raise e + raise except BPDCloseError: # An indication that the connection should close. Send @@ -1059,20 +1075,20 @@ class CommandList(list[Command]): self.append(item) self.verbose = verbose - def run(self, conn): - """Coroutine executing all the commands in this list.""" + async def run(self, conn) -> None: + """Execute all the commands in this list.""" for i, command in enumerate(self): try: - yield bluelet.call(command.run(conn)) + await command.run(conn) except BPDError as e: # If the command failed, stop executing. e.index = i # Give the error the correct index. - raise e + raise # Otherwise, possibly send the output delimiter if we're in a # verbose ("OK") command list. if self.verbose: - yield conn.send(RESP_CLIST_VERBOSE) + await conn.send(RESP_CLIST_VERBOSE) # A subclass of the basic, protocol-handling server that actually plays diff --git a/docs/changelog.rst b/docs/changelog.rst index 192c31a28..135459e36 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -68,9 +68,11 @@ Bug fixes For plugin developers ~~~~~~~~~~~~~~~~~~~~~ -.. - Other changes - ~~~~~~~~~~~~~ +Other changes +~~~~~~~~~~~~~ + +- :doc:`plugins/bpd`: Replace the bundled Bluelet scheduler with Python's + standard ``asyncio`` event loop. 2.13.1 (July 29, 2026) ---------------------- diff --git a/test/plugins/test_bpd.py b/test/plugins/test_bpd.py index ba9aba822..74f004105 100644 --- a/test/plugins/test_bpd.py +++ b/test/plugins/test_bpd.py @@ -1,5 +1,6 @@ """Tests for BPD's implementation of the MPD protocol.""" +import asyncio import multiprocessing as mp import os import socket @@ -16,7 +17,6 @@ import pytest import yaml from beets.test.helper import PluginTestCase -from beets.util import bluelet bpd = pytest.importorskip("beetsplug.bpd", exc_type=ImportError) @@ -206,24 +206,23 @@ def implements(commands, fail=False): return unittest.expectedFailure(_test) if fail else _test -bluelet_listener = bluelet.Listener +asyncio_start_server = asyncio.start_server -@patch("beets.util.bluelet.Listener") -def start_server(args, assigned_port, listener_patch): +@patch("beetsplug.bpd.asyncio.start_server") +def start_server(args, assigned_port, start_server_patch): """Start the bpd server, writing the port to `assigned_port`.""" - def listener_wrap(host, port): - """Wrap `bluelet.Listener`, writing the port to `assigend_port`.""" - # `bluelet.Listener` has previously been saved to - # `bluelet_listener` as this function will replace it at its - # original location. - listener = bluelet_listener(host, port) - # read port assigned by OS - assigned_port.put_nowait(listener.sock.getsockname()[1]) - return listener + async def start_server_wrap(callback, host, port, **kwargs): + """Start an asyncio server and report its assigned port.""" + # `asyncio.start_server` has previously been saved because this + # function replaces it at its original location. + server = await asyncio_start_server(callback, host, port, **kwargs) + # Read the port assigned by the OS. + assigned_port.put_nowait(server.sockets[0].getsockname()[1]) + return server - listener_patch.side_effect = listener_wrap + start_server_patch.side_effect = start_server_wrap import beets.ui From d53af833862197c87e5f129f5de89a4c9b7dfd3f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=A0ar=C5=ABnas=20Nejus?= Date: Tue, 4 Aug 2026 01:34:14 +0100 Subject: [PATCH 23/23] Serialize BPD notifications per connection - Track active notification tasks by connection so repeated dispatches do not send duplicate idle responses while a previous send is still draining. - Add regression coverage for serialized notification delivery and idle command disconnect handling. --- beetsplug/bpd/__init__.py | 26 +++++++++++-- test/plugins/test_bpd.py | 78 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 100 insertions(+), 4 deletions(-) diff --git a/beetsplug/bpd/__init__.py b/beetsplug/bpd/__init__.py index 0af635798..bd6108362 100644 --- a/beetsplug/bpd/__init__.py +++ b/beetsplug/bpd/__init__.py @@ -223,7 +223,7 @@ class BaseServer: # Current connections self.connections = set() - self._notification_tasks: set[asyncio.Task[None]] = set() + self._notification_tasks: dict[MPDConnection, asyncio.Task[None]] = {} # Object for random numbers generation self.random_obj = random.Random() @@ -267,9 +267,27 @@ class BaseServer: # We need a copy of `self.connections` here since clients might # disconnect once we try and send to them, changing `self.connections`. for conn in list(self.connections): - task = asyncio.create_task(conn.send_notifications()) - self._notification_tasks.add(task) - task.add_done_callback(self._notification_tasks.discard) + self._dispatch_connection_events(conn) + + def _dispatch_connection_events(self, conn) -> None: + """Start sending queued events unless this connection is busy.""" + if conn in self._notification_tasks: + return + task = asyncio.create_task(conn.send_notifications()) + self._notification_tasks[conn] = task + task.add_done_callback(lambda task: self._notification_done(conn, task)) + + def _notification_done(self, conn, task) -> None: + """Release a connection after its queued events have been sent.""" + del self._notification_tasks[conn] + if task.cancelled(): + return + if error := task.exception(): + self._log.error("Could not send BPD notifications: {}", error) + return + pending = conn.notifications.intersection(conn.idle_subscriptions) + if conn in self.connections and pending: + self._dispatch_connection_events(conn) def _ctrl_send(self, message): """Send some data over the control socket. diff --git a/test/plugins/test_bpd.py b/test/plugins/test_bpd.py index 74f004105..e21a8d7cd 100644 --- a/test/plugins/test_bpd.py +++ b/test/plugins/test_bpd.py @@ -206,6 +206,84 @@ def implements(commands, fail=False): return unittest.expectedFailure(_test) if fail else _test +class MemoryStreamWriter: + """Capture writes and optionally hold them at the drain boundary.""" + + def __init__(self, block_drain=False): + self.data = bytearray() + self.drain_started = asyncio.Event() + self.can_drain = asyncio.Event() + if not block_drain: + self.can_drain.set() + + def get_extra_info(self, name): + return ("localhost", 6600) if name == "peername" else None + + def write(self, data): + self.data.extend(data) + + async def drain(self): + self.drain_started.set() + await self.can_drain.wait() + + +class AsyncServerTest(unittest.TestCase): + def test_dispatch_events_sends_one_notification_at_a_time(self): + async def exercise(): + server = bpd.BaseServer("localhost", 0, None, 0, MagicMock()) + writer = MemoryStreamWriter(block_drain=True) + conn = bpd.MPDConnection(server, asyncio.StreamReader(), writer) + conn.notifications.add("player") + conn.idle_subscriptions.add("player") + server.connect(conn) + + server.dispatch_events() + await writer.drain_started.wait() + server.dispatch_events() + await asyncio.sleep(0) + tasks = tuple(server._notification_tasks.values()) + + writer.can_drain.set() + await asyncio.gather(*tasks) + + assert bytes(writer.data) == b"changed: player\nOK\n" + + asyncio.run(exercise()) + + def test_dispatch_events_sends_event_queued_while_task_finishes(self): + async def exercise(): + server = bpd.BaseServer("localhost", 0, None, 0, MagicMock()) + writer = MemoryStreamWriter() + conn = bpd.MPDConnection(server, asyncio.StreamReader(), writer) + conn.idle_subscriptions.add("player") + server.connect(conn) + + server.dispatch_events() + await asyncio.sleep(0) + conn.notify("player") + server.dispatch_events() + await asyncio.sleep(0) + await asyncio.gather(*server._notification_tasks.values()) + + assert bytes(writer.data) == b"changed: player\nOK\n" + + asyncio.run(exercise()) + + def test_idle_error_disconnects_client(self): + async def exercise(): + server = bpd.BaseServer("localhost", 0, None, 0, MagicMock()) + reader = asyncio.StreamReader() + reader.feed_data(b"idle\nnotacommand\n") + reader.feed_eof() + conn = bpd.MPDConnection(server, reader, MemoryStreamWriter()) + + await conn.run() + + assert conn not in server.connections + + asyncio.run(exercise()) + + asyncio_start_server = asyncio.start_server