]> kaliko git repositories - python-musicpdaio.git/blob - musicpdaio.py
Plain asio API
[python-musicpdaio.git] / musicpdaio.py
1 # -*- coding: utf-8 -*-
2 #
3 # python-musicpd: Python MPD client library
4 # Copyright (C) 2014-2015  Kaliko Jack <kaliko@azylum.org>
5 #
6 # python-musicpdasio is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU Lesser 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 # python-musicpd 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 Lesser General Public License for more details.
15 #
16 # You should have received a copy of the GNU Lesser General Public License
17 # along with python-musicpd.  If not, see <http://www.gnu.org/licenses/>.
18
19 try:
20     import asyncio
21 except ImportError:
22     import sys
23     print('Failed to import asyncio, need python >= 3.4')
24     sys.exit(1)
25
26 import logging
27
28 from os import environ
29 if 'DEBUG' in environ or 'PYTHONASYNCIODEBUG' in environ:
30     logging.basicConfig(level=logging.DEBUG)
31
32 HELLO_PREFIX = "OK MPD "
33 ERROR_PREFIX = "ACK "
34 SUCCESS = "OK"
35 NEXT = "list_OK"
36 VERSION = '0.0.1b'
37
38
39 class MPDError(Exception):
40     pass
41
42 class ConnectionError(MPDError):
43     pass
44
45 class ProtocolError(MPDError):
46     pass
47
48 class CommandError(MPDError):
49     pass
50
51 class CommandListError(MPDError):
52     pass
53
54 class PendingCommandError(MPDError):
55     pass
56
57 class IteratingError(MPDError):
58     pass
59
60
61 class Response:
62     def __init__(self):
63         self.version = None
64         self.resp = ''
65
66     def __repr__(self):
67         return '"{0}…" ({1})'.format(
68                 ' '.join(self.resp.split('\n')[:2]),
69                 self.version)
70
71 class MPDProto(asyncio.Protocol):
72     def __init__(self, future, payload, pwd):
73         self.pwd = pwd
74         self.transport = None
75         self.future = future
76         self.payload = payload
77         self.sess = Response()
78
79     def connection_made(self, transport):
80         self.transport = transport
81         self.transport.write(bytes('{}\n'.format(self.payload), 'utf-8'))
82
83     def eof_received(self):
84         self.transport.close()
85         err = ConnectionError('Connection lost while reading line')
86         self.future.set_exception(err)
87
88     def data_received(self, data):
89         #logging.debug(data.decode('utf-8'))
90         rcv = self._hello(data.decode('utf-8'))
91
92         if rcv.startswith(ERROR_PREFIX):
93             err = rcv[len(ERROR_PREFIX):].strip()
94             self.future.set_exception(CommandError(err))
95
96         self.sess.resp += rcv
97         if rcv.endswith(SUCCESS+'\n'):
98             # Strip final SUCCESS
99             self.sess.resp = self.sess.resp[:len(SUCCESS+'\n')*-1]
100             logging.debug('set future result')
101             self.transport.close()
102             self.future.set_result(self.sess)
103
104     def _hello(self, rcv):
105         """Consume HELLO_PREFIX"""
106         if rcv.startswith(HELLO_PREFIX):
107             logging.debug('consumed hello prefix')
108             self.sess.version = rcv.split('\n')[0][len(HELLO_PREFIX):]
109             return rcv[rcv.find('\n')+1:]
110         return rcv
111
112 class MPDClient:
113
114     def __init__(self, host='localhost', port=6600, passwd=None):
115         self._evloop = asyncio.get_event_loop()
116         self.asio = False
117         self.futures = []
118         self._host = host
119         self._port = port
120         self._pwd = passwd
121         self._commands = {
122                 'currentsong',
123                 'stats',
124                 'playlistinfo',
125         }
126
127     def __getattr__(self, attr):
128         #logging.debug(attr)
129         command = attr
130         wrapper = self._command
131         if command not in self._commands:
132             command = command.replace("_", " ")
133             if command not in self._commands:
134                 raise AttributeError("'%s' object has no attribute '%s'" %
135                                      (self.__class__.__name__, attr))
136         return lambda *args: wrapper(command, args)
137
138     @asyncio.coroutine
139     def _connect(self, proto):
140         # coroutine allowing Exception handling
141         # src: http://comments.gmane.org/gmane.comp.python.tulip/1401
142         try:
143             yield from self._evloop.create_connection(lambda: proto,
144                     host=self._host,
145                     port=self._port)
146         except Exception as err:
147             proto.future.set_exception(ConnectionError(err))
148
149     def _command(self, command, args):
150         payload = '{} {}'.format(command, ''.join(args))
151         future = asyncio.Future()
152         # kick off a task to create the connection to MPD
153         coro = self._connect(MPDProto(future, payload, self._pwd))
154         asyncio.async(coro)
155         self.futures.append(future)
156         if not self.asio:
157             # return once completed.
158             self._evloop.run_until_complete(future)
159         return future
160         # alternative w/ callback
161         #if not self.asio:
162         #    future.add_done_callback(lambda ftr: MPDClient.loop.stop())
163         #    self._evloop.run_forever()
164         #return future
165
166     def run(self):
167         """Run event loop gathering tasks from self.futures
168         """
169         if self.futures:
170            self._evloop.run_until_complete(asyncio.gather(*self.futures))
171            self.futures = []
172         else:
173             logging.info('No task found in queue, need to set self.asio?')