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__))
70 for elem in func(*args, **kwargs):
71 if bl_getter(elem, add_not=True):
72 cls.log.debug('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.debug('Blacklisted alb. "{0.album}"'.format(elem))
84 class PlayerClient(Player):
88 _fetch_item single str
89 _fetch_object single dict
90 _fetch_list list of str
91 _fetch_playlist list of str
92 _fetch_changes list of dict
93 _fetch_database list of dict
94 _fetch_songs list of dict, especially tracks
96 TODO: handle exception in command not going through _client_wrapper() (ie.
99 database = None # sima database (history, blaclist)
101 def __init__(self, host="localhost", port="6600", password=None):
103 self._comm = self._args = None
104 self._mpd = host, port, password
105 self._client = MPDClient()
106 self._client.iterate = True
109 def __getattr__(self, attr):
111 wrapper = self._execute
112 return lambda *args: wrapper(command, args)
114 def _execute(self, command, args):
115 self._write_command(command, args)
116 return self._client_wrapper()
118 def _write_command(self, command, args=None):
122 self._args.append(arg)
124 def _client_wrapper(self):
125 func = self._client.__getattr__(self._comm)
127 ans = func(*self._args)
128 # WARNING: MPDError is an ancestor class of # CommandError
129 except CommandError as err:
130 raise PlayerCommandError('MPD command error: %s' % err)
131 except (MPDError, IOError) as err:
132 raise PlayerError(err)
133 return self._track_format(ans)
135 def _track_format(self, ans):
137 unicode_obj = ["idle", "listplaylist", "list", "sticker list",
138 "commands", "notcommands", "tagtypes", "urlhandlers",]
140 # TODO: ain't working for "sticker find" and "sticker list"
141 tracks_listing = ["playlistfind", "playlistid", "playlistinfo",
142 "playlistsearch", "plchanges", "listplaylistinfo", "find",
143 "search", "sticker find",]
144 track_obj = ['currentsong']
145 if self._comm in tracks_listing + track_obj:
146 # pylint: disable=w0142
147 if isinstance(ans, list):
148 return [Track(**track) for track in ans]
149 elif isinstance(ans, dict):
153 def __skipped_track(self, old_curr):
154 if (self.state == 'stop'
155 or not hasattr(old_curr, 'id')
156 or not hasattr(self.current, 'id')):
158 return self.current.id != old_curr.id # pylint: disable=no-member
160 def _flush_cache(self):
162 Both flushes and instantiates _cache
164 if isinstance(self._cache, dict):
165 self.log.info('Player: Flushing cache!')
167 self.log.info('Player: Initialising cache!')
171 self._cache['artists'] = frozenset(self._client.list('artist'))
173 @blacklist(track=True)
174 def find_track(self, artist, title=None):
175 #return getattr(self, 'find')('artist', artist, 'title', title)
177 return self.find('artist', artist, 'title', title)
178 return self.find('artist', artist)
180 @blacklist(track=True)
181 def fuzzy_find_track(self, artist, title):
182 # Retrieve all tracks from artist
183 all_tracks = self.find('artist', artist)
184 # Get all titles (filter missing titles set to 'None')
185 all_artist_titles = frozenset([tr.title for tr in all_tracks
186 if tr.title is not None])
187 match = get_close_matches(title, all_artist_titles, 50, 0.78)
191 leven = levenshtein_ratio(title.lower(), title_.lower())
194 elif leven >= 0.79: # PARAM
195 self.log.debug('title: "%s" should match "%s" (lr=%1.3f)' %
196 (title_, title, leven))
198 self.log.debug('title: "%s" does not match "%s" (lr=%1.3f)' %
199 (title_, title, leven))
201 return self.find('artist', artist, 'title', title_)
203 @blacklist(artist=True)
204 def fuzzy_find_artist(self, art):
206 Controls presence of artist in music library.
207 Crosschecking artist names with SimaStr objects / difflib / levenshtein
209 TODO: proceed crosschecking even when an artist matched !!!
210 Not because we found "The Doors" as "The Doors" that there is no
211 remaining entries as "Doors" :/
212 not straight forward, need probably heavy refactoring.
214 matching_artists = list()
215 artist = SimaStr(art)
217 # Check against the actual string in artist list
218 if artist.orig in self.artists:
219 self.log.debug('found exact match for "%s"' % artist)
221 # Then proceed with fuzzy matching if got nothing
222 match = get_close_matches(artist.orig, self.artists, 50, 0.73)
225 self.log.debug('found close match for "%s": %s' %
226 (artist, '/'.join(match)))
227 # Does not perform fuzzy matching on short and single word strings
228 # Only lowercased comparison
229 if ' ' not in artist.orig and len(artist) < 8:
230 for fuzz_art in match:
231 # Regular string comparison SimaStr().lower is regular string
232 if artist.lower() == fuzz_art.lower():
233 matching_artists.append(fuzz_art)
234 self.log.debug('"%s" matches "%s".' % (fuzz_art, artist))
235 return matching_artists
236 for fuzz_art in match:
237 # Regular string comparison SimaStr().lower is regular string
238 if artist.lower() == fuzz_art.lower():
239 matching_artists.append(fuzz_art)
240 self.log.debug('"%s" matches "%s".' % (fuzz_art, artist))
241 return matching_artists
242 # SimaStr string __eq__ (not regular string comparison here)
243 if artist == fuzz_art:
244 matching_artists.append(fuzz_art)
245 self.log.info('"%s" quite probably matches "%s" (SimaStr)' %
248 self.log.debug('FZZZ: "%s" does not match "%s"' %
250 return matching_artists
252 def find_album(self, artist, album):
254 Special wrapper around album search:
255 Album lookup is made through AlbumArtist/Album instead of Artist/Album
257 alb_art_search = self.find('albumartist', artist, 'album', album)
259 return alb_art_search
260 return self.find('artist', artist, 'album', album)
262 @blacklist(album=True)
263 def find_albums(self, artist):
265 Fetch all albums for "AlbumArtist" == artist
266 Filter albums returned for "artist" == artist since MPD returns any
267 album containing at least a single track for artist
270 kwalbart = {'albumartist':artist, 'artist':artist}
271 for album in self.list('album', 'albumartist', artist):
272 if album not in albums:
273 albums.append(Album(name=album, **kwalbart))
274 for album in self.list('album', 'artist', artist):
275 album_trks = [trk for trk in self.find('album', album)]
276 if 'Various Artists' in [tr.albumartist for tr in album_trks]:
277 self.log.debug('Discarding {0} ("Various Artists" set)'.format(album))
279 arts = set([trk.artist for trk in album_trks])
280 if len(set(arts)) < 2: # TODO: better heuristic, use a ratio instead
281 if album not in albums:
282 albums.append(Album(name=album, albumartist=artist))
283 elif album and album not in albums:
284 self.log.debug('"{0}" probably not an album of "{1}"'.format(
285 album, artist) + '({0})'.format('/'.join(arts)))
291 self._client.send_idle('database', 'playlist', 'player', 'options')
292 select([self._client], [], [], 60)
293 ret = self._client.fetch_idle()
294 if self.__skipped_track(curr):
295 ret.append('skipped')
296 if 'database' in ret:
299 except (MPDError, IOError) as err:
300 raise PlayerError("Couldn't init idle: %s" % err)
302 def remove(self, position=0):
303 self._client.delete(position)
305 def add(self, track):
306 """Overriding MPD's add method to accept add signature with a Track
308 self._client.add(track.file)
312 return self._cache.get('artists')
316 return str(self._client.status().get('state'))
320 return self.currentsong()
326 return [trk for trk in plst if int(trk.pos) > int(self.current.pos)]
331 Override deprecated MPD playlist command
333 return self.playlistinfo()
336 host, port, password = self._mpd
339 self._client.connect(host, port)
341 # Catch socket errors
342 except IOError as err:
343 raise PlayerError('Could not connect to "%s:%s": %s' %
344 (host, port, err.strerror))
346 # Catch all other possible errors
347 # ConnectionError and ProtocolError are always fatal. Others may not
348 # be, but we don't know how to handle them here, so treat them as if
349 # they are instead of ignoring them.
350 except MPDError as err:
351 raise PlayerError('Could not connect to "%s:%s": %s' %
356 self._client.password(password)
358 # Catch errors with the password command (e.g., wrong password)
359 except CommandError as err:
360 raise PlayerError("Could not connect to '%s': "
361 "password command failed: %s" %
364 # Catch all other possible errors
365 except (MPDError, IOError) as err:
366 raise PlayerError("Could not connect to '%s': "
367 "error with password command: %s" %
369 # Controls we have sufficient rights
370 needed_cmds = ['status', 'stats', 'add', 'find', \
371 'search', 'currentsong', 'ping']
373 available_cmd = self._client.commands()
374 for nddcmd in needed_cmds:
375 if nddcmd not in available_cmd:
377 raise PlayerError('Could connect to "%s", '
378 'but command "%s" not available' %
382 def disconnect(self):
383 # Try to tell MPD we're closing the connection first
385 self._client.noidle()
387 # If that fails, don't worry, just ignore it and disconnect
388 except (MPDError, IOError):
391 self._client.disconnect()
392 # Disconnecting failed, so use a new client object instead
393 # This should never happen. If it does, something is seriously broken,
394 # and the client object shouldn't be trusted to be re-used.
395 except (MPDError, IOError):
396 self._client = MPDClient()
399 # vim: ai ts=4 sw=4 sts=4 expandtab