File: mpdstats.py

package info (click to toggle)
beets 1.3.8%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 3,636 kB
  • ctags: 3,973
  • sloc: python: 23,849; makefile: 137; sh: 96
file content (364 lines) | stat: -rw-r--r-- 11,358 bytes parent folder | download
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
# coding=utf-8
# This file is part of beets.
# Copyright 2013, 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 logging
import mpd
import socket
import select
import time
import os

from beets import ui
from beets import config
from beets import plugins
from beets import library
from beets.util import displayable_path
from beets.dbcore import types

log = logging.getLogger('beets')

# 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


def is_url(path):
    """Try to determine if the path is an URL.
    """
    return path.split('://', 1)[0] in ['http', 'https']


# Use the MPDClient internals to get unicode.
# see http://www.tarmack.eu/code/mpdunicode.py for the general idea
class MPDClient(mpd.MPDClient):
    def _write_command(self, command, args=[]):
        args = [unicode(arg).encode('utf-8') for arg in args]
        super(MPDClient, self)._write_command(command, args)

    def _read_line(self):
        line = super(MPDClient, self)._read_line()
        if line is not None:
            return line.decode('utf-8')
        return None


class MPDClientWrapper(object):
    def __init__(self):
        self.music_directory = (
            config['mpdstats']['music_directory'].get(unicode))

        self.client = MPDClient()

    def connect(self):
        """Connect to the MPD.
        """
        host = config['mpd']['host'].get(unicode)
        port = config['mpd']['port'].get(int)

        if host[0] in ['/', '~']:
            host = os.path.expanduser(host)

        log.info(u'mpdstats: connecting to {0}:{1}'.format(host, port))
        try:
            self.client.connect(host, port)
        except socket.error as e:
            raise ui.UserError('could not connect to MPD: {0}'.format(e))

        password = config['mpd']['password'].get(unicode)
        if password:
            try:
                self.client.password(password)
            except mpd.CommandError as e:
                raise ui.UserError(
                    'could not authenticate to MPD: {0}'.format(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 (select.error, mpd.ConnectionError) as err:
            log.error(u'mpdstats: {0}'.format(err))

        if retries <= 0:
            # if we exited without breaking, we couldn't reconnect in time :(
            raise ui.UserError(u'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 playlist(self):
        """Return the currently active playlist.  Prefixes paths with the
        music_directory, to get the absolute path.
        """
        result = {}
        for entry in self.get('playlistinfo'):
            if not is_url(entry['file']):
                result[entry['id']] = os.path.join(
                    self.music_directory, entry['file'])
            else:
                result[entry['id']] = entry['file']
        return result

    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(object):
    def __init__(self, lib):
        self.lib = lib

        self.do_rating = config['mpdstats']['rating'].get(bool)
        self.rating_mix = config['mpdstats']['rating_mix'].get(float)
        self.time_threshold = 10.0  # TODO: maybe add config option?

        self.now_playing = None
        self.mpd = MPDClientWrapper()

    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 = library.PathQuery('path', path)
        item = self.lib.items(query).get()
        if item:
            return item
        else:
            log.info(u'mpdstats: item not found: {0}'.format(
                displayable_path(path)
            ))

    @staticmethod
    def update_item(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()

            log.debug(u'mpdstats: updated: {0} = {1} [{2}]'.format(
                attribute,
                item[attribute],
                displayable_path(item.path),
            ))

    def update_rating(self, item, skipped):
        """Update the rating for a beets item.
        """
        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.
        """
        diff = abs(song['remaining'] - (time.time() - song['started']))

        skipped = diff >= self.time_threshold

        if skipped:
            self.handle_skipped(song)
        else:
            self.handle_played(song)

        if self.do_rating:
            self.update_rating(song['beets_item'], skipped)

    def handle_played(self, song):
        """Updates the play count of a song.
        """
        self.update_item(song['beets_item'], 'play_count', increment=1)
        log.info(u'mpdstats: played {0}'.format(
            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)
        log.info(u'mpdstats: skipped {0}'.format(
            displayable_path(song['path'])
        ))

    def on_stop(self, status):
        log.info(u'mpdstats: stop')

        if self.now_playing:
            self.handle_song_change(self.now_playing)

        self.now_playing = None

    def on_pause(self, status):
        log.info(u'mpdstats: pause')
        self.now_playing = None

    def on_play(self, status):
        playlist = self.mpd.playlist()
        path = playlist.get(status['songid'])

        if not path:
            return

        if is_url(path):
            log.info(u'mpdstats: playing stream {0}'.format(
                displayable_path(path)
            ))
            return

        played, duration = map(int, status['time'].split(':', 1))
        remaining = duration - played

        if self.now_playing and self.now_playing['path'] != path:
            self.handle_song_change(self.now_playing)

        log.info(u'mpdstats: playing {0}'.format(
            displayable_path(path)
        ))

        self.now_playing = {
            'started':    time.time(),
            'remaining':  remaining,
            'path':       path,
            '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, 'on_' + status['state'], None)

                if handler:
                    handler(status)
                else:
                    log.debug(u'mpdstats: unhandled status "{0}"'.
                              format(status))

            events = self.mpd.events()


class MPDStatsPlugin(plugins.BeetsPlugin):

    item_types = {
        'play_count':  types.INTEGER,
        'skip_count':  types.INTEGER,
        'last_played': library.Date(),
        'rating':      types.FLOAT,
    }

    def __init__(self):
        super(MPDStatsPlugin, self).__init__()
        self.config.add({
            'music_directory': config['directory'].as_filename(),
            'rating':          True,
            'rating_mix':      0.75,
        })
        config['mpd'].add({
            'host':            u'localhost',
            'port':            6600,
            'password':        u'',
        })

    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):
            self.config.set_args(opts)

            # Overrides for MPD settings.
            if opts.host:
                config['mpd']['host'] = opts.host.decode('utf8')
            if opts.port:
                config['mpd']['host'] = int(opts.port)
            if opts.password:
                config['mpd']['password'] = opts.password.decode('utf8')

            try:
                MPDStats(lib).run()
            except KeyboardInterrupt:
                pass

        cmd.func = func
        return [cmd]