Debian Codegraph @

beetsplug/mpdstats.py

raw
1 from __future__ import annotations
2
3 import os
4 import time
5 from typing import TYPE_CHECKING, Any, ClassVar, Literal, TypedDict, overload
6
7 import mpd
8 from typing_extensions import NotRequired
9
10 from beets import config, plugins, ui
11 from beets.dbcore import types
12 from beets.dbcore.query import PathQuery
13 from beets.exceptions import UserError
14 from beets.util import displayable_path
15
16 if TYPE_CHECKING:
17 import optparse
18
19 from beets.library import Item, Library
20 from beets.logging import BeetsLogger as Logger
21
22 from ._typing import JSONDict
23
24
25 #: When playlist is empty and status is "stop", it is an empty dictionary.
26 MPDCurrentSong = TypedDict(
27 "MPDCurrentSong",
28 {
29 "added": NotRequired[str],
30 "artist": NotRequired[str],
31 "date": NotRequired[str],
32 "duration": NotRequired[str],
33 "file": NotRequired[str],
34 "format": NotRequired[str],
35 "id": NotRequired[str],
36 "last-modified": NotRequired[str],
37 "pos": NotRequired[str],
38 "time": NotRequired[str],
39 "title": NotRequired[str],
40 },
41 )
42
43
44 class MPDStatus(TypedDict):
45 state: Literal["play", "pause", "stop"]
46 volume: str
47 repeat: str
48 random: str
49 single: str
50 consume: str
51 partition: str
52 playlist: str
53 playlistlength: str
54 mixrampdb: str
55 lastloadedplaylist: str
56 song: str
57 songid: str
58 # below are only set when status is "play" or "pause"
59 time: NotRequired[str]
60 elapsed: NotRequired[str]
61 bitrate: NotRequired[str]
62 duration: NotRequired[str]
63 audio: NotRequired[str]
64 nextsong: NotRequired[str]
65 nextsongid: NotRequired[str]
66
67
68 class NowPlaying(TypedDict):
69 started: float
70 elapsed_at_start: int
71 duration: int
72 path: str
73 id: str
74 beets_item: Item | None
75
76
77 # If we lose the connection, how many times do we want to retry and how
78 # much time should we wait between retries?
79 RETRIES = 10
80 RETRY_INTERVAL = 5
81 DUPLICATE_PLAY_THRESHOLD = 10.0
82
83
84 mpd_config = config["mpd"]
85
86
87 def is_url(path: str) -> bool:
88 """Try to determine if the path is an URL."""
89 if isinstance(path, bytes): # if it's bytes, then it's a path
90 return False
91 return path.split("://", 1)[0] in ["http", "https"]
92
93
94 class MPDClientWrapper:
95 def __init__(self, log: Logger) -> None:
96 self._log = log
97
98 self.music_directory = mpd_config["music_directory"].as_str()
99 self.strip_path = mpd_config["strip_path"].as_str()
100
101 # Ensure strip_path end with '/'
102 if not self.strip_path.endswith("/"):
103 self.strip_path += "/"
104
105 self._log.debug("music_directory: {.music_directory}", self)
106 self._log.debug("strip_path: {.strip_path}", self)
107
108 self.client = mpd.MPDClient()
109
110 def connect(self) -> None:
111 """Connect to the MPD."""
112 host = mpd_config["host"].as_str()
113 port = mpd_config["port"].get(int)
114
115 if host[0] in ["/", "~"]:
116 host = os.path.expanduser(host)
117
118 self._log.info("connecting to {}:{}", host, port)
119 try:
120 self.client.connect(host, port)
121 except OSError as e:
122 raise UserError(f"could not connect to MPD: {e}")
123
124 password = mpd_config["password"].as_str()
125 if password:
126 try:
127 self.client.password(password)
128 except mpd.CommandError as e:
129 raise UserError(f"could not authenticate to MPD: {e}")
130
131 def disconnect(self) -> None:
132 """Disconnect from the MPD."""
133 self.client.close()
134 self.client.disconnect()
135
136 @overload
137 def get(
138 self, command: Literal["currentsong"], retries: int = RETRIES
139 ) -> MPDCurrentSong: ...
140 @overload
141 def get(
142 self, command: Literal["status"], retries: int = RETRIES
143 ) -> MPDStatus: ...
144 @overload
145 def get(
146 self, command: Literal["idle"], retries: int = RETRIES
147 ) -> list[str]: ...
148 @overload
149 def get(self, command: str, retries: int = RETRIES) -> Any: ...
150 def get(self, command: str, retries: int = RETRIES) -> Any:
151 """Wrapper for requests to the MPD server. Tries to re-connect if the
152 connection was lost (f.ex. during MPD's library refresh).
153 """
154 try:
155 return getattr(self.client, command)()
156 except (OSError, mpd.ConnectionError) as err:
157 self._log.error("{}", err)
158
159 if retries <= 0:
160 # if we exited without breaking, we couldn't reconnect in time :(
161 raise UserError("communication with MPD server failed")
162
163 time.sleep(RETRY_INTERVAL)
164
165 try:
166 self.disconnect()
167 except mpd.ConnectionError:
168 pass
169
170 self.connect()
171 return self.get(command, retries=retries - 1)
172
173 def currentsong(self) -> tuple[str | None, str | None]:
174 """Return the path to the currently playing song, along with its
175 songid. Prefixes paths with the music_directory, to get the absolute
176 path.
177 In some cases, we need to remove the local path from MPD server,
178 we replace 'strip_path' with ''.
179 `strip_path` defaults to ''.
180 """
181 entry = self.get("currentsong")
182 file, id_ = entry.get("file"), entry.get("id")
183 if file and not is_url(file):
184 if file.startswith(self.strip_path):
185 file = file[len(self.strip_path) :]
186 file = os.path.join(self.music_directory, file)
187 self._log.debug("returning: {}", file)
188 return file, id_
189
190 def status(self) -> MPDStatus:
191 """Return the current status of the MPD."""
192 return self.get("status")
193
194 def events(self) -> list[str]:
195 """Return list of events. This may block a long time while waiting for
196 an answer from MPD.
197 """
198 return self.get("idle")
199
200
201 class MPDStats:
202 now_playing: NowPlaying | None = None
203
204 def __init__(self, lib: Library, log: Logger) -> None:
205 self.lib = lib
206 self._log = log
207
208 self.do_rating = mpd_config["rating"].get(bool)
209 self.rating_mix = mpd_config["rating_mix"].get(float)
210 self.played_ratio_threshold = mpd_config["played_ratio_threshold"].get(
211 float
212 )
213 self.mpd = MPDClientWrapper(log)
214
215 def rating(
216 self, play_count: int, skip_count: int, rating: float, skipped: bool
217 ) -> float:
218 """Calculate a new rating for a song based on play count, skip count,
219 old rating and the fact if it was skipped or not.
220 """
221 if skipped:
222 rolling = rating - rating / 2.0
223 else:
224 rolling = rating + (1.0 - rating) / 2.0
225 stable = (play_count + 1.0) / (play_count + skip_count + 2.0)
226 return self.rating_mix * stable + (1.0 - self.rating_mix) * rolling
227
228 def get_item(self, path: str) -> Item | None:
229 """Return the beets item related to path."""
230 query = PathQuery("path", os.fsencode(path))
231 item = self.lib.items(query).get()
232 if item:
233 return item
234 self._log.info("item not found: {}", displayable_path(path))
235 return None
236
237 def update_item(
238 self,
239 item: Item | None,
240 attribute: str,
241 value: float | None = None,
242 increment: float | None = None,
243 ) -> None:
244 """Update the beets item. Set attribute to value or increment the value
245 of attribute. If the increment argument is used the value is cast to
246 the corresponding type.
247 """
248 if item is None:
249 return
250
251 if increment is not None:
252 item.load()
253 value = type(increment)(item.get(attribute, 0)) + increment
254
255 if value is not None:
256 item[attribute] = value
257 item.store()
258
259 self._log.debug(
260 "updated: {} = {} [{.filepath}]",
261 attribute,
262 item[attribute],
263 item,
264 )
265
266 def update_rating(self, item: Item | None, skipped: bool) -> None:
267 """Update the rating for a beets item. The `item` can either be a
268 beets `Item` or None. If the item is None, nothing changes.
269 """
270 if item is None:
271 return
272
273 item.load()
274 rating = self.rating(
275 int(item.get("play_count", 0)),
276 int(item.get("skip_count", 0)),
277 float(item.get("rating", 0.5)),
278 skipped,
279 )
280
281 self.update_item(item, "rating", rating)
282
283 def handle_song_change(self, song: NowPlaying) -> bool:
284 """Determine if a song was skipped or not and update its attributes.
285 To this end the difference between the song's supposed end time
286 and the current time is calculated. If it's greater than a threshold,
287 the song is considered skipped.
288
289 Returns whether the change was manual (skipped previous song or not)
290 """
291 elapsed = song["elapsed_at_start"] + (time.time() - song["started"])
292 skipped = elapsed / song["duration"] < self.played_ratio_threshold
293 if skipped:
294 self.handle_skipped(song)
295 else:
296 self.handle_played(song)
297
298 if self.do_rating:
299 self.update_rating(song["beets_item"], skipped)
300
301 return skipped
302
303 def handle_played(self, song: NowPlaying) -> None:
304 """Updates the play count of a song."""
305 self.update_item(song["beets_item"], "play_count", increment=1)
306 self._log.info("played {}", displayable_path(song["path"]))
307
308 def handle_skipped(self, song: NowPlaying) -> None:
309 """Updates the skip count of a song."""
310 self.update_item(song["beets_item"], "skip_count", increment=1)
311 self._log.info("skipped {}", displayable_path(song["path"]))
312
313 def on_stop(self, status: JSONDict) -> None:
314 self._log.info("stop")
315
316 # if the current song stays the same it means that we stopped on the
317 # current track and should not record a skip.
318 if self.now_playing and self.now_playing["id"] != status.get("songid"):
319 self.handle_song_change(self.now_playing)
320
321 self.now_playing = None
322
323 def on_pause(self, status: JSONDict) -> None:
324 self._log.info("pause")
325 self.now_playing = None
326
327 def on_play(self, status: JSONDict) -> None:
328 path, songid = self.mpd.currentsong()
329 if not path or not songid:
330 return
331
332 played, duration = map(int, status["time"].split(":", 1))
333 if self.now_playing:
334 if self.now_playing["path"] != path:
335 self.handle_song_change(self.now_playing)
336 else:
337 # In case we got mpd play event with same song playing
338 # multiple times,
339 # assume low diff means redundant second play event
340 # after natural song start.
341 diff = abs(time.time() - self.now_playing["started"])
342
343 if diff <= DUPLICATE_PLAY_THRESHOLD:
344 return
345
346 if self.now_playing["path"] == path and played == 0:
347 self.handle_song_change(self.now_playing)
348
349 if is_url(path):
350 self._log.info("playing stream {}", displayable_path(path))
351 self.now_playing = None
352 return
353
354 self._log.info("playing {}", displayable_path(path))
355
356 self.now_playing = {
357 "started": time.time(),
358 "elapsed_at_start": played,
359 "duration": duration,
360 "path": path,
361 "id": songid,
362 "beets_item": self.get_item(path),
363 }
364
365 self.update_item(
366 self.now_playing["beets_item"],
367 "last_played",
368 value=int(time.time()),
369 )
370
371 def run(self) -> None:
372 self.mpd.connect()
373 events = ["player"]
374
375 while True:
376 if "player" in events:
377 status = self.mpd.status()
378 getattr(self, f"on_{status['state']}")(status)
379
380 events = self.mpd.events()
381
382
383 class MPDStatsPlugin(plugins.BeetsPlugin):
384 item_types: ClassVar[dict[str, types.Type]] = {
385 "play_count": types.INTEGER,
386 "skip_count": types.INTEGER,
387 "last_played": types.DATE,
388 "rating": types.FLOAT,
389 }
390
391 def __init__(self) -> None:
392 super().__init__()
393 mpd_config.add(
394 {
395 "music_directory": config["directory"].as_filename(),
396 "strip_path": "",
397 "rating": True,
398 "rating_mix": 0.75,
399 "host": os.environ.get("MPD_HOST", "localhost"),
400 "port": int(os.environ.get("MPD_PORT", 6600)),
401 "password": "",
402 "played_ratio_threshold": 0.85,
403 }
404 )
405 mpd_config["password"].redact = True
406
407 def commands(self) -> list[ui.Subcommand]:
408 cmd = ui.Subcommand(
409 "mpdstats", help="run a MPD client to gather play statistics"
410 )
411 cmd.parser.add_option(
412 "--host",
413 dest="host",
414 type="string",
415 help="set the hostname of the server to connect to",
416 )
417 cmd.parser.add_option(
418 "--port",
419 dest="port",
420 type="int",
421 help="set the port of the MPD server to connect to",
422 )
423 cmd.parser.add_option(
424 "--password",
425 dest="password",
426 type="string",
427 help="set the password of the MPD server to connect to",
428 )
429
430 def func(lib: Library, opts: optparse.Values, args: list[str]) -> None:
431 mpd_config.set_args(opts)
432
433 try:
434 MPDStats(lib, self._log).run()
435 except KeyboardInterrupt:
436 pass
437
438 cmd.func = func
439 return [cmd]