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