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