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