Debian Codegraph @

beetsplug/playlist.py

raw
1 from __future__ import annotations
2
3 import os
4 import tempfile
5 from pathlib import Path
6 from typing import TYPE_CHECKING, ClassVar, Literal
7
8 import confuse
9
10 import beets
11 from beets.dbcore.query import InQuery
12 from beets.util import path_as_posix
13
14 if TYPE_CHECKING:
15 from collections.abc import Iterator
16
17 from beets.dbcore.query import FieldQueryType
18 from beets.library import Item, Library
19
20
21 def is_m3u_file(path: str) -> bool:
22 return Path(path).suffix.lower() in {".m3u", ".m3u8"}
23
24
25 class PlaylistQuery(InQuery[bytes]):
26 """Matches files listed by a playlist file."""
27
28 def __init__(self, _, pattern: str, __) -> None:
29 config = beets.config["playlist"]
30
31 # Get the full path to the playlist
32 playlist_paths = (
33 pattern,
34 os.path.abspath(
35 os.path.join(
36 config["playlist_dir"].as_filename(), f"{pattern}.m3u"
37 )
38 ),
39 )
40
41 paths = []
42 for playlist_path in playlist_paths:
43 if not is_m3u_file(playlist_path):
44 # This is not am M3U playlist, skip this candidate
45 continue
46
47 try:
48 f = open(beets.util.syspath(playlist_path), mode="rb")
49 except OSError:
50 continue
51
52 if config["relative_to"].get() == "library":
53 relative_to = beets.config["directory"].as_filename()
54 elif config["relative_to"].get() == "playlist":
55 relative_to = os.path.dirname(playlist_path)
56 else:
57 relative_to = config["relative_to"].as_filename()
58 relative_to_bytes = beets.util.bytestring_path(relative_to)
59
60 for line in f:
61 if line[0] == "#":
62 # ignore comments, and extm3u extension
63 continue
64
65 paths.append(
66 beets.util.normpath(
67 os.path.join(relative_to_bytes, line.rstrip())
68 )
69 )
70 f.close()
71 break
72 super().__init__("path", paths)
73
74
75 class PlaylistPlugin(beets.plugins.BeetsPlugin):
76 item_queries: ClassVar[dict[str, FieldQueryType]] = {
77 "playlist": PlaylistQuery
78 }
79
80 changes: dict[bytes, bytes | None]
81
82 def __init__(self) -> None:
83 super().__init__()
84 self.config.add(
85 {
86 "auto": False,
87 "playlist_dir": ".",
88 "relative_to": "library",
89 "forward_slash": False,
90 }
91 )
92
93 self.playlist_dir = self.config["playlist_dir"].as_filename()
94 self.changes = {}
95
96 relative_to_val: Literal["library", "playlist"] | Path = self.config[
97 "relative_to"
98 ].get(
99 confuse.OneOf(
100 [confuse.Choice(["library", "playlist"]), confuse.Path()]
101 )
102 )
103 if relative_to_val == "playlist":
104 relative_to = None
105 else:
106 if relative_to_val == "library":
107 relative_to_filename = beets.config["directory"].as_filename()
108 else:
109 relative_to_filename = self.config["relative_to"].as_filename()
110 relative_to = beets.util.bytestring_path(relative_to_filename)
111 self.relative_to = relative_to
112
113 if self.config["auto"]:
114 self.register_listener("item_moved", self.item_moved)
115 self.register_listener("item_removed", self.item_removed)
116 self.register_listener("cli_exit", self.cli_exit)
117
118 def item_moved(self, item: Item, source: bytes, destination: bytes) -> None:
119 self.changes[source] = destination
120
121 def item_removed(self, item: Item) -> None:
122 if not os.path.exists(beets.util.syspath(item.path)):
123 self.changes[item.path] = None
124
125 def cli_exit(self, lib: Library) -> None:
126 for playlist in self.find_playlists():
127 self._log.info("Updating playlist: {}", playlist)
128 base_dir = beets.util.bytestring_path(
129 self.relative_to
130 if self.relative_to
131 else os.path.dirname(playlist)
132 )
133
134 try:
135 self.update_playlist(playlist, base_dir)
136 except beets.util.FilesystemError:
137 self._log.error("Failed to update playlist: {}", playlist)
138
139 def find_playlists(self) -> Iterator[str]:
140 """Find M3U playlists in the playlist directory."""
141 playlist_dir = beets.util.syspath(self.playlist_dir)
142 try:
143 dir_contents = os.listdir(playlist_dir)
144 except OSError:
145 self._log.warning(
146 "Unable to open playlist directory {.playlist_dir}", self
147 )
148 return
149
150 for filename in dir_contents:
151 if is_m3u_file(filename):
152 yield os.path.join(self.playlist_dir, filename)
153
154 def update_playlist(self, filename: str, base_dir: bytes) -> None:
155 """Find M3U playlists in the specified directory."""
156 changes = 0
157 deletions = 0
158
159 with tempfile.NamedTemporaryFile(mode="w+b", delete=False) as tempfp:
160 new_playlist = tempfp.name
161 with open(filename, mode="rb") as fp:
162 for line in fp:
163 original_path = line.rstrip(b"\r\n")
164
165 # Ensure that path from playlist is absolute
166 is_relative = not os.path.isabs(line)
167 if is_relative:
168 lookup = os.path.join(base_dir, original_path)
169 else:
170 lookup = original_path
171
172 try:
173 new_path = self.changes[beets.util.normpath(lookup)]
174 except KeyError:
175 if self.config["forward_slash"]:
176 line = path_as_posix(line)
177 tempfp.write(line)
178 else:
179 if new_path is None:
180 # Item has been deleted
181 deletions += 1
182 continue
183
184 changes += 1
185 if is_relative:
186 new_path = os.path.relpath(new_path, base_dir)
187 line = line.replace(original_path, new_path)
188 if self.config["forward_slash"]:
189 line = path_as_posix(line)
190 tempfp.write(line)
191
192 if changes or deletions:
193 self._log.info(
194 "Updated playlist {} ({} changes, {} deletions)",
195 filename,
196 changes,
197 deletions,
198 )
199 beets.util.copy(new_playlist, filename, replace=True)
200 beets.util.remove(new_playlist)