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 select import select
12 # third parties components
14 from musicpd import (MPDClient, MPDError, CommandError)
15 except ImportError as err:
16 from sys import exit as sexit
17 print('ERROR: missing python-musicpd?\n{0}'.format(err))
21 from .lib.player import Player
22 from .lib.track import Track
23 from .lib.simastr import SimaStr
26 class PlayerError(Exception):
27 """Fatal error in poller."""
29 class PlayerCommandError(PlayerError):
32 PlayerUnHandledError = MPDError # pylint: disable=C0103
35 class PlayerClient(Player):
39 _fetch_item single str
40 _fetch_object single dict
41 _fetch_list list of str
42 _fetch_playlist list of str
43 _fetch_changes list of dict
44 _fetch_database list of dict
45 _fetch_songs list of dict, especially tracks
47 TODO: handle exception in command not going through _client_wrapper() (ie.
50 def __init__(self, host="localhost", port="6600", password=None):
52 self._comm = self._args = None
53 self._mpd = host, port, password
54 self._client = MPDClient()
55 self._client.iterate = True
58 def __getattr__(self, attr):
60 wrapper = self._execute
61 return lambda *args: wrapper(command, args)
64 """Avoid hanging sockets"""
67 def _execute(self, command, args):
68 self._write_command(command, args)
69 return self._client_wrapper()
71 def _write_command(self, command, args=None):
75 self._args.append(arg)
77 def _client_wrapper(self):
78 func = self._client.__getattr__(self._comm)
80 ans = func(*self._args)
81 # WARNING: MPDError is an ancestor class of # CommandError
82 except CommandError as err:
83 raise PlayerCommandError('MPD command error: %s' % err)
84 except (MPDError, IOError) as err:
85 raise PlayerError(err)
86 return self._track_format(ans)
88 def _track_format(self, ans):
90 unicode_obj = ["idle", "listplaylist", "list", "sticker list",
91 "commands", "notcommands", "tagtypes", "urlhandlers",]
93 # TODO: ain't working for "sticker find" and "sticker list"
94 tracks_listing = ["playlistfind", "playlistid", "playlistinfo",
95 "playlistsearch", "plchanges", "listplaylistinfo", "find",
96 "search", "sticker find",]
97 track_obj = ['currentsong']
98 if self._comm in tracks_listing + track_obj:
99 # pylint: disable=w0142
100 if isinstance(ans, list):
101 return [Track(**track) for track in ans]
102 elif isinstance(ans, dict):
106 def __skipped_track(self, old_curr):
107 if (self.state == 'stop'
108 or not hasattr(old_curr, 'id')
109 or not hasattr(self.current, 'id')):
111 return (self.current.id != old_curr.id) # pylint: disable=no-member
113 def _flush_cache(self):
115 Both flushes and instantiates _cache
117 if isinstance(self._cache, dict):
118 self.log.info('Player: Flushing cache!')
120 self.log.info('Player: Initialising cache!')
124 self._cache['artists'] = frozenset(self._client.list('artist'))
126 def find_track(self, artist, title=None):
127 #return getattr(self, 'find')('artist', artist, 'title', title)
129 return self.find('artist', artist, 'title', title)
130 return self.find('artist', artist)
132 def fuzzy_find_artist(self, art):
134 Controls presence of artist in music library.
135 Crosschecking artist names with SimaStr objects / difflib / levenshtein
137 TODO: proceed crosschecking even when an artist matched !!!
138 Not because we found "The Doors" as "The Doors" that there is no
139 remaining entries as "Doors" :/
140 not straight forward, need probably heavy refactoring.
142 matching_artists = list()
143 artist = SimaStr(art)
145 # Check against the actual string in artist list
146 if artist.orig in self.artists:
147 self.log.debug('found exact match for "%s"' % artist)
149 # Then proceed with fuzzy matching if got nothing
150 match = get_close_matches(artist.orig, self.artists, 50, 0.73)
153 self.log.debug('found close match for "%s": %s' %
154 (artist, '/'.join(match)))
155 # Does not perform fuzzy matching on short and single word strings
156 # Only lowercased comparison
157 if ' ' not in artist.orig and len(artist) < 8:
158 for fuzz_art in match:
159 # Regular string comparison SimaStr().lower is regular string
160 if artist.lower() == fuzz_art.lower():
161 matching_artists.append(fuzz_art)
162 self.log.debug('"%s" matches "%s".' % (fuzz_art, artist))
163 return matching_artists
164 for fuzz_art in match:
165 # Regular string comparison SimaStr().lower is regular string
166 if artist.lower() == fuzz_art.lower():
167 matching_artists.append(fuzz_art)
168 self.log.debug('"%s" matches "%s".' % (fuzz_art, artist))
169 return matching_artists
170 # SimaStr string __eq__ (not regular string comparison here)
171 if artist == fuzz_art:
172 matching_artists.append(fuzz_art)
173 self.log.info('"%s" quite probably matches "%s" (SimaStr)' %
176 self.log.debug('FZZZ: "%s" does not match "%s"' %
178 return matching_artists
180 def find_album(self, artist, album):
182 Special wrapper around album search:
183 Album lookup is made through AlbumArtist/Album instead of Artist/Album
185 alb_art_search = self.find('albumartist', artist, 'album', album)
187 return alb_art_search
188 return self.find('artist', artist, 'album', album)
190 def find_albums(self, artist):
192 Fetch all albums for "AlbumArtist" == artist
193 Filter albums returned for "artist" == artist since MPD returns any
194 album containing at least a single track for artist
197 albums.update(self.list('album', 'albumartist', artist))
198 for album in self.list('album', 'artist', artist):
199 arts = set([trk.artist for trk in self.find('album', album)])
203 self.log.debug('"{0}" probably not an album of "{1}"'.format(
204 album, artist) + '({0})'.format('/'.join(arts)))
210 self._client.send_idle('database', 'playlist', 'player', 'options')
211 select([self._client], [], [], 60)
212 ret = self._client.fetch_idle()
213 if self.__skipped_track(curr):
214 ret.append('skipped')
215 if 'database' in ret:
218 except (MPDError, IOError) as err:
219 raise PlayerError("Couldn't init idle: %s" % err)
221 def remove(self, position=0):
222 self._client.delete(position)
224 def add(self, track):
225 """Overriding MPD's add method to accept add signature with a Track
227 self._client.add(track.file)
231 return self._cache.get('artists')
235 return str(self._client.status().get('state'))
239 return self.currentsong()
245 return [ trk for trk in plst if int(trk.pos) > int(self.current.pos)]
250 Override deprecated MPD playlist command
252 return self.playlistinfo()
255 host, port, password = self._mpd
258 self._client.connect(host, port)
260 # Catch socket errors
261 except IOError as err:
262 raise PlayerError('Could not connect to "%s:%s": %s' %
263 (host, port, err.strerror))
265 # Catch all other possible errors
266 # ConnectionError and ProtocolError are always fatal. Others may not
267 # be, but we don't know how to handle them here, so treat them as if
268 # they are instead of ignoring them.
269 except MPDError as err:
270 raise PlayerError('Could not connect to "%s:%s": %s' %
275 self._client.password(password)
277 # Catch errors with the password command (e.g., wrong password)
278 except CommandError as err:
279 raise PlayerError("Could not connect to '%s': "
280 "password command failed: %s" %
283 # Catch all other possible errors
284 except (MPDError, IOError) as err:
285 raise PlayerError("Could not connect to '%s': "
286 "error with password command: %s" %
288 # Controls we have sufficient rights
289 needed_cmds = ['status', 'stats', 'add', 'find', \
290 'search', 'currentsong', 'ping']
292 available_cmd = self._client.commands()
293 for nddcmd in needed_cmds:
294 if nddcmd not in available_cmd:
296 raise PlayerError('Could connect to "%s", '
297 'but command "%s" not available' %
301 def disconnect(self):
302 # Try to tell MPD we're closing the connection first
305 # If that fails, don't worry, just ignore it and disconnect
306 except (MPDError, IOError):
309 self._client.disconnect()
310 # Disconnecting failed, so use a new client object instead
311 # This should never happen. If it does, something is seriously broken,
312 # and the client object shouldn't be trusted to be re-used.
313 except (MPDError, IOError):
314 self._client = MPDClient()
317 # vim: ai ts=4 sw=4 sts=4 expandtab