4 This client is built above python-musicpd a fork of python-mpd
6 # pylint: disable=C0111
8 # standard library import
9 from difflib import get_close_matches
10 from itertools import dropwhile
11 from select import select
13 # third parties components
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))
22 from .lib.player import Player
23 from .lib.track import Track
24 from .lib.simastr import SimaStr
27 class PlayerError(Exception):
28 """Fatal error in poller."""
30 class PlayerCommandError(PlayerError):
33 PlayerUnHandledError = MPDError # pylint: disable=C0103
36 def blacklist(artist=False, album=False, track=False):
37 #pylint: disable=C0111,W0212
38 field = (artist, album, track)
40 def wrapper(*args, **kwargs):
42 boolgen = (bl for bl in field)
43 bl_fun = (cls.database.get_bl_artist,
44 cls.database.get_bl_album,
45 cls.database.get_bl_track,)
46 #bl_getter = next(fn for fn, bl in zip(bl_fun, boolgen) if bl is True)
47 bl_getter = next(dropwhile(lambda _: not next(boolgen), bl_fun))
48 #cls.log.debug('using {0} as bl filter'.format(bl_getter.__name__))
49 results = func(*args, **kwargs)
51 if bl_getter(elem, add_not=True):
52 cls.log.info('Blacklisted: {0}'.format(elem))
58 class PlayerClient(Player):
62 _fetch_item single str
63 _fetch_object single dict
64 _fetch_list list of str
65 _fetch_playlist list of str
66 _fetch_changes list of dict
67 _fetch_database list of dict
68 _fetch_songs list of dict, especially tracks
70 TODO: handle exception in command not going through _client_wrapper() (ie.
73 database = None # sima database (history, blaclist)
75 def __init__(self, host="localhost", port="6600", password=None):
77 self._comm = self._args = None
78 self._mpd = host, port, password
79 self._client = MPDClient()
80 self._client.iterate = True
83 def __getattr__(self, attr):
85 wrapper = self._execute
86 return lambda *args: wrapper(command, args)
89 """Avoid hanging sockets"""
92 def _execute(self, command, args):
93 self._write_command(command, args)
94 return self._client_wrapper()
96 def _write_command(self, command, args=None):
100 self._args.append(arg)
102 def _client_wrapper(self):
103 func = self._client.__getattr__(self._comm)
105 ans = func(*self._args)
106 # WARNING: MPDError is an ancestor class of # CommandError
107 except CommandError as err:
108 raise PlayerCommandError('MPD command error: %s' % err)
109 except (MPDError, IOError) as err:
110 raise PlayerError(err)
111 return self._track_format(ans)
113 def _track_format(self, ans):
115 unicode_obj = ["idle", "listplaylist", "list", "sticker list",
116 "commands", "notcommands", "tagtypes", "urlhandlers",]
118 # TODO: ain't working for "sticker find" and "sticker list"
119 tracks_listing = ["playlistfind", "playlistid", "playlistinfo",
120 "playlistsearch", "plchanges", "listplaylistinfo", "find",
121 "search", "sticker find",]
122 track_obj = ['currentsong']
123 if self._comm in tracks_listing + track_obj:
124 # pylint: disable=w0142
125 if isinstance(ans, list):
126 return [Track(**track) for track in ans]
127 elif isinstance(ans, dict):
131 def __skipped_track(self, old_curr):
132 if (self.state == 'stop'
133 or not hasattr(old_curr, 'id')
134 or not hasattr(self.current, 'id')):
136 return (self.current.id != old_curr.id) # pylint: disable=no-member
138 def _flush_cache(self):
140 Both flushes and instantiates _cache
142 if isinstance(self._cache, dict):
143 self.log.info('Player: Flushing cache!')
145 self.log.info('Player: Initialising cache!')
149 self._cache['artists'] = frozenset(self._client.list('artist'))
151 def find_track(self, artist, title=None):
152 #return getattr(self, 'find')('artist', artist, 'title', title)
154 return self.find('artist', artist, 'title', title)
155 return self.find('artist', artist)
157 @blacklist(artist=True)
158 def fuzzy_find_artist(self, art):
160 Controls presence of artist in music library.
161 Crosschecking artist names with SimaStr objects / difflib / levenshtein
163 TODO: proceed crosschecking even when an artist matched !!!
164 Not because we found "The Doors" as "The Doors" that there is no
165 remaining entries as "Doors" :/
166 not straight forward, need probably heavy refactoring.
168 matching_artists = list()
169 artist = SimaStr(art)
171 # Check against the actual string in artist list
172 if artist.orig in self.artists:
173 self.log.debug('found exact match for "%s"' % artist)
175 # Then proceed with fuzzy matching if got nothing
176 match = get_close_matches(artist.orig, self.artists, 50, 0.73)
179 self.log.debug('found close match for "%s": %s' %
180 (artist, '/'.join(match)))
181 # Does not perform fuzzy matching on short and single word strings
182 # Only lowercased comparison
183 if ' ' not in artist.orig and len(artist) < 8:
184 for fuzz_art in match:
185 # Regular string comparison SimaStr().lower is regular string
186 if artist.lower() == fuzz_art.lower():
187 matching_artists.append(fuzz_art)
188 self.log.debug('"%s" matches "%s".' % (fuzz_art, artist))
189 return matching_artists
190 for fuzz_art in match:
191 # Regular string comparison SimaStr().lower is regular string
192 if artist.lower() == fuzz_art.lower():
193 matching_artists.append(fuzz_art)
194 self.log.debug('"%s" matches "%s".' % (fuzz_art, artist))
195 return matching_artists
196 # SimaStr string __eq__ (not regular string comparison here)
197 if artist == fuzz_art:
198 matching_artists.append(fuzz_art)
199 self.log.info('"%s" quite probably matches "%s" (SimaStr)' %
202 self.log.debug('FZZZ: "%s" does not match "%s"' %
204 return matching_artists
206 def find_album(self, artist, album):
208 Special wrapper around album search:
209 Album lookup is made through AlbumArtist/Album instead of Artist/Album
211 alb_art_search = self.find('albumartist', artist, 'album', album)
213 return alb_art_search
214 return self.find('artist', artist, 'album', album)
216 #@blacklist(album=True)
217 def find_albums(self, artist):
219 Fetch all albums for "AlbumArtist" == artist
220 Filter albums returned for "artist" == artist since MPD returns any
221 album containing at least a single track for artist
224 albums.update(self.list('album', 'albumartist', artist))
225 for album in self.list('album', 'artist', artist):
226 arts = set([trk.artist for trk in self.find('album', album)])
230 self.log.debug('"{0}" probably not an album of "{1}"'.format(
231 album, artist) + '({0})'.format('/'.join(arts)))
233 self.log.debug('Albums candidate: {0}'.format('/'.join(albums)))
239 self._client.send_idle('database', 'playlist', 'player', 'options')
240 select([self._client], [], [], 60)
241 ret = self._client.fetch_idle()
242 if self.__skipped_track(curr):
243 ret.append('skipped')
244 if 'database' in ret:
247 except (MPDError, IOError) as err:
248 raise PlayerError("Couldn't init idle: %s" % err)
250 def remove(self, position=0):
251 self._client.delete(position)
253 def add(self, track):
254 """Overriding MPD's add method to accept add signature with a Track
256 self._client.add(track.file)
260 return self._cache.get('artists')
264 return str(self._client.status().get('state'))
268 return self.currentsong()
274 return [ trk for trk in plst if int(trk.pos) > int(self.current.pos)]
279 Override deprecated MPD playlist command
281 return self.playlistinfo()
284 host, port, password = self._mpd
287 self._client.connect(host, port)
289 # Catch socket errors
290 except IOError as err:
291 raise PlayerError('Could not connect to "%s:%s": %s' %
292 (host, port, err.strerror))
294 # Catch all other possible errors
295 # ConnectionError and ProtocolError are always fatal. Others may not
296 # be, but we don't know how to handle them here, so treat them as if
297 # they are instead of ignoring them.
298 except MPDError as err:
299 raise PlayerError('Could not connect to "%s:%s": %s' %
304 self._client.password(password)
306 # Catch errors with the password command (e.g., wrong password)
307 except CommandError as err:
308 raise PlayerError("Could not connect to '%s': "
309 "password command failed: %s" %
312 # Catch all other possible errors
313 except (MPDError, IOError) as err:
314 raise PlayerError("Could not connect to '%s': "
315 "error with password command: %s" %
317 # Controls we have sufficient rights
318 needed_cmds = ['status', 'stats', 'add', 'find', \
319 'search', 'currentsong', 'ping']
321 available_cmd = self._client.commands()
322 for nddcmd in needed_cmds:
323 if nddcmd not in available_cmd:
325 raise PlayerError('Could connect to "%s", '
326 'but command "%s" not available' %
330 def disconnect(self):
331 # Try to tell MPD we're closing the connection first
334 # If that fails, don't worry, just ignore it and disconnect
335 except (MPDError, IOError):
338 self._client.disconnect()
339 # Disconnecting failed, so use a new client object instead
340 # This should never happen. If it does, something is seriously broken,
341 # and the client object shouldn't be trusted to be re-used.
342 except (MPDError, IOError):
343 self._client = MPDClient()
346 # vim: ai ts=4 sw=4 sts=4 expandtab