]> kaliko git repositories - mpd-sima.git/blob - sima/client.py
Fixed blacklisting in track mode
[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 itertools import dropwhile
29 from select import select
30
31 # third parties components
32 try:
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))
37     sexit(1)
38
39 # local import
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
45
46
47 class PlayerError(Exception):
48     """Fatal error in poller."""
49
50 class PlayerCommandError(PlayerError):
51     """Command error"""
52
53 PlayerUnHandledError = MPDError  # pylint: disable=C0103
54
55
56 def blacklist(artist=False, album=False, track=False):
57     #pylint: disable=C0111,W0212
58     field = (artist, album, track)
59     def decorated(func):
60         def wrapper(*args, **kwargs):
61             cls = args[0]
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__))
69             results = func(*args, **kwargs)
70             for elem in results:
71                 if bl_getter(elem, add_not=True):
72                     cls.log.info('Blacklisted: {0}'.format(elem))
73                     results.remove(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.info('Blacklisted: {0}'.format(elem))
78                     results.remove(elem)
79             return results
80         return wrapper
81     return decorated
82
83 class PlayerClient(Player):
84     """MPD Client
85     From python-musicpd:
86         _fetch_nothing  …
87         _fetch_item     single str
88         _fetch_object   single dict
89         _fetch_list     list of str
90         _fetch_playlist list of str
91         _fetch_changes  list of dict
92         _fetch_database list of dict
93         _fetch_songs    list of dict, especially tracks
94         _fetch_plugins,
95     TODO: handle exception in command not going through _client_wrapper() (ie.
96           remove…)
97     """
98     database = None  # sima database (history, blaclist)
99
100     def __init__(self, host="localhost", port="6600", password=None):
101         super().__init__()
102         self._comm = self._args = None
103         self._mpd = host, port, password
104         self._client = MPDClient()
105         self._client.iterate = True
106         self._cache = None
107
108     def __getattr__(self, attr):
109         command = attr
110         wrapper = self._execute
111         return lambda *args: wrapper(command, args)
112
113     def _execute(self, command, args):
114         self._write_command(command, args)
115         return self._client_wrapper()
116
117     def _write_command(self, command, args=None):
118         self._comm = command
119         self._args = list()
120         for arg in args:
121             self._args.append(arg)
122
123     def _client_wrapper(self):
124         func = self._client.__getattr__(self._comm)
125         try:
126             ans = func(*self._args)
127         # WARNING: MPDError is an ancestor class of # CommandError
128         except CommandError as err:
129             raise PlayerCommandError('MPD command error: %s' % err)
130         except (MPDError, IOError) as err:
131             raise PlayerError(err)
132         return self._track_format(ans)
133
134     def _track_format(self, ans):
135         """
136         unicode_obj = ["idle", "listplaylist", "list", "sticker list",
137                 "commands", "notcommands", "tagtypes", "urlhandlers",]
138         """
139         # TODO: ain't working for "sticker find" and "sticker list"
140         tracks_listing = ["playlistfind", "playlistid", "playlistinfo",
141                 "playlistsearch", "plchanges", "listplaylistinfo", "find",
142                 "search", "sticker find",]
143         track_obj = ['currentsong']
144         if self._comm in tracks_listing + track_obj:
145             #  pylint: disable=w0142
146             if isinstance(ans, list):
147                 return [Track(**track) for track in ans]
148             elif isinstance(ans, dict):
149                 return Track(**ans)
150         return ans
151
152     def __skipped_track(self, old_curr):
153         if (self.state == 'stop'
154             or not hasattr(old_curr, 'id')
155             or not hasattr(self.current, 'id')):
156             return False
157         return self.current.id != old_curr.id  # pylint: disable=no-member
158
159     def _flush_cache(self):
160         """
161         Both flushes and instantiates _cache
162         """
163         if isinstance(self._cache, dict):
164             self.log.info('Player: Flushing cache!')
165         else:
166             self.log.info('Player: Initialising cache!')
167         self._cache = {
168                 'artists': None,
169                 }
170         self._cache['artists'] = frozenset(self._client.list('artist'))
171
172     @blacklist(track=True)
173     def find_track(self, artist, title=None):
174         #return getattr(self, 'find')('artist', artist, 'title', title)
175         if title:
176             return self.find('artist', artist, 'title', title)
177         return self.find('artist', artist)
178
179     @blacklist(track=True)
180     def fuzzy_find_track(self, artist, title):
181         # Retrieve all tracks from artist
182         all_tracks = self.find('artist', artist)
183         # Get all titles (filter missing titles set to 'None')
184         all_artist_titles = frozenset([tr.title for tr in all_tracks
185                                        if tr.title is not None])
186         match = get_close_matches(title, all_artist_titles, 50, 0.78)
187         if not match:
188             return []
189         for title_ in match:
190             leven = levenshtein_ratio(title.lower(), title_.lower())
191             if leven == 1:
192                 pass
193             elif leven >= 0.79:  # PARAM
194                 self.log.debug('title: "%s" should match "%s" (lr=%1.3f)' %
195                                (title_, title, leven))
196             else:
197                 self.log.debug('title: "%s" does not match "%s" (lr=%1.3f)' %
198                                (title_, title, leven))
199                 return []
200             return self.find('artist', artist, 'title', title_)
201
202     @blacklist(artist=True)
203     def fuzzy_find_artist(self, art):
204         """
205         Controls presence of artist in music library.
206         Crosschecking artist names with SimaStr objects / difflib / levenshtein
207
208         TODO: proceed crosschecking even when an artist matched !!!
209               Not because we found "The Doors" as "The Doors" that there is no
210               remaining entries as "Doors" :/
211               not straight forward, need probably heavy refactoring.
212         """
213         matching_artists = list()
214         artist = SimaStr(art)
215
216         # Check against the actual string in artist list
217         if artist.orig in self.artists:
218             self.log.debug('found exact match for "%s"' % artist)
219             return [artist]
220         # Then proceed with fuzzy matching if got nothing
221         match = get_close_matches(artist.orig, self.artists, 50, 0.73)
222         if not match:
223             return []
224         self.log.debug('found close match for "%s": %s' %
225                        (artist, '/'.join(match)))
226         # Does not perform fuzzy matching on short and single word strings
227         # Only lowercased comparison
228         if ' ' not in artist.orig and len(artist) < 8:
229             for fuzz_art in match:
230                 # Regular string comparison SimaStr().lower is regular string
231                 if artist.lower() == fuzz_art.lower():
232                     matching_artists.append(fuzz_art)
233                     self.log.debug('"%s" matches "%s".' % (fuzz_art, artist))
234             return matching_artists
235         for fuzz_art in match:
236             # Regular string comparison SimaStr().lower is regular string
237             if artist.lower() == fuzz_art.lower():
238                 matching_artists.append(fuzz_art)
239                 self.log.debug('"%s" matches "%s".' % (fuzz_art, artist))
240                 return matching_artists
241             # SimaStr string __eq__ (not regular string comparison here)
242             if artist == fuzz_art:
243                 matching_artists.append(fuzz_art)
244                 self.log.info('"%s" quite probably matches "%s" (SimaStr)' %
245                               (fuzz_art, artist))
246             else:
247                 self.log.debug('FZZZ: "%s" does not match "%s"' %
248                                (fuzz_art, artist))
249         return matching_artists
250
251     def find_album(self, artist, album):
252         """
253         Special wrapper around album search:
254         Album lookup is made through AlbumArtist/Album instead of Artist/Album
255         """
256         alb_art_search = self.find('albumartist', artist, 'album', album)
257         if alb_art_search:
258             return alb_art_search
259         return self.find('artist', artist, 'album', album)
260
261     @blacklist(album=True)
262     def find_albums(self, artist):
263         """
264         Fetch all albums for "AlbumArtist"  == artist
265         Filter albums returned for "artist" == artist since MPD returns any
266                album containing at least a single track for artist
267         """
268         albums = []
269         kwalbart = {'albumartist':artist, 'artist':artist}
270         for album in self.list('album', 'albumartist', artist):
271             if album not in albums:
272                 albums.append(Album(name=album, **kwalbart))
273         for album in self.list('album', 'artist', artist):
274             album_trks = [trk for trk in self.find('album', album)]
275             if 'Various Artists' in [tr.albumartist for tr in album_trks]:
276                 self.log.debug('Discarding {0} ("Various Artists" set)'.format(album))
277                 continue
278             arts = set([trk.artist for trk in album_trks])
279             if len(set(arts)) < 2:  # TODO: better heuristic, use a ratio instead
280                 if album not in albums:
281                     albums.append(Album(name=album, albumartist=artist))
282             elif album and album not in albums:
283                 self.log.debug('"{0}" probably not an album of "{1}"'.format(
284                                album, artist) + '({0})'.format('/'.join(arts)))
285         return albums
286
287     def monitor(self):
288         curr = self.current
289         try:
290             self._client.send_idle('database', 'playlist', 'player', 'options')
291             select([self._client], [], [], 60)
292             ret = self._client.fetch_idle()
293             if self.__skipped_track(curr):
294                 ret.append('skipped')
295             if 'database' in ret:
296                 self._flush_cache()
297             return ret
298         except (MPDError, IOError) as err:
299             raise PlayerError("Couldn't init idle: %s" % err)
300
301     def remove(self, position=0):
302         self._client.delete(position)
303
304     def add(self, track):
305         """Overriding MPD's add method to accept add signature with a Track
306         object"""
307         self._client.add(track.file)
308
309     @property
310     def artists(self):
311         return self._cache.get('artists')
312
313     @property
314     def state(self):
315         return str(self._client.status().get('state'))
316
317     @property
318     def current(self):
319         return self.currentsong()
320
321     @property
322     def queue(self):
323         plst = self.playlist
324         plst.reverse()
325         return [trk for trk in plst if int(trk.pos) > int(self.current.pos)]
326
327     @property
328     def playlist(self):
329         """
330         Override deprecated MPD playlist command
331         """
332         return self.playlistinfo()
333
334     def connect(self):
335         host, port, password = self._mpd
336         self.disconnect()
337         try:
338             self._client.connect(host, port)
339
340         # Catch socket errors
341         except IOError as err:
342             raise PlayerError('Could not connect to "%s:%s": %s' %
343                               (host, port, err.strerror))
344
345         # Catch all other possible errors
346         # ConnectionError and ProtocolError are always fatal.  Others may not
347         # be, but we don't know how to handle them here, so treat them as if
348         # they are instead of ignoring them.
349         except MPDError as err:
350             raise PlayerError('Could not connect to "%s:%s": %s' %
351                               (host, port, err))
352
353         if password:
354             try:
355                 self._client.password(password)
356
357             # Catch errors with the password command (e.g., wrong password)
358             except CommandError as err:
359                 raise PlayerError("Could not connect to '%s': "
360                                   "password command failed: %s" %
361                                   (host, err))
362
363             # Catch all other possible errors
364             except (MPDError, IOError) as err:
365                 raise PlayerError("Could not connect to '%s': "
366                                   "error with password command: %s" %
367                                   (host, err))
368         # Controls we have sufficient rights
369         needed_cmds = ['status', 'stats', 'add', 'find', \
370                        'search', 'currentsong', 'ping']
371
372         available_cmd = self._client.commands()
373         for nddcmd in needed_cmds:
374             if nddcmd not in available_cmd:
375                 self.disconnect()
376                 raise PlayerError('Could connect to "%s", '
377                                   'but command "%s" not available' %
378                                   (host, nddcmd))
379         self._flush_cache()
380
381     def disconnect(self):
382         # Try to tell MPD we're closing the connection first
383         try:
384             self._client.noidle()
385             self._client.close()
386         # If that fails, don't worry, just ignore it and disconnect
387         except (MPDError, IOError):
388             pass
389         try:
390             self._client.disconnect()
391         # Disconnecting failed, so use a new client object instead
392         # This should never happen.  If it does, something is seriously broken,
393         # and the client object shouldn't be trusted to be re-used.
394         except (MPDError, IOError):
395             self._client = MPDClient()
396
397 # VIM MODLINE
398 # vim: ai ts=4 sw=4 sts=4 expandtab