Debian Codegraph @

beetsplug/scrub.py

raw
1 """Cleans extraneous metadata from files' tags via a command or
2 automatically whenever tags are written.
3 """
4
5 from __future__ import annotations
6
7 from typing import TYPE_CHECKING, Any, Protocol
8
9 import mediafile
10 import mutagen
11
12 from beets import config, ui, util
13 from beets.plugins import BeetsPlugin
14
15 if TYPE_CHECKING:
16 from beets.importer import ImportSession, ImportTask
17 from beets.library import Item, Library
18
19
20 class ScrubCLIOpts(Protocol):
21 write: bool
22
23
24 _MUTAGEN_FORMATS = {
25 "asf": "ASF",
26 "apev2": "APEv2File",
27 "flac": "FLAC",
28 "id3": "ID3FileType",
29 "mp3": "MP3",
30 "mp4": "MP4",
31 "oggflac": "OggFLAC",
32 "oggspeex": "OggSpeex",
33 "oggtheora": "OggTheora",
34 "oggvorbis": "OggVorbis",
35 "oggopus": "OggOpus",
36 "trueaudio": "TrueAudio",
37 "wavpack": "WavPack",
38 "monkeysaudio": "MonkeysAudio",
39 "optimfrog": "OptimFROG",
40 }
41
42
43 class ScrubPlugin(BeetsPlugin):
44 """Removes extraneous metadata from files' tags."""
45
46 def __init__(self) -> None:
47 super().__init__()
48 self.config.add({"auto": True})
49
50 if self.config["auto"]:
51 self.register_listener("import_task_files", self.import_task_files)
52
53 def commands(self) -> list[ui.Subcommand]:
54 def scrub_func(
55 lib: Library, opts: ScrubCLIOpts, args: list[str]
56 ) -> None:
57 # Walk through matching files and remove tags.
58 for item in lib.items(args):
59 self._log.info("scrubbing: {.filepath}", item)
60 self._scrub_item(item, opts.write)
61
62 scrub_cmd = ui.Subcommand("scrub", help="clean audio tags")
63 scrub_cmd.parser.add_option(
64 "-W",
65 "--nowrite",
66 dest="write",
67 action="store_false",
68 default=True,
69 help="leave tags empty",
70 )
71 scrub_cmd.func = scrub_func
72
73 return [scrub_cmd]
74
75 @staticmethod
76 def _mutagen_classes() -> list[type[Any]]:
77 """Get a list of file type classes from the Mutagen module."""
78 classes = []
79 for modname, clsname in _MUTAGEN_FORMATS.items():
80 mod = __import__(f"mutagen.{modname}", fromlist=[clsname])
81 classes.append(getattr(mod, clsname))
82 return classes
83
84 def _scrub(self, path: bytes) -> None:
85 """Remove all tags from a file."""
86 for cls in self._mutagen_classes():
87 # Try opening the file with this type, but just skip in the
88 # event of any error.
89 try:
90 f = cls(util.syspath(path))
91 except Exception:
92 continue
93 if f.tags is None:
94 continue
95
96 # Remove the tag for this type.
97 try:
98 f.delete()
99 except NotImplementedError:
100 # Some Mutagen metadata subclasses (namely, ASFTag) do not
101 # support .delete(), presumably because it is impossible to
102 # remove them. In this case, we just remove all the tags.
103 for tag in f.keys():
104 del f[tag]
105 f.save()
106 except (OSError, mutagen.MutagenError) as exc:
107 self._log.error(
108 "could not scrub {}: {}", util.displayable_path(path), exc
109 )
110
111 def _scrub_item(self, item: Item, restore: bool) -> None:
112 """Remove tags from an Item's associated file and, if `restore`
113 is enabled, write the database's tags back to the file.
114 """
115 # Get album art if we need to restore it.
116 if restore:
117 try:
118 mf = mediafile.MediaFile(
119 util.syspath(item.path), config["id3v23"].get(bool)
120 )
121 except mediafile.UnreadableFileError as exc:
122 self._log.error("could not open file to scrub: {}", exc)
123 return
124 images = mf.images
125
126 # Remove all tags.
127 self._scrub(item.path)
128
129 # Restore tags, if enabled.
130 if restore:
131 self._log.debug("writing new tags after scrub")
132 item.try_write()
133 if images:
134 self._log.debug("restoring art")
135 try:
136 mf = mediafile.MediaFile(
137 util.syspath(item.path), config["id3v23"].get(bool)
138 )
139 mf.images = images
140 mf.save()
141 except mediafile.UnreadableFileError as exc:
142 self._log.error("could not write tags: {}", exc)
143
144 def import_task_files(
145 self, session: ImportSession, task: ImportTask
146 ) -> None:
147 """Automatically scrub imported files."""
148 if not ui.should_write():
149 return
150 for item in task.imported_items():
151 self._log.debug("auto-scrubbing {.filepath}", item)
152 self._scrub_item(item, True)