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