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