diff --git a/beetsplug/_utils/playcount.py b/beetsplug/_utils/playcount.py index 7bc0e3d94..4b84f5a66 100644 --- a/beetsplug/_utils/playcount.py +++ b/beetsplug/_utils/playcount.py @@ -5,7 +5,7 @@ from typing import TYPE_CHECKING, TypedDict from typing_extensions import NotRequired from beets.dbcore import AndQuery, MatchQuery, OrQuery -from beets.dbcore.query import SubstringQuery +from beets.dbcore.query import StringQuery, SubstringQuery if TYPE_CHECKING: from collections.abc import Sequence @@ -36,6 +36,24 @@ def get_items(lib: Library, track: Track, log: BeetsLogger) -> Sequence[Item]: log.debug("query: {} - {} ({})", artist, title, album) + # Try exact match first + title_query = OrQuery( + [ + StringQuery("title", title), + # try a right single quotation mark instead of an apostrophe + StringQuery("title", title.replace("'", "\u2019")), + ] + ) + + or_queries: list[Query] = [StringQuery("artist", artist)] + if album: + or_queries.append(StringQuery("album", album)) + + items = list(lib.items(AndQuery([title_query, OrQuery(or_queries)]))) + if items: + return items + + # Fall back to substring matches title_query = OrQuery( [ SubstringQuery("title", title), @@ -43,7 +61,7 @@ def get_items(lib: Library, track: Track, log: BeetsLogger) -> Sequence[Item]: SubstringQuery("title", title.replace("'", "\u2019")), ] ) - or_queries: list[Query] = [SubstringQuery("artist", artist)] + or_queries = [SubstringQuery("artist", artist)] if album: or_queries.append(SubstringQuery("album", album)) diff --git a/test/plugins/utils/test_playcount.py b/test/plugins/utils/test_playcount.py index 61c32404b..ca8dbb6ca 100644 --- a/test/plugins/utils/test_playcount.py +++ b/test/plugins/utils/test_playcount.py @@ -110,6 +110,27 @@ class TestPlayCount(TestHelper): assert matched_ids == [by_mbid.id] + def test_get_items_prefers_exact_match(self, log): + exact_match = self.add_item(title="Song", artist="Artist") + self.add_item(title="Song (inst.)", artist="Artist") + + matched_ids = [ + matched.id for matched in get_items(self.lib, self.track(), log) + ] + + assert matched_ids == [exact_match.id] + + def test_get_items_falls_back_to_substring_match(self, log): + substring_match = self.add_item( + title="Song (feat. Artist)", artist="Artist" + ) + + matched_ids = [ + matched.id for matched in get_items(self.lib, self.track(), log) + ] + + assert matched_ids == [substring_match.id] + def test_process_track_updates_every_matching_song(self, log): first = self.add_item( title="Song", artist="Artist", album="First Album", play_count=1