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