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 itertools import dropwhile
29 from select import select
31 # third parties components
33 from musicpd import (MPDClient, MPDError, CommandError)
34 except ImportError as err:
35 from sys import exit as sexit
36 print('ERROR: missing python-musicpd?\n{0}'.format(err))
40 from .lib.player import Player
41 from .lib.track import Track
42 from .lib.meta import Album
43 from .lib.simastr import SimaStr
44 from .utils.leven import levenshtein_ratio
47 class PlayerError(Exception):
48 """Fatal error in poller."""
50 class PlayerCommandError(PlayerError):
53 PlayerUnHandledError = MPDError # pylint: disable=C0103
56 def blacklist(artist=False, album=False, track=False):
57 #pylint: disable=C0111,W0212
58 field = (artist, album, track)
60 def wrapper(*args, **kwargs):
62 boolgen = (bl for bl in field)
63 bl_fun = (cls.database.get_bl_artist,
64 cls.database.get_bl_album,
65 cls.database.get_bl_track,)
66 #bl_getter = next(fn for fn, bl in zip(bl_fun, boolgen) if bl is True)
67 bl_getter = next(dropwhile(lambda _: not next(boolgen), bl_fun))
68 #cls.log.debug('using {0} as bl filter'.format(bl_getter.__name__))
69 results = func(*args, **kwargs)
71 if bl_getter(elem, add_not=True):
72 cls.log.info('Blacklisted: {0}'.format(elem))
74 if track and cls.database.get_bl_album(elem, add_not=True):
75 # filter album as well in track mode
76 # (artist have already been)
77 cls.log.info('Blacklisted: {0}'.format(elem))
83 class PlayerClient(Player):
87 _fetch_item single str
88 _fetch_object single dict
89 _fetch_list list of str
90 _fetch_playlist list of str
91 _fetch_changes list of dict
92 _fetch_database list of dict
93 _fetch_songs list of dict, especially tracks
95 TODO: handle exception in command not going through _client_wrapper() (ie.
98 database = None # sima database (history, blaclist)
100 def __init__(self, host="localhost", port="6600", password=None):
102 self._comm = self._args = None
103 self._mpd = host, port, password
104 self._client = MPDClient()
105 self._client.iterate = True
108 def __getattr__(self, attr):
110 wrapper = self._execute
111 return lambda *args: wrapper(command, args)
113 def _execute(self, command, args):
114 self._write_command(command, args)
115 return self._client_wrapper()
117 def _write_command(self, command, args=None):
121 self._args.append(arg)
123 def _client_wrapper(self):
124 func = self._client.__getattr__(self._comm)
126 ans = func(*self._args)
127 # WARNING: MPDError is an ancestor class of # CommandError
128 except CommandError as err:
129 raise PlayerCommandError('MPD command error: %s' % err)
130 except (MPDError, IOError) as err:
131 raise PlayerError(err)
132 return self._track_format(ans)
134 def _track_format(self, ans):
136 unicode_obj = ["idle", "listplaylist", "list", "sticker list",
137 "commands", "notcommands", "tagtypes", "urlhandlers",]
139 # TODO: ain't working for "sticker find" and "sticker list"
140 tracks_listing = ["playlistfind", "playlistid", "playlistinfo",
141 "playlistsearch", "plchanges", "listplaylistinfo", "find",
142 "search", "sticker find",]
143 track_obj = ['currentsong']
144 if self._comm in tracks_listing + track_obj:
145 # pylint: disable=w0142
146 if isinstance(ans, list):
147 return [Track(**track) for track in ans]
148 elif isinstance(ans, dict):
152 def __skipped_track(self, old_curr):
153 if (self.state == 'stop'
154 or not hasattr(old_curr, 'id')
155 or not hasattr(self.current, 'id')):
157 return self.current.id != old_curr.id # pylint: disable=no-member
159 def _flush_cache(self):
161 Both flushes and instantiates _cache
163 if isinstance(self._cache, dict):
164 self.log.info('Player: Flushing cache!')
166 self.log.info('Player: Initialising cache!')
170 self._cache['artists'] = frozenset(self._client.list('artist'))
172 def find_track(self, artist, title=None):
173 #return getattr(self, 'find')('artist', artist, 'title', title)
175 return self.find('artist', artist, 'title', title)
176 return self.find('artist', artist)
178 @blacklist(track=True)
179 def fuzzy_find_track(self, artist, title):
180 # Retrieve all tracks from artist
181 all_tracks = self.find('artist', artist)
182 # Get all titles (filter missing titles set to 'None')
183 all_artist_titles = frozenset([tr.title for tr in all_tracks
184 if tr.title is not None])
185 match = get_close_matches(title, all_artist_titles, 50, 0.78)
189 leven = levenshtein_ratio(title.lower(), title_.lower())
192 elif leven >= 0.79: # PARAM
193 self.log.debug('title: "%s" should match "%s" (lr=%1.3f)' %
194 (title_, title, leven))
196 self.log.debug('title: "%s" does not match "%s" (lr=%1.3f)' %
197 (title_, title, leven))
199 return self.find('artist', artist, 'title', title_)
201 @blacklist(artist=True)
202 def fuzzy_find_artist(self, art):
204 Controls presence of artist in music library.
205 Crosschecking artist names with SimaStr objects / difflib / levenshtein
207 TODO: proceed crosschecking even when an artist matched !!!
208 Not because we found "The Doors" as "The Doors" that there is no
209 remaining entries as "Doors" :/
210 not straight forward, need probably heavy refactoring.
212 matching_artists = list()
213 artist = SimaStr(art)
215 # Check against the actual string in artist list
216 if artist.orig in self.artists:
217 self.log.debug('found exact match for "%s"' % artist)
219 # Then proceed with fuzzy matching if got nothing
220 match = get_close_matches(artist.orig, self.artists, 50, 0.73)
223 self.log.debug('found close match for "%s": %s' %
224 (artist, '/'.join(match)))
225 # Does not perform fuzzy matching on short and single word strings
226 # Only lowercased comparison
227 if ' ' not in artist.orig and len(artist) < 8:
228 for fuzz_art in match:
229 # Regular string comparison SimaStr().lower is regular string
230 if artist.lower() == fuzz_art.lower():
231 matching_artists.append(fuzz_art)
232 self.log.debug('"%s" matches "%s".' % (fuzz_art, artist))
233 return matching_artists
234 for fuzz_art in match:
235 # Regular string comparison SimaStr().lower is regular string
236 if artist.lower() == fuzz_art.lower():
237 matching_artists.append(fuzz_art)
238 self.log.debug('"%s" matches "%s".' % (fuzz_art, artist))
239 return matching_artists
240 # SimaStr string __eq__ (not regular string comparison here)
241 if artist == fuzz_art:
242 matching_artists.append(fuzz_art)
243 self.log.info('"%s" quite probably matches "%s" (SimaStr)' %
246 self.log.debug('FZZZ: "%s" does not match "%s"' %
248 return matching_artists
250 def find_album(self, artist, album):
252 Special wrapper around album search:
253 Album lookup is made through AlbumArtist/Album instead of Artist/Album
255 alb_art_search = self.find('albumartist', artist, 'album', album)
257 return alb_art_search
258 return self.find('artist', artist, 'album', album)
260 @blacklist(album=True)
261 def find_albums(self, artist):
263 Fetch all albums for "AlbumArtist" == artist
264 Filter albums returned for "artist" == artist since MPD returns any
265 album containing at least a single track for artist
268 kwalbart = {'albumartist':artist, 'artist':artist}
269 for album in self.list('album', 'albumartist', artist):
270 if album not in albums:
271 albums.append(Album(name=album, **kwalbart))
272 for album in self.list('album', 'artist', artist):
273 album_trks = [trk for trk in self.find('album', album)]
274 if 'Various Artists' in [tr.albumartist for tr in album_trks]:
275 self.log.debug('Discarding {0} ("Various Artists" set)'.format(album))
277 arts = set([trk.artist for trk in album_trks])
278 if len(set(arts)) < 2: # TODO: better heuristic, use a ratio instead
279 if album not in albums:
280 albums.append(Album(name=album, albumartist=artist))
281 elif album and album not in albums:
282 self.log.debug('"{0}" probably not an album of "{1}"'.format(
283 album, artist) + '({0})'.format('/'.join(arts)))
289 self._client.send_idle('database', 'playlist', 'player', 'options')
290 select([self._client], [], [], 60)
291 ret = self._client.fetch_idle()
292 if self.__skipped_track(curr):
293 ret.append('skipped')
294 if 'database' in ret:
297 except (MPDError, IOError) as err:
298 raise PlayerError("Couldn't init idle: %s" % err)
300 def remove(self, position=0):
301 self._client.delete(position)
303 def add(self, track):
304 """Overriding MPD's add method to accept add signature with a Track
306 self._client.add(track.file)
310 return self._cache.get('artists')
314 return str(self._client.status().get('state'))
318 return self.currentsong()
324 return [trk for trk in plst if int(trk.pos) > int(self.current.pos)]
329 Override deprecated MPD playlist command
331 return self.playlistinfo()
334 host, port, password = self._mpd
337 self._client.connect(host, port)
339 # Catch socket errors
340 except IOError as err:
341 raise PlayerError('Could not connect to "%s:%s": %s' %
342 (host, port, err.strerror))
344 # Catch all other possible errors
345 # ConnectionError and ProtocolError are always fatal. Others may not
346 # be, but we don't know how to handle them here, so treat them as if
347 # they are instead of ignoring them.
348 except MPDError as err:
349 raise PlayerError('Could not connect to "%s:%s": %s' %
354 self._client.password(password)
356 # Catch errors with the password command (e.g., wrong password)
357 except CommandError as err:
358 raise PlayerError("Could not connect to '%s': "
359 "password command failed: %s" %
362 # Catch all other possible errors
363 except (MPDError, IOError) as err:
364 raise PlayerError("Could not connect to '%s': "
365 "error with password command: %s" %
367 # Controls we have sufficient rights
368 needed_cmds = ['status', 'stats', 'add', 'find', \
369 'search', 'currentsong', 'ping']
371 available_cmd = self._client.commands()
372 for nddcmd in needed_cmds:
373 if nddcmd not in available_cmd:
375 raise PlayerError('Could connect to "%s", '
376 'but command "%s" not available' %
380 def disconnect(self):
381 # Try to tell MPD we're closing the connection first
383 self._client.noidle()
385 # If that fails, don't worry, just ignore it and disconnect
386 except (MPDError, IOError):
389 self._client.disconnect()
390 # Disconnecting failed, so use a new client object instead
391 # This should never happen. If it does, something is seriously broken,
392 # and the client object shouldn't be trusted to be re-used.
393 except (MPDError, IOError):
394 self._client = MPDClient()
397 # vim: ai ts=4 sw=4 sts=4 expandtab