Debian Codegraph @

beetsplug/bpd/__init__.py

raw
1 """A clone of the Music Player Daemon (MPD) that plays music from a
2 Beets library. Attempts to implement a compatible protocol to allow
3 use of the wide range of MPD clients.
4 """
5
6 from __future__ import annotations
7
8 import asyncio
9 import inspect
10 import math
11 import random
12 import re
13 import socket
14 import sys
15 import time
16 import traceback
17 from string import Template
18 from typing import TYPE_CHECKING, Any, ClassVar, NoReturn, overload
19
20 import beets
21 import beets.ui
22 from beets import dbcore
23 from beets.exceptions import UserError
24 from beets.library import Item
25 from beets.plugins import BeetsPlugin
26 from beets.util import as_string
27 from beetsplug._utils import vfs
28
29 if TYPE_CHECKING:
30 import optparse
31 from collections.abc import Iterable, Iterator
32 from typing import Literal
33
34 from beets.dbcore.query import FieldQueryType, Query
35 from beets.library import Library
36 from beets.logging import BeetsLogger as Logger
37 from beetsplug._utils.vfs import Node
38
39
40 try:
41 from . import gstplayer
42 except ImportError as e:
43 raise ImportError(
44 "Gstreamer Python bindings not found."
45 ' Install "gstreamer1.0" and "python-gi" or similar package to use BPD.'
46 ) from e
47
48 PROTOCOL_VERSION = "0.16.0"
49 BUFSIZE = 1024
50
51 HELLO = f"OK MPD {PROTOCOL_VERSION}"
52 CLIST_BEGIN = "command_list_begin"
53 CLIST_VERBOSE_BEGIN = "command_list_ok_begin"
54 CLIST_END = "command_list_end"
55 RESP_OK = "OK"
56 RESP_CLIST_VERBOSE = "list_OK"
57 RESP_ERR = "ACK"
58
59 NEWLINE = "\n"
60
61 ERROR_NOT_LIST = 1
62 ERROR_ARG = 2
63 ERROR_PASSWORD = 3
64 ERROR_PERMISSION = 4
65 ERROR_UNKNOWN = 5
66 ERROR_NO_EXIST = 50
67 ERROR_PLAYLIST_MAX = 51
68 ERROR_SYSTEM = 52
69 ERROR_PLAYLIST_LOAD = 53
70 ERROR_UPDATE_ALREADY = 54
71 ERROR_PLAYER_SYNC = 55
72 ERROR_EXIST = 56
73
74 VOLUME_MIN = 0
75 VOLUME_MAX = 100
76
77 SAFE_COMMANDS = (
78 # Commands that are available when unauthenticated.
79 "close",
80 "commands",
81 "notcommands",
82 "password",
83 "ping",
84 )
85
86 # List of subsystems/events used by the `idle` command.
87 SUBSYSTEMS = [
88 "update",
89 "player",
90 "mixer",
91 "options",
92 "playlist",
93 "database",
94 # Related to unsupported commands:
95 "stored_playlist",
96 "output",
97 "subscription",
98 "sticker",
99 "message",
100 "partition",
101 ]
102
103
104 # Error-handling, exceptions, parameter parsing.
105
106
107 class BPDError(Exception):
108 """An error that should be exposed to the client to the BPD
109 server.
110 """
111
112 def __init__(
113 self, code: int, message: str, cmd_name: str = "", index: int = 0
114 ) -> None:
115 self.code = code
116 self.message = message
117 self.cmd_name = cmd_name
118 self.index = index
119
120 template = Template("$resp [$code@$index] {$cmd_name} $message")
121
122 def response(self) -> str:
123 """Returns a string to be used as the response code for the
124 erring command.
125 """
126 return self.template.substitute(
127 {
128 "resp": RESP_ERR,
129 "code": self.code,
130 "index": self.index,
131 "cmd_name": self.cmd_name,
132 "message": self.message,
133 }
134 )
135
136
137 def make_bpd_error(s_code: int, s_message: str) -> type[Exception]:
138 """Create a BPDError subclass for a static code and message."""
139
140 class NewBPDError(BPDError):
141 code = s_code
142 message = s_message
143 cmd_name = ""
144 index = 0
145
146 def __init__(self) -> None:
147 pass
148
149 return NewBPDError
150
151
152 ArgumentTypeError = make_bpd_error(ERROR_ARG, "invalid type for argument")
153 ArgumentIndexError = make_bpd_error(ERROR_ARG, "argument out of range")
154 ArgumentNotFoundError = make_bpd_error(ERROR_NO_EXIST, "argument not found")
155
156
157 @overload
158 def cast_arg(t: type[bool], val: str | int | float | bool) -> bool: ...
159 @overload
160 def cast_arg(t: type[int], val: str | int | float | bool) -> int: ...
161 @overload
162 def cast_arg(t: type[float], val: str | int | float | bool) -> float: ...
163 @overload
164 def cast_arg(t: Literal["intbool"], val: str | int | float | bool) -> bool: ...
165 def cast_arg(
166 t: type[bool | int | float] | Literal["intbool"],
167 val: str | int | float | bool,
168 ) -> Any:
169 """Attempts to call t on val, raising a ArgumentTypeError
170 on ValueError.
171
172 If 't' is the special string 'intbool', attempts to cast first
173 to an int and then to a bool (i.e., 1=True, 0=False).
174 """
175 if t == "intbool":
176 return cast_arg(bool, cast_arg(int, val))
177 try:
178 return t(val)
179 except ValueError:
180 raise ArgumentTypeError()
181
182
183 class BPDCloseError(Exception):
184 """Raised by a command invocation to indicate that the connection
185 should be closed.
186 """
187
188
189 class BPDIdleError(Exception):
190 """Raised by a command to indicate the client wants to enter the idle state
191 and should be notified when a relevant event happens.
192 """
193
194 def __init__(self, subsystems: Iterable[str]) -> None:
195 super().__init__()
196 self.subsystems = set(subsystems)
197
198
199 # Generic server infrastructure, implementing the basic protocol.
200
201
202 class BaseServer:
203 """A MPD-compatible music player server.
204
205 The functions with the `cmd_` prefix are invoked in response to
206 client commands. For instance, if the client says `status`,
207 `cmd_status` will be invoked. The arguments to the client's commands
208 are used as function arguments following the connection issuing the
209 command. The functions may send data on the connection. They may
210 also raise BPDError exceptions to report errors.
211
212 This is a generic superclass and doesn't support many commands.
213 """
214
215 playlist: list[Item]
216 connections: set[MPDConnection]
217 ctrl_sock: socket.socket | None
218
219 def __init__(
220 self,
221 host: str,
222 port: int,
223 password: str,
224 ctrl_port: int,
225 log: Logger,
226 ctrl_host: str | None = None,
227 ) -> None:
228 """Create a new server bound to address `host` and listening
229 on port `port`. If `password` is given, it is required to do
230 anything significant on the server.
231 A separate control socket is established listening to `ctrl_host` on
232 port `ctrl_port` which is used to forward notifications from the player
233 and can be sent debug commands (e.g. using netcat).
234 """
235 self.host, self.port, self.password = host, port, password
236 self.ctrl_host, self.ctrl_port = ctrl_host or host, ctrl_port
237 self.ctrl_sock = None
238 self._log = log
239
240 # Default server values.
241 self.random = False
242 self.repeat = False
243 self.consume = False
244 self.single = False
245 self.volume = VOLUME_MAX
246 self.crossfade = 0
247 self.mixrampdb = 0.0
248 self.mixrampdelay = float("nan")
249 self.replay_gain_mode = "off"
250 self.playlist = []
251 self.playlist_version = 0
252 self.current_index = -1
253 self.paused = False
254 self.error = None
255
256 # Current connections
257 self.connections = set()
258 self._notification_tasks: dict[MPDConnection, asyncio.Task[None]] = {}
259
260 # Object for random numbers generation
261 self.random_obj = random.Random()
262
263 def connect(self, conn: MPDConnection) -> None:
264 """A new client has connected."""
265 self.connections.add(conn)
266
267 def disconnect(self, conn: MPDConnection) -> None:
268 """Client has disconnected; clean up residual state."""
269 self.connections.discard(conn)
270
271 def run(self) -> None:
272 """Block and start listening for connections from clients. An
273 interrupt (^C) closes the server.
274 """
275 asyncio.run(self._run())
276
277 async def _run(self) -> None:
278 """Serve MPD and control connections in one event loop."""
279 self.startup_time = time.time()
280
281 async with await asyncio.start_server(
282 ControlConnection.handler(self),
283 self.ctrl_host,
284 self.ctrl_port,
285 family=socket.AF_INET,
286 ) as control_server:
287 async with await asyncio.start_server(
288 MPDConnection.handler(self),
289 self.host,
290 self.port,
291 family=socket.AF_INET,
292 ) as mpd_server:
293 await asyncio.gather(
294 control_server.serve_forever(), mpd_server.serve_forever()
295 )
296
297 def dispatch_events(self) -> None:
298 """If any clients have idle events ready, send them."""
299 # We need a copy of `self.connections` here since clients might
300 # disconnect once we try and send to them, changing `self.connections`.
301 for conn in list(self.connections):
302 self._dispatch_connection_events(conn)
303
304 def _dispatch_connection_events(self, conn: MPDConnection) -> None:
305 """Start sending queued events unless this connection is busy."""
306 if conn in self._notification_tasks:
307 return
308 task = asyncio.create_task(conn.send_notifications())
309 self._notification_tasks[conn] = task
310 task.add_done_callback(lambda task: self._notification_done(conn, task))
311
312 def _notification_done(
313 self, conn: MPDConnection, task: asyncio.Task[None]
314 ) -> None:
315 """Release a connection after its queued events have been sent."""
316 del self._notification_tasks[conn]
317 if task.cancelled():
318 return
319 if error := task.exception():
320 self._log.error("Could not send BPD notifications: {}", error)
321 return
322 pending = conn.notifications.intersection(conn.idle_subscriptions)
323 if conn in self.connections and pending:
324 self._dispatch_connection_events(conn)
325
326 def _ctrl_send(self, message: str) -> None:
327 """Send some data over the control socket.
328 If it's our first time, open the socket. The message should be a
329 string without a terminal newline.
330 """
331 if not self.ctrl_sock:
332 self.ctrl_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
333 self.ctrl_sock.connect((self.ctrl_host, self.ctrl_port))
334 self.ctrl_sock.sendall((f"{message}\n").encode())
335
336 def _send_event(self, event: str) -> None:
337 """Notify subscribed connections of an event."""
338 for conn in self.connections:
339 conn.notify(event)
340
341 def _item_info(self, item: Item) -> list[str]:
342 """An abstract method that should response lines containing a
343 single song's metadata.
344 """
345 raise NotImplementedError
346
347 def _item_id(self, item: Item) -> int | None:
348 """An abstract method returning the integer id for an item."""
349 raise NotImplementedError
350
351 def _id_to_index(self, track_id: int) -> int:
352 """Searches the playlist for a song with the given id and
353 returns its index in the playlist.
354 """
355 track_id = cast_arg(int, track_id)
356 for index, track in enumerate(self.playlist):
357 if self._item_id(track) == track_id:
358 return index
359 # Loop finished with no track found.
360 raise ArgumentNotFoundError()
361
362 def _random_idx(self) -> int:
363 """Returns a random index different from the current one.
364 If there are no songs in the playlist it returns -1.
365 If there is only one song in the playlist it returns 0.
366 """
367 if len(self.playlist) < 2:
368 return len(self.playlist) - 1
369 new_index = self.random_obj.randint(0, len(self.playlist) - 1)
370 while new_index == self.current_index:
371 new_index = self.random_obj.randint(0, len(self.playlist) - 1)
372 return new_index
373
374 def _succ_idx(self) -> int:
375 """Returns the index for the next song to play.
376 It also considers random, single and repeat flags.
377 No boundaries are checked.
378 """
379 if self.repeat and self.single:
380 return self.current_index
381 if self.random:
382 return self._random_idx()
383 return self.current_index + 1
384
385 def _prev_idx(self) -> int:
386 """Returns the index for the previous song to play.
387 It also considers random and repeat flags.
388 No boundaries are checked.
389 """
390 if self.repeat and self.single:
391 return self.current_index
392 if self.random:
393 return self._random_idx()
394 return self.current_index - 1
395
396 def cmd_ping(self, conn: MPDConnection) -> None:
397 """Succeeds."""
398
399 def cmd_idle(self, conn: MPDConnection, *subsystems: str) -> NoReturn:
400 subsystems = tuple(subsystems or SUBSYSTEMS)
401 for system in subsystems:
402 if system not in SUBSYSTEMS:
403 raise BPDError(ERROR_ARG, f"Unrecognised idle event: {system}")
404 raise BPDIdleError(subsystems) # put the connection into idle mode
405
406 def cmd_kill(self, conn: MPDConnection) -> None:
407 """Exits the server process."""
408 sys.exit(0)
409
410 def cmd_close(self, conn: MPDConnection) -> NoReturn:
411 """Closes the connection."""
412 raise BPDCloseError()
413
414 def cmd_password(self, conn: MPDConnection, password: str) -> None:
415 """Attempts password authentication."""
416 if password == self.password:
417 conn.authenticated = True
418 else:
419 conn.authenticated = False
420 raise BPDError(ERROR_PASSWORD, "incorrect password")
421
422 def cmd_commands(self, conn: MPDConnection) -> Iterator[Any]:
423 """Lists the commands available to the user."""
424 if self.password and not conn.authenticated:
425 # Not authenticated. Show limited list of commands.
426 for cmd in SAFE_COMMANDS:
427 yield f"command: {cmd}"
428
429 else:
430 # Authenticated. Show all commands.
431 for func in dir(self):
432 if func.startswith("cmd_"):
433 yield f"command: {func[4:]}"
434
435 def cmd_notcommands(self, conn: MPDConnection) -> Iterator[Any]:
436 """Lists all unavailable commands."""
437 if self.password and not conn.authenticated:
438 # Not authenticated. Show privileged commands.
439 for func in dir(self):
440 if func.startswith("cmd_"):
441 cmd = func[4:]
442 if cmd not in SAFE_COMMANDS:
443 yield f"command: {cmd}"
444
445 else:
446 # Authenticated. No commands are unavailable.
447 pass
448
449 def cmd_status(self, conn: MPDConnection) -> Iterator[Any]:
450 """Returns some status information for use with an
451 implementation of cmd_status.
452
453 Gives a list of response-lines for: volume, repeat, random,
454 playlist, playlistlength, and xfade.
455 """
456 yield (
457 f"repeat: {int(self.repeat)}",
458 f"random: {int(self.random)}",
459 f"consume: {int(self.consume)}",
460 f"single: {int(self.single)}",
461 f"playlist: {self.playlist_version}",
462 f"playlistlength: {len(self.playlist)}",
463 f"mixrampdb: {self.mixrampdb}",
464 )
465
466 if self.volume > 0:
467 yield f"volume: {self.volume}"
468
469 if not math.isnan(self.mixrampdelay):
470 yield f"mixrampdelay: {self.mixrampdelay}"
471 if self.crossfade > 0:
472 yield f"xfade: {self.crossfade}"
473
474 if self.current_index == -1:
475 state = "stop"
476 elif self.paused:
477 state = "pause"
478 else:
479 state = "play"
480 yield f"state: {state}"
481
482 if self.current_index != -1: # i.e., paused or playing
483 current_id = self._item_id(self.playlist[self.current_index])
484 yield f"song: {self.current_index}"
485 yield f"songid: {current_id}"
486 if len(self.playlist) > self.current_index + 1:
487 # If there's a next song, report its index too.
488 next_id = self._item_id(self.playlist[self.current_index + 1])
489 yield f"nextsong: {self.current_index + 1}"
490 yield f"nextsongid: {next_id}"
491
492 if self.error:
493 yield f"error: {self.error}"
494
495 def cmd_clearerror(self, conn: MPDConnection) -> None:
496 """Removes the persistent error state of the server. This
497 error is set when a problem arises not in response to a
498 command (for instance, when playing a file).
499 """
500 self.error = None
501
502 def cmd_random(self, conn: MPDConnection, state: str) -> None:
503 """Set or unset random (shuffle) mode."""
504 self.random = cast_arg("intbool", state)
505 self._send_event("options")
506
507 def cmd_repeat(self, conn: MPDConnection, state: str) -> None:
508 """Set or unset repeat mode."""
509 self.repeat = cast_arg("intbool", state)
510 self._send_event("options")
511
512 def cmd_consume(self, conn: MPDConnection, state: str) -> None:
513 """Set or unset consume mode."""
514 self.consume = cast_arg("intbool", state)
515 self._send_event("options")
516
517 def cmd_single(self, conn: MPDConnection, state: str) -> None:
518 """Set or unset single mode."""
519 # TODO support oneshot in addition to 0 and 1 [MPD 0.20]
520 self.single = cast_arg("intbool", state)
521 self._send_event("options")
522
523 def cmd_setvol(self, conn: MPDConnection | None, vol: str | int) -> None:
524 """Set the player's volume level (0-100)."""
525 vol = cast_arg(int, vol)
526 if vol < VOLUME_MIN or vol > VOLUME_MAX:
527 raise BPDError(ERROR_ARG, "volume out of range")
528 self.volume = vol
529 self._send_event("mixer")
530
531 def cmd_volume(self, conn: MPDConnection, vol_delta: int) -> None:
532 """Deprecated command to change the volume by a relative amount."""
533 vol_delta = cast_arg(int, vol_delta)
534 return self.cmd_setvol(conn, self.volume + vol_delta)
535
536 def cmd_crossfade(self, conn: MPDConnection, crossfade: int) -> None:
537 """Set the number of seconds of crossfading."""
538 crossfade = cast_arg(int, crossfade)
539 if crossfade < 0:
540 raise BPDError(ERROR_ARG, "crossfade time must be nonnegative")
541 self._log.warning("crossfade is not implemented in bpd")
542 self.crossfade = crossfade
543 self._send_event("options")
544
545 def cmd_mixrampdb(self, conn: MPDConnection, db: float) -> None:
546 """Set the mixramp normalised max volume in dB."""
547 db = cast_arg(float, db)
548 if db > 0:
549 raise BPDError(ERROR_ARG, "mixrampdb time must be negative")
550 self._log.warning("mixramp is not implemented in bpd")
551 self.mixrampdb = db
552 self._send_event("options")
553
554 def cmd_mixrampdelay(self, conn: MPDConnection, delay: float) -> None:
555 """Set the mixramp delay in seconds."""
556 delay = cast_arg(float, delay)
557 if delay < 0:
558 raise BPDError(ERROR_ARG, "mixrampdelay time must be nonnegative")
559 self._log.warning("mixramp is not implemented in bpd")
560 self.mixrampdelay = delay
561 self._send_event("options")
562
563 def cmd_replay_gain_mode(self, conn: MPDConnection, mode: str) -> None:
564 """Set the replay gain mode."""
565 if mode not in ["off", "track", "album", "auto"]:
566 raise BPDError(ERROR_ARG, "Unrecognised replay gain mode")
567 self._log.warning("replay gain is not implemented in bpd")
568 self.replay_gain_mode = mode
569 self._send_event("options")
570
571 def cmd_replay_gain_status(self, conn: MPDConnection) -> Iterator[Any]:
572 """Get the replaygain mode."""
573 yield f"replay_gain_mode: {self.replay_gain_mode}"
574
575 def cmd_clear(self, conn: MPDConnection) -> None:
576 """Clear the playlist."""
577 self.playlist = []
578 self.playlist_version += 1
579 self.cmd_stop(conn)
580 self._send_event("playlist")
581
582 def cmd_delete(self, conn: MPDConnection, index: int) -> None:
583 """Remove the song at index from the playlist."""
584 index = cast_arg(int, index)
585 try:
586 del self.playlist[index]
587 except IndexError:
588 raise ArgumentIndexError()
589 self.playlist_version += 1
590
591 if self.current_index == index: # Deleted playing song.
592 self.cmd_stop(conn)
593 elif index < self.current_index: # Deleted before playing.
594 # Shift playing index down.
595 self.current_index -= 1
596 self._send_event("playlist")
597
598 def cmd_deleteid(self, conn: MPDConnection, track_id: int) -> None:
599 self.cmd_delete(conn, self._id_to_index(track_id))
600
601 def cmd_move(self, conn: MPDConnection, idx_from: int, idx_to: int) -> None:
602 """Move a track in the playlist."""
603 idx_from = cast_arg(int, idx_from)
604 idx_to = cast_arg(int, idx_to)
605 try:
606 track = self.playlist.pop(idx_from)
607 self.playlist.insert(idx_to, track)
608 except IndexError:
609 raise ArgumentIndexError()
610
611 # Update currently-playing song.
612 if idx_from == self.current_index:
613 self.current_index = idx_to
614 elif idx_from < self.current_index <= idx_to:
615 self.current_index -= 1
616 elif idx_from > self.current_index >= idx_to:
617 self.current_index += 1
618
619 self.playlist_version += 1
620 self._send_event("playlist")
621
622 def cmd_moveid(
623 self, conn: MPDConnection, idx_from: int, idx_to: int
624 ) -> None:
625 idx_from = self._id_to_index(idx_from)
626 return self.cmd_move(conn, idx_from, idx_to)
627
628 def cmd_swap(self, conn: MPDConnection, i: int, j: int) -> None:
629 """Swaps two tracks in the playlist."""
630 i = cast_arg(int, i)
631 j = cast_arg(int, j)
632 try:
633 track_i = self.playlist[i]
634 track_j = self.playlist[j]
635 except IndexError:
636 raise ArgumentIndexError()
637
638 self.playlist[j] = track_i
639 self.playlist[i] = track_j
640
641 # Update currently-playing song.
642 if self.current_index == i:
643 self.current_index = j
644 elif self.current_index == j:
645 self.current_index = i
646
647 self.playlist_version += 1
648 self._send_event("playlist")
649
650 def cmd_swapid(self, conn: MPDConnection, i_id: int, j_id: int) -> None:
651 i = self._id_to_index(i_id)
652 j = self._id_to_index(j_id)
653 return self.cmd_swap(conn, i, j)
654
655 def cmd_urlhandlers(self, conn: MPDConnection) -> None:
656 """Indicates supported URL schemes. None by default."""
657
658 @staticmethod
659 def _parse_range(
660 items: str | int, accept_single_number: bool = False
661 ) -> list[int] | range:
662 """Convert a range of positions to a list of item info.
663 MPD specifies ranges as START:STOP (endpoint excluded) for some
664 commands. Sometimes a single number can be provided instead.
665 """
666 try:
667 start, stop = str(items).split(":", 1)
668 except ValueError:
669 if accept_single_number:
670 return [cast_arg(int, items)]
671 raise BPDError(ERROR_ARG, "bad range syntax")
672 return range(cast_arg(int, start), cast_arg(int, stop))
673
674 def cmd_playlistinfo(
675 self, conn: MPDConnection, index: str | int | None = None
676 ) -> Iterator[Any]:
677 """Gives metadata information about the entire playlist or a
678 single track, given by its index.
679 """
680 if index is None:
681 for track in self.playlist:
682 yield self._item_info(track)
683 else:
684 indices = self._parse_range(index, accept_single_number=True)
685 try:
686 tracks = [self.playlist[i] for i in indices]
687 except IndexError:
688 raise ArgumentIndexError()
689 for track in tracks:
690 yield self._item_info(track)
691
692 def cmd_playlistid(
693 self, conn: MPDConnection, track_id: int | None = None
694 ) -> Iterator[Any]:
695 if track_id is not None:
696 track_id = cast_arg(int, track_id)
697 track_id = self._id_to_index(track_id)
698 return self.cmd_playlistinfo(conn, track_id)
699
700 def cmd_plchanges(self, conn: MPDConnection, version: str) -> Iterator[Any]:
701 """Sends playlist changes since the given version.
702
703 This is a "fake" implementation that ignores the version and
704 just returns the entire playlist (rather like version=0). This
705 seems to satisfy many clients.
706 """
707 return self.cmd_playlistinfo(conn)
708
709 def cmd_plchangesposid(
710 self, conn: MPDConnection, version: str
711 ) -> Iterator[Any]:
712 """Like plchanges, but only sends position and id.
713
714 Also a dummy implementation.
715 """
716 for idx, track in enumerate(self.playlist):
717 yield f"cpos: {idx}"
718 yield f"Id: {track.id}"
719
720 def cmd_currentsong(self, conn: MPDConnection) -> Iterator[Any]:
721 """Sends information about the currently-playing song."""
722 if self.current_index != -1: # -1 means stopped.
723 track = self.playlist[self.current_index]
724 yield self._item_info(track)
725
726 def cmd_next(self, conn: MPDConnection | None) -> None:
727 """Advance to the next song in the playlist."""
728 old_index = self.current_index
729 self.current_index = self._succ_idx()
730 if self.consume:
731 # TODO how does consume interact with single+repeat?
732 self.playlist.pop(old_index)
733 if self.current_index > old_index:
734 self.current_index -= 1
735 self.playlist_version += 1
736 self._send_event("playlist")
737 if self.current_index >= len(self.playlist):
738 # Fallen off the end. Move to stopped state or loop.
739 if self.repeat:
740 self.current_index = -1
741 return self.cmd_play(conn)
742 return self.cmd_stop(conn)
743 if self.single and not self.repeat:
744 return self.cmd_stop(conn)
745 return self.cmd_play(conn)
746
747 def cmd_previous(self, conn: MPDConnection) -> None:
748 """Step back to the last song."""
749 old_index = self.current_index
750 self.current_index = self._prev_idx()
751 if self.consume:
752 self.playlist.pop(old_index)
753 if self.current_index < 0:
754 if self.repeat:
755 self.current_index = len(self.playlist) - 1
756 else:
757 self.current_index = 0
758 return self.cmd_play(conn)
759
760 def cmd_pause(self, conn: MPDConnection, state: str | None = None) -> None:
761 """Set the pause state playback."""
762 if state is None:
763 self.paused = not self.paused # Toggle.
764 else:
765 self.paused = cast_arg("intbool", state)
766 self._send_event("player")
767
768 def cmd_play(self, conn: MPDConnection | None, index: int = -1) -> None:
769 """Begin playback, possibly at a specified playlist index."""
770 index = cast_arg(int, index)
771
772 if index < -1 or index >= len(self.playlist):
773 raise ArgumentIndexError()
774
775 if index == -1: # No index specified: start where we are.
776 if not self.playlist: # Empty playlist: stop immediately.
777 return self.cmd_stop(conn)
778 if self.current_index == -1: # No current song.
779 self.current_index = 0 # Start at the beginning.
780 # If we have a current song, just stay there.
781
782 else: # Start with the specified index.
783 self.current_index = index
784
785 self.paused = False
786 self._send_event("player")
787 return None
788
789 def cmd_playid(self, conn: MPDConnection, track_id: int = 0) -> None:
790 track_id = cast_arg(int, track_id)
791 if track_id == -1:
792 index = -1
793 else:
794 index = self._id_to_index(track_id)
795 return self.cmd_play(conn, index)
796
797 def cmd_stop(self, conn: MPDConnection | None) -> None:
798 """Stop playback."""
799 self.current_index = -1
800 self.paused = False
801 self._send_event("player")
802
803 def cmd_seek(self, conn: MPDConnection, index: int, pos: float) -> None:
804 """Seek to a specified point in a specified song."""
805 index = cast_arg(int, index)
806 if index < 0 or index >= len(self.playlist):
807 raise ArgumentIndexError()
808 self.current_index = index
809 self._send_event("player")
810
811 def cmd_seekid(
812 self, conn: MPDConnection, track_id: int, pos: float
813 ) -> None:
814 index = self._id_to_index(track_id)
815 return self.cmd_seek(conn, index, pos)
816
817 # Additions to the MPD protocol.
818
819 def cmd_crash(self, conn: MPDConnection) -> NoReturn:
820 """Deliberately trigger a TypeError for testing purposes.
821 We want to test that the server properly responds with ERROR_SYSTEM
822 without crashing, and that this is not treated as ERROR_ARG (since it
823 is caused by a programming error, not a protocol error).
824 """
825 raise TypeError
826
827
828 class Connection:
829 """A connection between a client and the server."""
830
831 def __init__(
832 self,
833 server: BaseServer,
834 reader: asyncio.streams.StreamReader,
835 writer: asyncio.streams.StreamWriter,
836 ) -> None:
837 """Create a new connection for the accepted client streams."""
838 self.server = server
839 self.reader = reader
840 self.writer = writer
841 peername = writer.get_extra_info("peername")
842 self.address = ":".join(map(str, peername)) if peername else "<unknown>"
843
844 def debug(self, message: str, kind: str = " ") -> None:
845 """Log a debug message about this connection."""
846 self.server._log.debug("{}[{.address}]: {}", kind, self, message)
847
848 async def run(self) -> None:
849 raise NotImplementedError
850
851 async def send(self, lines: str | Iterable[str]) -> None:
852 """Send lines, which is either a single string or an
853 iterable consisting of strings, to the client. A newline is
854 added after every string.
855 """
856 if isinstance(lines, str):
857 lines = [lines]
858 out = NEWLINE.join(lines) + NEWLINE
859 for line in out.split(NEWLINE)[:-1]:
860 self.debug(line, kind=">")
861 self.writer.write(out.encode("utf-8"))
862 await self.writer.drain()
863
864 @classmethod
865 def handler(cls, server: BaseServer) -> Any:
866 async def _handle(
867 reader: asyncio.streams.StreamReader,
868 writer: asyncio.streams.StreamWriter,
869 ) -> None:
870 """Creates a new `Connection` and runs it."""
871 try:
872 await cls(server, reader, writer).run()
873 finally:
874 writer.close()
875 try:
876 await writer.wait_closed()
877 except ConnectionError:
878 pass
879
880 return _handle
881
882
883 class MPDConnection(Connection):
884 """A connection that receives commands from an MPD-compatible client."""
885
886 notifications: set[str]
887 idle_subscriptions: set[str]
888
889 def __init__(
890 self,
891 server: BaseServer,
892 reader: asyncio.streams.StreamReader,
893 writer: asyncio.streams.StreamWriter,
894 ) -> None:
895 """Create a new connection for the accepted socket `client`."""
896 super().__init__(server, reader, writer)
897 self.authenticated = False
898 self.notifications = set()
899 self.idle_subscriptions = set()
900
901 async def do_command(self, command: Command | CommandList) -> None:
902 """Run the given command and send an appropriate response."""
903 try:
904 await command.run(self)
905 except BPDError as e:
906 # Send the error.
907 await self.send(e.response())
908 else:
909 # Send success code.
910 await self.send(RESP_OK)
911
912 def disconnect(self) -> None:
913 """The connection has closed for any reason."""
914 self.server.disconnect(self)
915 self.debug("disconnected", kind="*")
916
917 def notify(self, event: str) -> None:
918 """Queue up an event for sending to this client."""
919 self.notifications.add(event)
920
921 async def send_notifications(self, force_close_idle: bool = False) -> None:
922 """Send the client any queued events now."""
923 pending = self.notifications.intersection(self.idle_subscriptions)
924 try:
925 for event in pending:
926 await self.send(f"changed: {event}")
927 if pending or force_close_idle:
928 self.idle_subscriptions = set()
929 self.notifications = self.notifications.difference(pending)
930 await self.send(RESP_OK)
931 except ConnectionError:
932 self.disconnect() # Client disappeared.
933
934 async def run(self) -> None:
935 """Send a greeting to the client and begin processing commands
936 as they arrive.
937 """
938 self.debug("connected", kind="*")
939 self.server.connect(self)
940 await self.send(HELLO)
941
942 clist = None # Initially, no command list is being constructed.
943 while True:
944 bytes_line = await self.reader.readline()
945 if not bytes_line:
946 self.disconnect() # Client disappeared.
947 break
948 bytes_line = bytes_line.strip()
949 if not bytes_line:
950 err = BPDError(ERROR_UNKNOWN, "No command given")
951 await self.send(err.response())
952 self.disconnect() # Client sent a blank line.
953 break
954 line = bytes_line.decode("utf8") # MPD protocol uses UTF-8.
955 for line in line.split(NEWLINE):
956 self.debug(line, kind="<")
957
958 if self.idle_subscriptions:
959 # The connection is in idle mode.
960 if line == "noidle":
961 await self.send_notifications(True)
962 else:
963 err = BPDError(
964 ERROR_UNKNOWN, f"Got command while idle: {line}"
965 )
966 await self.send(err.response())
967 self.disconnect()
968 break
969 continue
970 if line == "noidle":
971 # When not in idle, this command sends no response.
972 continue
973
974 if clist is not None:
975 # Command list already opened.
976 if line == CLIST_END:
977 await self.do_command(clist)
978 clist = None # Clear the command list.
979 self.server.dispatch_events()
980 else:
981 clist.append(Command(line))
982
983 elif line == CLIST_BEGIN or line == CLIST_VERBOSE_BEGIN:
984 # Begin a command list.
985 clist = CommandList([], line == CLIST_VERBOSE_BEGIN)
986
987 else:
988 # Ordinary command.
989 try:
990 await self.do_command(Command(line))
991 except BPDCloseError:
992 # Command indicates that the conn should close.
993 self.disconnect() # Client explicitly closed.
994 return
995 except BPDIdleError as e:
996 self.idle_subscriptions = e.subsystems
997 self.debug(f"awaiting: {' '.join(e.subsystems)}", kind="z")
998 self.server.dispatch_events()
999
1000
1001 class ControlConnection(Connection):
1002 """A connection used to control BPD for debugging and internal events."""
1003
1004 def __init__(
1005 self,
1006 server: BaseServer,
1007 reader: asyncio.streams.StreamReader,
1008 writer: asyncio.streams.StreamWriter,
1009 ) -> None:
1010 """Create a new connection for the accepted socket `client`."""
1011 super().__init__(server, reader, writer)
1012
1013 def debug(self, message: str, kind: str = " ") -> None:
1014 self.server._log.debug("CTRL {}[{.address}]: {}", kind, self, message)
1015
1016 async def run(self) -> None:
1017 """Listen for control commands and delegate to `ctrl_*` methods."""
1018 self.debug("connected", kind="*")
1019 while True:
1020 bytes_line = await self.reader.readline()
1021 if not bytes_line:
1022 break # Client disappeared.
1023 bytes_line = bytes_line.strip()
1024 if not bytes_line:
1025 break # Client sent a blank line.
1026 line = bytes_line.decode("utf8") # Protocol uses UTF-8.
1027 for line in line.split(NEWLINE):
1028 self.debug(line, kind="<")
1029 command = Command(line)
1030 try:
1031 func = command.delegate("ctrl_", self)
1032 await func(*command.args)
1033 except (AttributeError, TypeError) as e:
1034 await self.send(f"ERROR: {e.args[0]}")
1035 except Exception:
1036 await self.send(
1037 ["ERROR: server error", traceback.format_exc().rstrip()]
1038 )
1039
1040 async def ctrl_play_finished(self) -> None:
1041 """Callback from the player signalling a song finished playing."""
1042 self.server.dispatch_events()
1043
1044 async def ctrl_profile(self) -> None:
1045 """Memory profiling for debugging."""
1046 from guppy import hpy
1047
1048 heap = hpy().heap()
1049 await self.send(str(heap))
1050
1051 async def ctrl_nickname(self, oldlabel: str, newlabel: str) -> None:
1052 """Rename a client in the log messages."""
1053 for c in self.server.connections:
1054 if c.address == oldlabel:
1055 c.address = newlabel
1056 break
1057 else:
1058 await self.send(f"ERROR: no such client: {oldlabel}")
1059
1060
1061 class Command:
1062 """A command issued by the client for processing by the server."""
1063
1064 arg_re = re.compile(r'"((?:\\"|[^"])+)"|([^ \t"]+)')
1065
1066 def __init__(self, s: str) -> None:
1067 """Creates a new `Command` from the given string, `s`, parsing
1068 the string for command name and arguments.
1069 """
1070 try:
1071 self.name, args = s.split(maxsplit=1)
1072 except ValueError:
1073 self.name = s
1074 args = ""
1075
1076 self.args = []
1077 arg_matches = self.arg_re.findall(args)
1078 for match in arg_matches:
1079 if match[0]:
1080 # Quoted argument.
1081 arg = match[0]
1082 arg = arg.replace('\\"', '"').replace("\\\\", "\\")
1083 else:
1084 # Unquoted argument.
1085 arg = match[1]
1086 self.args.append(arg)
1087
1088 def delegate(
1089 self,
1090 prefix: str,
1091 target: ControlConnection | BaseServer,
1092 extra_args: int = 0,
1093 ) -> Any:
1094 """Get the target method that corresponds to this command.
1095 The `prefix` is prepended to the command name and then the resulting
1096 name is used to search `target` for a method with a compatible number
1097 of arguments.
1098 """
1099 # Attempt to get correct command function.
1100 func_name = f"{prefix}{self.name}"
1101 if not hasattr(target, func_name):
1102 raise AttributeError(f'unknown command "{self.name}"')
1103 func = getattr(target, func_name)
1104
1105 argspec = inspect.getfullargspec(func)
1106
1107 # Check that `func` is able to handle the number of arguments sent
1108 # by the client (so we can raise ERROR_ARG instead of ERROR_SYSTEM).
1109 # Maximum accepted arguments: argspec includes "self".
1110 max_args = len(argspec.args) - 1 - extra_args
1111 # Minimum accepted arguments: some arguments might be optional.
1112 min_args = max_args
1113 if argspec.defaults:
1114 min_args -= len(argspec.defaults)
1115 wrong_num = (len(self.args) > max_args) or (len(self.args) < min_args)
1116 # If the command accepts a variable number of arguments skip the check.
1117 if wrong_num and not argspec.varargs:
1118 raise TypeError(
1119 f'wrong number of arguments for "{self.name}"', self.name
1120 )
1121
1122 return func
1123
1124 async def run(self, conn: MPDConnection) -> None:
1125 """Execute the command on the given connection."""
1126 try:
1127 # `conn` is an extra argument to all cmd handlers.
1128 func = self.delegate("cmd_", conn.server, extra_args=1)
1129 except AttributeError as e:
1130 raise BPDError(ERROR_UNKNOWN, e.args[0])
1131 except TypeError as e:
1132 raise BPDError(ERROR_ARG, e.args[0], self.name)
1133
1134 # Ensure we have permission for this command.
1135 if (
1136 conn.server.password
1137 and not conn.authenticated
1138 and self.name not in SAFE_COMMANDS
1139 ):
1140 raise BPDError(ERROR_PERMISSION, "insufficient privileges")
1141
1142 try:
1143 args = [conn, *self.args]
1144 results = func(*args)
1145 if results:
1146 for data in results:
1147 await conn.send(data)
1148
1149 except BPDError as e:
1150 # An exposed error. Set the command name and then let
1151 # the Connection handle it.
1152 e.cmd_name = self.name
1153 raise
1154
1155 except BPDCloseError:
1156 # An indication that the connection should close. Send
1157 # it on the Connection.
1158 raise
1159
1160 except BPDIdleError:
1161 raise
1162
1163 except Exception:
1164 # An "unintentional" error. Hide it from the client.
1165 conn.server._log.error("{}", traceback.format_exc())
1166 raise BPDError(ERROR_SYSTEM, "server error", self.name)
1167
1168
1169 class CommandList(list[Command]):
1170 """A list of commands issued by the client for processing by the
1171 server. May be verbose, in which case the response is delimited, or
1172 not. Should be a list of `Command` objects.
1173 """
1174
1175 def __init__(
1176 self, sequence: Iterable[Command] | None = None, verbose: bool = False
1177 ) -> None:
1178 """Create a new `CommandList` from the given sequence of
1179 `Command`s. If `verbose`, this is a verbose command list.
1180 """
1181 if sequence:
1182 for item in sequence:
1183 self.append(item)
1184 self.verbose = verbose
1185
1186 async def run(self, conn: MPDConnection) -> None:
1187 """Execute all the commands in this list."""
1188 for i, command in enumerate(self):
1189 try:
1190 await command.run(conn)
1191 except BPDError as e:
1192 # If the command failed, stop executing.
1193 e.index = i # Give the error the correct index.
1194 raise
1195
1196 # Otherwise, possibly send the output delimiter if we're in a
1197 # verbose ("OK") command list.
1198 if self.verbose:
1199 await conn.send(RESP_CLIST_VERBOSE)
1200
1201
1202 # A subclass of the basic, protocol-handling server that actually plays
1203 # music.
1204
1205
1206 class Server(BaseServer):
1207 """An MPD-compatible server using GStreamer to play audio and beets
1208 to store its library.
1209 """
1210
1211 def __init__(
1212 self,
1213 library: Library,
1214 host: str,
1215 port: int,
1216 password: str,
1217 ctrl_port: int,
1218 log: Logger,
1219 ) -> None:
1220 log.info("Starting server...")
1221 super().__init__(host, port, password, ctrl_port, log)
1222 self.lib = library
1223 self.player = gstplayer.GstPlayer(self.play_finished)
1224 self.cmd_update(None)
1225 log.info("Server ready and listening on {}:{}", host, port)
1226 log.debug("Listening for control signals on {}:{}", host, ctrl_port)
1227
1228 def run(self) -> None:
1229 self.player.run()
1230 super().run()
1231
1232 def play_finished(self) -> None:
1233 """A callback invoked every time our player finishes a track."""
1234 self.cmd_next(None)
1235 self._ctrl_send("play_finished")
1236
1237 # Metadata helper functions.
1238
1239 def _item_info(self, item: Item) -> list[str]:
1240 info_lines = [
1241 f"file: {as_string(item.destination(relative_to_libdir=True))}",
1242 f"Time: {int(item.length)}",
1243 "duration: {item.length:.3f}",
1244 f"Id: {item.id}",
1245 ]
1246
1247 try:
1248 if item.id is not None:
1249 pos = self._id_to_index(item.id)
1250 info_lines.append(f"Pos: {pos}")
1251 except ArgumentNotFoundError:
1252 # Don't include position if not in playlist.
1253 pass
1254
1255 for tagtype, field in self.tagtype_map.items():
1256 field_value = getattr(item, field)
1257 if isinstance(field_value, list):
1258 field_value = "; ".join(field_value)
1259 info_lines.append(f"{tagtype}: {field_value}")
1260
1261 return info_lines
1262
1263 def _item_id(self, item: Item) -> int | None:
1264 return item.id
1265
1266 # Database updating.
1267
1268 def cmd_update(self, conn: MPDConnection | None, path: str = "/") -> None:
1269 """Updates the catalog to reflect the current database state."""
1270 # Path is ignored. Also, the real MPD does this asynchronously;
1271 # this is done inline.
1272 self._log.debug("Building directory tree...")
1273 self.tree = vfs.libtree(self.lib)
1274 self._log.debug("Finished building directory tree.")
1275 self.updated_time = time.time()
1276 self._send_event("update")
1277 self._send_event("database")
1278
1279 # Path (directory tree) browsing.
1280
1281 def _resolve_path(self, path: str) -> vfs.Node | int:
1282 """Returns a VFS node or an item ID located at the path given.
1283 If the path does not exist, raises a
1284 """
1285 components = path.split("/")
1286 node: Node | int = self.tree
1287
1288 for component in components:
1289 if not component:
1290 continue
1291
1292 if isinstance(node, int):
1293 # We're trying to descend into a file node.
1294 raise ArgumentNotFoundError()
1295
1296 if component in node.files:
1297 node = node.files[component]
1298 elif component in node.dirs:
1299 node = node.dirs[component]
1300 else:
1301 raise ArgumentNotFoundError()
1302
1303 return node
1304
1305 def _path_join(self, p1: str, p2: str) -> str:
1306 """Smashes together two BPD paths."""
1307 out = f"{p1}/{p2}"
1308 return out.replace("//", "/").replace("//", "/")
1309
1310 def cmd_lsinfo(self, conn: MPDConnection, path: str = "/") -> Iterator[Any]:
1311 """Sends info on all the items in the path."""
1312 node = self._resolve_path(path)
1313 if isinstance(node, int):
1314 # Trying to list a track.
1315 raise BPDError(ERROR_ARG, "this is not a directory")
1316 elif node:
1317 for name, itemid in iter(sorted(node.files.items())):
1318 if item := self.lib.get_item(itemid):
1319 yield self._item_info(item)
1320 for name, _ in iter(sorted(node.dirs.items())):
1321 dirpath = self._path_join(path, name)
1322 if dirpath.startswith("/"):
1323 # Strip leading slash (libmpc rejects this).
1324 dirpath = dirpath[1:]
1325 yield f"directory: {dirpath}"
1326
1327 def _listall(
1328 self, basepath: str, node: vfs.Node | int | None, info: bool = False
1329 ) -> Iterator[Any]:
1330 """Helper function for recursive listing. If info, show
1331 tracks' complete info; otherwise, just show items' paths.
1332 """
1333 if isinstance(node, int):
1334 # List a single file.
1335 if info:
1336 if item := self.lib.get_item(node):
1337 yield self._item_info(item)
1338 else:
1339 yield f"file: {basepath}"
1340 elif node:
1341 # List a directory. Recurse into both directories and files.
1342 for name, itemid in sorted(node.files.items()):
1343 newpath = self._path_join(basepath, name)
1344 # "yield from"
1345 yield from self._listall(newpath, itemid, info)
1346 for name, subdir in sorted(node.dirs.items()):
1347 newpath = self._path_join(basepath, name)
1348 yield f"directory: {newpath}"
1349 yield from self._listall(newpath, subdir, info)
1350
1351 def cmd_listall(
1352 self, conn: MPDConnection, path: str = "/"
1353 ) -> Iterator[Any]:
1354 """Send the paths all items in the directory, recursively."""
1355 return self._listall(path, self._resolve_path(path), False)
1356
1357 def cmd_listallinfo(
1358 self, conn: MPDConnection, path: str = "/"
1359 ) -> Iterator[Any]:
1360 """Send info on all the items in the directory, recursively."""
1361 return self._listall(path, self._resolve_path(path), True)
1362
1363 # Playlist manipulation.
1364
1365 def _all_items(self, node: vfs.Node | int | None) -> Iterator[Item]:
1366 """Generator yielding all items under a VFS node."""
1367 if isinstance(node, int):
1368 # Could be more efficient if we built up all the IDs and
1369 # then issued a single SELECT.
1370 if item := self.lib.get_item(node):
1371 yield item
1372 elif node:
1373 # Recurse into a directory.
1374 for name, itemid in sorted(node.files.items()):
1375 # "yield from"
1376 yield from self._all_items(itemid)
1377 for name, subdir in sorted(node.dirs.items()):
1378 yield from self._all_items(subdir)
1379
1380 def _add(self, path: str, send_id: bool = False) -> Iterator[Any]:
1381 """Adds a track or directory to the playlist, specified by the
1382 path. If `send_id`, write each item's id to the client.
1383 """
1384 for item in self._all_items(self._resolve_path(path)):
1385 self.playlist.append(item)
1386 if send_id:
1387 yield f"Id: {item.id}"
1388 self.playlist_version += 1
1389 self._send_event("playlist")
1390
1391 def cmd_add(self, conn: MPDConnection, path: str) -> Iterator[Any]:
1392 """Adds a track or directory to the playlist, specified by a
1393 path.
1394 """
1395 return self._add(path, False)
1396
1397 def cmd_addid(self, conn: MPDConnection, path: str) -> Iterator[Any]:
1398 """Same as `cmd_add` but sends an id back to the client."""
1399 return self._add(path, True)
1400
1401 # Server info.
1402
1403 def cmd_status(self, conn: MPDConnection) -> Iterator[Any]:
1404 yield from super().cmd_status(conn)
1405 if self.current_index > -1:
1406 item = self.playlist[self.current_index]
1407
1408 yield (
1409 f"bitrate: {item.bitrate / 1000}",
1410 f"audio: {item.samplerate}:{item.bitdepth}:{item.channels}",
1411 )
1412
1413 (pos, total) = self.player.time()
1414 yield (
1415 f"time: {int(pos)}:{int(total)}",
1416 "elapsed: " + f"{pos:.3f}",
1417 "duration: " + f"{total:.3f}",
1418 )
1419
1420 # Also missing 'updating_db'.
1421
1422 def cmd_stats(self, conn: MPDConnection) -> Iterator[Any]:
1423 """Sends some statistics about the library."""
1424 with self.lib.transaction() as tx:
1425 statement = (
1426 "SELECT COUNT(DISTINCT artist), "
1427 "COUNT(DISTINCT album), "
1428 "COUNT(id), "
1429 "SUM(length) "
1430 "FROM items"
1431 )
1432 artists, albums, songs, totaltime = tx.query(statement)[0]
1433
1434 yield (
1435 f"artists: {artists}",
1436 f"albums: {albums}",
1437 f"songs: {songs}",
1438 f"uptime: {int(time.time() - self.startup_time)}",
1439 "playtime: 0", # Missing.
1440 f"db_playtime: {int(totaltime)}",
1441 f"db_update: {int(self.updated_time)}",
1442 )
1443
1444 def cmd_decoders(self, conn: MPDConnection) -> Iterator[Any]:
1445 """Send list of supported decoders and formats."""
1446 decoders = self.player.get_decoders()
1447 for name, (mimes, exts) in decoders.items():
1448 yield f"plugin: {name}"
1449 for ext in exts:
1450 yield f"suffix: {ext}"
1451 for mime in mimes:
1452 yield f"mime_type: {mime}"
1453
1454 # Searching.
1455
1456 tagtype_map: ClassVar[dict[str, str]] = {
1457 "Artist": "artist",
1458 "ArtistSort": "artist_sort",
1459 "Album": "album",
1460 "Title": "title",
1461 "Track": "track",
1462 "AlbumArtist": "albumartist",
1463 "AlbumArtistSort": "albumartist_sort",
1464 "Label": "label",
1465 "Genre": "genres",
1466 "Date": "year",
1467 "OriginalDate": "original_year",
1468 "Composer": "composers",
1469 "Disc": "disc",
1470 "Comment": "comments",
1471 "MUSICBRAINZ_TRACKID": "mb_trackid",
1472 "MUSICBRAINZ_ALBUMID": "mb_albumid",
1473 "MUSICBRAINZ_ARTISTID": "mb_artistid",
1474 "MUSICBRAINZ_ALBUMARTISTID": "mb_albumartistid",
1475 "MUSICBRAINZ_RELEASETRACKID": "mb_releasetrackid",
1476 }
1477
1478 def cmd_tagtypes(self, conn: MPDConnection) -> Iterator[Any]:
1479 """Returns a list of the metadata (tag) fields available for
1480 searching.
1481 """
1482 for tag in self.tagtype_map:
1483 yield f"tagtype: {tag}"
1484
1485 def _tagtype_lookup(self, tag: str) -> tuple[str, str]:
1486 """Uses `tagtype_map` to look up the beets column name for an
1487 MPD tagtype (or throw an appropriate exception). Returns both
1488 the canonical name of the MPD tagtype and the beets column
1489 name.
1490 """
1491 for test_tag, key in self.tagtype_map.items():
1492 # Match case-insensitively.
1493 if test_tag.lower() == tag.lower():
1494 return test_tag, key
1495 raise BPDError(ERROR_UNKNOWN, "no such tagtype")
1496
1497 def _metadata_query(
1498 self,
1499 query_type: FieldQueryType,
1500 kv: tuple[str, ...],
1501 allow_any_query: bool = False,
1502 ) -> dbcore.query.AndQuery | dbcore.query.TrueQuery:
1503 """Helper function returns a query object that will find items
1504 according to the library query type provided and the key-value
1505 pairs specified. The any_query_type is used for queries of
1506 type "any"; if None, then an error is thrown.
1507 """
1508 if kv: # At least one key-value pair.
1509 queries: list[Query] = []
1510 # Iterate pairwise over the arguments.
1511 it = iter(kv)
1512 for tag, value in zip(it, it):
1513 if tag.lower() == "any":
1514 if allow_any_query:
1515 queries.append(
1516 Item.any_writable_media_field_query(
1517 value, query_type
1518 )
1519 )
1520 else:
1521 raise BPDError(ERROR_UNKNOWN, "no such tagtype")
1522 else:
1523 _, key = self._tagtype_lookup(tag)
1524 queries.append(Item.field_query(key, value, query_type))
1525 return dbcore.query.AndQuery(queries)
1526 # No key-value pairs.
1527 return dbcore.query.TrueQuery()
1528
1529 def cmd_search(self, conn: MPDConnection, *kv: str) -> Iterator[Any]:
1530 """Perform a substring match for items."""
1531 query = self._metadata_query(
1532 dbcore.query.SubstringQuery, kv, allow_any_query=True
1533 )
1534 for item in self.lib.items(query):
1535 yield self._item_info(item)
1536
1537 def cmd_find(self, conn: MPDConnection, *kv: str) -> Iterator[Any]:
1538 """Perform an exact match for items."""
1539 query = self._metadata_query(dbcore.query.MatchQuery, kv)
1540 for item in self.lib.items(query):
1541 yield self._item_info(item)
1542
1543 def cmd_list(
1544 self, conn: MPDConnection, show_tag: str, *kv: str
1545 ) -> Iterator[Any]:
1546 """List distinct metadata values for show_tag, possibly
1547 filtered by matching match_tag to match_term.
1548 """
1549 show_tag_canon, show_key = self._tagtype_lookup(show_tag)
1550 if len(kv) == 1:
1551 if show_tag_canon == "Album":
1552 # If no tag was given, assume artist. This is because MPD
1553 # supports a short version of this command for fetching the
1554 # albums belonging to a particular artist, and some clients
1555 # rely on this behaviour (e.g. MPDroid, M.A.L.P.).
1556 kv = ("Artist", kv[0])
1557 else:
1558 raise BPDError(ERROR_ARG, 'should be "Album" for 3 arguments')
1559 elif len(kv) % 2 != 0:
1560 raise BPDError(ERROR_ARG, "Incorrect number of filter arguments")
1561 query = self._metadata_query(dbcore.query.MatchQuery, kv)
1562
1563 clause, subvals = query.clause()
1564 statement = (
1565 f"SELECT DISTINCT {show_key}"
1566 f" FROM items WHERE {clause}"
1567 f" ORDER BY {show_key}"
1568 )
1569 self._log.debug(statement)
1570 with self.lib.transaction() as tx:
1571 rows = tx.query(statement, subvals)
1572
1573 for row in rows:
1574 if not row[0]:
1575 # Skip any empty values of the field.
1576 continue
1577 yield f"{show_tag_canon}: {row[0]}"
1578
1579 def cmd_count(
1580 self, conn: MPDConnection, tag: str, value: str
1581 ) -> Iterator[Any]:
1582 """Returns the number and total time of songs matching the
1583 tag/value query.
1584 """
1585 _, key = self._tagtype_lookup(tag)
1586 songs = 0
1587 playtime = 0.0
1588 for item in self.lib.items(
1589 Item.field_query(key, value, dbcore.query.MatchQuery)
1590 ):
1591 songs += 1
1592 playtime += item.length
1593 yield f"songs: {songs}"
1594 yield f"playtime: {int(playtime)}"
1595
1596 # Persistent playlist manipulation. In MPD this is an optional feature so
1597 # these dummy implementations match MPD's behaviour with the feature off.
1598
1599 def cmd_listplaylist(self, conn: MPDConnection, playlist: str) -> NoReturn:
1600 raise BPDError(ERROR_NO_EXIST, "No such playlist")
1601
1602 def cmd_listplaylistinfo(
1603 self, conn: MPDConnection, playlist: str
1604 ) -> NoReturn:
1605 raise BPDError(ERROR_NO_EXIST, "No such playlist")
1606
1607 def cmd_listplaylists(self, conn: MPDConnection) -> NoReturn:
1608 raise BPDError(ERROR_UNKNOWN, "Stored playlists are disabled")
1609
1610 def cmd_load(self, conn: MPDConnection, playlist: str) -> NoReturn:
1611 raise BPDError(ERROR_NO_EXIST, "Stored playlists are disabled")
1612
1613 def cmd_playlistadd(
1614 self, conn: MPDConnection, playlist: str, uri: str
1615 ) -> NoReturn:
1616 raise BPDError(ERROR_UNKNOWN, "Stored playlists are disabled")
1617
1618 def cmd_playlistclear(self, conn: MPDConnection, playlist: str) -> NoReturn:
1619 raise BPDError(ERROR_UNKNOWN, "Stored playlists are disabled")
1620
1621 def cmd_playlistdelete(
1622 self, conn: MPDConnection, playlist: str, index: int
1623 ) -> NoReturn:
1624 raise BPDError(ERROR_UNKNOWN, "Stored playlists are disabled")
1625
1626 def cmd_playlistmove(
1627 self, conn: MPDConnection, playlist: str, from_index: int, to_index: int
1628 ) -> NoReturn:
1629 raise BPDError(ERROR_UNKNOWN, "Stored playlists are disabled")
1630
1631 def cmd_rename(
1632 self, conn: MPDConnection, playlist: str, new_name: str
1633 ) -> NoReturn:
1634 raise BPDError(ERROR_UNKNOWN, "Stored playlists are disabled")
1635
1636 def cmd_rm(self, conn: MPDConnection, playlist: str) -> NoReturn:
1637 raise BPDError(ERROR_UNKNOWN, "Stored playlists are disabled")
1638
1639 def cmd_save(self, conn: MPDConnection, playlist: str) -> NoReturn:
1640 raise BPDError(ERROR_UNKNOWN, "Stored playlists are disabled")
1641
1642 # "Outputs." Just a dummy implementation because we don't control
1643 # any outputs.
1644
1645 def cmd_outputs(self, conn: MPDConnection) -> Iterator[Any]:
1646 """List the available outputs."""
1647 yield ("outputid: 0", "outputname: gstreamer", "outputenabled: 1")
1648
1649 def cmd_enableoutput(self, conn: MPDConnection, output_id: int) -> None:
1650 output_id = cast_arg(int, output_id)
1651 if output_id != 0:
1652 raise ArgumentIndexError()
1653
1654 def cmd_disableoutput(
1655 self, conn: MPDConnection, output_id: int
1656 ) -> NoReturn:
1657 output_id = cast_arg(int, output_id)
1658 if output_id == 0:
1659 raise BPDError(ERROR_ARG, "cannot disable this output")
1660 raise ArgumentIndexError()
1661
1662 # Playback control. The functions below hook into the
1663 # half-implementations provided by the base class. Together, they're
1664 # enough to implement all normal playback functionality.
1665
1666 def cmd_play(self, conn: MPDConnection | None, index: int = -1) -> None:
1667 new_index = index != -1 and index != self.current_index
1668 was_paused = self.paused
1669 super().cmd_play(conn, index)
1670
1671 if self.current_index > -1: # Not stopped.
1672 if was_paused and not new_index:
1673 # Just unpause.
1674 self.player.play()
1675 else:
1676 self.player.play_file(self.playlist[self.current_index].path)
1677
1678 def cmd_pause(self, conn: MPDConnection, state: str | None = None) -> None:
1679 super().cmd_pause(conn, state)
1680 if self.paused:
1681 self.player.pause()
1682 elif self.player.playing:
1683 self.player.play()
1684
1685 def cmd_stop(self, conn: MPDConnection | None) -> None:
1686 super().cmd_stop(conn)
1687 self.player.stop()
1688
1689 def cmd_seek(self, conn: MPDConnection, index: int, pos: float) -> None:
1690 """Seeks to the specified position in the specified song."""
1691 index = cast_arg(int, index)
1692 pos = cast_arg(float, pos)
1693 super().cmd_seek(conn, index, pos)
1694 self.player.seek(pos)
1695
1696 # Volume control.
1697
1698 def cmd_setvol(self, conn: MPDConnection | None, vol: str | int) -> None:
1699 vol = cast_arg(int, vol)
1700 super().cmd_setvol(conn, vol)
1701 self.player.volume = float(vol) / 100
1702
1703
1704 # Beets plugin hooks.
1705
1706
1707 class BPDPlugin(BeetsPlugin):
1708 """Provides the "beet bpd" command for running a music player
1709 server.
1710 """
1711
1712 def __init__(self) -> None:
1713 super().__init__()
1714 self.config.add(
1715 {
1716 "host": "",
1717 "port": 6600,
1718 "control_port": 6601,
1719 "password": "",
1720 "volume": VOLUME_MAX,
1721 }
1722 )
1723 self.config["password"].redact = True
1724
1725 def start_bpd(
1726 self,
1727 lib: Library,
1728 host: str,
1729 port: int,
1730 password: str,
1731 volume: int,
1732 ctrl_port: int,
1733 ) -> None:
1734 """Starts a BPD server."""
1735 server = Server(lib, host, port, password, ctrl_port, self._log)
1736 server.cmd_setvol(None, volume)
1737 server.run()
1738
1739 def commands(self) -> list[beets.ui.Subcommand]:
1740 cmd = beets.ui.Subcommand(
1741 "bpd", help="run an MPD-compatible music player server"
1742 )
1743
1744 def func(lib: Library, opts: optparse.Values, args: list[str]) -> None:
1745 host = self.config["host"].as_str()
1746 host = args.pop(0) if args else host
1747 port = args.pop(0) if args else self.config["port"].get(int)
1748 if args:
1749 ctrl_port = int(args.pop(0))
1750 else:
1751 ctrl_port = self.config["control_port"].get(int)
1752 if args:
1753 raise UserError("too many arguments")
1754 password = self.config["password"].as_str()
1755 volume = self.config["volume"].get(int)
1756 self.start_bpd(lib, host, int(port), password, volume, ctrl_port)
1757
1758 cmd.func = func
1759 return [cmd]