~naglis/aio_mpv_ipc

ref: 6175665969a83688cc6a3fec08c5683018c18a92 aio_mpv_ipc/aio_mpv_ipc/_client.py -rw-r--r-- 6.4 KiB
61756659Naglis Jonaitis Bump version 11 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
import asyncio
import collections
import contextlib
import json
import logging
import pathlib
import typing

from aio_mpv_ipc.exceptions import (
    AioMpvIPCException,
    IPCConnectionException,
    IPCException,
    MpvStartException,
)

logger = logging.getLogger("aio_mpv_ipc")

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


def _json_serialize_default(o):
    if isinstance(o, pathlib.Path):
        return str(o)
    return o


def _default_json_loads(s: bytes):
    return json.loads(s.decode(encoding=IPC_ENCODING))


def _default_json_dumps(obj: typing.Any) -> str:
    return json.dumps(obj, default=_json_serialize_default)


@contextlib.asynccontextmanager
async def start_mpv(
    socket_path: typing.Union[pathlib.Path, str],
    *mpv_args: str,
    mpv_path: typing.Union[pathlib.Path, str] = "mpv",
    terminate: bool = False,
):
    if isinstance(socket_path, pathlib.Path):
        socket_path = str(socket_path.resolve(strict=False))
    if isinstance(mpv_path, pathlib.Path):
        mpv_path = str(mpv_path)

    mpv = await asyncio.create_subprocess_exec(
        mpv_path, f"--input-ipc-server={socket_path}", *mpv_args
    )
    logger.debug("Started mpv process with PID: %d", mpv.pid)

    try:
        yield mpv
    except IPCConnectionException as exc:
        if mpv.returncode is not None:
            raise MpvStartException(
                f"mpv exited with status code: {mpv.returncode}"
            ) from exc
        else:
            raise
    except asyncio.CancelledError:
        raise
    except Exception:
        logger.exception("An unexpected error occurred while executing mpv")
        raise
    finally:
        if terminate and mpv.returncode is None:
            mpv.terminate()
        await mpv.wait()


class MpvClient:
    def __init__(
        self,
        socket_path: pathlib.Path,
        *,
        max_connect_attempts: int = 5,
        connect_sleep_timeout: float = 0.5,
        json_loads=_default_json_loads,
        json_dumps=_default_json_dumps,
    ) -> None:
        self._socket_path = socket_path
        self._reader, self._writer = None, None
        self._max_connect_attempts = max_connect_attempts
        self._connect_sleep_timeout = connect_sleep_timeout
        self._json_loads, self._json_dumps = json_loads, json_dumps
        self._poll_task = None

        self._request_counter = 0

        self._futures: typing.Dict[str, asyncio.Future] = {}
        self._event_subscribers: typing.Dict[
            str, typing.Set[asyncio.Queue]
        ] = collections.defaultdict(set)

    @property
    def socket_path(self) -> pathlib.Path:
        return self._socket_path

    def subscribe(self, event_name: str, queue: asyncio.Queue):
        self._event_subscribers[event_name].add(queue)

    def unsubscribe(self, event_name: str, queue: asyncio.Queue):
        self._event_subscribers[event_name].remove(queue)

    async def __aenter__(self):
        attempt = 0
        while True:
            attempt += 1
            try:
                self._reader, self._writer = await asyncio.open_unix_connection(
                    self._socket_path
                )
                break
            except (ConnectionRefusedError, FileNotFoundError) as exc:
                if attempt >= self._max_connect_attempts:
                    raise IPCConnectionException("Failed to connect to mpv") from exc
                logger.debug(
                    "%d connection attempt failed, will retry after %f seconds",
                    attempt,
                    self._connect_sleep_timeout,
                )
                await asyncio.sleep(self._connect_sleep_timeout)

        self._poll_task = asyncio.create_task(self._poll(), name="Poll mpv IPC socket")

        return self

    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

        if self._futures:
            logger.debug("Cancelling pending futures")
            for fut in self._futures.values():
                fut.cancel()

    async def _poll(self):
        while not self._reader.at_eof():
            data = await self._reader.readline()
            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 not fut.cancelled():
                        if is_error:
                            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("mpv IPC socket writer was not initialized")

        self._request_counter += 1

        payload = {"command": [command_name, *params]}

        fut = None
        if not nowait:
            request_id = self._request_counter
            fut = asyncio.get_running_loop().create_future()
            payload.update(request_id=request_id)
            self._futures.update({request_id: fut})

        logger.debug("mpv IPC payload (nowait=%r): %s", nowait, payload)

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

        if not nowait:
            return await fut