]> kaliko git repositories - mpd-sima.git/blob - sima/client.py
40842ba3fa4a46d1a2ecc22b4653420fe35d95a5
[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 "%s"', 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             if isinstance(ans, list):
140                 return [Track(**track) for track in ans]
141             elif isinstance(ans, dict):
142                 return Track(**ans)
143         return ans
144
145     def __skipped_track(self, old_curr):
146         if (self.state == 'stop'
147                 or not hasattr(old_curr, 'id')
148                 or not hasattr(self.current, 'id')):
149             return False
150         return self.current.id != old_curr.id  # pylint: disable=no-member
151
152     def _flush_cache(self):
153         """
154         Both flushes and instantiates _cache
155         """
156         if isinstance(self._cache, dict):
157             self.log.info('Player: Flushing cache!')
158         else:
159             self.log.info('Player: Initialising cache!')
160         self._cache = {'artists': frozenset(),
161                        'nombid_artists': frozenset(),}
162         self._cache['artists'] = frozenset(filter(None, self._execute('list', ['artist'])))
163         if Artist.use_mbid:
164             self._cache['nombid_artists'] = frozenset(filter(None, self._execute('list', ['artist', 'musicbrainz_artistid', ''])))
165
166     @blacklist(track=True)
167     def find_track(self, artist, title=None):
168         tracks = set()
169         if artist.mbid:
170             if title:
171                 tracks |= set(self.find('musicbrainz_artistid', artist.mbid,
172                                         'title', title))
173             else:
174                 tracks |= set(self.find('musicbrainz_artistid', artist.mbid))
175         for name in artist.names:
176             if title:
177                 tracks |= set(self.find('artist', name, 'title', title))
178             else:
179                 tracks |= set(self.find('artist', name))
180         return list(tracks)
181
182     @bl_artist
183     def search_artist(self, artist):
184         """
185         Search artists based on a fuzzy search in the media library
186             >>> art = Artist(name='the beatles', mbid=<UUID4>) # mbid optional
187             >>> bea = player.search_artist(art)
188             >>> print(bea.names)
189             >>> ['The Beatles', 'Beatles', 'the beatles']
190
191         Returns an Artist object
192         """
193         found = False
194         if artist.mbid:
195             # look for exact search w/ musicbrainz_artistid
196             exact_m = self._execute('list', ['artist', 'musicbrainz_artistid', artist.mbid])
197             if exact_m:
198                 _ = [artist.add_alias(name) for name in exact_m]
199                 found = True
200         # then complete with fuzzy search on artist with no musicbrainz_artistid
201         if artist.mbid:
202             # we already performed a lookup on artists with mbid set
203             # search through remaining artists
204             artists = self._cache.get('nombid_artists')
205         else:
206             artists = self._cache.get('artists')
207         match = get_close_matches(artist.name, artists, 50, 0.73)
208         if not match and not found:
209             return
210         if len(match) > 1:
211             self.log.debug('found close match for "%s": %s', artist, '/'.join(match))
212         # Does not perform fuzzy matching on short and single word strings
213         # Only lowercased comparison
214         if ' ' not in artist.name and len(artist.name) < 8:
215             for close_art in match:
216                 # Regular lowered string comparison
217                 if artist.name.lower() == close_art.lower():
218                     artist.add_alias(close_art)
219                     return artist
220                 else:
221                     return
222         for fuzz_art in match:
223             # Regular lowered string comparison
224             if artist.name.lower() == fuzz_art.lower():
225                 found = True
226                 artist.add_alias(fuzz_art)
227                 if artist.name != fuzz_art:
228                     self.log.debug('"%s" matches "%s".', fuzz_art, artist)
229                 continue
230             # SimaStr string __eq__ (not regular string comparison here)
231             if SimaStr(artist.name) == fuzz_art:
232                 found = True
233                 artist.add_alias(fuzz_art)
234                 self.log.info('"%s" quite probably matches "%s" (SimaStr)',
235                               fuzz_art, artist)
236         if found:
237             if artist.aliases:
238                 self.log.debug('Found: %s', '/'.join(list(artist.names)[:4]))
239             return artist
240
241     def fuzzy_find_track(self, artist, title):
242         # Retrieve all tracks from artist
243         all_tracks = self.find_track(artist, title)
244         # Get all titles (filter missing titles set to 'None')
245         all_artist_titles = frozenset([tr.title for tr in all_tracks
246                                        if tr.title is not None])
247         match = get_close_matches(title, all_artist_titles, 50, 0.78)
248         if not match:
249             return []
250         for mtitle in match:
251             leven = levenshtein_ratio(title.lower(), mtitle.lower())
252             if leven == 1:
253                 pass
254             elif leven >= 0.79:  # PARAM
255                 self.log.debug('title: "%s" should match "%s" (lr=%1.3f)',
256                                mtitle, title, leven)
257             else:
258                 self.log.debug('title: "%s" does not match "%s" (lr=%1.3f)',
259                                mtitle, title, leven)
260                 return []
261             return self.find('artist', artist, 'title', mtitle)
262
263     def find_album(self, artist, album):
264         """
265         Special wrapper around album search:
266         Album lookup is made through AlbumArtist/Album instead of Artist/Album
267         MPD falls back to Artist if AlbumArtist is not found  (cf. documentation)
268         """
269         return self.find('albumartist', artist, 'album', album)
270
271     @blacklist(album=True)
272     def search_albums(self, artist):
273         """
274         Fetch all albums for "AlbumArtist"  == artist
275         Filter albums returned for "artist" == artist since MPD returns any
276                album containing at least a single track for artist
277         """
278         albums = []
279         for name in artist.names:
280             if len(artist.names) > 1:
281                 self.log.debug('Searching album for aliase: "%s"', name)
282             kwalbart = {'albumartist':name, 'artist':name}
283             for album in self.list('album', 'albumartist', artist):
284                 if album and album not in albums:
285                     albums.append(Album(name=album, **kwalbart))
286             for album in self.list('album', 'artist', artist):
287                 album_trks = [trk for trk in self.find('album', album)]
288                 if 'Various Artists' in [tr.albumartist for tr in album_trks]:
289                     self.log.debug('Discarding %s ("Various Artists" set)', album)
290                     continue
291                 arts = set([trk.artist for trk in album_trks])
292                 if len(set(arts)) < 2:  # TODO: better heuristic, use a ratio instead
293                     if album not in albums:
294                         albums.append(Album(name=album, **kwalbart))
295                 elif album and album not in albums:
296                     self.log.debug('"{0}" probably not an album of "{1}"'.format(
297                         album, artist) + '({0})'.format('/'.join(arts)))
298         return albums
299
300     def monitor(self):
301         curr = self.current
302         try:
303             self.send_idle('database', 'playlist', 'player', 'options')
304             select([self._client], [], [], 60)
305             ret = self.fetch_idle()
306             if self.__skipped_track(curr):
307                 ret.append('skipped')
308             if 'database' in ret:
309                 self._flush_cache()
310             return ret
311         except (MPDError, IOError) as err:
312             raise PlayerError("Couldn't init idle: %s" % err)
313
314     def clean(self):
315         """Clean blocking event (idle) and pending commands
316         """
317         if 'idle' in self._client._pending:
318             self._client.noidle()
319         elif self._client._pending:
320             self.log.warning('pending commands: %s', self._client._pending)
321
322     def remove(self, position=0):
323         self.delete(position)
324
325     def add(self, track):
326         """Overriding MPD's add method to accept add signature with a Track
327         object"""
328         self._execute('add', [track.file])
329
330     @property
331     def artists(self):
332         return self._cache.get('artists')
333
334     @property
335     def state(self):
336         return str(self.status().get('state'))
337
338     @property
339     def playmode(self):
340         plm = {'repeat': None,
341                'single': None,
342                'random': None,
343                'consume': None,
344               }
345         for key, val in self.status().items():
346             if key in plm.keys():
347                 plm.update({key:bool(int(val))})
348         return plm
349
350     @property
351     def current(self):
352         return self.currentsong()
353
354     @property
355     def queue(self):
356         plst = self.playlist
357         plst.reverse()
358         return [trk for trk in plst if int(trk.pos) > int(self.current.pos)]
359
360     @property
361     def playlist(self):
362         """
363         Override deprecated MPD playlist command
364         """
365         return self.playlistinfo()
366
367     def connect(self):
368         host, port, password = self._mpd
369         self.disconnect()
370         try:
371             self._client.connect(host, port)
372
373         # Catch socket errors
374         except IOError as err:
375             raise PlayerError('Could not connect to "%s:%s": %s' %
376                               (host, port, err.strerror))
377
378         # Catch all other possible errors
379         # ConnectionError and ProtocolError are always fatal.  Others may not
380         # be, but we don't know how to handle them here, so treat them as if
381         # they are instead of ignoring them.
382         except MPDError as err:
383             raise PlayerError('Could not connect to "%s:%s": %s' %
384                               (host, port, err))
385
386         if password:
387             try:
388                 self._client.password(password)
389             except (MPDError, IOError) as err:
390                 raise PlayerError("Could not connect to '%s': %s", (host, err))
391         # Controls we have sufficient rights
392         needed_cmds = ['status', 'stats', 'add', 'find', \
393                        'search', 'currentsong', 'ping']
394
395         available_cmd = self._client.commands()
396         for nddcmd in needed_cmds:
397             if nddcmd not in available_cmd:
398                 self.disconnect()
399                 raise PlayerError('Could connect to "%s", '
400                                   'but command "%s" not available' %
401                                   (host, nddcmd))
402
403         #  Controls use of MusicBrainzIdentifier
404         if Artist.use_mbid:
405             if 'MUSICBRAINZ_ARTISTID' not in self._client.tagtypes():
406                 self.log.warning('Use of MusicBrainzIdentifier is set but MPD is '
407                                  'not providing related metadata')
408                 self.log.info(self._client.tagtypes())
409                 self.log.warning('Disabling MusicBrainzIdentifier')
410                 Artist.use_mbid = False
411             else:
412                 self.log.trace('Available metadata: %s', self._client.tagtypes())  # pylint: disable=no-member
413         else:
414             self.log.warning('Use of MusicBrainzIdentifier disabled!')
415             self.log.info('Consider using MusicBrainzIdentifier for your music library')
416         self._flush_cache()
417
418     def disconnect(self):
419         # Try to tell MPD we're closing the connection first
420         try:
421             self._client.noidle()
422             self._client.close()
423         # If that fails, don't worry, just ignore it and disconnect
424         except (MPDError, IOError):
425             pass
426         try:
427             self._client.disconnect()
428         # Disconnecting failed, so use a new client object instead
429         # This should never happen.  If it does, something is seriously broken,
430         # and the client object shouldn't be trusted to be re-used.
431         except (MPDError, IOError):
432             self._client = MPDClient()
433
434 # VIM MODLINE
435 # vim: ai ts=4 sw=4 sts=4 expandtab