]> kaliko git repositories - mpd-sima.git/blob - sima/client.py
More robust MPD client
[mpd-sima.git] / sima / client.py
1 # -*- coding: utf-8 -*-
2 # Copyright (c) 2013, 2014 Jack Kaliko <kaliko@azylum.org>
3 #
4 #  This file is part of sima
5 #
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.
10 #
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.
15 #
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/>.
18 #
19 #
20 """MPD client for Sima
21
22 This client is built above python-musicpd a fork of python-mpd
23 """
24 #  pylint: disable=C0111
25
26 # standard library import
27 from difflib import get_close_matches
28 from select import select
29
30 # third parties components
31 try:
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))
36     sexit(1)
37
38 # local import
39 from .lib.simastr import SimaStr
40 from .lib.player import Player, blacklist
41 from .lib.track import Track
42 from .lib.meta import Album, Artist
43 from .utils.leven import levenshtein_ratio
44
45
46 class PlayerError(Exception):
47     """Fatal error in poller."""
48
49 class PlayerCommandError(PlayerError):
50     """Command error"""
51
52 PlayerUnHandledError = MPDError  # pylint: disable=C0103
53
54 def bl_artist(func):
55     def wrapper(*args, **kwargs):
56         cls = args[0]
57         if not args[0].database:
58             return func(*args, **kwargs)
59         result = func(*args, **kwargs)
60         if not result:
61             return
62         names = list()
63         for art in result.names:
64             if cls.database.get_bl_artist(art, add_not=True):
65                 cls.log.debug('Blacklisted "{0}"'.format(art))
66                 continue
67             names.append(art)
68         if not names:
69             return
70         resp = Artist(name=names.pop(), mbid=result.mbid)
71         for name in names:
72             resp.add_alias(name)
73         return resp
74     return wrapper
75
76
77 class PlayerClient(Player):
78     """MPD Client
79     From python-musicpd:
80         _fetch_nothing  …
81         _fetch_item     single str
82         _fetch_object   single dict
83         _fetch_list     list of str
84         _fetch_playlist list of str
85         _fetch_changes  list of dict
86         _fetch_database list of dict
87         _fetch_songs    list of dict, especially tracks
88         _fetch_plugins,
89     TODO: handle exception in command not going through _client_wrapper() (ie.
90           remove…)
91     """
92     database = None  # sima database (history, blacklist)
93
94     def __init__(self, host="localhost", port="6600", password=None):
95         super().__init__()
96         self._comm = self._args = None
97         self._mpd = host, port, password
98         self._client = MPDClient()
99         self._client.iterate = True
100         self._cache = None
101
102     def __getattr__(self, attr):
103         command = attr
104         wrapper = self._execute
105         return lambda *args: wrapper(command, args)
106
107     def _execute(self, command, args):
108         self._write_command(command, args)
109         return self._client_wrapper()
110
111     def _write_command(self, command, args=None):
112         self._comm = command
113         self._args = list()
114         for arg in args:
115             self._args.append(arg)
116
117     def _client_wrapper(self):
118         func = self._client.__getattr__(self._comm)
119         try:
120             ans = func(*self._args)
121         # WARNING: MPDError is an ancestor class of # CommandError
122         except CommandError as err:
123             raise PlayerCommandError('MPD command error: %s' % err)
124         except (MPDError, IOError) as err:
125             raise PlayerError(err)
126         return self._track_format(ans)
127
128     def _track_format(self, ans):
129         """
130         unicode_obj = ["idle", "listplaylist", "list", "sticker list",
131                 "commands", "notcommands", "tagtypes", "urlhandlers",]
132         """
133         # TODO: ain't working for "sticker find" and "sticker list"
134         tracks_listing = ["playlistfind", "playlistid", "playlistinfo",
135                 "playlistsearch", "plchanges", "listplaylistinfo", "find",
136                 "search", "sticker find",]
137         track_obj = ['currentsong']
138         if self._comm in tracks_listing + track_obj:
139             #  pylint: disable=w0142
140             if isinstance(ans, list):
141                 return [Track(**track) for track in ans]
142             elif isinstance(ans, dict):
143                 return Track(**ans)
144         return ans
145
146     def __skipped_track(self, old_curr):
147         if (self.state == 'stop'
148             or not hasattr(old_curr, 'id')
149             or not hasattr(self.current, 'id')):
150             return False
151         return self.current.id != old_curr.id  # pylint: disable=no-member
152
153     def _flush_cache(self):
154         """
155         Both flushes and instantiates _cache
156         """
157         if isinstance(self._cache, dict):
158             self.log.info('Player: Flushing cache!')
159         else:
160             self.log.info('Player: Initialising cache!')
161         self._cache = {
162                 'artists': None,
163                 'nombid_artists': None,
164                 }
165         self._cache['artists'] = frozenset(self._execute('list', ['artist']))
166         if Artist.use_mbid:
167             self._cache['nombid_artists'] = frozenset(self._execute('list', ['artist', 'musicbrainz_artistid', '']))
168
169     @blacklist(track=True)
170     def find_track(self, artist, title=None):
171         tracks = set()
172         for name in artist.names:
173             if title:
174                 tracks |= set(self.find('artist', name, 'title', title))
175             else:
176                 tracks |= set(self.find('artist', name))
177         if artist.mbid:
178             if title:
179                 tracks |= set(self.find('musicbrainz_artistid', artist.mbid))
180             else:
181                 tracks |= set(self.find('musicbrainz_artistid', artist.mbid,
182                                         'title', title))
183         return list(tracks)
184
185     @bl_artist
186     def search_artist(self, artist):
187         """
188         Search artists based on a fuzzy search in the media library
189             >>> art = Artist(name='the beatles', mbid=<UUID4>) # mbid optional
190             >>> bea = player.search_artist(art)
191             >>> print(bea.names)
192             >>> ['The Beatles', 'Beatles', 'the beatles']
193
194         Returns an Artist object
195         """
196         found = False
197         if artist.mbid:
198             # look for exact search w/ musicbrainz_artistid
199             exact_m = self._execute('list', ['artist', 'musicbrainz_artistid', artist.mbid])
200             if exact_m:
201                 [artist.add_alias(name) for name in exact_m]
202                 found = True
203         else:
204             artist = Artist(name=artist.name)
205         # then complete with fuzzy search on artist with no musicbrainz_artistid
206         if artist.mbid:
207             # we already performed a lookup on artists with mbid set
208             # search through remaining artists
209             artists = self._cache.get('nombid_artists', [])
210         else:
211             artists = self._cache.get('artists', [])
212         match = get_close_matches(artist.name, artists, 50, 0.73)
213         if not match and not found:
214             return
215         if len(match) > 1:
216             self.log.debug('found close match for "%s": %s' %
217                            (artist, '/'.join(match)))
218         # Does not perform fuzzy matching on short and single word strings
219         # Only lowercased comparison
220         if ' ' not in artist.name and len(artist.name) < 8:
221             for fuzz_art in match:
222                 # Regular lowered string comparison
223                 if artist.name.lower() == fuzz_art.lower():
224                     artist.add_alias(fuzz_art)
225                     return artist
226         fzartist = SimaStr(artist.name)
227         for fuzz_art in match:
228             # Regular lowered string comparison
229             if artist.name.lower() == fuzz_art.lower():
230                 found = True
231                 artist.add_alias(fuzz_art)
232                 if artist.name != fuzz_art:
233                     self.log.debug('"%s" matches "%s".' % (fuzz_art, artist))
234                 continue
235             # SimaStr string __eq__ (not regular string comparison here)
236             if fzartist == fuzz_art:
237                 found = True
238                 artist.add_alias(fuzz_art)
239                 self.log.info('"%s" quite probably matches "%s" (SimaStr)' %
240                               (fuzz_art, artist))
241         if found:
242             if artist.aliases:
243                 self.log.debug('Found: {}'.format('/'.join(list(artist.names)[:4])))
244             return artist
245
246     def fuzzy_find_track(self, artist, title):
247         # Retrieve all tracks from artist
248         all_tracks = self.find_track(artist, title)
249         # Get all titles (filter missing titles set to 'None')
250         all_artist_titles = frozenset([tr.title for tr in all_tracks
251                                        if tr.title is not None])
252         match = get_close_matches(title, all_artist_titles, 50, 0.78)
253         if not match:
254             return []
255         for title_ in match:
256             leven = levenshtein_ratio(title.lower(), title_.lower())
257             if leven == 1:
258                 pass
259             elif leven >= 0.79:  # PARAM
260                 self.log.debug('title: "%s" should match "%s" (lr=%1.3f)' %
261                                (title_, title, leven))
262             else:
263                 self.log.debug('title: "%s" does not match "%s" (lr=%1.3f)' %
264                                (title_, title, leven))
265                 return []
266             return self.find('artist', artist, 'title', title_)
267
268     def find_album(self, artist, album):
269         """
270         Special wrapper around album search:
271         Album lookup is made through AlbumArtist/Album instead of Artist/Album
272         """
273         alb_art_search = self.find('albumartist', artist, 'album', album)
274         if alb_art_search:
275             return alb_art_search
276         return self.find('artist', artist, 'album', album)
277
278     @blacklist(album=True)
279     def search_albums(self, artist):
280         """
281         Fetch all albums for "AlbumArtist"  == artist
282         Filter albums returned for "artist" == artist since MPD returns any
283                album containing at least a single track for artist
284         """
285         albums = []
286         for name in artist.names:
287             if len(artist.names) > 1:
288                 self.log.debug('Searching album for aliase: "{}"'.format(name))
289             kwalbart = {'albumartist':name, 'artist':name}
290             for album in self.list('album', 'albumartist', artist):
291                 if album and album not in albums:
292                     albums.append(Album(name=album, **kwalbart))
293             for album in self.list('album', 'artist', artist):
294                 album_trks = [trk for trk in self.find('album', album)]
295                 if 'Various Artists' in [tr.albumartist for tr in album_trks]:
296                     self.log.debug('Discarding {0} ("Various Artists" set)'.format(album))
297                     continue
298                 arts = set([trk.artist for trk in album_trks])
299                 if len(set(arts)) < 2:  # TODO: better heuristic, use a ratio instead
300                     if album not in albums:
301                         albums.append(Album(name=album, **kwalbart))
302                 elif album and album not in albums:
303                     self.log.debug('"{0}" probably not an album of "{1}"'.format(
304                                    album, artist) + '({0})'.format('/'.join(arts)))
305         return albums
306
307     def monitor(self):
308         curr = self.current
309         try:
310             self.send_idle('database', 'playlist', 'player', 'options')
311             select([self._client], [], [], 60)
312             ret = self.fetch_idle()
313             if self.__skipped_track(curr):
314                 ret.append('skipped')
315             if 'database' in ret:
316                 self._flush_cache()
317             return ret
318         except (MPDError, IOError) as err:
319             raise PlayerError("Couldn't init idle: %s" % err)
320
321     def clean(self):
322         """Clean blocking event (idle) and pending commands
323         """
324         if 'idle' in self._client._pending:
325             self._client.noidle()
326         elif self._client._pending:
327             self.log.warning('pending commands: {}'.format(self._client._pending))
328
329     def remove(self, position=0):
330         self.delete(position)
331
332     def add(self, track):
333         """Overriding MPD's add method to accept add signature with a Track
334         object"""
335         self._execute('add', [track.file])
336
337     @property
338     def artists(self):
339         return self._cache.get('artists')
340
341     @property
342     def state(self):
343         return str(self.status().get('state'))
344
345     @property
346     def current(self):
347         return self.currentsong()
348
349     @property
350     def queue(self):
351         plst = self.playlist
352         plst.reverse()
353         return [trk for trk in plst if int(trk.pos) > int(self.current.pos)]
354
355     @property
356     def playlist(self):
357         """
358         Override deprecated MPD playlist command
359         """
360         return self.playlistinfo()
361
362     def connect(self):
363         host, port, password = self._mpd
364         self.disconnect()
365         try:
366             self._client.connect(host, port)
367
368         # Catch socket errors
369         except IOError as err:
370             raise PlayerError('Could not connect to "%s:%s": %s' %
371                               (host, port, err.strerror))
372
373         # Catch all other possible errors
374         # ConnectionError and ProtocolError are always fatal.  Others may not
375         # be, but we don't know how to handle them here, so treat them as if
376         # they are instead of ignoring them.
377         except MPDError as err:
378             raise PlayerError('Could not connect to "%s:%s": %s' %
379                               (host, port, err))
380
381         if password:
382             try:
383                 self._client.password(password)
384
385             # Catch errors with the password command (e.g., wrong password)
386             except CommandError as err:
387                 raise PlayerError("Could not connect to '%s': "
388                                   "password command failed: %s" %
389                                   (host, err))
390
391             # Catch all other possible errors
392             except (MPDError, IOError) as err:
393                 raise PlayerError("Could not connect to '%s': "
394                                   "error with password command: %s" %
395                                   (host, err))
396         # Controls we have sufficient rights
397         needed_cmds = ['status', 'stats', 'add', 'find', \
398                        'search', 'currentsong', 'ping']
399
400         available_cmd = self._client.commands()
401         for nddcmd in needed_cmds:
402             if nddcmd not in available_cmd:
403                 self.disconnect()
404                 raise PlayerError('Could connect to "%s", '
405                                   'but command "%s" not available' %
406                                   (host, nddcmd))
407
408         #  Controls use of MusicBrainzIdentifier
409         if Artist.use_mbid:
410             if 'MUSICBRAINZ_ARTISTID' not in self._client.tagtypes():
411                 self.log.warning('Use of MusicBrainzIdentifier is set but MPD is '
412                         'not providing related metadata')
413                 self.log.info(self._client.tagtypes())
414                 self.log.warning('Disabling MusicBrainzIdentifier')
415                 Artist.use_mbid = False
416         else:
417             self.log.warning('Use of MusicBrainzIdentifier disabled!')
418             self.log.info('Consider using MusicBrainzIdentifier for your music library')
419         self._flush_cache()
420
421     def disconnect(self):
422         # Try to tell MPD we're closing the connection first
423         try:
424             self._client.noidle()
425             self._client.close()
426         # If that fails, don't worry, just ignore it and disconnect
427         except (MPDError, IOError):
428             pass
429         try:
430             self._client.disconnect()
431         # Disconnecting failed, so use a new client object instead
432         # This should never happen.  If it does, something is seriously broken,
433         # and the client object shouldn't be trusted to be re-used.
434         except (MPDError, IOError):
435             self._client = MPDClient()
436
437 # VIM MODLINE
438 # vim: ai ts=4 sw=4 sts=4 expandtab