Debian Codegraph @

beetsplug/badfiles.py

raw
1 """Use command-line tools to check for audio file corruption."""
2
3 from __future__ import annotations
4
5 import errno
6 import os
7 import shlex
8 import sys
9 from subprocess import STDOUT, CalledProcessError, check_output, list2cmdline
10 from typing import TYPE_CHECKING, Literal, Protocol
11
12 import confuse
13
14 from beets import config, importer, ui
15 from beets.plugins import BeetsPlugin
16 from beets.ui import Subcommand
17 from beets.util import displayable_path, par_map
18 from beets.util.color import colorize
19
20 if TYPE_CHECKING:
21 from collections.abc import Callable, Sequence
22
23 from beets.importer import ImportSession, ImportTask
24 from beets.library import Item, Library
25
26 ImportAction = Literal["abort", "skip", "continue"]
27
28
29 class BadCLIOpts(Protocol):
30 verbose: bool
31
32
33 class CheckerCommandError(Exception):
34 """Raised when running a checker failed.
35
36 Attributes:
37 checker: Checker command name.
38 path: Path to the file being validated.
39 errno: Error number from the checker execution error.
40 msg: Message from the checker execution error.
41 """
42
43 def __init__(self, cmd: Sequence[str], oserror: OSError) -> None:
44 self.checker = cmd[0]
45 self.path = cmd[-1]
46 self.errno = oserror.errno
47 self.msg = str(oserror)
48
49
50 class BadFiles(BeetsPlugin):
51 def __init__(self) -> None:
52 super().__init__()
53 self.verbose = False
54
55 self.config.add(
56 {
57 "check_on_import": False,
58 "import_action_on_warning": "ask",
59 "import_action_on_error": "ask",
60 }
61 )
62
63 self.register_listener("import_task_start", self.on_import_task_start)
64 self.register_listener(
65 "import_task_before_choice", self.on_import_task_before_choice
66 )
67
68 def run_command(self, cmd: Sequence[str]) -> tuple[int, int, list[str]]:
69 self._log.debug(
70 "running command: {}", displayable_path(list2cmdline(cmd))
71 )
72 try:
73 output = check_output(cmd, stderr=STDOUT)
74 errors = 0
75 status = 0
76 except CalledProcessError as e:
77 output = e.output
78 errors = 1
79 status = e.returncode
80 except OSError as e:
81 raise CheckerCommandError(cmd, e)
82 output_str = output.decode(sys.getdefaultencoding(), "replace")
83 return status, errors, [line for line in output_str.split("\n") if line]
84
85 def check_mp3val(self, path: str) -> tuple[int, int, list[str]]:
86 status, errors, output = self.run_command(["mp3val", path])
87 if status == 0:
88 output = [line for line in output if line.startswith("WARNING:")]
89 errors = len(output)
90 return status, errors, output
91
92 def check_flac(self, path: str) -> tuple[int, int, list[str]]:
93 return self.run_command(["flac", "-wst", path])
94
95 def check_custom(
96 self, command: str
97 ) -> Callable[[str], tuple[int, int, list[str]]]:
98 def checker(path: str) -> tuple[int, int, list[str]]:
99 return self.run_command([*shlex.split(command), path])
100
101 return checker
102
103 def get_checker(
104 self, ext: str
105 ) -> Callable[[str], tuple[int, int, list[str]]] | None:
106 ext = ext.lower()
107 try:
108 command = self.config["commands"].get(confuse.MappingValues(str))[
109 ext
110 ]
111 except (confuse.NotFoundError, KeyError):
112 if ext == "mp3":
113 return self.check_mp3val
114 if ext == "flac":
115 return self.check_flac
116 else:
117 return self.check_custom(command)
118
119 return None
120
121 def check_item(self, item: Item) -> list[str]:
122 # First, check whether the path exists. If not, the user
123 # should probably run `beet update` to cleanup your library.
124 dpath = displayable_path(item.path)
125 self._log.debug("checking path: {}", dpath)
126 if not os.path.exists(item.path):
127 ui.print_(f"{colorize('text_error', dpath)}: file does not exist")
128
129 # Run the checker against the file if one is found
130 ext = os.path.splitext(item.path)[1][1:].decode("utf8", "ignore")
131 checker = self.get_checker(ext)
132 if not checker:
133 self._log.error("no checker specified in the config for {}", ext)
134 return []
135 path = str(item.filepath)
136 try:
137 status, errors, output = checker(path)
138 except CheckerCommandError as e:
139 if e.errno == errno.ENOENT:
140 self._log.error(
141 "command not found: {0.checker} when validating file: {0.path}",
142 e,
143 )
144 else:
145 self._log.error("error invoking {0.checker}: {0.msg}", e)
146 return []
147
148 error_lines = []
149
150 if status > 0:
151 error_lines.append(
152 f"{colorize('text_error', dpath)}: checker exited with status {status}"
153 )
154 for line in output:
155 error_lines.append(f" {line}")
156
157 elif errors > 0:
158 error_lines.append(
159 f"{colorize('text_warning', dpath)}: checker found"
160 f" {errors} errors or warnings"
161 )
162 for line in output:
163 error_lines.append(f" {line}")
164 elif self.verbose:
165 error_lines.append(f"{colorize('text_success', dpath)}: ok")
166
167 return error_lines
168
169 def on_import_task_start(
170 self, task: ImportTask, session: ImportSession
171 ) -> None:
172 if not self.config["check_on_import"].get(bool):
173 return
174
175 checks_failed = []
176
177 for item in task.items:
178 error_lines = self.check_item(item)
179 if error_lines:
180 checks_failed.append(error_lines)
181
182 if checks_failed:
183 task._badfiles_checks_failed = checks_failed # type: ignore[attr-defined]
184
185 def handle_import_action(
186 self, action: ImportAction, failure_type: Literal["error", "warning"]
187 ) -> importer.Action | None:
188 action_name_by_action = {
189 "abort": "Aborting",
190 "skip": "Skipping",
191 "continue": "Continuing",
192 }
193 ui.print_(
194 f"{ui.colorize('text_warning', action_name_by_action[action])}"
195 f" due to import_action_on_{failure_type} configuration"
196 )
197 if action == "abort":
198 raise importer.ImportAbortError()
199 if action == "skip":
200 return importer.Action.SKIP
201 return None
202
203 def on_import_task_before_choice(
204 self, task: ImportTask, session: ImportSession
205 ) -> importer.Action | None:
206 if hasattr(task, "_badfiles_checks_failed"):
207 actions = confuse.Choice[ImportAction | Literal["ask"]](
208 ["ask", "abort", "skip", "continue"]
209 )
210 warning_action = self.config["import_action_on_warning"].get(
211 actions
212 )
213 error_action = self.config["import_action_on_error"].get(actions)
214
215 ui.print_(
216 f"{colorize('text_warning', 'BAD')} one or more files failed checks:"
217 )
218
219 found_warning = False
220 found_error = False
221 for error in task._badfiles_checks_failed:
222 for error_line in error:
223 if (
224 "checker found 0 errors or warnings"
225 in error_line.lower()
226 ):
227 continue
228
229 if "warning" in error_line.lower():
230 found_warning = True
231 if "error" in error_line.lower():
232 found_error = True
233
234 ui.print_(error_line)
235
236 # Check for and handle automatic actions.
237 # Errors always take precedence over warnings.
238 if found_error and error_action != "ask":
239 return self.handle_import_action(error_action, "error")
240 if found_warning and warning_action != "ask":
241 return self.handle_import_action(warning_action, "warning")
242
243 # Defer the quiet check to after automatic import action options are handled
244 if config["import"]["quiet"]:
245 return None
246
247 ui.print_()
248 ui.print_("What would you like to do?")
249
250 sel = ui.input_options(["aBort", "skip", "continue"])
251
252 if sel == "s":
253 return importer.Action.SKIP
254 if sel == "c":
255 return None
256 if sel == "b":
257 raise importer.ImportAbortError()
258 raise Exception(f"Unexpected selection: {sel}")
259 return None
260
261 def command(self, lib: Library, opts: BadCLIOpts, args: list[str]) -> None:
262 # Get items from arguments
263 items = lib.items(args)
264 self.verbose = opts.verbose
265
266 def check_and_print(item: Item) -> None:
267 for error_line in self.check_item(item):
268 ui.print_(error_line)
269
270 par_map(check_and_print, items)
271
272 def commands(self) -> list[Subcommand]:
273 bad_command = Subcommand(
274 "bad", help="check for corrupt or missing files"
275 )
276 bad_command.parser.add_option(
277 "-v",
278 "--verbose",
279 action="store_true",
280 default=False,
281 dest="verbose",
282 help="view results for both the bad and uncorrupted files",
283 )
284 bad_command.func = self.command
285 return [bad_command]