~naglis/aio_mpv_ipc

35886d416942308eee2d38baff5f1eafc0557495 — Naglis Jonaitis 11 months ago 2aef1d4
Simplify, add more debug logging
2 files changed, 39 insertions(+), 38 deletions(-)

M aio_mpv_ipc/_client.py
M tests/test_client.py
M aio_mpv_ipc/_client.py => aio_mpv_ipc/_client.py +35 -36
@@ 17,6 17,7 @@ from aio_mpv_ipc.exceptions import (
logger = logging.getLogger("aio_mpv_ipc")

IPC_ENCODING = "utf-8"
NEWLINE = b"\n"


def _json_serialize_default(o):


@@ 127,59 128,57 @@ class MpvClient:

        return self

    async def __aexit__(
        self,
        exc_type: typing.Optional[typing.Type[BaseException]] = None,
        exc_value: typing.Optional[BaseException] = None,
        traceback: typing.Optional[types.TracebackType] = None,
    ):
    async def __aexit__(self, _, __, ___):
        if self._writer is not None:
            logger.debug("Closing mpv IPC socket writer")
            self._writer.close()

        if self._poll_task is not None:
            logger.debug("Cancelling mpv polling task")
            self._poll_task.cancel()
            try:
                await self._poll_task
            except asyncio.CancelledError:
                pass
            self._poll_task = None

    async def _poll(self):
        while True:
        while not self._reader.at_eof():
            data = await self._reader.readline()
            if data:
                response = self._json_loads(data.rstrip(b"\n"))

                logger.debug("Response from mpv: %r", response)

                event_name = response.get("event")
                if event_name is not None:
                    # This is an event notification, notify subscribers (if any).
                    if event_name in self._event_subscribers:
                        for queue in self._event_subscribers[event_name]:
                            queue.put_nowait(response)
                else:
                    status = response.get("error")
                    is_error = status and status != "success"
            if not data:
                continue

            response = self._json_loads(data.rstrip(NEWLINE))

            logger.debug("Response from mpv: %r", response)

            event_name = response.get("event")
            if event_name is not None:
                # This is an event notification, notify subscribers (if any).
                if event_name in self._event_subscribers:
                    for queue in self._event_subscribers[event_name]:
                        queue.put_nowait(response)
            else:
                status = response.get("error")
                is_error = status and status != "success"
                if is_error:
                    logger.debug("mpv returned an error: %r", response)

                request_id = response.get("request_id")
                if request_id:
                    fut = self._futures.pop(request_id)
                    if is_error:
                        logger.debug("mpv returned an error: %r", response)

                    request_id = response.get("request_id")
                    if request_id:
                        fut = self._futures.pop(request_id)
                        if is_error:
                            fut.set_exception(IPCException(status, response))
                        else:
                            fut.set_result(response.get("data"))

            if self._reader.at_eof():
                logger.debug("EOF received, stopping polling")
                break
                        fut.set_exception(IPCException(status, response))
                    else:
                        fut.set_result(response.get("data"))

        logger.debug("EOF received, stopping polling")

    async def ipc(
        self, command_name: str, *params, nowait: bool = False
    ) -> typing.Optional[typing.Any]:
        if self._writer is None:
            raise AioMpvIPCException("Socket writer was not initialized")
            raise AioMpvIPCException("mpv IPC socket writer was not initialized")

        self._request_counter += 1



@@ 196,7 195,7 @@ class MpvClient:

        data = self._json_dumps(payload)
        self._writer.write(data.encode(encoding=IPC_ENCODING))
        self._writer.write(b"\n")
        self._writer.write(NEWLINE)
        await self._writer.drain()

        if not nowait:

M tests/test_client.py => tests/test_client.py +4 -2
@@ 4,9 4,10 @@ import pathlib
import shutil
import tempfile

import aio_mpv_ipc
import pytest

import aio_mpv_ipc

TEST_FILE_SILENCE = pathlib.Path(__file__).parent / "test_data" / "silence.ogg"

MPV_PATH = shutil.which("mpv")


@@ 145,6 146,7 @@ async def test_client_not_used_as_context_manager_ipc_raises_error():
    ) as socket_file:
        client = aio_mpv_ipc.MpvClient(socket_file.name, max_connect_attempts=3)
        with pytest.raises(
            aio_mpv_ipc.AioMpvIPCException, match=r"Socket writer was not initialized"
            aio_mpv_ipc.AioMpvIPCException,
            match=r"mpv IPC socket writer was not initialized",
        ):
            await client.ipc("client_name")