1 # -*- coding: utf-8 -*-
2 # Copyright (c) 2013, 2014 Jack Kaliko <kaliko@azylum.org>
4 # This file is part of sima
6 # sima is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
11 # sima is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with sima. If not, see <http://www.gnu.org/licenses/>.
20 """MPD client for Sima
22 This client is built above python-musicpd a fork of python-mpd
24 # pylint: disable=C0111
26 # standard library import
27 from difflib import get_close_matches
28 from select import select
30 # third parties components
32 from musicpd import (MPDClient, MPDError, CommandError)
33 except ImportError as err:
34 from sys import exit as sexit
35 print('ERROR: missing python-musicpd?\n{0}'.format(err))
39 from .lib.player import Player, blacklist
40 from .lib.track import Track
41 from .lib.meta import Album, Artist
42 from .utils.leven import levenshtein_ratio
45 class PlayerError(Exception):
46 """Fatal error in poller."""
48 class PlayerCommandError(PlayerError):
51 PlayerUnHandledError = MPDError # pylint: disable=C0103
54 class PlayerClient(Player):
58 _fetch_item single str
59 _fetch_object single dict
60 _fetch_list list of str
61 _fetch_playlist list of str
62 _fetch_changes list of dict
63 _fetch_database list of dict
64 _fetch_songs list of dict, especially tracks
66 TODO: handle exception in command not going through _client_wrapper() (ie.
69 database = None # sima database (history, blacklist)
71 def __init__(self, host="localhost", port="6600", password=None):
73 self._comm = self._args = None
74 self._mpd = host, port, password
75 self._client = MPDClient()
76 self._client.iterate = True
79 def __getattr__(self, attr):
81 wrapper = self._execute
82 return lambda *args: wrapper(command, args)
84 def _execute(self, command, args):
85 self._write_command(command, args)
86 return self._client_wrapper()
88 def _write_command(self, command, args=None):
92 self._args.append(arg)
94 def _client_wrapper(self):
95 func = self._client.__getattr__(self._comm)
97 ans = func(*self._args)
98 # WARNING: MPDError is an ancestor class of # CommandError
99 except CommandError as err:
100 raise PlayerCommandError('MPD command error: %s' % err)
101 except (MPDError, IOError) as err:
102 raise PlayerError(err)
103 return self._track_format(ans)
105 def _track_format(self, ans):
107 unicode_obj = ["idle", "listplaylist", "list", "sticker list",
108 "commands", "notcommands", "tagtypes", "urlhandlers",]
110 # TODO: ain't working for "sticker find" and "sticker list"
111 tracks_listing = ["playlistfind", "playlistid", "playlistinfo",
112 "playlistsearch", "plchanges", "listplaylistinfo", "find",
113 "search", "sticker find",]
114 track_obj = ['currentsong']
115 if self._comm in tracks_listing + track_obj:
116 # pylint: disable=w0142
117 if isinstance(ans, list):
118 return [Track(**track) for track in ans]
119 elif isinstance(ans, dict):
123 def __skipped_track(self, old_curr):
124 if (self.state == 'stop'
125 or not hasattr(old_curr, 'id')
126 or not hasattr(self.current, 'id')):
128 return self.current.id != old_curr.id # pylint: disable=no-member
130 def _flush_cache(self):
132 Both flushes and instantiates _cache
134 if isinstance(self._cache, dict):
135 self.log.info('Player: Flushing cache!')
137 self.log.info('Player: Initialising cache!')
141 self._cache['artists'] = frozenset(self._client.list('artist'))
143 @blacklist(track=True)
144 def find_track(self, artist, title=None):
146 for name in artist.names:
148 tracks |= set(self.find('artist', name, 'title', title))
150 tracks |= set(self.find('artist', name))
153 tracks |= set(self.find('musicbrainz_artistid', artist.mbid))
155 tracks |= set(self.find('musicbrainz_artistid', artist.mbid,
159 def fuzzy_find_track(self, artist, title):
160 # Retrieve all tracks from artist
161 all_tracks = self.find_track(artist, title)
162 # Get all titles (filter missing titles set to 'None')
163 all_artist_titles = frozenset([tr.title for tr in all_tracks
164 if tr.title is not None])
165 match = get_close_matches(title, all_artist_titles, 50, 0.78)
169 leven = levenshtein_ratio(title.lower(), title_.lower())
172 elif leven >= 0.79: # PARAM
173 self.log.debug('title: "%s" should match "%s" (lr=%1.3f)' %
174 (title_, title, leven))
176 self.log.debug('title: "%s" does not match "%s" (lr=%1.3f)' %
177 (title_, title, leven))
179 return self.find('artist', artist, 'title', title_)
181 def find_album(self, artist, album):
183 Special wrapper around album search:
184 Album lookup is made through AlbumArtist/Album instead of Artist/Album
186 alb_art_search = self.find('albumartist', artist, 'album', album)
188 return alb_art_search
189 return self.find('artist', artist, 'album', album)
191 @blacklist(album=True)
192 def search_albums(self, artist):
194 Fetch all albums for "AlbumArtist" == artist
195 Filter albums returned for "artist" == artist since MPD returns any
196 album containing at least a single track for artist
199 for name in artist.names:
200 if len(artist.names) > 1:
201 self.log.debug('Searching album for aliase: "{}"'.format(name))
202 kwalbart = {'albumartist':name, 'artist':name}
203 for album in self.list('album', 'albumartist', artist):
204 if album and album not in albums:
205 albums.append(Album(name=album, **kwalbart))
206 for album in self.list('album', 'artist', artist):
207 album_trks = [trk for trk in self.find('album', album)]
208 if 'Various Artists' in [tr.albumartist for tr in album_trks]:
209 self.log.debug('Discarding {0} ("Various Artists" set)'.format(album))
211 arts = set([trk.artist for trk in album_trks])
212 if len(set(arts)) < 2: # TODO: better heuristic, use a ratio instead
213 if album not in albums:
214 albums.append(Album(name=album, albumartist=artist))
215 elif album and album not in albums:
216 self.log.debug('"{0}" probably not an album of "{1}"'.format(
217 album, artist) + '({0})'.format('/'.join(arts)))
223 self.send_idle('database', 'playlist', 'player', 'options')
224 select([self._client], [], [], 60)
225 ret = self.fetch_idle()
226 if self.__skipped_track(curr):
227 ret.append('skipped')
228 if 'database' in ret:
231 except (MPDError, IOError) as err:
232 raise PlayerError("Couldn't init idle: %s" % err)
235 """Clean blocking event (idle) and pending commands
237 if 'idle' in self._client._pending:
238 self._client.noidle()
239 elif self._client._pending:
240 self.log.warning('pending commands: {}'.format(self._client._pending))
242 def remove(self, position=0):
243 self.delete(position)
245 def add(self, track):
246 """Overriding MPD's add method to accept add signature with a Track
248 self._client.add(track.file)
252 return self._cache.get('artists')
256 return str(self.status().get('state'))
260 return self.currentsong()
266 return [trk for trk in plst if int(trk.pos) > int(self.current.pos)]
271 Override deprecated MPD playlist command
273 return self.playlistinfo()
276 host, port, password = self._mpd
279 self._client.connect(host, port)
281 # Catch socket errors
282 except IOError as err:
283 raise PlayerError('Could not connect to "%s:%s": %s' %
284 (host, port, err.strerror))
286 # Catch all other possible errors
287 # ConnectionError and ProtocolError are always fatal. Others may not
288 # be, but we don't know how to handle them here, so treat them as if
289 # they are instead of ignoring them.
290 except MPDError as err:
291 raise PlayerError('Could not connect to "%s:%s": %s' %
296 self._client.password(password)
298 # Catch errors with the password command (e.g., wrong password)
299 except CommandError as err:
300 raise PlayerError("Could not connect to '%s': "
301 "password command failed: %s" %
304 # Catch all other possible errors
305 except (MPDError, IOError) as err:
306 raise PlayerError("Could not connect to '%s': "
307 "error with password command: %s" %
309 # Controls we have sufficient rights
310 needed_cmds = ['status', 'stats', 'add', 'find', \
311 'search', 'currentsong', 'ping']
313 available_cmd = self._client.commands()
314 for nddcmd in needed_cmds:
315 if nddcmd not in available_cmd:
317 raise PlayerError('Could connect to "%s", '
318 'but command "%s" not available' %
321 # Controls use of MusicBrainzIdentifier
323 if 'MUSICBRAINZ_ARTISTID' not in self._client.tagtypes():
324 self.log.warning('Use of MusicBrainzIdentifier is set but MPD is '
325 'not providing related metadata')
326 self.log.info(self._client.tagtypes())
327 self.log.warning('Disabling MusicBrainzIdentifier')
328 Artist.use_mbid = False
330 self.log.warning('Use of MusicBrainzIdentifier disabled!')
331 self.log.info('Consider using MusicBrainzIdentifier for your music library')
334 def disconnect(self):
335 # Try to tell MPD we're closing the connection first
337 self._client.noidle()
339 # If that fails, don't worry, just ignore it and disconnect
340 except (MPDError, IOError):
343 self._client.disconnect()
344 # Disconnecting failed, so use a new client object instead
345 # This should never happen. If it does, something is seriously broken,
346 # and the client object shouldn't be trusted to be re-used.
347 except (MPDError, IOError):
348 self._client = MPDClient()
351 # vim: ai ts=4 sw=4 sts=4 expandtab