update Beets

This commit is contained in:
AdeHub
2024-08-24 16:44:41 +12:00
parent a63098a919
commit 046d4d82b4
116 changed files with 17353 additions and 9964 deletions
+88 -76
View File
@@ -15,31 +15,37 @@
"""Send the results of a query to the configured music player as a playlist.
"""
import shlex
import subprocess
from os.path import relpath
from beets import config, ui, util
from beets.plugins import BeetsPlugin
from beets.ui import Subcommand
from beets.ui.commands import PromptChoice
from beets import config
from beets import ui
from beets import util
from os.path import relpath
from tempfile import NamedTemporaryFile
import subprocess
import shlex
from beets.util import get_temp_filename
# Indicate where arguments should be inserted into the command string.
# If this is missing, they're placed at the end.
ARGS_MARKER = '$args'
ARGS_MARKER = "$args"
def play(command_str, selection, paths, open_args, log, item_type='track',
keep_open=False):
def play(
command_str,
selection,
paths,
open_args,
log,
item_type="track",
keep_open=False,
):
"""Play items in paths with command_str and optional arguments. If
keep_open, return to beets, otherwise exit once command runs.
"""
# Print number of tracks or albums to be played, log command to be run.
item_type += 's' if len(selection) > 1 else ''
ui.print_('Playing {} {}.'.format(len(selection), item_type))
log.debug('executing command: {} {!r}', command_str, open_args)
item_type += "s" if len(selection) > 1 else ""
ui.print_("Playing {} {}.".format(len(selection), item_type))
log.debug("executing command: {} {!r}", command_str, open_args)
try:
if keep_open:
@@ -49,42 +55,44 @@ def play(command_str, selection, paths, open_args, log, item_type='track',
else:
util.interactive_open(open_args, command_str)
except OSError as exc:
raise ui.UserError(
f"Could not play the query: {exc}")
raise ui.UserError(f"Could not play the query: {exc}")
class PlayPlugin(BeetsPlugin):
def __init__(self):
super().__init__()
config['play'].add({
'command': None,
'use_folders': False,
'relative_to': None,
'raw': False,
'warning_threshold': 100,
'bom': False,
})
config["play"].add(
{
"command": None,
"use_folders": False,
"relative_to": None,
"raw": False,
"warning_threshold": 100,
"bom": False,
}
)
self.register_listener('before_choose_candidate',
self.before_choose_candidate_listener)
self.register_listener(
"before_choose_candidate", self.before_choose_candidate_listener
)
def commands(self):
play_command = Subcommand(
'play',
help='send music to a player as a playlist'
"play", help="send music to a player as a playlist"
)
play_command.parser.add_album_option()
play_command.parser.add_option(
'-A', '--args',
action='store',
help='add additional arguments to the command',
"-A",
"--args",
action="store",
help="add additional arguments to the command",
)
play_command.parser.add_option(
'-y', '--yes',
"-y",
"--yes",
action="store_true",
help='skip the warning threshold',
help="skip the warning threshold",
)
play_command.func = self._play_command
return [play_command]
@@ -93,8 +101,8 @@ class PlayPlugin(BeetsPlugin):
"""The CLI command function for `beet play`. Create a list of paths
from query, determine if tracks or albums are to be played.
"""
use_folders = config['play']['use_folders'].get(bool)
relative_to = config['play']['relative_to'].get()
use_folders = config["play"]["use_folders"].get(bool)
relative_to = config["play"]["relative_to"].get()
if relative_to:
relative_to = util.normpath(relative_to)
# Perform search by album and add folders rather than tracks to
@@ -108,22 +116,20 @@ class PlayPlugin(BeetsPlugin):
if use_folders:
paths.append(album.item_dir())
else:
paths.extend(item.path
for item in sort.sort(album.items()))
item_type = 'album'
paths.extend(item.path for item in sort.sort(album.items()))
item_type = "album"
# Perform item query and add tracks to playlist.
else:
selection = lib.items(ui.decargs(args))
paths = [item.path for item in selection]
item_type = 'track'
item_type = "track"
if relative_to:
paths = [relpath(path, relative_to) for path in paths]
if not selection:
ui.print_(ui.colorize('text_warning',
f'No {item_type} to play.'))
ui.print_(ui.colorize("text_warning", f"No {item_type} to play."))
return
open_args = self._playlist_or_paths(paths)
@@ -132,14 +138,13 @@ class PlayPlugin(BeetsPlugin):
# Check if the selection exceeds configured threshold. If True,
# cancel, otherwise proceed with play command.
if opts.yes or not self._exceeds_threshold(
selection, command_str, open_args, item_type):
play(command_str, selection, paths, open_args, self._log,
item_type)
selection, command_str, open_args, item_type
):
play(command_str, selection, paths, open_args, self._log, item_type)
def _command_str(self, args=None):
"""Create a command string from the config command and optional args.
"""
command_str = config['play']['command'].get()
"""Create a command string from the config command and optional args."""
command_str = config["play"]["command"].get()
if not command_str:
return util.open_anything()
# Add optional arguments to the player command.
@@ -153,57 +158,58 @@ class PlayPlugin(BeetsPlugin):
return command_str.replace(" " + ARGS_MARKER, "")
def _playlist_or_paths(self, paths):
"""Return either the raw paths of items or a playlist of the items.
"""
if config['play']['raw']:
"""Return either the raw paths of items or a playlist of the items."""
if config["play"]["raw"]:
return paths
else:
return [self._create_tmp_playlist(paths)]
def _exceeds_threshold(self, selection, command_str, open_args,
item_type='track'):
def _exceeds_threshold(
self, selection, command_str, open_args, item_type="track"
):
"""Prompt user whether to abort if playlist exceeds threshold. If
True, cancel playback. If False, execute play command.
"""
warning_threshold = config['play']['warning_threshold'].get(int)
warning_threshold = config["play"]["warning_threshold"].get(int)
# Warn user before playing any huge playlists.
if warning_threshold and len(selection) > warning_threshold:
if len(selection) > 1:
item_type += 's'
item_type += "s"
ui.print_(ui.colorize(
'text_warning',
'You are about to queue {} {}.'.format(
len(selection), item_type)))
ui.print_(
ui.colorize(
"text_warning",
"You are about to queue {} {}.".format(
len(selection), item_type
),
)
)
if ui.input_options(('Continue', 'Abort')) == 'a':
if ui.input_options(("Continue", "Abort")) == "a":
return True
return False
def _create_tmp_playlist(self, paths_list):
"""Create a temporary .m3u file. Return the filename.
"""
utf8_bom = config['play']['bom'].get(bool)
m3u = NamedTemporaryFile('wb', suffix='.m3u', delete=False)
"""Create a temporary .m3u file. Return the filename."""
utf8_bom = config["play"]["bom"].get(bool)
filename = get_temp_filename(__name__, suffix=".m3u")
with open(filename, "wb") as m3u:
if utf8_bom:
m3u.write(b"\xEF\xBB\xBF")
if utf8_bom:
m3u.write(b'\xEF\xBB\xBF')
for item in paths_list:
m3u.write(item + b"\n")
for item in paths_list:
m3u.write(item + b'\n')
m3u.close()
return m3u.name
return filename
def before_choose_candidate_listener(self, session, task):
"""Append a "Play" choice to the interactive importer prompt.
"""
return [PromptChoice('y', 'plaY', self.importer_play)]
"""Append a "Play" choice to the interactive importer prompt."""
return [PromptChoice("y", "plaY", self.importer_play)]
def importer_play(self, session, task):
"""Get items from current import task and send to play function.
"""
"""Get items from current import task and send to play function."""
selection = task.items
paths = [item.path for item in selection]
@@ -211,5 +217,11 @@ class PlayPlugin(BeetsPlugin):
command_str = self._command_str()
if not self._exceeds_threshold(selection, command_str, open_args):
play(command_str, selection, paths, open_args, self._log,
keep_open=True)
play(
command_str,
selection,
paths,
open_args,
self._log,
keep_open=True,
)