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)
89 def _execute(self, command, args):
90 self._write_command(command, args)
91 return self._client_wrapper()
93 def _write_command(self, command, args=None):
97 self._args.append(arg)
99 def _client_wrapper(self):
100 func = self._client.__getattr__(self._comm)
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)
110 def _track_format(self, ans):
112 unicode_obj = ["idle", "listplaylist", "list", "sticker list",
113 "commands", "notcommands", "tagtypes", "urlhandlers",]
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):
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')):
133 return (self.current.id != old_curr.id) # pylint: disable=no-member
135 def _flush_cache(self):
137 Both flushes and instantiates _cache
139 if isinstance(self._cache, dict):
140 self.log.info('Player: Flushing cache!')
142 self.log.info('Player: Initialising cache!')
146 self._cache['artists'] = frozenset(self._client.list('artist'))
148 def find_track(self, artist, title=None):
149 #return getattr(self, 'find')('artist', artist, 'title', title)
151 return self.find('artist', artist, 'title', title)
152 return self.find('artist', artist)
154 @blacklist(artist=True)
155 def fuzzy_find_artist(self, art):
157 Controls presence of artist in music library.
158 Crosschecking artist names with SimaStr objects / difflib / levenshtein
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.
165 matching_artists = list()
166 artist = SimaStr(art)
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)
172 # Then proceed with fuzzy matching if got nothing
173 match = get_close_matches(artist.orig, self.artists, 50, 0.73)
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)' %
199 self.log.debug('FZZZ: "%s" does not match "%s"' %
201 return matching_artists
203 def find_album(self, artist, album):
205 Special wrapper around album search:
206 Album lookup is made through AlbumArtist/Album instead of Artist/Album
208 alb_art_search = self.find('albumartist', artist, 'album', album)
210 return alb_art_search
211 return self.find('artist', artist, 'album', album)
213 @blacklist(album=True)
214 def find_albums(self, artist):
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
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)))
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:
246 except (MPDError, IOError) as err:
247 raise PlayerError("Couldn't init idle: %s" % err)
249 def remove(self, position=0):
250 self._client.delete(position)
252 def add(self, track):
253 """Overriding MPD's add method to accept add signature with a Track
255 self._client.add(track.file)
259 return self._cache.get('artists')
263 return str(self._client.status().get('state'))
267 return self.currentsong()
273 return [ trk for trk in plst if int(trk.pos) > int(self.current.pos)]
278 Override deprecated MPD playlist command
280 return self.playlistinfo()
283 host, port, password = self._mpd
286 self._client.connect(host, port)
288 # Catch socket errors
289 except IOError as err:
290 raise PlayerError('Could not connect to "%s:%s": %s' %
291 (host, port, err.strerror))
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' %
303 self._client.password(password)
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" %
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" %
316 # Controls we have sufficient rights
317 needed_cmds = ['status', 'stats', 'add', 'find', \
318 'search', 'currentsong', 'ping']
320 available_cmd = self._client.commands()
321 for nddcmd in needed_cmds:
322 if nddcmd not in available_cmd:
324 raise PlayerError('Could connect to "%s", '
325 'but command "%s" not available' %
329 def disconnect(self):
330 # Try to tell MPD we're closing the connection first
333 # If that fails, don't worry, just ignore it and disconnect
334 except (MPDError, IOError):
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()
345 # vim: ai ts=4 sw=4 sts=4 expandtab