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