Debian Codegraph @

beetsplug/_utils/playcount.py

raw
1 from __future__ import annotations
2
3 from typing import TYPE_CHECKING, TypedDict
4
5 from typing_extensions import NotRequired
6
7 from beets.dbcore import AndQuery, MatchQuery, OrQuery
8 from beets.dbcore.query import StringQuery, SubstringQuery
9
10 if TYPE_CHECKING:
11 from collections.abc import Sequence
12
13 from beets.dbcore import Query
14 from beets.library import Item, Library
15 from beets.logging import BeetsLogger
16
17
18 class Track(TypedDict):
19 mbid: str | None
20 name: str
21 artist: str
22 playcount: int
23 album: NotRequired[str | None]
24
25
26 def get_items(lib: Library, track: Track, log: BeetsLogger) -> Sequence[Item]:
27 mbid = track["mbid"]
28 if mbid:
29 items = list(lib.items(MatchQuery("mb_trackid", mbid)))
30 if items:
31 # Prefer MBID if there is a match
32 return items
33
34 artist, title = track["artist"], track["name"]
35 album = track.get("album") or ""
36
37 log.debug("query: {} - {} ({})", artist, title, album)
38
39 # Try exact match first
40 title_query = OrQuery(
41 [
42 StringQuery("title", title),
43 # try a right single quotation mark instead of an apostrophe
44 StringQuery("title", title.replace("'", "\u2019")),
45 ]
46 )
47
48 or_queries: list[Query] = [StringQuery("artist", artist)]
49 if album:
50 or_queries.append(StringQuery("album", album))
51
52 items = list(lib.items(AndQuery([title_query, OrQuery(or_queries)])))
53 if items:
54 return items
55
56 # Fall back to substring matches
57 title_query = OrQuery(
58 [
59 SubstringQuery("title", title),
60 # try a right single quotation mark instead of an apostrophe
61 SubstringQuery("title", title.replace("'", "\u2019")),
62 ]
63 )
64 or_queries = [SubstringQuery("artist", artist)]
65 if album:
66 or_queries.append(SubstringQuery("album", album))
67
68 return list(lib.items(AndQuery([title_query, OrQuery(or_queries)])))
69
70
71 def process_track(
72 lib: Library, track: Track, log: BeetsLogger, source: str
73 ) -> bool:
74 items = get_items(lib, track, log)
75 if not items:
76 return False
77
78 new_count = track["playcount"]
79 field = f"{source}_play_count"
80 for song in items:
81 count = int(song.get(field, 0))
82 log.debug(
83 "match: {0.artist} - {0.title} ({0.album}) updating:"
84 " {1} {2} => {3}",
85 song,
86 field,
87 count,
88 new_count,
89 )
90 song[field] = new_count
91 song.store()
92
93 return True
94
95
96 def update_play_counts(
97 lib: Library, tracks: Sequence[Track], log: BeetsLogger, source: str
98 ) -> tuple[int, int]:
99 total = len(tracks)
100 total_found = 0
101 total_fails = 0
102 log.info("Received {} tracks in this page, processing...", total)
103
104 with lib.transaction():
105 for i, track in enumerate(tracks, 1):
106 if i % 250 == 0:
107 log.info("Processing track {}/{} ...", i, total)
108 if process_track(lib, track, log, source):
109 total_found += 1
110 else:
111 total_fails += 1
112
113 if total_fails > 0:
114 log.info(
115 "Acquired {}/{} play-counts ({} unknown)",
116 total_found,
117 total,
118 total_fails,
119 )
120
121 return total_found, total_fails