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