Debian Codegraph @

beetsplug/play.py

raw
1 """Send the results of a query to the configured music player as a playlist."""
2
3 from __future__ import annotations
4
5 import random
6 import shlex
7 import subprocess
8 from os.path import relpath
9 from typing import TYPE_CHECKING, Protocol
10
11 from beets import config, ui, util
12 from beets.exceptions import UserError
13 from beets.plugins import BeetsPlugin
14 from beets.ui import Subcommand
15 from beets.util import PromptChoice, get_temp_filename
16 from beets.util.color import colorize
17
18 if TYPE_CHECKING:
19 from collections.abc import Iterable, Sequence
20
21 from beets.importer import ImportSession, ImportTask
22 from beets.library import LibModel, Library
23 from beets.logging import BeetsLogger as Logger
24
25
26 # Indicate where arguments should be inserted into the command string.
27 # If this is missing, they're placed at the end.
28 ARGS_MARKER = "$args"
29
30
31 class PlayCLIOpts(Protocol):
32 album: bool
33 args: str | None
34 randomize: bool | None
35 yes: bool | None
36
37
38 # Indicate where the playlist file (with absolute path) should be inserted into
39 # the command string. If this is missing, its placed at the end, but before
40 # arguments.
41 PLS_MARKER = "$playlist"
42
43
44 def play(
45 command_str: str,
46 selection: Sequence[LibModel],
47 paths: Sequence[bytes],
48 open_args: Sequence[bytes],
49 log: Logger,
50 item_type: str = "track",
51 keep_open: bool = False,
52 ) -> None:
53 """Play items in paths with command_str and optional arguments. If
54 keep_open, return to beets, otherwise exit once command runs.
55 """
56 # Print number of tracks or albums to be played, log command to be run.
57 item_type += "s" if len(selection) > 1 else ""
58 ui.print_(f"Playing {len(selection)} {item_type}.")
59 log.debug("executing command: {} {!r}", command_str, open_args)
60
61 try:
62 if keep_open:
63 subprocess.call([*shlex.split(command_str), *open_args])
64 else:
65 util.interactive_open(open_args, command_str)
66 except OSError as exc:
67 raise UserError(f"Could not play the query: {exc}")
68
69
70 class PlayPlugin(BeetsPlugin):
71 def __init__(self) -> None:
72 super().__init__()
73
74 config["play"].add(
75 {
76 "command": None,
77 "use_folders": False,
78 "relative_to": None,
79 "raw": False,
80 "warning_threshold": 100,
81 "bom": False,
82 }
83 )
84
85 self.register_listener(
86 "before_choose_candidate", self.before_choose_candidate_listener
87 )
88
89 def commands(self) -> list[Subcommand]:
90 play_command = Subcommand(
91 "play", help="send music to a player as a playlist"
92 )
93 play_command.parser.add_album_option()
94 play_command.parser.add_option(
95 "-A",
96 "--args",
97 action="store",
98 help="add additional arguments to the command",
99 )
100 play_command.parser.add_option(
101 "-R",
102 "--randomize",
103 action="store_true",
104 help="randomize the order of playlist entries",
105 )
106 play_command.parser.add_option(
107 "-y",
108 "--yes",
109 action="store_true",
110 help="skip the warning threshold",
111 )
112 play_command.func = self._play_command
113 return [play_command]
114
115 def _play_command(
116 self, lib: Library, opts: PlayCLIOpts, args: list[str]
117 ) -> None:
118 """The CLI command function for `beet play`. Create a list of paths
119 from query, determine if tracks or albums are to be played.
120 """
121 use_folders = config["play"]["use_folders"].get(bool)
122 relative_to = config["play"]["relative_to"].get()
123 if relative_to:
124 relative_to = util.normpath(relative_to)
125 # Perform search by album and add folders rather than tracks to
126 # playlist.
127 selection: Sequence[LibModel]
128 if opts.album:
129 selection = lib.albums(args)
130 paths = []
131
132 sort = lib.get_default_album_sort()
133 for album in selection:
134 if use_folders:
135 paths.append(album.item_dir())
136 else:
137 paths.extend(item.path for item in sort.sort(album.items()))
138 item_type = "album"
139
140 # Perform item query and add tracks to playlist.
141 else:
142 selection = lib.items(args)
143 paths = [item.path for item in selection]
144 item_type = "track"
145
146 if relative_to:
147 paths = [relpath(path, relative_to) for path in paths]
148
149 if not selection:
150 ui.print_(colorize("text_warning", f"No {item_type} to play."))
151 return
152
153 if opts.randomize:
154 random.shuffle(paths)
155
156 open_args = self._playlist_or_paths(paths)
157 open_args_str = [
158 p.decode("utf-8") for p in self._playlist_or_paths(paths)
159 ]
160 command_str = self._command_str(opts.args)
161
162 if PLS_MARKER in command_str:
163 if not config["play"]["raw"]:
164 command_str = command_str.replace(
165 PLS_MARKER, "".join(open_args_str)
166 )
167 self._log.debug(
168 "command altered by PLS_MARKER to: {}", command_str
169 )
170 open_args = []
171 else:
172 command_str = command_str.replace(PLS_MARKER, " ")
173
174 # Check if the selection exceeds configured threshold. If True,
175 # cancel, otherwise proceed with play command.
176 if opts.yes or not self._exceeds_threshold(
177 selection, command_str, open_args, item_type
178 ):
179 play(command_str, selection, paths, open_args, self._log, item_type)
180
181 def _command_str(self, args: str | None = None) -> str:
182 """Create a command string from the config command and optional args."""
183 command_str = config["play"]["command"].get()
184 if not command_str:
185 return util.open_anything()
186 # Add optional arguments to the player command.
187 if args:
188 if ARGS_MARKER in command_str:
189 return command_str.replace(ARGS_MARKER, args)
190 return f"{command_str} {args}"
191 # Don't include the marker in the command.
192 return command_str.replace(f" {ARGS_MARKER}", "")
193
194 def _playlist_or_paths(self, paths: list[bytes]) -> list[bytes]:
195 """Return either the raw paths of items or a playlist of the items."""
196 if config["play"]["raw"]:
197 return paths
198 return [self._create_tmp_playlist(paths)]
199
200 def _exceeds_threshold(
201 self,
202 selection: Sequence[LibModel],
203 command_str: str,
204 open_args: Sequence[bytes],
205 item_type: str = "track",
206 ) -> bool:
207 """Prompt user whether to abort if playlist exceeds threshold. If
208 True, cancel playback. If False, execute play command.
209 """
210 warning_threshold = config["play"]["warning_threshold"].get(int)
211
212 # Warn user before playing any huge playlists.
213 if warning_threshold and len(selection) > warning_threshold:
214 if len(selection) > 1:
215 item_type += "s"
216
217 ui.print_(
218 colorize(
219 "text_warning",
220 f"You are about to queue {len(selection)} {item_type}.",
221 )
222 )
223
224 if ui.input_options(("Continue", "Abort")) == "a":
225 return True
226
227 return False
228
229 def _create_tmp_playlist(self, paths_list: Iterable[bytes]) -> bytes:
230 """Create a temporary .m3u file. Return the filename."""
231 utf8_bom = config["play"]["bom"].get(bool)
232 filename = get_temp_filename(__name__, suffix=".m3u")
233 with open(filename, "wb") as m3u:
234 if utf8_bom:
235 m3u.write(b"\xef\xbb\xbf")
236
237 for item in paths_list:
238 m3u.write(item + b"\n")
239
240 return filename
241
242 def before_choose_candidate_listener(
243 self, session: ImportSession, task: ImportTask
244 ) -> list[PromptChoice]:
245 """Append a "Play" choice to the interactive importer prompt."""
246 return [PromptChoice("y", "plaY", self.importer_play)]
247
248 def importer_play(self, session: ImportSession, task: ImportTask) -> None:
249 """Get items from current import task and send to play function."""
250 selection = task.items
251 paths = [item.path for item in selection]
252
253 open_args = self._playlist_or_paths(paths)
254 command_str = self._command_str()
255
256 if not self._exceeds_threshold(selection, command_str, open_args):
257 play(
258 command_str,
259 selection,
260 paths,
261 open_args,
262 self._log,
263 keep_open=True,
264 )