]> kaliko git repositories - python-musicpdaio.git/blobdiff - mpdaio/client.py
Add per connection command wrapper
[python-musicpdaio.git] / mpdaio / client.py
index 190f809f19ba1bb89675c92153ecca1167d8303f..65e1497f3aba091474a8eceed5933325f6f9269e 100644 (file)
@@ -9,28 +9,93 @@ from .connection import ConnectionPool, Connection
 from .exceptions import MPDConnectionError, MPDProtocolError, MPDCommandError
 from .utils import Range, escape
 
-HELLO_PREFIX = 'OK MPD '
-ERROR_PREFIX = 'ACK '
-SUCCESS = 'OK'
-NEXT = 'list_OK'
-#: Module version
-VERSION = '0.9.0b2'
-#: Seconds before a connection attempt times out
-#: (overriden by :envvar:`MPD_TIMEOUT` env. var.)
-CONNECTION_TIMEOUT = 30
-#: Socket timeout in second > 0 (Default is :py:obj:`None` for no timeout)
-SOCKET_TIMEOUT = None
-#: Maximum concurrent connections
-CONNECTION_MAX = 10
-
-logging.basicConfig(level=logging.DEBUG,
-                    format='%(levelname)-8s %(module)-10s %(message)s')
+from . import CONNECTION_MAX, CONNECTION_TIMEOUT
+from . import ERROR_PREFIX, SUCCESS, NEXT
+
 log = logging.getLogger(__name__)
 
 
 class MPDClient:
 
-    def __init__(self,):
+    def __init__(self, host: str | None = None, port: str | int | None = None, password: str | None = None):
+        self._pool = ConnectionPool(max_connections=CONNECTION_MAX)
+        self._get_envvars()
+        #: host used with the current connection (:py:obj:`str`)
+        self.host = host or self.server_discovery[0]
+        #: password detected in :envvar:`MPD_HOST` environment variable (:py:obj:`str`)
+        self.password = password or self.server_discovery[2]
+        #: port used with the current connection (:py:obj:`int`, :py:obj:`str`)
+        self.port = port or self.server_discovery[1]
+        log.info('logger : "%s"', __name__)
+        #: Protocol version
+        self.version: [None, str] = None
+        self.mpd_timeout = CONNECTION_TIMEOUT
+
+    def _get_envvars(self):
+        """
+        Retrieve MPD env. var. to overrides default "localhost:6600"
+        """
+        # Set some defaults
+        disco_host = 'localhost'
+        disco_port = os.getenv('MPD_PORT', '6600')
+        pwd = None
+        _host = os.getenv('MPD_HOST', '')
+        if _host:
+            # If password is set: MPD_HOST=pass@host
+            if '@' in _host:
+                mpd_host_env = _host.split('@', 1)
+                if mpd_host_env[0]:
+                    # A password is actually set
+                    log.debug(
+                        'password detected in MPD_HOST, set client pwd attribute')
+                    pwd = mpd_host_env[0]
+                    if mpd_host_env[1]:
+                        disco_host = mpd_host_env[1]
+                        log.debug('host detected in MPD_HOST: %s', disco_host)
+                elif mpd_host_env[1]:
+                    # No password set but leading @ is an abstract socket
+                    disco_host = '@'+mpd_host_env[1]
+                    log.debug(
+                        'host detected in MPD_HOST: %s (abstract socket)', disco_host)
+            else:
+                # MPD_HOST is a plain host
+                disco_host = _host
+                log.debug('host detected in MPD_HOST: %s', disco_host)
+        else:
+            # Is socket there
+            xdg_runtime_dir = os.getenv('XDG_RUNTIME_DIR', '/run')
+            rundir = os.path.join(xdg_runtime_dir, 'mpd/socket')
+            if os.path.exists(rundir):
+                disco_host = rundir
+                log.debug(
+                    'host detected in ${XDG_RUNTIME_DIR}/run: %s (unix socket)', disco_host)
+        _mpd_timeout = os.getenv('MPD_TIMEOUT', '')
+        if _mpd_timeout.isdigit():
+            self.mpd_timeout = int(_mpd_timeout)
+            log.debug('timeout detected in MPD_TIMEOUT: %d', self.mpd_timeout)
+        else:  # Use CONNECTION_TIMEOUT as default even if MPD_TIMEOUT carries gargage
+            self.mpd_timeout = CONNECTION_TIMEOUT
+        self.server_discovery = (disco_host, disco_port, pwd)
+
+    def __getattr__(self, attr):
+        command = attr
+        wrapper = CmdHandler(self._pool, self.host, self.port, self.password, self.mpd_timeout)
+        if command not in wrapper._commands:
+            command = command.replace("_", " ")
+            if command not in wrapper._commands:
+                raise AttributeError(
+                    f"'CmdHandler' object has no attribute '{attr}'")
+        return lambda *args: wrapper(command, args)
+
+    async def close(self):
+        await self._pool.close()
+
+
+class CmdHandler:
+    #TODO: CmdHandler to intanciate in place of MPDClient._execute
+    # The MPDClient.__getattr__ wrapper should instanciate an CmdHandler object
+
+    def __init__(self, pool, server, port, password, timeout):
         self._commands = {
             # Status Commands
             "clearerror":         self._fetch_nothing,
@@ -162,105 +227,33 @@ class MPDClient:
             "readmessages":       self._fetch_messages,
             "sendmessage":        self._fetch_nothing,
         }
-        #: host used with the current connection (:py:obj:`str`)
-        self.host = None
-        #: password detected in :envvar:`MPD_HOST` environment variable (:py:obj:`str`)
-        self.pwd = None
-        #: port used with the current connection (:py:obj:`int`, :py:obj:`str`)
-        self.port = None
-        self._get_envvars()
-        self._pool = ConnectionPool(max_connections=CONNECTION_MAX)
-        log.info('logger : "%s"', __name__)
-        #: current connection
-        self.connection: [None,Connection] = None
-        #: Protocol version
-        self.version: [None,str] = None
+        self.command = None
         self._command_list = None
-
-    def _get_envvars(self):
-        """
-        Retrieve MPD env. var. to overrides default "localhost:6600"
-        """
-        # Set some defaults
-        self.host = 'localhost'
-        self.port = os.getenv('MPD_PORT', '6600')
-        _host = os.getenv('MPD_HOST', '')
-        if _host:
-            # If password is set: MPD_HOST=pass@host
-            if '@' in _host:
-                mpd_host_env = _host.split('@', 1)
-                if mpd_host_env[0]:
-                    # A password is actually set
-                    log.debug(
-                        'password detected in MPD_HOST, set client pwd attribute')
-                    self.pwd = mpd_host_env[0]
-                    if mpd_host_env[1]:
-                        self.host = mpd_host_env[1]
-                        log.debug('host detected in MPD_HOST: %s', self.host)
-                elif mpd_host_env[1]:
-                    # No password set but leading @ is an abstract socket
-                    self.host = '@'+mpd_host_env[1]
-                    log.debug(
-                        'host detected in MPD_HOST: %s (abstract socket)', self.host)
-            else:
-                # MPD_HOST is a plain host
-                self.host = _host
-                log.debug('host detected in MPD_HOST: %s', self.host)
-        else:
-            # Is socket there
-            xdg_runtime_dir = os.getenv('XDG_RUNTIME_DIR', '/run')
-            rundir = os.path.join(xdg_runtime_dir, 'mpd/socket')
-            if os.path.exists(rundir):
-                self.host = rundir
-                log.debug(
-                    'host detected in ${XDG_RUNTIME_DIR}/run: %s (unix socket)', self.host)
-        _mpd_timeout = os.getenv('MPD_TIMEOUT', '')
-        if _mpd_timeout.isdigit():
-            self.mpd_timeout = int(_mpd_timeout)
-            log.debug('timeout detected in MPD_TIMEOUT: %d', self.mpd_timeout)
-        else:  # Use CONNECTION_TIMEOUT as default even if MPD_TIMEOUT carries gargage
-            self.mpd_timeout = CONNECTION_TIMEOUT
-
-    def __getattr__(self, attr):
-        # if attr == 'send_noidle':  # have send_noidle to cancel idle as well as noidle
-        #     return self.noidle
-        if attr.startswith("send_"):
-            command = attr.replace("send_", "", 1)
-            wrapper = self._send
-        elif attr.startswith("fetch_"):
-            command = attr.replace("fetch_", "", 1)
-            wrapper = self._fetch
-        else:
-            command = attr
-            wrapper = self._execute
-        if command not in self._commands:
-            command = command.replace("_", " ")
-            if command not in self._commands:
-                cls = self.__class__.__name__
-                raise AttributeError(
-                    f"'{cls}' object has no attribute '{attr}'")
-        return lambda *args: wrapper(command, args)
-
-    async def _execute(self, command, args):  # pylint: disable=unused-argument
-        self.connection = await self._pool.connect(self.host, self.port)
+        self.args = None
+        self.pool = pool
+        self.host = (server, port)
+        self.password = password
+        self.timeout = timeout
+        #: current connection
+        self.connection: [None, Connection] = None
+
+    def __repr__(self):
+        args = [str(_) for _ in self.args]
+        args = ','.join(args or [])
+        return f'{self.command}({args})'
+
+    async def __call__(self, command: str, args: list | None):
+        server, port = self.host
+        self.command = command
+        self.args = args or ''
+        self.connection = await self.pool.connect(server, port, timeout=self.timeout)
         async with self.connection:
-            # if self._pending:
-            #     raise MPDCommandError(
-            #         f"Cannot execute '{command}' with pending commands")
             retval = self._commands[command]
-            if self._command_list is not None:
-                if not callable(retval):
-                    raise MPDCommandError(
-                        f"'{command}' not allowed in command list")
-                self._write_command(command, args)
-                self._command_list.append(retval)
-            else:
-                await self._write_command(command, args)
-                if callable(retval):
-                    log.debug('retvat: %s', retval)
-                    return await retval()
-                return retval
-            return None
+            await self._write_command(command, args)
+            if callable(retval):
+                log.debug('retvat: %s', retval)
+                return await retval()
+            return retval
 
     async def _write_line(self, line):
         self.connection.write(f"{line!s}\n".encode())
@@ -277,6 +270,7 @@ class MPDClient:
                 parts.append(f'"{escape(str(arg))}"')
         if '\n' in ' '.join(parts):
             raise MPDCommandError('new line found in the command!')
+        #log.debug(' '.join(parts))
         await self._write_line(' '.join(parts))
 
     def _read_binary(self, amount):
@@ -331,10 +325,11 @@ class MPDClient:
 
     async def _read_list(self):
         seen = None
-        for key, value in await self._read_pairs():
+        async for key, value in self._read_pairs():
             if key != seen:
                 if seen is not None:
-                    raise MPDProtocolError(f"Expected key '{seen}', got '{key}'")
+                    raise MPDProtocolError(
+                        f"Expected key '{seen}', got '{key}'")
                 seen = key
             yield value
 
@@ -376,13 +371,13 @@ class MPDClient:
             raise ProtocolError(f"Got unexpected return value: '{line}'")
 
     async def _fetch_item(self):
-        pairs = list(await self._read_pairs())
+        pairs = [_ async for _ in self._read_pairs()]
         if len(pairs) != 1:
             return None
         return pairs[0][1]
 
-    def _fetch_list(self):
-        return self._read_list()
+    async def _fetch_list(self):
+        return [_ async for _ in self._read_list()]
 
     def _fetch_playlist(self):
         return self._read_playlist()
@@ -452,29 +447,3 @@ class MPDClient:
 
     def _fetch_command_list(self):
         return self._read_command_list()
-
-    async def _hello(self):
-        """Consume HELLO_PREFIX"""
-        data = await self.connection.readuntil(b'\n')
-        rcv = data.decode('utf-8')
-        if not rcv.startswith(HELLO_PREFIX):
-            raise MPDProtocolError(f'Got invalid MPD hello: "{rcv}"')
-        log.debug('consumed hello prefix: %r', rcv)
-        self.version = rcv.split('\n')[0][len(HELLO_PREFIX):]
-        log.info('protocol version: %s', self.version)
-
-    async def connect(self, server=None, port=None) -> Connection:
-        if not server:
-            server = self.host
-        if not port:
-            port = self.port
-        try:
-            self.connection = await self._pool.connect(server, port)
-        except (ValueError, OSError) as err:
-            #TODO: Is this the right way to raise Excep
-            raise MPDConnectionError(err) from err
-        async with self.connection:
-            await self._hello()
-
-    async def close(self):
-        await self.connection.close()