Debian Codegraph @

beetsplug/lastimport.py

raw
1 from __future__ import annotations
2
3 from typing import TYPE_CHECKING, NamedTuple
4
5 import pylast
6 from pylast import _extract, _number
7
8 from beets import config, plugins, ui
9 from beets.dbcore import types
10 from beets.exceptions import UserError
11
12 from ._utils.playcount import update_play_counts
13
14 if TYPE_CHECKING:
15 import optparse
16
17 from beets.library import Library
18 from beets.logging import BeetsLogger as Logger
19
20 from ._utils.playcount import Track
21
22 API_URL = "https://ws.audioscrobbler.com/2.0/"
23
24
25 class OurTrack(pylast.Track):
26 mbid: str
27
28
29 class OurTopItem(NamedTuple):
30 item: OurTrack
31 weight: float
32
33
34 class LastImportPlugin(plugins.BeetsPlugin):
35 def __init__(self) -> None:
36 super().__init__()
37 config["lastfm"].add({"user": "", "api_key": plugins.LASTFM_KEY})
38 config["lastfm"]["user"].redact = True
39 config["lastfm"]["api_key"].redact = True
40 self.config.add({"per_page": 500, "retry_limit": 3})
41 self.item_types = {"lastfm_play_count": types.INTEGER}
42
43 def commands(self) -> list[ui.Subcommand]:
44 cmd = ui.Subcommand("lastimport", help="import last.fm play-count")
45
46 def func(lib: Library, opts: optparse.Values, args: list[str]) -> None:
47 import_lastfm(lib, self._log)
48
49 cmd.func = func
50 return [cmd]
51
52
53 class CustomUser(pylast.User):
54 """Custom user class derived from pylast.User, and overriding the
55 _get_things method to return MBID and album. Also introduces new
56 get_top_tracks_by_page method to allow access to more than one page of top
57 tracks.
58 """
59
60 def __init__(self, *args, **kwargs) -> None:
61 super().__init__(*args, **kwargs)
62
63 def _get_things(
64 self,
65 method: str,
66 thing_type: type[pylast.Track | pylast.Album],
67 params: type[pylast._Opus] | None = None,
68 cacheable: bool = True,
69 stream: bool = False,
70 ) -> tuple[list[OurTopItem], int]:
71 """Returns a list of the most played thing_types by this thing, in a
72 tuple with the total number of pages of results. Includes an MBID, if
73 found.
74 """
75 doc = self._request(f"{self.ws_prefix}.{method}", cacheable, params)
76
77 toptracks_node = doc.getElementsByTagName("toptracks")[0]
78 total_pages = int(toptracks_node.getAttribute("totalPages"))
79
80 seq = []
81 for node in doc.getElementsByTagName(thing_type.__name__.lower()):
82 title = _extract(node, "name")
83 artist = _extract(node, "name", 1)
84 mbid = _extract(node, "mbid")
85 playcount = _number(_extract(node, "playcount"))
86
87 thing = OurTrack(artist, title, self.network)
88 thing.mbid = mbid # type: ignore[union-attr]
89 seq.append(OurTopItem(thing, playcount))
90
91 return seq, total_pages
92
93 def get_top_tracks_by_page(
94 self,
95 period: str = pylast.PERIOD_OVERALL,
96 limit: int | None = None,
97 page: int = 1,
98 cacheable: bool = True,
99 ) -> tuple[list[OurTopItem], int]:
100 """Returns the top tracks played by a user, in a tuple with the total
101 number of pages of results.
102 * period: The period of time. Possible values:
103 o PERIOD_OVERALL
104 o PERIOD_7DAYS
105 o PERIOD_1MONTH
106 o PERIOD_3MONTHS
107 o PERIOD_6MONTHS
108 o PERIOD_12MONTHS
109 """
110
111 params = self._get_params()
112 params["period"] = period
113 params["page"] = page
114 if limit:
115 params["limit"] = limit
116
117 return self._get_things("getTopTracks", pylast.Track, params, cacheable)
118
119
120 def import_lastfm(lib: Library, log: Logger) -> None:
121 user = config["lastfm"]["user"].as_str()
122 per_page = config["lastimport"]["per_page"].get(int)
123
124 if not user:
125 raise UserError("You must specify a user name for lastimport")
126
127 log.info("Fetching last.fm library for @{}", user)
128
129 page_total = 1
130 page_current = 0
131 found_total = 0
132 unknown_total = 0
133 retry_limit = config["lastimport"]["retry_limit"].get(int)
134 # Iterate through a yet to be known page total count
135 while page_current < page_total:
136 log.info(
137 "Querying page #{}{}...",
138 page_current + 1,
139 f"/{page_total}" if page_total > 1 else "",
140 )
141
142 for retry in range(retry_limit):
143 tracks, page_total = fetch_tracks(user, page_current + 1, per_page)
144 if page_total < 1:
145 # It means nothing to us!
146 raise UserError("Last.fm reported no data.")
147
148 if tracks:
149 found, unknown = update_play_counts(lib, tracks, log, "lastfm")
150 found_total += found
151 unknown_total += unknown
152 break
153 log.error("ERROR: unable to read page #{}", page_current + 1)
154 if retry < retry_limit:
155 log.info(
156 "Retrying page #{}... ({}/{} retry)",
157 page_current + 1,
158 retry + 1,
159 retry_limit,
160 )
161 else:
162 log.error(
163 "FAIL: unable to fetch page #{}, ",
164 "tried {} times",
165 page_current,
166 retry + 1,
167 )
168 page_current += 1
169
170 log.info("... done!")
171 log.info("finished processing {} song pages", page_total)
172 log.info("{} unknown play-counts", unknown_total)
173 log.info("{} play-counts imported", found_total)
174
175
176 def fetch_tracks(user: str, page: int, limit: int) -> tuple[list[Track], int]:
177 network = pylast.LastFMNetwork(api_key=config["lastfm"]["api_key"].get(str))
178 user_obj = CustomUser(user, network)
179 results, total_pages = user_obj.get_top_tracks_by_page(
180 limit=limit, page=page
181 )
182 return [
183 {
184 "mbid": t.item.mbid or "",
185 "artist": (
186 n.strip() if ((a := t.item.artist) and (n := a.name)) else ""
187 ),
188 "name": ti.strip() if ((i := t.item) and (ti := i.title)) else "",
189 "playcount": int(t.weight),
190 }
191 for t in results
192 ], total_pages