]> kaliko git repositories - mpd-sima.git/blob - sima/client.py
Add EchoNest top tracks
[mpd-sima.git] / sima / client.py
1 # -*- coding: utf-8 -*-
2 # Copyright (c) 2013, 2014 Jack Kaliko <kaliko@azylum.org>
3 #
4 #  This file is part of sima
5 #
6 #  sima is free software: you can redistribute it and/or modify
7 #  it under the terms of the GNU General Public License as published by
8 #  the Free Software Foundation, either version 3 of the License, or
9 #  (at your option) any later version.
10 #
11 #  sima is distributed in the hope that it will be useful,
12 #  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 #  GNU General Public License for more details.
15 #
16 #  You should have received a copy of the GNU General Public License
17 #  along with sima.  If not, see <http://www.gnu.org/licenses/>.
18 #
19 #
20 """MPD client for Sima
21
22 This client is built above python-musicpd a fork of python-mpd
23 """
24 #  pylint: disable=C0111
25
26 # standard library import
27 from difflib import get_close_matches
28 from itertools import dropwhile
29 from select import select
30
31 # third parties components
32 try:
33     from musicpd import (MPDClient, MPDError, CommandError)
34 except ImportError as err:
35     from sys import exit as sexit
36     print('ERROR: missing python-musicpd?\n{0}'.format(err))
37     sexit(1)
38
39 # local import
40 from .lib.player import Player
41 from .lib.track import Track
42 from .lib.meta import Album
43 from .lib.simastr import SimaStr
44 from .utils.leven import levenshtein_ratio
45
46
47 class PlayerError(Exception):
48     """Fatal error in poller."""
49
50 class PlayerCommandError(PlayerError):
51     """Command error"""
52
53 PlayerUnHandledError = MPDError  # pylint: disable=C0103
54
55
56 def blacklist(artist=False, album=False, track=False):
57     #pylint: disable=C0111,W0212
58     field = (artist, album, track)
59     def decorated(func):
60         def wrapper(*args, **kwargs):
61             cls = args[0]
62             boolgen = (bl for bl in field)
63             bl_fun = (cls.database.get_bl_artist,
64                       cls.database.get_bl_album,
65                       cls.database.get_bl_track,)
66             #bl_getter = next(fn for fn, bl in zip(bl_fun, boolgen) if bl is True)
67             bl_getter = next(dropwhile(lambda _: not next(boolgen), bl_fun))
68             #cls.log.debug('using {0} as bl filter'.format(bl_getter.__name__))
69             results = func(*args, **kwargs)
70             for elem in results:
71                 if bl_getter(elem, add_not=True):
72                     cls.log.info('Blacklisted: {0}'.format(elem))
73                     results.remove(elem)
74                 if track and cls.database.get_bl_album(elem, add_not=True):
75                     # filter album as well in track mode
76                     # (artist have already been)
77                     cls.log.info('Blacklisted: {0}'.format(elem))
78                     results.remove(elem)
79             return results
80         return wrapper
81     return decorated
82
83 class PlayerClient(Player):
84     """MPD Client
85     From python-musicpd:
86         _fetch_nothing  …
87         _fetch_item     single str
88         _fetch_object   single dict
89         _fetch_list     list of str
90         _fetch_playlist list of str
91         _fetch_changes  list of dict
92         _fetch_database list of dict
93         _fetch_songs    list of dict, especially tracks
94         _fetch_plugins,
95     TODO: handle exception in command not going through _client_wrapper() (ie.
96           remove…)
97     """
98     database = None  # sima database (history, blaclist)
99
100     def __init__(self, host="localhost", port="6600", password=None):
101         super().__init__()
102         self._comm = self._args = None
103         self._mpd = host, port, password
104         self._client = MPDClient()
105         self._client.iterate = True
106         self._cache = None
107
108     def __getattr__(self, attr):
109         command = attr
110         wrapper = self._execute
111         return lambda *args: wrapper(command, args)
112
113     def _execute(self, command, args):
114         self._write_command(command, args)
115         return self._client_wrapper()
116
117     def _write_command(self, command, args=None):
118         self._comm = command
119         self._args = list()
120         for arg in args:
121             self._args.append(arg)
122
123     def _client_wrapper(self):
124         func = self._client.__getattr__(self._comm)
125         try:
126             ans = func(*self._args)
127         # WARNING: MPDError is an ancestor class of # CommandError
128         except CommandError as err:
129             raise PlayerCommandError('MPD command error: %s' % err)
130         except (MPDError, IOError) as err:
131             raise PlayerError(err)
132         return self._track_format(ans)
133
134     def _track_format(self, ans):
135         """
136         unicode_obj = ["idle", "listplaylist", "list", "sticker list",
137                 "commands", "notcommands", "tagtypes", "urlhandlers",]
138         """
139         # TODO: ain't working for "sticker find" and "sticker list"
140         tracks_listing = ["playlistfind", "playlistid", "playlistinfo",
141                 "playlistsearch", "plchanges", "listplaylistinfo", "find",
142                 "search", "sticker find",]
143         track_obj = ['currentsong']
144         if self._comm in tracks_listing + track_obj:
145             #  pylint: disable=w0142
146             if isinstance(ans, list):
147                 return [Track(**track) for track in ans]
148             elif isinstance(ans, dict):
149                 return Track(**ans)
150         return ans
151
152     def __skipped_track(self, old_curr):
153         if (self.state == 'stop'
154             or not hasattr(old_curr, 'id')
155             or not hasattr(self.current, 'id')):
156             return False
157         return self.current.id != old_curr.id  # pylint: disable=no-member
158
159     def _flush_cache(self):
160         """
161         Both flushes and instantiates _cache
162         """
163         if isinstance(self._cache, dict):
164             self.log.info('Player: Flushing cache!')
165         else:
166             self.log.info('Player: Initialising cache!')
167         self._cache = {
168                 'artists': None,
169                 }
170         self._cache['artists'] = frozenset(self._client.list('artist'))
171
172     def find_track(self, artist, title=None):
173         #return getattr(self, 'find')('artist', artist, 'title', title)
174         if title:
175             return self.find('artist', artist, 'title', title)
176         return self.find('artist', artist)
177
178     @blacklist(track=True)
179     def fuzzy_find_track(self, artist, title):
180         # Retrieve all tracks from artist
181         all_tracks = self.find('artist', artist)
182         # Get all titles (filter missing titles set to 'None')
183         all_artist_titles = frozenset([tr.title for tr in all_tracks
184                                        if tr.title is not None])
185         match = get_close_matches(title, all_artist_titles, 50, 0.78)
186         if not match:
187             return []
188         for title_ in match:
189             leven = levenshtein_ratio(title.lower(), title_.lower())
190             if leven == 1:
191                 pass
192             elif leven >= 0.79:  # PARAM
193                 self.log.debug('title: "%s" should match "%s" (lr=%1.3f)' %
194                                (title_, title, leven))
195             else:
196                 self.log.debug('title: "%s" does not match "%s" (lr=%1.3f)' %
197                                (title_, title, leven))
198                 return []
199             return self.find('artist', artist, 'title', title_)
200
201     @blacklist(artist=True)
202     def fuzzy_find_artist(self, art):
203         """
204         Controls presence of artist in music library.
205         Crosschecking artist names with SimaStr objects / difflib / levenshtein
206
207         TODO: proceed crosschecking even when an artist matched !!!
208               Not because we found "The Doors" as "The Doors" that there is no
209               remaining entries as "Doors" :/
210               not straight forward, need probably heavy refactoring.
211         """
212         matching_artists = list()
213         artist = SimaStr(art)
214
215         # Check against the actual string in artist list
216         if artist.orig in self.artists:
217             self.log.debug('found exact match for "%s"' % artist)
218             return [artist]
219         # Then proceed with fuzzy matching if got nothing
220         match = get_close_matches(artist.orig, self.artists, 50, 0.73)
221         if not match:
222             return []
223         self.log.debug('found close match for "%s": %s' %
224                        (artist, '/'.join(match)))
225         # Does not perform fuzzy matching on short and single word strings
226         # Only lowercased comparison
227         if ' ' not in artist.orig and len(artist) < 8:
228             for fuzz_art in match:
229                 # Regular string comparison SimaStr().lower is regular string
230                 if artist.lower() == fuzz_art.lower():
231                     matching_artists.append(fuzz_art)
232                     self.log.debug('"%s" matches "%s".' % (fuzz_art, artist))
233             return matching_artists
234         for fuzz_art in match:
235             # Regular string comparison SimaStr().lower is regular string
236             if artist.lower() == fuzz_art.lower():
237                 matching_artists.append(fuzz_art)
238                 self.log.debug('"%s" matches "%s".' % (fuzz_art, artist))
239                 return matching_artists
240             # SimaStr string __eq__ (not regular string comparison here)
241             if artist == fuzz_art:
242                 matching_artists.append(fuzz_art)
243                 self.log.info('"%s" quite probably matches "%s" (SimaStr)' %
244                               (fuzz_art, artist))
245             else:
246                 self.log.debug('FZZZ: "%s" does not match "%s"' %
247                                (fuzz_art, artist))
248         return matching_artists
249
250     def find_album(self, artist, album):
251         """
252         Special wrapper around album search:
253         Album lookup is made through AlbumArtist/Album instead of Artist/Album
254         """
255         alb_art_search = self.find('albumartist', artist, 'album', album)
256         if alb_art_search:
257             return alb_art_search
258         return self.find('artist', artist, 'album', album)
259
260     @blacklist(album=True)
261     def find_albums(self, artist):
262         """
263         Fetch all albums for "AlbumArtist"  == artist
264         Filter albums returned for "artist" == artist since MPD returns any
265                album containing at least a single track for artist
266         """
267         albums = []
268         kwalbart = {'albumartist':artist, 'artist':artist}
269         for album in self.list('album', 'albumartist', artist):
270             if album not in albums:
271                 albums.append(Album(name=album, **kwalbart))
272         for album in self.list('album', 'artist', artist):
273             album_trks = [trk for trk in self.find('album', album)]
274             if 'Various Artists' in [tr.albumartist for tr in album_trks]:
275                 self.log.debug('Discarding {0} ("Various Artists" set)'.format(album))
276                 continue
277             arts = set([trk.artist for trk in album_trks])
278             if len(set(arts)) < 2:  # TODO: better heuristic, use a ratio instead
279                 if album not in albums:
280                     albums.append(Album(name=album, albumartist=artist))
281             elif album and album not in albums:
282                 self.log.debug('"{0}" probably not an album of "{1}"'.format(
283                                album, artist) + '({0})'.format('/'.join(arts)))
284         return albums
285
286     def monitor(self):
287         curr = self.current
288         try:
289             self._client.send_idle('database', 'playlist', 'player', 'options')
290             select([self._client], [], [], 60)
291             ret = self._client.fetch_idle()
292             if self.__skipped_track(curr):
293                 ret.append('skipped')
294             if 'database' in ret:
295                 self._flush_cache()
296             return ret
297         except (MPDError, IOError) as err:
298             raise PlayerError("Couldn't init idle: %s" % err)
299
300     def remove(self, position=0):
301         self._client.delete(position)
302
303     def add(self, track):
304         """Overriding MPD's add method to accept add signature with a Track
305         object"""
306         self._client.add(track.file)
307
308     @property
309     def artists(self):
310         return self._cache.get('artists')
311
312     @property
313     def state(self):
314         return str(self._client.status().get('state'))
315
316     @property
317     def current(self):
318         return self.currentsong()
319
320     @property
321     def queue(self):
322         plst = self.playlist
323         plst.reverse()
324         return [trk for trk in plst if int(trk.pos) > int(self.current.pos)]
325
326     @property
327     def playlist(self):
328         """
329         Override deprecated MPD playlist command
330         """
331         return self.playlistinfo()
332
333     def connect(self):
334         host, port, password = self._mpd
335         self.disconnect()
336         try:
337             self._client.connect(host, port)
338
339         # Catch socket errors
340         except IOError as err:
341             raise PlayerError('Could not connect to "%s:%s": %s' %
342                               (host, port, err.strerror))
343
344         # Catch all other possible errors
345         # ConnectionError and ProtocolError are always fatal.  Others may not
346         # be, but we don't know how to handle them here, so treat them as if
347         # they are instead of ignoring them.
348         except MPDError as err:
349             raise PlayerError('Could not connect to "%s:%s": %s' %
350                               (host, port, err))
351
352         if password:
353             try:
354                 self._client.password(password)
355
356             # Catch errors with the password command (e.g., wrong password)
357             except CommandError as err:
358                 raise PlayerError("Could not connect to '%s': "
359                                   "password command failed: %s" %
360                                   (host, err))
361
362             # Catch all other possible errors
363             except (MPDError, IOError) as err:
364                 raise PlayerError("Could not connect to '%s': "
365                                   "error with password command: %s" %
366                                   (host, err))
367         # Controls we have sufficient rights
368         needed_cmds = ['status', 'stats', 'add', 'find', \
369                        'search', 'currentsong', 'ping']
370
371         available_cmd = self._client.commands()
372         for nddcmd in needed_cmds:
373             if nddcmd not in available_cmd:
374                 self.disconnect()
375                 raise PlayerError('Could connect to "%s", '
376                                   'but command "%s" not available' %
377                                   (host, nddcmd))
378         self._flush_cache()
379
380     def disconnect(self):
381         # Try to tell MPD we're closing the connection first
382         try:
383             self._client.noidle()
384             self._client.close()
385         # If that fails, don't worry, just ignore it and disconnect
386         except (MPDError, IOError):
387             pass
388         try:
389             self._client.disconnect()
390         # Disconnecting failed, so use a new client object instead
391         # This should never happen.  If it does, something is seriously broken,
392         # and the client object shouldn't be trusted to be re-used.
393         except (MPDError, IOError):
394             self._client = MPDClient()
395
396 # VIM MODLINE
397 # vim: ai ts=4 sw=4 sts=4 expandtab