4 This client is built above python-musicpd a fork of python-mpd
7 # standart library import
8 from select import select
10 # third parties componants
12 from musicpd import (MPDClient, MPDError, CommandError)
13 except ImportError as err:
14 from sys import exit as sexit
15 print('ERROR: missing python-musicpd?\n{0}'.format(err))
19 from .lib.player import Player
20 from .lib.track import Track
23 class PlayerError(Exception):
24 """Fatal error in poller."""
26 class PlayerCommandError(PlayerError):
29 PlayerUnHandledError = MPDError
31 class PlayerClient(Player):
35 _fetch_item single str
36 _fetch_object single dict
37 _fetch_list list of str
38 _fetch_playlist list of str
39 _fetch_changes list of dict
40 _fetch_database list of dict
41 _fetch_songs list of dict, especially tracks
43 TODO: handle exception in command not going through _client_wrapper() (ie.
46 def __init__(self, host="localhost", port="6600", password=None):
49 self._password = password
50 self._client = MPDClient()
51 self._client.iterate = True
53 def __getattr__(self, attr):
55 wrapper = self._execute
56 return lambda *args: wrapper(command, args)
58 def _execute(self, command, args):
59 self._write_command(command, args)
60 return self._client_wrapper()
62 def _write_command(self, command, args=[]):
66 self._args.append(arg)
68 def _client_wrapper(self):
69 func = self._client.__getattr__(self._comm)
71 ans = func(*self._args)
72 # WARNING: MPDError is an ancestor class of # CommandError
73 except CommandError as err:
74 raise PlayerCommandError('MPD command error: %s' % err)
75 except (MPDError, IOError) as err:
76 raise PlayerError(err)
77 return self._track_format(ans)
79 def _track_format(self, ans):
80 # TODO: ain't working for "sticker find" and "sticker list"
81 tracks_listing = ["playlistfind", "playlistid", "playlistinfo",
82 "playlistsearch", "plchanges", "listplaylistinfo", "find",
83 "search", "sticker find",]
84 track_obj = ['currentsong']
85 unicode_obj = ["idle", "listplaylist", "list", "sticker list",
86 "commands", "notcommands", "tagtypes", "urlhandlers",]
87 if self._comm in tracks_listing + track_obj:
88 # pylint: disable=w0142
89 if isinstance(ans, list):
90 return [Track(**track) for track in ans]
91 elif isinstance(ans, dict):
95 def __skipped_track(self, old_curr):
96 if (self.state == 'stop'
97 or not hasattr(old_curr, 'id')
98 or not hasattr(self.current, 'id')):
100 return (self.current.id != old_curr.id) # pylint: disable=no-member
102 def find_track(self, artist, title=None):
103 #return getattr(self, 'find')('artist', artist, 'title', title)
105 return self.find('artist', artist, 'title', title)
106 return self.find('artist', artist)
108 def find_album(self, artist, album):
110 Special wrapper around album search:
111 Album lookup is made through AlbumArtist/Album instead of Artist/Album
113 alb_art_search = self.find('albumartist', artist, 'album', album)
115 return alb_art_search
116 return self.find('artist', artist, 'album', album)
121 self._client.send_idle('database', 'playlist', 'player', 'options')
122 select([self._client], [], [], 60)
123 ret = self._client.fetch_idle()
124 if self.__skipped_track(curr):
125 ret.append('skipped')
127 except (MPDError, IOError) as err:
128 raise PlayerError("Couldn't init idle: %s" % err)
130 def remove(self, position=0):
131 self._client.delete(position)
133 def add(self, track):
134 """Overriding MPD's add method to accept add signature with a Track
136 self._client.add(track.file)
140 return str(self._client.status().get('state'))
144 return self.currentsong()
150 return [ trk for trk in plst if int(trk.pos) > int(self.current.pos)]
155 Override deprecated MPD playlist command
157 return self.playlistinfo()
162 self._client.connect(self._host, self._port)
164 # Catch socket errors
165 except IOError as err:
166 raise PlayerError('Could not connect to "%s:%s": %s' %
167 (self._host, self._port, err.strerror))
169 # Catch all other possible errors
170 # ConnectionError and ProtocolError are always fatal. Others may not
171 # be, but we don't know how to handle them here, so treat them as if
172 # they are instead of ignoring them.
173 except MPDError as err:
174 raise PlayerError('Could not connect to "%s:%s": %s' %
175 (self._host, self._port, err))
179 self._client.password(self._password)
181 # Catch errors with the password command (e.g., wrong password)
182 except CommandError as err:
183 raise PlayerError("Could not connect to '%s': "
184 "password command failed: %s" %
187 # Catch all other possible errors
188 except (MPDError, IOError) as err:
189 raise PlayerError("Could not connect to '%s': "
190 "error with password command: %s" %
192 # Controls we have sufficient rights
193 needed_cmds = ['status', 'stats', 'add', 'find', \
194 'search', 'currentsong', 'ping']
196 available_cmd = self._client.commands()
197 for nddcmd in needed_cmds:
198 if nddcmd not in available_cmd:
200 raise PlayerError('Could connect to "%s", '
201 'but command "%s" not available' %
202 (self._host, nddcmd))
204 def disconnect(self):
205 # Try to tell MPD we're closing the connection first
208 # If that fails, don't worry, just ignore it and disconnect
209 except (MPDError, IOError):
212 self._client.disconnect()
213 # Disconnecting failed, so use a new client object instead
214 # This should never happen. If it does, something is seriously broken,
215 # and the client object shouldn't be trusted to be re-used.
216 except (MPDError, IOError):
217 self._client = MPDClient()
220 # vim: ai ts=4 sw=4 sts=4 expandtab