Skip to content

Commit

Permalink
smartplaylist: add --format option
Browse files Browse the repository at this point in the history
Beets web API already allows remote players to access audio files but it doesn't provide a way to expose the playlists defined using the smartplaylist plugin.
Now the smartplaylist plugin provides an option to generate ID-based item URIs/URLs instead of paths.
Once playlists are generated this way, they can be served using a regular HTTP server such as nginx.

To provide sufficient flexibility for various ways of integrating beets remotely (e.g. beets API, beets API with context path, AURA API, mopidy resource URI, etc), the new option has been defined as a template with an `$id` placeholder (assuming each remote integration requires a different path schema but they all rely on using the beets item `id` as identifier/path segment).

To prevent local path-related plugin configuration from leaking into a HTTP URL-based playlist generation (invoked with CLI option in addition to the local playlists generated into another directory), setting the new option makes the plugin ignore the other path-related options `prefix`, `relative_to`, `forward_slash` and `urlencode`.

Usage examples:
* `beet splupdate --format 'http://beets:8337/item/$id/file'` (for beets web API)
* `beet splupdate --format 'http://beets:8337/aura/tracks/$id/audio'` (for AURA API)

(While it was already possible to generate playlists containing HTTP URLs previously using the `prefix` option, it did not allow to generate ID-based URLs pointing to the beets web API but required to expose the audio files using a web server directly and refer to them using their file system `$path`.)

Relates to beetbox#5037
  • Loading branch information
mgoltzsche committed Dec 15, 2023
1 parent b803d84 commit b723c5b
Show file tree
Hide file tree
Showing 4 changed files with 76 additions and 15 deletions.
37 changes: 24 additions & 13 deletions beetsplug/smartplaylist.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ def __init__(self):
"playlist_dir": ".",
"auto": True,
"playlists": [],
"format": None,
"forward_slash": False,
"prefix": "",
"urlencode": False,
Expand Down Expand Up @@ -109,6 +110,11 @@ def commands(self):
action="store_true",
help="URL-encode all paths.",
)
spl_update.parser.add_option(
"--format",
type="string",
help="playlist item URI template, e.g. http://beets:8337/item/$id/file.",
)
spl_update.parser.add_option(
"--extm3u",
action="store_true",
Expand Down Expand Up @@ -253,6 +259,8 @@ def update_playlists(self, lib, pretend=False):

playlist_dir = self.config["playlist_dir"].as_filename()
playlist_dir = bytestring_path(playlist_dir)
tpl = self.config["format"].get()
prefix = bytestring_path(self.config["prefix"].as_str())
relative_to = self.config["relative_to"].get()
if relative_to:
relative_to = normpath(relative_to)
Expand Down Expand Up @@ -281,18 +289,26 @@ def update_playlists(self, lib, pretend=False):
m3u_name = sanitize_path(m3u_name, lib.replacements)
if m3u_name not in m3us:
m3us[m3u_name] = []
item_path = item.path
if relative_to:
item_path = os.path.relpath(item.path, relative_to)
if item_path not in m3us[m3u_name]:
m3us[m3u_name].append({"item": item, "path": item_path})
item_uri = item.path
if tpl:
item_uri = tpl.replace("$id", str(item.id)).encode("utf-8")
else:
if relative_to:
item_uri = os.path.relpath(item_uri, relative_to)
if self.config["forward_slash"].get():
item_uri = path_as_posix(item_uri)
if self.config["urlencode"]:
item_uri = bytestring_path(pathname2url(item_uri))
item_uri = prefix + item_uri

if item_uri not in m3us[m3u_name]:
m3us[m3u_name].append({"item": item, "uri": item_uri})
if pretend and self.config["pretend_paths"]:
print(displayable_path(item_path))
print(displayable_path(item_uri))
elif pretend:
print(item)

if not pretend:
prefix = bytestring_path(self.config["prefix"].as_str())
# Write all of the accumulated track lists to files.
for m3u in m3us:
m3u_path = normpath(
Expand All @@ -304,18 +320,13 @@ def update_playlists(self, lib, pretend=False):
if extm3u:
f.write(b"#EXTM3U\n")
for entry in m3us[m3u]:
path = entry["path"]
item = entry["item"]
if self.config["forward_slash"].get():
path = path_as_posix(path)
if self.config["urlencode"]:
path = bytestring_path(pathname2url(path))
comment = ""
if extm3u:
comment = "#EXTINF:{},{} - {}\n".format(
int(item.length), item.artist, item.title
)
f.write(comment.encode("utf-8") + prefix + path + b"\n")
f.write(comment.encode("utf-8") + entry["uri"] + b"\n")
# Send an event when playlists were updated.
send_event("smartplaylist_update")

Expand Down
3 changes: 2 additions & 1 deletion docs/changelog.rst
Original file line number Diff line number Diff line change
Expand Up @@ -148,8 +148,9 @@ New features:
`synced` option to prefer synced lyrics over plain lyrics.
* :ref:`import-cmd`: Expose import.quiet_fallback as CLI option.
* :ref:`import-cmd`: Expose `import.incremental_skip_later` as CLI option.
* :doc:`/plugins/smartplaylist`: Add new config option `smartplaylist.extm3u`.
* :doc:`/plugins/smartplaylist`: Expose config options as CLI options.
* :doc:`/plugins/smartplaylist`: Add new option `smartplaylist.extm3u`.
* :doc:`/plugins/smartplaylist`: Add new option `smartplaylist.format`.

Bug fixes:

Expand Down
6 changes: 5 additions & 1 deletion docs/plugins/smartplaylist.rst
Original file line number Diff line number Diff line change
Expand Up @@ -118,9 +118,13 @@ other configuration options are:
- **urlencode**: URL-encode all paths. Default: ``no``.
- **pretend_paths**: When running with ``--pretend``, show the actual file
paths that will be written to the m3u file. Default: ``false``.
- **format**: Template with an ``$id`` placeholder used generate a
playlist item URI, e.g. ``http://beets:8337/item/$id/file``.
When this option is specified, the local path-related options ``prefix``,
``relative_to``, ``forward_slash`` and ``urlencode`` are ignored.
- **extm3u**: Generate extm3u/m3u8 playlists. Default ``ǹo``.

For many configuration options, there is a corresponding CLI option, e.g.
``--playlist-dir``, ``--relative-to``, ``--prefix``, ``--forward-slash``,
``--urlencode``, ``--extm3u``, ``--pretend-paths``.
``--urlencode``, ``--format``, ``--extm3u``, ``--pretend-paths``.
CLI options take precedence over those specified within the configuration file.
45 changes: 45 additions & 0 deletions test/plugins/test_smartplaylist.py
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,51 @@ def test_playlist_update_extm3u(self):
+ b"http://beets:8337/files/tagada.mp3\n",
)

def test_playlist_update_uri_template(self):
spl = SmartPlaylistPlugin()

i = MagicMock()
type(i).id = PropertyMock(return_value=3)
type(i).path = PropertyMock(return_value=b"/tagada.mp3")
i.evaluate_template.side_effect = lambda pl, _: pl.replace(
b"$title", b"ta:ga:da"
).decode()

lib = Mock()
lib.replacements = CHAR_REPLACE
lib.items.return_value = [i]
lib.albums.return_value = []

q = Mock()
a_q = Mock()
pl = b"$title-my<playlist>.m3u", (q, None), (a_q, None)
spl._matched_playlists = [pl]

dir = bytestring_path(mkdtemp())
tpl = "http://beets:8337/item/$id/file"
config["smartplaylist"]["format"] = tpl
config["smartplaylist"]["playlist_dir"] = py3_path(dir)
# The following options should be ignored when format is set
config["smartplaylist"]["relative_to"] = "/data"
config["smartplaylist"]["prefix"] = "/prefix"
config["smartplaylist"]["urlencode"] = True
try:
spl.update_playlists(lib)
except Exception:
rmtree(syspath(dir))
raise

lib.items.assert_called_once_with(q, None)
lib.albums.assert_called_once_with(a_q, None)

m3u_filepath = path.join(dir, b"ta_ga_da-my_playlist_.m3u")
self.assertExists(m3u_filepath)
with open(syspath(m3u_filepath), "rb") as f:
content = f.read()
rmtree(syspath(dir))

self.assertEqual(content, b"http://beets:8337/item/3/file\n")


class SmartPlaylistCLITest(_common.TestCase, TestHelper):
def setUp(self):
Expand Down

0 comments on commit b723c5b

Please sign in to comment.