]> kaliko git repositories - mpd-sima.git/blob - sima/client.py
Add SimaDB and deal with history
[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
7 # standart library import
8 from select import select
9
10 # third parties componants
11 try:
12     from musicpd import (MPDClient, MPDError, CommandError)
13 except ImportError as err:
14     from sys import exit as sexit
15     print('ERROR: missing python-musicpd?\n{0}'.format(err))
16     sexit(1)
17
18 # local import
19 from .lib.player import Player
20 from .lib.track import Track
21
22
23 class PlayerError(Exception):
24     """Fatal error in poller."""
25
26 class PlayerCommandError(PlayerError):
27     """Command error"""
28
29 PlayerUnHandledError = MPDError
30
31 class PlayerClient(Player):
32     """MPC Client
33     From python-musicpd:
34         _fetch_nothing  …
35         _fetch_item     single str
36         _fetch_object   single dict
37         _fetch_list     list of str
38         _fetch_playlist list of str
39         _fetch_changes  list of dict
40         _fetch_database list of dict
41         _fetch_songs    list of dict, especially tracks
42         _fetch_plugins,
43     TODO: handle exception in command not going through _client_wrapper() (ie.
44           find_aa, remove…)
45     """
46     def __init__(self, host="localhost", port="6600", password=None):
47         self._host = host
48         self._port = port
49         self._password = password
50         self._client = MPDClient()
51         self._client.iterate = True
52
53     def __getattr__(self, attr):
54         command = attr
55         wrapper = self._execute
56         return lambda *args: wrapper(command, args)
57
58     def _execute(self, command, args):
59         self._write_command(command, args)
60         return self._client_wrapper()
61
62     def _write_command(self, command, args=[]):
63         self._comm = command
64         self._args = list()
65         for arg in args:
66             self._args.append(arg)
67
68     def _client_wrapper(self):
69         func = self._client.__getattr__(self._comm)
70         try:
71             ans = func(*self._args)
72         # WARNING: MPDError is an ancestor class of # CommandError
73         except CommandError as err:
74             raise PlayerCommandError('MPD command error: %s' % err)
75         except (MPDError, IOError) as err:
76             raise PlayerError(err)
77         return self._track_format(ans)
78
79     def _track_format(self, ans):
80         # TODO: ain't working for "sticker find" and "sticker list"
81         tracks_listing = ["playlistfind", "playlistid", "playlistinfo",
82                 "playlistsearch", "plchanges", "listplaylistinfo", "find",
83                 "search", "sticker find",]
84         track_obj = ['currentsong']
85         unicode_obj = ["idle", "listplaylist", "list", "sticker list",
86                 "commands", "notcommands", "tagtypes", "urlhandlers",]
87         if self._comm in tracks_listing + track_obj:
88             #  pylint: disable=w0142
89             if isinstance(ans, list):
90                 return [Track(**track) for track in ans]
91             elif isinstance(ans, dict):
92                 return Track(**ans)
93         return ans
94
95     def __skipped_track(self, old_curr):
96         if (self.state == 'stop'
97             or not hasattr(old_curr, 'id')
98             or not hasattr(self.current, 'id')):
99             return False
100         return (self.current.id != old_curr.id)  # pylint: disable=no-member
101
102     def find_track(self, artist, title=None):
103         #return getattr(self, 'find')('artist', artist, 'title', title)
104         if title:
105             return self.find('artist', artist, 'title', title)
106         return self.find('artist', artist)
107
108     def find_album(self, artist, album):
109         """
110         Special wrapper around album search:
111         Album lookup is made through AlbumArtist/Album instead of Artist/Album
112         """
113         alb_art_search = self.find('albumartist', artist, 'album', album)
114         if alb_art_search:
115             return alb_art_search
116         return self.find('artist', artist, 'album', album)
117
118     def monitor(self):
119         curr = self.current
120         try:
121             self._client.send_idle('database', 'playlist', 'player', 'options')
122             select([self._client], [], [], 60)
123             ret = self._client.fetch_idle()
124             if self.__skipped_track(curr):
125                 ret.append('skipped')
126             return ret
127         except (MPDError, IOError) as err:
128             raise PlayerError("Couldn't init idle: %s" % err)
129
130     def remove(self, position=0):
131         self._client.delete(position)
132
133     @property
134     def state(self):
135         return str(self._client.status().get('state'))
136
137     @property
138     def current(self):
139         return self.currentsong()
140
141     @property
142     def playlist(self):
143         """
144         Override deprecated MPD playlist command
145         """
146         return self.playlistinfo()
147
148     def connect(self):
149         self.disconnect()
150         try:
151             self._client.connect(self._host, self._port)
152
153         # Catch socket errors
154         except IOError as err:
155             raise PlayerError('Could not connect to "%s:%s": %s' %
156                               (self._host, self._port, err.strerror))
157
158         # Catch all other possible errors
159         # ConnectionError and ProtocolError are always fatal.  Others may not
160         # be, but we don't know how to handle them here, so treat them as if
161         # they are instead of ignoring them.
162         except MPDError as err:
163             raise PlayerError('Could not connect to "%s:%s": %s' %
164                               (self._host, self._port, err))
165
166         if self._password:
167             try:
168                 self._client.password(self._password)
169
170             # Catch errors with the password command (e.g., wrong password)
171             except CommandError as err:
172                 raise PlayerError("Could not connect to '%s': "
173                                   "password command failed: %s" %
174                                   (self._host, err))
175
176             # Catch all other possible errors
177             except (MPDError, IOError) as err:
178                 raise PlayerError("Could not connect to '%s': "
179                                   "error with password command: %s" %
180                                   (self._host, err))
181         # Controls we have sufficient rights for MPD_sima
182         needed_cmds = ['status', 'stats', 'add', 'find', \
183                        'search', 'currentsong', 'ping']
184
185         available_cmd = self._client.commands()
186         for nddcmd in needed_cmds:
187             if nddcmd not in available_cmd:
188                 self.disconnect()
189                 raise PlayerError('Could connect to "%s", '
190                                   'but command "%s" not available' %
191                                   (self._host, nddcmd))
192
193     def disconnect(self):
194         # Try to tell MPD we're closing the connection first
195         try:
196             self._client.close()
197         # If that fails, don't worry, just ignore it and disconnect
198         except (MPDError, IOError):
199             pass
200         try:
201             self._client.disconnect()
202         # Disconnecting failed, so use a new client object instead
203         # This should never happen.  If it does, something is seriously broken,
204         # and the client object shouldn't be trusted to be re-used.
205         except (MPDError, IOError):
206             self._client = MPDClient()
207
208 # VIM MODLINE
209 # vim: ai ts=4 sw=4 sts=4 expandtab