Debian Codegraph @

src/aiovlc/model/command.py

raw
1 """Provide commands for aiovlc."""
2
3 from __future__ import annotations
4
5 import contextlib
6 from dataclasses import dataclass, field
7 import re
8 from typing import TYPE_CHECKING, Generic, Literal, TypeVar
9
10 from ..const import LOGGER
11 from ..exceptions import (
12 AuthError,
13 CommandError,
14 CommandParameterError,
15 CommandParseError,
16 )
17
18 if TYPE_CHECKING:
19 from ..client import Client
20
21 T = TypeVar("T")
22 DEFAULT_COMMAND_READ_TERMINATOR = "> "
23
24
25 @dataclass
26 class Command(Generic[T]):
27 """Represent a VLC command."""
28
29 log_command: bool = field(init=False, default=True)
30 prefix: str = field(init=False)
31 read_terminator: str = field(init=False, default=DEFAULT_COMMAND_READ_TERMINATOR)
32
33 async def send(self, client: Client) -> T:
34 """Send the command."""
35 return await self._send_command(client)
36
37 async def _send_command(self, client: Client) -> T:
38 """Send the command."""
39 command_string = self.build_command()
40
41 async with client.command_lock:
42 if self.log_command:
43 LOGGER.debug("Sending command: %s", command_string.strip())
44 await client.write(command_string)
45 raw_output = await client.read(self.read_terminator)
46
47 command_output = raw_output.split("\r\n")[:-1]
48 LOGGER.debug("Command output: %s", command_output)
49
50 if command_output:
51 if re.match(
52 r"Unknown command `.*'\. Type `help' for help\.",
53 command_output[0],
54 ):
55 raise CommandError("Unknown Command")
56 if command_error := re.match(r"Error in.*", command_output[0]):
57 raise CommandError(command_error.group())
58
59 return self.parse_output(command_output)
60
61 def build_command(self) -> str:
62 """Return the full command string."""
63 return f"{self.prefix}\n"
64
65 def parse_output(self, output: list[str]) -> T: # noqa: ARG002
66 """Parse command output."""
67 # Disable mypy to have cleaner code in child classes.
68 return None # type: ignore[return-value]
69
70
71 @dataclass
72 class CommandOutput:
73 """Represent a command output."""
74
75
76 @dataclass
77 class Add(Command[None]):
78 """Represent the add command."""
79
80 prefix = "add"
81 playlist_item: str
82
83 def build_command(self) -> str:
84 """Return the full command string."""
85 return f"{self.prefix} {self.playlist_item}\n"
86
87
88 @dataclass
89 class Clear(Command[None]):
90 """Represent the clear command."""
91
92 prefix = "clear"
93
94
95 @dataclass
96 class Enqueue(Command[None]):
97 """Represent the enqueue command."""
98
99 prefix = "enqueue"
100 playlist_item: str
101
102 def build_command(self) -> str:
103 """Return the full command string."""
104 return f"{self.prefix} {self.playlist_item}\n"
105
106
107 @dataclass
108 class GetLengthOutput(CommandOutput):
109 """Represent the get length command output."""
110
111 length: int
112
113
114 @dataclass
115 class GetLength(Command[GetLengthOutput]):
116 """Represent the get length command."""
117
118 prefix = "get_length"
119
120 def parse_output(self, output: list[str]) -> GetLengthOutput:
121 """Parse command output."""
122 try:
123 if not (length_string := output[0]):
124 return GetLengthOutput(length=0)
125 length = int(length_string)
126 except (IndexError, ValueError) as err:
127 raise CommandParseError("Could not get length.") from err
128 return GetLengthOutput(length=length)
129
130
131 @dataclass
132 class GetTimeOutput(CommandOutput):
133 """Represent the get time command output."""
134
135 time: int
136
137
138 @dataclass
139 class GetTime(Command[GetTimeOutput]):
140 """Represent the get time command."""
141
142 prefix = "get_time"
143
144 def parse_output(self, output: list[str]) -> GetTimeOutput:
145 """Parse command output."""
146 try:
147 if not (time_string := output[0]):
148 return GetTimeOutput(time=0)
149 time = int(time_string)
150 except (IndexError, ValueError) as err:
151 raise CommandParseError("Could not get time.") from err
152 return GetTimeOutput(time=time)
153
154
155 @dataclass
156 class InfoOutput(CommandOutput):
157 """Represent the info command output."""
158
159 data: dict[str | int, dict[str, str | int | float]] = field(default_factory=dict)
160
161
162 @dataclass
163 class Info(Command[InfoOutput]):
164 """Represent the info command."""
165
166 prefix = "info"
167
168 def parse_output(self, output: list[str]) -> InfoOutput:
169 """Parse command output."""
170 data: dict[str | int, dict[str, str | int | float]] = {}
171 section: int | str = "unknown"
172 for line in output:
173 if line[0] == "+":
174 # Example: "+----[ Stream 5 ]" or "+----[ Meta data ]" # noqa: ERA001
175 if "end of stream info" in line:
176 continue
177 section = line.split("[")[1].replace("]", "").strip().split(" ")[1]
178 with contextlib.suppress(ValueError):
179 section = int(section)
180 data[section] = {}
181 elif line[0] == "|":
182 # Example: "| Description: Closed captions 4" # noqa: ERA001
183 if len(line[2:]) == 0:
184 continue
185 value: int | float | str = "unknown"
186 key, value = line[2:].split(":", 1)
187 try:
188 value = int(value)
189 except ValueError:
190 try:
191 value = float(value)
192 except ValueError:
193 value = value.strip() # type: ignore[union-attr]
194 data[section][key.strip()] = value
195 else:
196 raise CommandParseError(f"Unexpected line in info output: {line}")
197 return InfoOutput(data=data)
198
199
200 @dataclass
201 class PasswordOutput(CommandOutput):
202 """Represent the password command output."""
203
204 response: str
205
206
207 @dataclass
208 class Password(Command[PasswordOutput]):
209 """Represent the password command."""
210
211 log_command = False
212 prefix = ""
213 password: str
214 read_terminator = "\n"
215
216 def build_command(self) -> str:
217 """Return the full command string."""
218 return f"{self.prefix}{self.password}\n"
219
220 def parse_output(self, output: list[str]) -> PasswordOutput:
221 """Parse command output."""
222 response: str = ""
223 for line in output:
224 if not line:
225 continue
226 response = line
227 parsed_output = response.lower()
228 if "wrong password" in parsed_output:
229 raise AuthError("Failed to login to VLC.")
230 if "welcome" not in parsed_output:
231 raise CommandError(f"Unexpected password response: {response}")
232
233 if not response:
234 raise CommandError("Empty password response")
235 return PasswordOutput(response)
236
237 async def send(self, client: Client) -> PasswordOutput:
238 """Send the command."""
239 await client.read("Password: ")
240 password_output = await super().send(client)
241 if DEFAULT_COMMAND_READ_TERMINATOR in password_output.response:
242 password_output.response = password_output.response.strip(
243 DEFAULT_COMMAND_READ_TERMINATOR,
244 )
245 return password_output
246 # Read until prompt
247 await client.read(DEFAULT_COMMAND_READ_TERMINATOR)
248 return password_output
249
250
251 @dataclass
252 class Next(Command[None]):
253 """Represent the next command."""
254
255 prefix = "next"
256
257
258 @dataclass
259 class Pause(Command[None]):
260 """Represent the pause command."""
261
262 prefix = "pause"
263
264
265 @dataclass
266 class Play(Command[None]):
267 """Represent the play command."""
268
269 prefix = "play"
270
271
272 @dataclass
273 class Prev(Command[None]):
274 """Represent the prev command."""
275
276 prefix = "prev"
277
278
279 @dataclass
280 class Random(Command[None]):
281 """Represent the random command."""
282
283 prefix = "random"
284 mode: Literal["on", "off"] | None = None
285 VALID_MODES = (None, "on", "off")
286
287 def build_command(self) -> str:
288 """Return the full command string."""
289 if self.mode not in self.VALID_MODES:
290 raise CommandParameterError(f"Parameter mode not in {self.VALID_MODES}")
291 mode = "" if self.mode is None else f" {self.mode}"
292 return f"{self.prefix}{mode}\n"
293
294
295 @dataclass
296 class Seek(Command[None]):
297 """Represent the seek command."""
298
299 prefix = "seek"
300 seconds: int
301
302 def build_command(self) -> str:
303 """Return the full command string."""
304 return f"{self.prefix} {self.seconds}\n"
305
306
307 @dataclass
308 class StatusOutput(CommandOutput):
309 """Represent the status command output."""
310
311 audio_volume: int
312 state: str
313 input_loc: str | None = None
314
315
316 @dataclass
317 class Status(Command[StatusOutput]):
318 """Represent the status command."""
319
320 prefix = "status"
321
322 def parse_output(self, output: list[str]) -> StatusOutput:
323 """Parse command output."""
324 input_loc: str | None = None
325 if len(output) == 3:
326 input_loc_item = output.pop(0)
327 input_loc = "%20".join(input_loc_item.split(" ")[3:-1])
328 if len(output) == 2:
329 audio_volume = int(float(output[0].split(" ")[3].replace(",", ".")))
330 state = output[1].split(" ")[2]
331 else:
332 raise CommandParseError("Could not get status.")
333 return StatusOutput(audio_volume=audio_volume, state=state, input_loc=input_loc)
334
335
336 @dataclass
337 class Stop(Command[None]):
338 """Represent the stop command."""
339
340 prefix = "stop"
341
342
343 @dataclass
344 class VolumeOutput(CommandOutput):
345 """Represent the volume command output."""
346
347 audio_volume: int
348
349
350 @dataclass
351 class Volume(Command[VolumeOutput]):
352 """Represent the volume command."""
353
354 prefix = "volume"
355
356 def parse_output(self, output: list[str]) -> VolumeOutput:
357 """Parse command output."""
358 try:
359 audio_volume = int(float(output[0].replace(",", ".")))
360 except (IndexError, ValueError) as err:
361 raise CommandParseError("Could not get volume.") from err
362 return VolumeOutput(audio_volume=audio_volume)
363
364
365 @dataclass
366 class SetVolume(Command[None]):
367 """Represent the set volume command."""
368
369 prefix = "volume"
370 volume: int
371 VALID_VOLUME = range(500)
372
373 def build_command(self) -> str:
374 """Return the full command string."""
375 try:
376 volume = int(self.volume)
377 except ValueError as err:
378 raise CommandParameterError(
379 f"Invalid volume parameter: {self.volume}",
380 ) from err
381 if volume not in self.VALID_VOLUME:
382 raise CommandParameterError(f"Parameter volume not in {self.VALID_VOLUME}")
383 return f"{self.prefix} {volume}\n"