Debian Codegraph @

beetsplug/smartplaylist.py

raw
1 """Generates smart playlists based on beets queries."""
2
3 from __future__ import annotations
4
5 import os
6 from collections import defaultdict
7 from functools import cached_property
8 from shlex import quote as shell_quote
9 from typing import TYPE_CHECKING, Literal, Protocol, TypeAlias
10 from urllib.parse import quote
11 from urllib.request import pathname2url
12
13 import confuse
14
15 from beets import plugins, ui
16 from beets.dbcore import Query
17 from beets.dbcore.query import ParsingError
18 from beets.dbcore.sort import Sort
19 from beets.exceptions import UserError
20 from beets.library import Album, Item, parse_query_string
21 from beets.util import (
22 bytestring_path,
23 mkdirall,
24 normpath,
25 path_as_posix,
26 sanitize_path,
27 syspath,
28 )
29
30 if TYPE_CHECKING:
31 from collections.abc import Iterator
32
33 from beets.library import LibModel, Library
34
35 from ._typing import JSONDict
36
37 QueryAndSort = tuple[Query, Sort]
38 PlaylistQuery = Query | tuple[QueryAndSort, ...] | None
39 PlaylistQueryAndSort = tuple[PlaylistQuery, Sort | None]
40 PlaylistMatch: TypeAlias = tuple[
41 str, PlaylistQueryAndSort, PlaylistQueryAndSort
42 ]
43
44
45 class SmartPlaylistCLIOpts(Protocol):
46 pretend: bool | None
47 format: str
48 playlist_dir: str
49 dest_regen: bool
50 relative_to: str | None
51 prefix: str
52 forward_slash: bool
53 urlencode: bool
54 uri_format: str | None
55 output: Literal["m3u", "extm3u"]
56
57
58 class SmartPlaylistPlugin(plugins.BeetsPlugin):
59 def __init__(self) -> None:
60 super().__init__()
61 self.config.add(
62 {
63 "dest_regen": False,
64 "relative_to": None,
65 "playlist_dir": ".",
66 "auto": True,
67 "playlists": [],
68 "uri_format": None,
69 "fields": [],
70 "forward_slash": False,
71 "prefix": "",
72 "urlencode": False,
73 "format": "$artist - $title",
74 "output": "m3u",
75 "pretend": False,
76 }
77 )
78
79 self.config["prefix"].redact = True # May contain username/password.
80 self._matched_playlists: set[PlaylistMatch] = set()
81 self._unmatched_playlists: set[PlaylistMatch] = set()
82 # validate output format
83 self.config["output"].get(confuse.Choice(["m3u", "extm3u"]))
84
85 if self.config["auto"]:
86 self.register_listener("database_change", self.db_change)
87
88 @cached_property
89 def prefix(self) -> bytes:
90 return bytestring_path(self.config["prefix"].as_str())
91
92 @cached_property
93 def relative_to(self) -> bytes | None:
94 if relative_to := self.config["relative_to"].get():
95 return normpath(relative_to)
96
97 return None
98
99 @cached_property
100 def dest_regen(self) -> bool:
101 return self.config["dest_regen"].get(bool)
102
103 @cached_property
104 def forward_slash(self) -> bool:
105 return self.config["forward_slash"].get(bool)
106
107 @cached_property
108 def urlencode(self) -> bool:
109 return self.config["urlencode"].get(bool)
110
111 @cached_property
112 def uri_format(self) -> str | None:
113 return self.config["uri_format"].get()
114
115 def commands(self) -> list[ui.Subcommand]:
116 spl_update = ui.Subcommand(
117 "splupdate",
118 help="update the smart playlists. Playlist names may be "
119 "passed as arguments.",
120 )
121 spl_update.parser.add_option(
122 "-p",
123 "--pretend",
124 action="store_true",
125 help="display query results but don't write playlist files.",
126 )
127 spl_update.parser.add_option(
128 "-f",
129 "--format",
130 type="string",
131 default=self.config["format"].get(),
132 help="print per-track log lines with custom format",
133 )
134 spl_update.parser.add_option(
135 "-d",
136 "--playlist-dir",
137 dest="playlist_dir",
138 metavar="PATH",
139 type="string",
140 default=self.config["playlist_dir"].get(),
141 help="directory to write the generated playlist files to.",
142 )
143 spl_update.parser.add_option(
144 "--dest-regen",
145 action="store_true",
146 dest="dest_regen",
147 default=self.config["dest_regen"].get(bool),
148 help="regenerate the destination path as 'move' or 'convert' "
149 "commands would do.",
150 )
151 spl_update.parser.add_option(
152 "--relative-to",
153 dest="relative_to",
154 metavar="PATH",
155 type="string",
156 default=self.config["relative_to"].get(),
157 help="generate playlist item paths relative to this path.",
158 )
159 spl_update.parser.add_option(
160 "--prefix",
161 type="string",
162 default=self.config["prefix"].get(),
163 help="prepend string to every path in the playlist file.",
164 )
165 spl_update.parser.add_option(
166 "--forward-slash",
167 action="store_true",
168 dest="forward_slash",
169 default=self.config["forward_slash"].get(bool),
170 help="force forward slash in paths within playlists.",
171 )
172 spl_update.parser.add_option(
173 "--urlencode",
174 action="store_true",
175 default=self.config["urlencode"].get(bool),
176 help="URL-encode all paths.",
177 )
178 spl_update.parser.add_option(
179 "--uri-format",
180 dest="uri_format",
181 type="string",
182 default=self.config["uri_format"].get(),
183 help="playlist item URI template, e.g. http://beets:8337/item/$id/file.",
184 )
185 spl_update.parser.add_option(
186 "--output",
187 type="choice",
188 choices=["m3u", "extm3u"],
189 default=self.config["output"].get(),
190 help="specify the playlist format: m3u|extm3u.",
191 )
192 spl_update.func = self.update_cmd
193 return [spl_update]
194
195 def update_cmd(
196 self, lib: Library, opts: SmartPlaylistCLIOpts, args: list[str]
197 ) -> None:
198 self.build_queries()
199 if args:
200 args_set = set(args)
201 for a in list(args_set):
202 if not a.endswith(".m3u"):
203 args_set.add(f"{a}.m3u")
204
205 playlists = {
206 (name, q, a_q)
207 for name, q, a_q in self._unmatched_playlists
208 if name in args_set
209 }
210 if not playlists:
211 unmatched = [name for name, _, _ in self._unmatched_playlists]
212 unmatched.sort()
213 quoted_names = " ".join(shell_quote(name) for name in unmatched)
214 raise UserError(
215 f"No playlist matching any of {quoted_names} found"
216 )
217
218 self._matched_playlists = playlists
219 self._unmatched_playlists -= playlists
220 else:
221 self._matched_playlists = self._unmatched_playlists
222
223 self.config.set(vars(opts))
224 self.update_playlists(lib)
225
226 def _parse_one_query(
227 self, playlist: JSONDict, key: str, model_cls: type[LibModel]
228 ) -> tuple[PlaylistQuery, Sort | None]:
229 qs = playlist.get(key)
230 if qs is None:
231 return None, None
232 if isinstance(qs, str):
233 return parse_query_string(qs, model_cls)
234 if len(qs) == 1:
235 return parse_query_string(qs[0], model_cls)
236
237 queries_and_sorts: tuple[QueryAndSort, ...] = tuple(
238 parse_query_string(q, model_cls) for q in qs
239 )
240 return queries_and_sorts, None
241
242 def build_queries(self) -> None:
243 """
244 Instantiate queries for the playlists.
245
246 Each playlist has 2 queries: one for items, one for albums, each with a
247 sort. We must also remember its name. _unmatched_playlists is a set of
248 tuples (name, (q, q_sort), (album_q, album_q_sort)).
249
250 sort may be any sort, or NullSort, or None. None and NullSort are
251 equivalent and both eval to False.
252 More precisely
253 - it will be NullSort when a playlist query ('query' or 'album_query')
254 is a single item or a list with 1 element
255 - it will be None when there are multiple items in a query
256 """
257 self._unmatched_playlists = set()
258 self._matched_playlists = set()
259
260 for playlist in self.config["playlists"].get(list):
261 if "name" not in playlist:
262 self._log.warning("playlist configuration is missing name")
263 continue
264
265 try:
266 q_match = self._parse_one_query(playlist, "query", Item)
267 a_match = self._parse_one_query(playlist, "album_query", Album)
268 except ParsingError as exc:
269 self._log.warning(
270 "invalid query in playlist {}: {}", playlist["name"], exc
271 )
272 continue
273
274 self._unmatched_playlists.add((playlist["name"], q_match, a_match))
275
276 def _matches_query(self, model: LibModel, query: PlaylistQuery) -> bool:
277 if not query:
278 return False
279 if isinstance(query, (list, tuple)):
280 return any(q.match(model) for q, _ in query)
281 return query.match(model)
282
283 def matches(
284 self, model: LibModel, query: PlaylistQuery, album_query: PlaylistQuery
285 ) -> bool:
286 if isinstance(model, Album):
287 return self._matches_query(model, album_query)
288 if isinstance(model, Item):
289 return self._matches_query(model, query)
290 return False
291
292 def db_change(self, lib: Library, model: LibModel) -> None:
293 if self._unmatched_playlists is None:
294 self.build_queries()
295
296 for playlist in self._unmatched_playlists:
297 n, (q, _), (a_q, _) = playlist
298 if self.matches(model, q, a_q):
299 self._log.debug("{} will be updated because of {}", n, model)
300 self._matched_playlists.add(playlist)
301 self.register_listener("cli_exit", self.update_playlists)
302
303 self._unmatched_playlists -= self._matched_playlists
304
305 @staticmethod
306 def get_queries(
307 query: PlaylistQueryAndSort,
308 ) -> list[tuple[Query, Sort | None]]:
309 """Normalize a playlist query into a flat list of query-sort pairs.
310
311 Handles both compound (list/tuple of pairs) and single query inputs,
312 returning an empty list when no query is present.
313 """
314 q, sort = query
315
316 if isinstance(q, (list, tuple)):
317 return list(q)
318 if q:
319 return [(q, sort)]
320
321 return []
322
323 @classmethod
324 def get_playlist_items(
325 cls,
326 lib: Library,
327 item_q: PlaylistQueryAndSort,
328 album_q: PlaylistQueryAndSort,
329 ) -> Iterator[Item]:
330 """Collect unique items matching the playlist's item and album queries.
331
332 Queries both tracks directly and albums (expanding them to their
333 tracks), then merges the results into a deduplicated list preserving
334 insertion order.
335 """
336 items: list[Item] = []
337
338 for q, sort in cls.get_queries(item_q):
339 items.extend(lib.items(q, sort))
340
341 albums: list[Album] = []
342 for q, sort in cls.get_queries(album_q):
343 albums.extend(lib.albums(q, sort))
344
345 seen_album_ids = set()
346 for album in albums:
347 if album.id not in seen_album_ids:
348 seen_album_ids.add(album.id)
349 items.extend(album.items())
350
351 seen_ids = set()
352 for item in items:
353 if item.id not in seen_ids:
354 seen_ids.add(item.id)
355 yield item
356
357 def get_item_uri(self, item: Item) -> bytes:
358 item_uri = item.path
359 if uri_format := self.uri_format:
360 return uri_format.replace("$id", str(item.id)).encode("utf-8")
361
362 if self.dest_regen:
363 item_uri = item.destination()
364 if self.relative_to:
365 item_uri = os.path.relpath(item_uri, self.relative_to)
366 if self.forward_slash:
367 item_uri = path_as_posix(item_uri)
368 if self.urlencode:
369 item_uri = bytestring_path(pathname2url(os.fsdecode(item_uri)))
370
371 return self.prefix + item_uri
372
373 def write_playlist(
374 self, path: bytes, is_extm3u: bool, entries: list[PlaylistItem]
375 ) -> None:
376 """Write a playlist file with the given entries."""
377 mkdirall(path)
378 with open(syspath(path), "wb") as f:
379 keys = []
380 if is_extm3u:
381 keys = self.config["fields"].get(list)
382 f.write(b"#EXTM3U\n")
383 for entry in entries:
384 f.write(entry.get_comment(is_extm3u, keys))
385
386 def update_playlists(self, lib: Library) -> None:
387 playlist_count = len(self._matched_playlists)
388 self._log.info("Updating {} smart playlists...", playlist_count)
389
390 playlist_dir = bytestring_path(
391 self.config["playlist_dir"].as_filename()
392 )
393
394 # Maps playlist filenames to lists of track entries and URI sets used
395 # to deduplicate output lines.
396 m3us: dict[str, list[PlaylistItem]] = defaultdict(list)
397 m3u_uris_by_name: dict[str, set[bytes]] = defaultdict(set)
398
399 for playlist in self._matched_playlists:
400 name, item_q, album_q = playlist
401 items = self.get_playlist_items(lib, item_q, album_q)
402
403 # As we allow tags in the m3u names, we'll need to iterate through
404 # the items and generate the correct m3u file names.
405 matched_items: list[Item] = []
406 for item in items:
407 m3u_name = item.evaluate_template(name, for_path=True)
408 m3u_name = sanitize_path(m3u_name, lib.replacements)
409 item_uri = self.get_item_uri(item)
410
411 if item_uri not in m3u_uris_by_name[m3u_name]:
412 m3u_uris_by_name[m3u_name].add(item_uri)
413 m3us[m3u_name].append(PlaylistItem(item, item_uri))
414 matched_items.append(item)
415
416 self._log.info(
417 "Creating playlist {}: {} tracks.", name, len(matched_items)
418 )
419 for item in matched_items:
420 self._log.debug(
421 item.evaluate_template(self.config["format"].as_str())
422 )
423
424 if self.config["pretend"].get():
425 self._log.info("{} playlists would be updated", playlist_count)
426 else:
427 # Write all of the accumulated track lists to files.
428 is_extm3u = self.config["output"].get() == "extm3u"
429 for m3u, entries in m3us.items():
430 m3u_path = normpath(
431 os.path.join(playlist_dir, bytestring_path(m3u))
432 )
433 self.write_playlist(m3u_path, is_extm3u, entries)
434
435 # Send an event when playlists were updated.
436 plugins.send("smartplaylist_update")
437 self._log.info("{} playlists updated", playlist_count)
438
439
440 class PlaylistItem:
441 def __init__(self, item: Item, uri: bytes) -> None:
442 self.item = item
443 self.uri = uri
444
445 def get_comment(self, is_extm3u: bool, fields: list[str]) -> bytes:
446 comment = ""
447 if is_extm3u:
448 attr = [(k, self.item[k]) for k in fields]
449 al = [
450 f' {k}="{quote("; ".join(v) if isinstance(v, list) else str(v), safe="/:")}"' # noqa: E501
451 for k, v in attr
452 ]
453 attrs = "".join(al)
454 comment = (
455 f"#EXTINF:{int(self.item.length)}{attrs},"
456 f"{self.item.artist} - {self.item.title}\n"
457 )
458
459 return comment.encode("utf-8") + self.uri + b"\n"