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.album import Album
25 from .lib.simastr import SimaStr
28 class PlayerError(Exception):
29 """Fatal error in poller."""
31 class PlayerCommandError(PlayerError):
34 PlayerUnHandledError = MPDError # pylint: disable=C0103
37 def blacklist(artist=False, album=False, track=False):
38 #pylint: disable=C0111,W0212
39 field = (artist, album, track)
41 def wrapper(*args, **kwargs):
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)
52 if bl_getter(elem, add_not=True):
53 cls.log.info('Blacklisted: {0}'.format(elem))
59 class PlayerClient(Player):
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
71 TODO: handle exception in command not going through _client_wrapper() (ie.
74 database = None # sima database (history, blaclist)
76 def __init__(self, host="localhost", port="6600", password=None):
78 self._comm = self._args = None
79 self._mpd = host, port, password
80 self._client = MPDClient()
81 self._client.iterate = True
84 def __getattr__(self, attr):
86 wrapper = self._execute
87 return lambda *args: wrapper(command, args)
90 """Avoid hanging sockets"""
93 def _execute(self, command, args):
94 self._write_command(command, args)
95 return self._client_wrapper()
97 def _write_command(self, command, args=None):
101 self._args.append(arg)
103 def _client_wrapper(self):
104 func = self._client.__getattr__(self._comm)
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)
114 def _track_format(self, ans):
116 unicode_obj = ["idle", "listplaylist", "list", "sticker list",
117 "commands", "notcommands", "tagtypes", "urlhandlers",]
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):
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')):
137 return (self.current.id != old_curr.id) # pylint: disable=no-member
139 def _flush_cache(self):
141 Both flushes and instantiates _cache
143 if isinstance(self._cache, dict):
144 self.log.info('Player: Flushing cache!')
146 self.log.info('Player: Initialising cache!')
150 self._cache['artists'] = frozenset(self._client.list('artist'))
152 def find_track(self, artist, title=None):
153 #return getattr(self, 'find')('artist', artist, 'title', title)
155 return self.find('artist', artist, 'title', title)
156 return self.find('artist', artist)
158 @blacklist(artist=True)
159 def fuzzy_find_artist(self, art):
161 Controls presence of artist in music library.
162 Crosschecking artist names with SimaStr objects / difflib / levenshtein
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.
169 matching_artists = list()
170 artist = SimaStr(art)
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)
176 # Then proceed with fuzzy matching if got nothing
177 match = get_close_matches(artist.orig, self.artists, 50, 0.73)
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)' %
203 self.log.debug('FZZZ: "%s" does not match "%s"' %
205 return matching_artists
207 def find_album(self, artist, album):
209 Special wrapper around album search:
210 Album lookup is made through AlbumArtist/Album instead of Artist/Album
212 alb_art_search = self.find('albumartist', artist, 'album', album)
214 return alb_art_search
215 return self.find('artist', artist, 'album', album)
217 @blacklist(album=True)
218 def find_albums(self, artist):
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
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)))
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:
250 except (MPDError, IOError) as err:
251 raise PlayerError("Couldn't init idle: %s" % err)
253 def remove(self, position=0):
254 self._client.delete(position)
256 def add(self, track):
257 """Overriding MPD's add method to accept add signature with a Track
259 self._client.add(track.file)
263 return self._cache.get('artists')
267 return str(self._client.status().get('state'))
271 return self.currentsong()
277 return [ trk for trk in plst if int(trk.pos) > int(self.current.pos)]
282 Override deprecated MPD playlist command
284 return self.playlistinfo()
287 host, port, password = self._mpd
290 self._client.connect(host, port)
292 # Catch socket errors
293 except IOError as err:
294 raise PlayerError('Could not connect to "%s:%s": %s' %
295 (host, port, err.strerror))
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' %
307 self._client.password(password)
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" %
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" %
320 # Controls we have sufficient rights
321 needed_cmds = ['status', 'stats', 'add', 'find', \
322 'search', 'currentsong', 'ping']
324 available_cmd = self._client.commands()
325 for nddcmd in needed_cmds:
326 if nddcmd not in available_cmd:
328 raise PlayerError('Could connect to "%s", '
329 'but command "%s" not available' %
333 def disconnect(self):
334 # Try to tell MPD we're closing the connection first
337 # If that fails, don't worry, just ignore it and disconnect
338 except (MPDError, IOError):
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()
349 # vim: ai ts=4 sw=4 sts=4 expandtab