]> kaliko git repositories - mpd-sima.git/blob - sima/client.py
2893d9b52cf52bb5a53266ec2bdedc7f0e05ebcd
[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.aliases:
200             self.log.debug('Searching album for {}'.format(name))
201             kwalbart = {'albumartist':name, 'artist':name}
202             for album in self.list('album', 'albumartist', artist):
203                 if album and album not in albums:
204                     albums.append(Album(name=album, **kwalbart))
205             for album in self.list('album', 'artist', artist):
206                 album_trks = [trk for trk in self.find('album', album)]
207                 if 'Various Artists' in [tr.albumartist for tr in album_trks]:
208                     self.log.debug('Discarding {0} ("Various Artists" set)'.format(album))
209                     continue
210                 arts = set([trk.artist for trk in album_trks])
211                 if len(set(arts)) < 2:  # TODO: better heuristic, use a ratio instead
212                     if album not in albums:
213                         albums.append(Album(name=album, albumartist=artist))
214                 elif album and album not in albums:
215                     self.log.debug('"{0}" probably not an album of "{1}"'.format(
216                                    album, artist) + '({0})'.format('/'.join(arts)))
217         return albums
218
219     def monitor(self):
220         curr = self.current
221         try:
222             self.send_idle('database', 'playlist', 'player', 'options')
223             select([self._client], [], [], 60)
224             ret = self.fetch_idle()
225             if self.__skipped_track(curr):
226                 ret.append('skipped')
227             if 'database' in ret:
228                 self._flush_cache()
229             return ret
230         except (MPDError, IOError) as err:
231             raise PlayerError("Couldn't init idle: %s" % err)
232
233     def clean(self):
234         """Clean blocking event (idle) and pending commands
235         """
236         if 'idle' in self._client._pending:
237             self._client.noidle()
238         elif self._client._pending:
239             self.log.warning('pending commands: {}'.format(self._client._pending))
240
241     def remove(self, position=0):
242         self.delete(position)
243
244     def add(self, track):
245         """Overriding MPD's add method to accept add signature with a Track
246         object"""
247         self._client.add(track.file)
248
249     @property
250     def artists(self):
251         return self._cache.get('artists')
252
253     @property
254     def state(self):
255         return str(self.status().get('state'))
256
257     @property
258     def current(self):
259         return self.currentsong()
260
261     @property
262     def queue(self):
263         plst = self.playlist
264         plst.reverse()
265         return [trk for trk in plst if int(trk.pos) > int(self.current.pos)]
266
267     @property
268     def playlist(self):
269         """
270         Override deprecated MPD playlist command
271         """
272         return self.playlistinfo()
273
274     def connect(self):
275         host, port, password = self._mpd
276         self.disconnect()
277         try:
278             self._client.connect(host, port)
279
280         # Catch socket errors
281         except IOError as err:
282             raise PlayerError('Could not connect to "%s:%s": %s' %
283                               (host, port, err.strerror))
284
285         # Catch all other possible errors
286         # ConnectionError and ProtocolError are always fatal.  Others may not
287         # be, but we don't know how to handle them here, so treat them as if
288         # they are instead of ignoring them.
289         except MPDError as err:
290             raise PlayerError('Could not connect to "%s:%s": %s' %
291                               (host, port, err))
292
293         if password:
294             try:
295                 self._client.password(password)
296
297             # Catch errors with the password command (e.g., wrong password)
298             except CommandError as err:
299                 raise PlayerError("Could not connect to '%s': "
300                                   "password command failed: %s" %
301                                   (host, err))
302
303             # Catch all other possible errors
304             except (MPDError, IOError) as err:
305                 raise PlayerError("Could not connect to '%s': "
306                                   "error with password command: %s" %
307                                   (host, err))
308         # Controls we have sufficient rights
309         needed_cmds = ['status', 'stats', 'add', 'find', \
310                        'search', 'currentsong', 'ping']
311
312         available_cmd = self._client.commands()
313         for nddcmd in needed_cmds:
314             if nddcmd not in available_cmd:
315                 self.disconnect()
316                 raise PlayerError('Could connect to "%s", '
317                                   'but command "%s" not available' %
318                                   (host, nddcmd))
319
320         #  Controls use of MusicBrainzIdentifier
321         if Artist.use_mbid:
322             if 'MUSICBRAINZ_ARTISTID' not in self._client.tagtypes():
323                 self.log.warning('Use of MusicBrainzIdentifier is set but MPD is '
324                         'not providing related metadata')
325                 self.log.info(self._client.tagtypes())
326                 self.log.warning('Disabling MusicBrainzIdentifier')
327                 Artist.use_mbid = False
328         else:
329             self.log.warning('Use of MusicBrainzIdentifier disabled!')
330             self.log.info('Consider using MusicBrainzIdentifier for your music library')
331         self._flush_cache()
332
333     def disconnect(self):
334         # Try to tell MPD we're closing the connection first
335         try:
336             self._client.noidle()
337             self._client.close()
338         # If that fails, don't worry, just ignore it and disconnect
339         except (MPDError, IOError):
340             pass
341         try:
342             self._client.disconnect()
343         # Disconnecting failed, so use a new client object instead
344         # This should never happen.  If it does, something is seriously broken,
345         # and the client object shouldn't be trusted to be re-used.
346         except (MPDError, IOError):
347             self._client = MPDClient()
348
349 # VIM MODLINE
350 # vim: ai ts=4 sw=4 sts=4 expandtab