]> kaliko git repositories - mpd-sima.git/blob - sima/client.py
Fixed search_albums
[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.player import Player, blacklist
40 from .lib.track import Track
41 from .lib.meta import Album, Artist
42 from .utils.leven import levenshtein_ratio
43
44
45 class PlayerError(Exception):
46     """Fatal error in poller."""
47
48 class PlayerCommandError(PlayerError):
49     """Command error"""
50
51 PlayerUnHandledError = MPDError  # pylint: disable=C0103
52
53
54 class PlayerClient(Player):
55     """MPD Client
56     From python-musicpd:
57         _fetch_nothing  …
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
65         _fetch_plugins,
66     TODO: handle exception in command not going through _client_wrapper() (ie.
67           remove…)
68     """
69     database = None  # sima database (history, blacklist)
70
71     def __init__(self, host="localhost", port="6600", password=None):
72         super().__init__()
73         self._comm = self._args = None
74         self._mpd = host, port, password
75         self._client = MPDClient()
76         self._client.iterate = True
77         self._cache = None
78
79     def __getattr__(self, attr):
80         command = attr
81         wrapper = self._execute
82         return lambda *args: wrapper(command, args)
83
84     def _execute(self, command, args):
85         self._write_command(command, args)
86         return self._client_wrapper()
87
88     def _write_command(self, command, args=None):
89         self._comm = command
90         self._args = list()
91         for arg in args:
92             self._args.append(arg)
93
94     def _client_wrapper(self):
95         func = self._client.__getattr__(self._comm)
96         try:
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)
104
105     def _track_format(self, ans):
106         """
107         unicode_obj = ["idle", "listplaylist", "list", "sticker list",
108                 "commands", "notcommands", "tagtypes", "urlhandlers",]
109         """
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):
120                 return Track(**ans)
121         return ans
122
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')):
127             return False
128         return self.current.id != old_curr.id  # pylint: disable=no-member
129
130     def _flush_cache(self):
131         """
132         Both flushes and instantiates _cache
133         """
134         if isinstance(self._cache, dict):
135             self.log.info('Player: Flushing cache!')
136         else:
137             self.log.info('Player: Initialising cache!')
138         self._cache = {
139                 'artists': None,
140                 }
141         self._cache['artists'] = frozenset(self._client.list('artist'))
142
143     @blacklist(track=True)
144     def find_track(self, artist, title=None):
145         tracks = set()
146         for name in artist.names:
147             if title:
148                 tracks |= set(self.find('artist', name, 'title', title))
149             else:
150                 tracks |= set(self.find('artist', name))
151         if artist.mbid:
152             if title:
153                 tracks |= set(self.find('musicbrainz_artistid', artist.mbid))
154             else:
155                 tracks |= set(self.find('musicbrainz_artistid', artist.mbid,
156                                         'title', title))
157         return list(tracks)
158
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)
166         if not match:
167             return []
168         for title_ in match:
169             leven = levenshtein_ratio(title.lower(), title_.lower())
170             if leven == 1:
171                 pass
172             elif leven >= 0.79:  # PARAM
173                 self.log.debug('title: "%s" should match "%s" (lr=%1.3f)' %
174                                (title_, title, leven))
175             else:
176                 self.log.debug('title: "%s" does not match "%s" (lr=%1.3f)' %
177                                (title_, title, leven))
178                 return []
179             return self.find('artist', artist, 'title', title_)
180
181     def find_album(self, artist, album):
182         """
183         Special wrapper around album search:
184         Album lookup is made through AlbumArtist/Album instead of Artist/Album
185         """
186         alb_art_search = self.find('albumartist', artist, 'album', album)
187         if alb_art_search:
188             return alb_art_search
189         return self.find('artist', artist, 'album', album)
190
191     @blacklist(album=True)
192     def search_albums(self, artist):
193         """
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
197         """
198         albums = []
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))
210                     continue
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)))
218         return albums
219
220     def monitor(self):
221         curr = self.current
222         try:
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:
229                 self._flush_cache()
230             return ret
231         except (MPDError, IOError) as err:
232             raise PlayerError("Couldn't init idle: %s" % err)
233
234     def clean(self):
235         """Clean blocking event (idle) and pending commands
236         """
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))
241
242     def remove(self, position=0):
243         self.delete(position)
244
245     def add(self, track):
246         """Overriding MPD's add method to accept add signature with a Track
247         object"""
248         self._client.add(track.file)
249
250     @property
251     def artists(self):
252         return self._cache.get('artists')
253
254     @property
255     def state(self):
256         return str(self.status().get('state'))
257
258     @property
259     def current(self):
260         return self.currentsong()
261
262     @property
263     def queue(self):
264         plst = self.playlist
265         plst.reverse()
266         return [trk for trk in plst if int(trk.pos) > int(self.current.pos)]
267
268     @property
269     def playlist(self):
270         """
271         Override deprecated MPD playlist command
272         """
273         return self.playlistinfo()
274
275     def connect(self):
276         host, port, password = self._mpd
277         self.disconnect()
278         try:
279             self._client.connect(host, port)
280
281         # Catch socket errors
282         except IOError as err:
283             raise PlayerError('Could not connect to "%s:%s": %s' %
284                               (host, port, err.strerror))
285
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' %
292                               (host, port, err))
293
294         if password:
295             try:
296                 self._client.password(password)
297
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" %
302                                   (host, err))
303
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" %
308                                   (host, err))
309         # Controls we have sufficient rights
310         needed_cmds = ['status', 'stats', 'add', 'find', \
311                        'search', 'currentsong', 'ping']
312
313         available_cmd = self._client.commands()
314         for nddcmd in needed_cmds:
315             if nddcmd not in available_cmd:
316                 self.disconnect()
317                 raise PlayerError('Could connect to "%s", '
318                                   'but command "%s" not available' %
319                                   (host, nddcmd))
320
321         #  Controls use of MusicBrainzIdentifier
322         if Artist.use_mbid:
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
329         else:
330             self.log.warning('Use of MusicBrainzIdentifier disabled!')
331             self.log.info('Consider using MusicBrainzIdentifier for your music library')
332         self._flush_cache()
333
334     def disconnect(self):
335         # Try to tell MPD we're closing the connection first
336         try:
337             self._client.noidle()
338             self._client.close()
339         # If that fails, don't worry, just ignore it and disconnect
340         except (MPDError, IOError):
341             pass
342         try:
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()
349
350 # VIM MODLINE
351 # vim: ai ts=4 sw=4 sts=4 expandtab