Debian Codegraph @

beetsplug/zero.py

raw
1 """Clears tag fields in media files."""
2
3 from __future__ import annotations
4
5 import re
6 from typing import TYPE_CHECKING
7
8 import confuse
9 from mediafile import MediaFile
10
11 from beets.importer import Action
12 from beets.plugins import BeetsPlugin
13 from beets.ui import Subcommand, input_yn
14
15 if TYPE_CHECKING:
16 import optparse
17 from collections.abc import Iterable
18
19 from beets.importer import ImportSession, ImportTask
20 from beets.library import Item, Library
21
22 from ._typing import JSONDict
23
24
25 __author__ = "[email protected]"
26
27
28 ARTWORK_FIELDS = {"images", "art"}
29
30
31 class ZeroPlugin(BeetsPlugin):
32 fields_to_progs: dict[str, list[re.Pattern[str]]]
33
34 def __init__(self) -> None:
35 super().__init__()
36
37 self.register_listener("write", self.write_event)
38 self.register_listener(
39 "import_task_choice", self.import_task_choice_event
40 )
41
42 self.config.add(
43 {
44 "auto": True,
45 "fields": [],
46 "keep_fields": [],
47 "update_database": False,
48 "omit_single_disc": False,
49 }
50 )
51
52 self.fields_to_progs = {}
53 self.warned = False
54
55 """Read the bulk of the config into `self.fields_to_progs`.
56 After construction, `fields_to_progs` contains all the fields that
57 should be zeroed as keys and maps each of those to a list of compiled
58 regexes (progs) as values.
59 A field is zeroed if its value matches one of the associated progs. If
60 progs is empty, then the associated field is always zeroed.
61 """
62 if self.config["fields"] and self.config["keep_fields"]:
63 self._log.warning("cannot blacklist and whitelist at the same time")
64 # Blacklist mode.
65 elif self.config["fields"]:
66 for field in self.config["fields"].as_str_seq():
67 self._set_pattern(field)
68 # Whitelist mode.
69 elif self.config["keep_fields"]:
70 keep = set(self.config["keep_fields"].as_str_seq())
71 # ensure that all artwork fields are added when at least
72 # one of them is present
73 if keep & ARTWORK_FIELDS:
74 keep.update(ARTWORK_FIELDS)
75 for field in MediaFile.fields():
76 if field not in keep and field not in (
77 "id",
78 "path",
79 "album_id",
80 ):
81 self._set_pattern(field)
82
83 def commands(self) -> list[Subcommand]:
84 zero_command = Subcommand("zero", help="set fields to null")
85
86 def zero_fields(
87 lib: Library, opts: optparse.Values, args: list[str]
88 ) -> None:
89 if not args and not input_yn(
90 "Remove fields for all items? (Y/n)", True
91 ):
92 return
93 for item in lib.items(args):
94 self.process_item(item)
95
96 zero_command.func = zero_fields
97 return [zero_command]
98
99 def _set_pattern(self, field: str) -> None:
100 """Populate `self.fields_to_progs` for a given field.
101 Do some sanity checks then compile the regexes.
102 """
103 if field not in MediaFile.fields():
104 self._log.error("invalid field: {}", field)
105 elif field in ("id", "path", "album_id"):
106 self._log.warning(
107 "field '{}' ignored, zeroing it would be dangerous", field
108 )
109 else:
110 try:
111 for pattern in self.config[field].as_str_seq():
112 prog = re.compile(pattern, re.IGNORECASE)
113 self.fields_to_progs.setdefault(field, []).append(prog)
114 except confuse.NotFoundError:
115 # Matches everything
116 self.fields_to_progs[field] = []
117
118 def import_task_choice_event(
119 self, session: ImportSession, task: ImportTask
120 ) -> None:
121 if task.choice_flag == Action.ASIS and not self.warned:
122 self._log.warning('cannot zero in "as-is" mode')
123 self.warned = True
124 # TODO request write in as-is mode
125
126 def write_event(self, item: Item, path: bytes, tags: JSONDict) -> None:
127 if self.config["auto"]:
128 self.set_fields(item, tags)
129
130 def set_fields(self, item: Item, tags: JSONDict) -> bool:
131 """Set values in `tags` to `None` if the field is in
132 `self.fields_to_progs` and any of the corresponding `progs` matches the
133 field value.
134 Also update the `item` itself if `update_database` is set in the
135 config.
136 """
137 fields_set = False
138 if self.config["omit_single_disc"].get(bool) and item.disctotal == 1:
139 for tag in {"disc", "disctotal"} & set(tags):
140 tags[tag] = None
141 fields_set = True
142
143 if not self.fields_to_progs:
144 self._log.warning("no fields list to remove")
145
146 for field, progs in self.fields_to_progs.items():
147 if field in tags:
148 value = tags[field]
149 match = _match_progs(tags[field], progs)
150 else:
151 value = ""
152 match = not progs
153
154 if match:
155 fields_set = True
156 self._log.debug("{}: {} -> None", field, value)
157 tags[field] = None
158 if self.config["update_database"]:
159 item[field] = None
160
161 return fields_set
162
163 def process_item(self, item: Item) -> None:
164 tags = dict(item)
165
166 if self.set_fields(item, tags):
167 item.write(tags=tags)
168 if self.config["update_database"]:
169 item.store(fields=tags)
170
171
172 def _match_progs(value: str, progs: Iterable[re.Pattern[str]]) -> bool:
173 """Check if `value` (as string) is matching any of the compiled regexes in
174 the `progs` list.
175 """
176 if not progs:
177 return True
178 for prog in progs:
179 if prog.search(str(value)):
180 return True
181 return False