Debian Codegraph @

src/aiovlc/client.py

raw
1 """Provide a client for aiovlc."""
2
3 from __future__ import annotations
4
5 import asyncio
6 from types import TracebackType
7 from typing import Literal, Self
8
9 from .const import LOGGER
10 from .exceptions import ConnectError, ConnectReadError
11 from .model.command import (
12 Add,
13 Clear,
14 Enqueue,
15 GetLength,
16 GetLengthOutput,
17 GetTime,
18 GetTimeOutput,
19 Info,
20 InfoOutput,
21 Next,
22 Password,
23 PasswordOutput,
24 Pause,
25 Play,
26 Prev,
27 Random,
28 Seek,
29 SetVolume,
30 Status,
31 StatusOutput,
32 Stop,
33 Volume,
34 VolumeOutput,
35 )
36
37 IAC = bytes([255]) # "Interpret As Command"
38 TERMINATOR = "\n"
39
40
41 class Client:
42 """Represent a client for aiovlc."""
43
44 # pylint: disable=too-many-public-methods
45
46 def __init__(
47 self,
48 password: str,
49 host: str = "localhost",
50 port: int = 4212,
51 ) -> None:
52 """Set up the client client."""
53 self.host = host
54 self.password = password
55 self.port = port
56 self.command_lock = asyncio.Lock()
57 self._reader: asyncio.StreamReader | None = None
58 self._writer: asyncio.StreamWriter | None = None
59
60 async def __aenter__(self) -> Self:
61 """Connect the client with context manager."""
62 await self.connect()
63 return self
64
65 async def __aexit__(
66 self,
67 exc_type: type[BaseException] | None,
68 exc_value: BaseException | None,
69 traceback: TracebackType | None,
70 ) -> None:
71 """Disconnect the client with context manager."""
72 await self.disconnect()
73
74 async def connect(self) -> None:
75 """Connect the client."""
76 try:
77 self._reader, self._writer = await asyncio.open_connection(
78 host=self.host,
79 port=self.port,
80 )
81 except OSError as err:
82 raise ConnectError(f"Failed to connect: {err}") from err
83
84 async def disconnect(self) -> None:
85 """Disconnect the client."""
86 if self._writer is None:
87 raise RuntimeError("Client is not connected")
88 try:
89 self._writer.close()
90 await self._writer.wait_closed()
91 except OSError:
92 pass
93
94 async def read(self, read_until: str = TERMINATOR) -> str:
95 """Return a decoded message."""
96 if self._reader is None:
97 raise RuntimeError("Client is not connected")
98
99 try:
100 read = await self._reader.readuntil(read_until.encode("utf-8"))
101 except asyncio.LimitOverrunError as err:
102 raise ConnectReadError(err) from err
103 except asyncio.IncompleteReadError as err:
104 raise ConnectReadError(err, err.partial) from err
105 except OSError as err:
106 raise ConnectError(f"Failed to read: {err}") from err
107
108 LOGGER.debug("Bytes read: %s", read)
109
110 # Drop IAC command and read again.
111 if IAC in read:
112 return await self.read(read_until)
113 return read.decode("utf-8")
114
115 async def write(self, command: str) -> None:
116 """Write a command to the connection."""
117 if self._writer is None:
118 raise RuntimeError("Client is not connected")
119
120 try:
121 self._writer.write(command.encode("utf-8"))
122 await self._writer.drain()
123 except OSError as err:
124 raise ConnectError(f"Failed to write: {err}") from err
125
126 async def login(self) -> PasswordOutput:
127 """Login."""
128 return await Password(self.password).send(self)
129
130 async def add(self, playlist_item: str) -> None:
131 """Send the add command."""
132 await Add(playlist_item).send(self)
133
134 async def clear(self) -> None:
135 """Send the clear command."""
136 await Clear().send(self)
137
138 async def enqueue(self, playlist_item: str) -> None:
139 """Send the enqueue command."""
140 await Enqueue(playlist_item).send(self)
141
142 async def get_length(self) -> GetLengthOutput:
143 """Send the get_length command."""
144 return await GetLength().send(self)
145
146 async def get_time(self) -> GetTimeOutput:
147 """Send the get_time command."""
148 return await GetTime().send(self)
149
150 async def info(self) -> InfoOutput:
151 """Send the info command."""
152 return await Info().send(self)
153
154 async def next(self) -> None:
155 """Send the next command."""
156 await Next().send(self)
157
158 async def pause(self) -> None:
159 """Send the pause command."""
160 await Pause().send(self)
161
162 async def play(self) -> None:
163 """Send the play command."""
164 await Play().send(self)
165
166 async def prev(self) -> None:
167 """Send the prev command."""
168 await Prev().send(self)
169
170 async def random(self, mode: Literal["on", "off"] | None = None) -> None:
171 """Send the random command."""
172 await Random(mode).send(self)
173
174 async def seek(self, seconds: int) -> None:
175 """Send the seek command."""
176 await Seek(seconds).send(self)
177
178 async def set_volume(self, volume: int) -> None:
179 """Send the volume command with a parameter to set volume."""
180 await SetVolume(volume).send(self)
181
182 async def status(self) -> StatusOutput:
183 """Send the status command."""
184 return await Status().send(self)
185
186 async def stop(self) -> None:
187 """Send the stop command."""
188 await Stop().send(self)
189
190 async def volume(self) -> VolumeOutput:
191 """Send the volume command."""
192 return await Volume().send(self)