mirror of
https://github.com/beetbox/beets.git
synced 2026-12-01 00:11:21 -06:00
Merge branch 'master' into fromfilename-improvements
This commit is contained in:
@@ -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
|
||||
@@ -271,3 +273,5 @@ d24c0d341ec6074c343cd8054083fe358da8fa14
|
||||
b2f52ac12443c102712b735e456fd07a6525786b
|
||||
# Return Path from TestHelper.create_mediafile_fixture
|
||||
bb66b0c378e9bf7d97622a1582d93c4dfcf20fdd
|
||||
# Move AttrDict under beets.util
|
||||
ea334bd977ee8ed0cdbd627b7e9564dd08dd43f7
|
||||
|
||||
@@ -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,
|
||||
@@ -19,6 +19,7 @@ from .match import (
|
||||
tag_album,
|
||||
tag_item,
|
||||
)
|
||||
from .source import Source
|
||||
|
||||
|
||||
def __getattr__(name: str):
|
||||
@@ -34,12 +35,12 @@ def __getattr__(name: str):
|
||||
__all__ = [
|
||||
"AlbumInfo",
|
||||
"AlbumMatch",
|
||||
"AttrDict",
|
||||
"Distance",
|
||||
"Info",
|
||||
"Match",
|
||||
"Proposal",
|
||||
"Recommendation",
|
||||
"Source",
|
||||
"TrackInfo",
|
||||
"TrackMatch",
|
||||
"assign_items",
|
||||
|
||||
+35
-37
@@ -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 Likelies
|
||||
from beets.util.color import ColorName
|
||||
|
||||
from .hooks import AlbumInfo, TrackInfo
|
||||
@@ -427,28 +428,27 @@ def track_distance(
|
||||
|
||||
|
||||
def distance(
|
||||
items: Sequence[Item],
|
||||
original: Likelies,
|
||||
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` 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.
|
||||
"""
|
||||
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
|
||||
|
||||
+2
-51
@@ -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."""
|
||||
|
||||
|
||||
+22
-38
@@ -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.
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING, Literal, NamedTuple
|
||||
|
||||
from beets.util import Likelies, 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: Likelies
|
||||
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=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=Likelies(item),
|
||||
items=[item],
|
||||
id=item.mb_trackid,
|
||||
id_consensus=True,
|
||||
)
|
||||
@@ -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"
|
||||
|
||||
+14
-21
@@ -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
|
||||
|
||||
@@ -412,6 +412,10 @@ class SearchApiMetadataSourcePlugin(
|
||||
if self.config["search_query_ascii"].get():
|
||||
query = unidecode.unidecode(query)
|
||||
|
||||
if not query and not filters:
|
||||
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)
|
||||
|
||||
|
||||
@@ -684,6 +684,7 @@ class TerminalImportSessionFixture(TerminalImportSession):
|
||||
self.io = kwargs.pop("io")
|
||||
super().__init__(*args, **kwargs)
|
||||
self._choices = []
|
||||
self._duplicate_actions = []
|
||||
|
||||
default_choice = importer.Action.APPLY
|
||||
|
||||
@@ -692,6 +693,17 @@ 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)
|
||||
|
||||
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
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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):
|
||||
|
||||
+71
-14
@@ -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]) -> Likelies:
|
||||
"""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(likelies)
|
||||
|
||||
|
||||
# stdout and stderr as bytes
|
||||
@@ -1206,3 +1200,66 @@ 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)
|
||||
|
||||
|
||||
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
|
||||
|
||||
@@ -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()
|
||||
+3
-2
@@ -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(
|
||||
|
||||
+112
-78
@@ -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: dict[MPDConnection, asyncio.Task[None]] = {}
|
||||
|
||||
# Object for random numbers generation
|
||||
self.random_obj = random.Random()
|
||||
@@ -230,34 +234,60 @@ 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())
|
||||
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.
|
||||
@@ -738,39 +768,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 "<unknown>"
|
||||
|
||||
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 +815,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 +842,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 +882,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 +898,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 +911,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 +948,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 +1033,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 +1056,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 +1093,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
|
||||
|
||||
+8
-4
@@ -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"),
|
||||
|
||||
@@ -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:
|
||||
|
||||
+2
-11
@@ -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:
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -40,6 +40,19 @@ if TYPE_CHECKING:
|
||||
|
||||
log = getLogger("beets.tidal")
|
||||
|
||||
_normalize_label_re = re.compile(
|
||||
r"""
|
||||
^(?:.*(?:©|℗|\([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,
|
||||
)
|
||||
|
||||
|
||||
class TidalPlugin(MetadataSourcePlugin):
|
||||
item_types: ClassVar[dict[str, types.Type]] = {
|
||||
@@ -392,6 +405,13 @@ class TidalPlugin(MetadataSourcePlugin):
|
||||
tidal_updated=time.time(),
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _normalize_label(text: str) -> str:
|
||||
"""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(
|
||||
album: TidalAlbum, artwork_by_id: dict[str, TidalArtwork]
|
||||
@@ -487,7 +507,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
|
||||
|
||||
+23
-4
@@ -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
|
||||
~~~~~~~~~
|
||||
@@ -50,14 +52,31 @@ 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`
|
||||
- :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`
|
||||
- :doc:`plugins/discogs`: Retry a search once when Discogs returns an invalid
|
||||
JSON response instead of immediately discarding all Discogs candidates.
|
||||
- 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
|
||||
~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
..
|
||||
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)
|
||||
----------------------
|
||||
|
||||
@@ -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.
|
||||
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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``.
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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)
|
||||
|
||||
+91
-14
@@ -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,101 @@ def implements(commands, fail=False):
|
||||
return unittest.expectedFailure(_test) if fail else _test
|
||||
|
||||
|
||||
bluelet_listener = bluelet.Listener
|
||||
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()
|
||||
|
||||
|
||||
@patch("beets.util.bluelet.Listener")
|
||||
def start_server(args, assigned_port, listener_patch):
|
||||
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
|
||||
|
||||
|
||||
@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
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -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",
|
||||
[
|
||||
|
||||
@@ -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`.
|
||||
|
||||
@@ -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()
|
||||
|
||||
+1
-6
@@ -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):
|
||||
|
||||
@@ -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()
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user