Debian Codegraph @

beetsplug/filefilter.py

raw
1 """Filter imported files using a regular expression."""
2
3 from __future__ import annotations
4
5 import re
6 from typing import TYPE_CHECKING
7
8 from beets import config
9 from beets.importer import SingletonImportTask
10 from beets.plugins import BeetsPlugin
11 from beets.util import bytestring_path
12
13 if TYPE_CHECKING:
14 from beets.importer import ImportSession, ImportTask
15
16
17 class FileFilterPlugin(BeetsPlugin):
18 def __init__(self) -> None:
19 super().__init__()
20 self.register_listener(
21 "import_task_created", self.import_task_created_event
22 )
23 self.config.add({"path": ".*"})
24
25 self.path_album_regex = self.path_singleton_regex = re.compile(
26 bytestring_path(self.config["path"].get())
27 )
28
29 if "album_path" in self.config:
30 self.path_album_regex = re.compile(
31 bytestring_path(self.config["album_path"].get())
32 )
33
34 if "singleton_path" in self.config:
35 self.path_singleton_regex = re.compile(
36 bytestring_path(self.config["singleton_path"].get())
37 )
38
39 def import_task_created_event(
40 self, session: ImportSession, task: ImportTask
41 ) -> list[ImportTask] | None:
42 if task.items and len(task.items) > 0:
43 items_to_import = []
44 for item in task.items:
45 if self.file_filter(item["path"]):
46 items_to_import.append(item)
47 if len(items_to_import) > 0:
48 task.items = items_to_import
49 else:
50 # Returning an empty list of tasks from the handler
51 # drops the task from the rest of the importer pipeline.
52 return []
53
54 elif isinstance(task, SingletonImportTask):
55 if not self.file_filter(task.item["path"]):
56 return []
57
58 # If not filtered, return the original task unchanged.
59 return [task]
60
61 def file_filter(self, full_path: bytes) -> bool:
62 """Checks if the configured regular expressions allow the import
63 of the file given in full_path.
64 """
65 import_config = dict(config["import"])
66 full_path = bytestring_path(full_path)
67 if "singletons" not in import_config or not import_config["singletons"]:
68 # Album
69 return self.path_album_regex.match(full_path) is not None
70 # Singleton
71 return self.path_singleton_regex.match(full_path) is not None