Debian Codegraph @

beetsplug/embedart.py

raw
1 """Allows beets to embed album art into file metadata."""
2
3 from __future__ import annotations
4
5 import os
6 import tempfile
7 from mimetypes import guess_extension
8 from typing import TYPE_CHECKING, Protocol
9
10 import requests
11
12 from beets import config, ui
13 from beets.exceptions import UserError
14 from beets.plugins import BeetsPlugin
15 from beets.ui import print_
16 from beets.util import bytestring_path, displayable_path, normpath, syspath
17 from beets.util.artresizer import ArtResizer
18 from beetsplug._utils import art
19
20 if TYPE_CHECKING:
21 from collections.abc import Sequence
22
23 from beets.importer import ImportSession, ImportTask
24 from beets.library import Album, LibModel, Library
25
26
27 class EmbedArtCLIOpts(Protocol):
28 file: str | None
29 url: str | None
30 yes: bool | None
31
32
33 class ExtractArtCLIOpts(Protocol):
34 associate: bool | None
35 filename: str | None
36 outpath: str | None
37
38
39 class ClearArtCLIOpts(Protocol):
40 yes: bool | None
41
42
43 def _confirm(objs: Sequence[LibModel], album: bool) -> bool:
44 """Show the list of affected objects (items or albums) and confirm
45 that the user wants to modify their artwork.
46
47 `album` is a Boolean indicating whether these are albums (as opposed
48 to items).
49 """
50 noun = "album" if album else "file"
51 prompt = (
52 "Modify artwork for"
53 f" {len(objs)} {noun}{'s' if len(objs) > 1 else ''} (Y/n)?"
54 )
55
56 # Show all the items or albums.
57 for obj in objs:
58 print_(format(obj))
59
60 # Confirm with user.
61 return ui.input_yn(prompt)
62
63
64 class EmbedCoverArtPlugin(BeetsPlugin):
65 """Allows albumart to be embedded into the actual files."""
66
67 def __init__(self) -> None:
68 super().__init__()
69 self.config.add(
70 {
71 "maxwidth": 0,
72 "auto": True,
73 "compare_threshold": 0,
74 "ifempty": False,
75 "remove_art_file": False,
76 "quality": 0,
77 "clearart_on_import": False,
78 }
79 )
80
81 if self.config["maxwidth"].get(int) and not ArtResizer.shared.local:
82 self.config["maxwidth"] = 0
83 self._log.warning(
84 "ImageMagick or PIL not found; 'maxwidth' option ignored"
85 )
86 if (
87 self.config["compare_threshold"].get(int)
88 and not ArtResizer.shared.can_compare
89 ):
90 self.config["compare_threshold"] = 0
91 self._log.warning(
92 "ImageMagick 6.8.7 or higher not installed; "
93 "'compare_threshold' option ignored"
94 )
95
96 self.register_listener("art_set", self.process_album)
97
98 if self.config["clearart_on_import"].get(bool):
99 self.register_listener("import_task_files", self.import_task_files)
100
101 def commands(self) -> list[ui.Subcommand]:
102 # Embed command.
103 embed_cmd = ui.Subcommand(
104 "embedart", help="embed image files into file metadata"
105 )
106 embed_cmd.parser.add_option(
107 "-f", "--file", metavar="PATH", help="the image file to embed"
108 )
109
110 embed_cmd.parser.add_option(
111 "-y", "--yes", action="store_true", help="skip confirmation"
112 )
113
114 embed_cmd.parser.add_option(
115 "-u",
116 "--url",
117 metavar="URL",
118 help="the URL of the image file to embed",
119 )
120
121 maxwidth = self.config["maxwidth"].get(int)
122 quality = self.config["quality"].get(int)
123 compare_threshold = self.config["compare_threshold"].get(int)
124 ifempty = self.config["ifempty"].get(bool)
125
126 def embed_func(
127 lib: Library, opts: EmbedArtCLIOpts, args: list[str]
128 ) -> None:
129 if opts.file:
130 imagepath = normpath(opts.file)
131 if not os.path.isfile(syspath(imagepath)):
132 raise UserError(
133 f"image file {displayable_path(imagepath)} not found"
134 )
135
136 items = lib.items(args)
137
138 # Confirm with user.
139 if not opts.yes and not _confirm(items, not opts.file):
140 return
141
142 for item in items:
143 art.embed_item(
144 self._log,
145 item,
146 imagepath,
147 maxwidth,
148 None,
149 compare_threshold,
150 ifempty,
151 quality=quality,
152 )
153 elif opts.url:
154 try:
155 response = requests.get(opts.url, timeout=5)
156 response.raise_for_status()
157 except requests.exceptions.RequestException as e:
158 self._log.error("{}", e)
159 return
160 extension = guess_extension(response.headers["Content-Type"])
161 if extension is None:
162 self._log.error("Invalid image file")
163 return
164 file = f"image{extension}"
165 tempimg = os.fsencode(os.path.join(tempfile.gettempdir(), file))
166 try:
167 with open(tempimg, "wb") as f:
168 f.write(response.content)
169 except Exception as e:
170 self._log.error("Unable to save image: {}", e)
171 return
172 items = lib.items(args)
173 # Confirm with user.
174 if not opts.yes and not _confirm(items, not opts.url):
175 os.remove(tempimg)
176 return
177 for item in items:
178 art.embed_item(
179 self._log,
180 item,
181 tempimg,
182 maxwidth,
183 None,
184 compare_threshold,
185 ifempty,
186 quality=quality,
187 )
188 os.remove(tempimg)
189 else:
190 albums = lib.albums(args)
191 # Confirm with user.
192 if not opts.yes and not _confirm(albums, not opts.file):
193 return
194 for album in albums:
195 art.embed_album(
196 self._log,
197 album,
198 maxwidth,
199 False,
200 compare_threshold,
201 ifempty,
202 quality=quality,
203 )
204 self.remove_artfile(album)
205
206 embed_cmd.func = embed_func
207
208 # Extract command.
209 extract_cmd = ui.Subcommand(
210 "extractart", help="extract an image from file metadata"
211 )
212 extract_cmd.parser.add_option(
213 "-o", dest="outpath", help="image output file"
214 )
215 extract_cmd.parser.add_option(
216 "-n",
217 dest="filename",
218 help="image filename to create for all matched albums",
219 )
220 extract_cmd.parser.add_option(
221 "-a",
222 dest="associate",
223 action="store_true",
224 help="associate the extracted images with the album",
225 )
226
227 def extract_func(
228 lib: Library, opts: ExtractArtCLIOpts, args: list[str]
229 ) -> None:
230 if opts.outpath:
231 art.extract_first(
232 self._log, normpath(opts.outpath), lib.items(args)
233 )
234 else:
235 filename = bytestring_path(
236 opts.filename or config["art_filename"].get()
237 )
238 if os.path.dirname(filename) != b"":
239 self._log.error(
240 "Only specify a name rather than a path for -n"
241 )
242 return
243 for album in lib.albums(args):
244 if opts.associate and (
245 artpath := art.extract_first(
246 self._log,
247 normpath(os.path.join(album.path, filename)),
248 album.items(),
249 )
250 ):
251 album.set_art(artpath)
252 album.store()
253
254 extract_cmd.func = extract_func
255
256 # Clear command.
257 clear_cmd = ui.Subcommand(
258 "clearart", help="remove images from file metadata"
259 )
260 clear_cmd.parser.add_option(
261 "-y", "--yes", action="store_true", help="skip confirmation"
262 )
263
264 def clear_func(
265 lib: Library, opts: ClearArtCLIOpts, args: list[str]
266 ) -> None:
267 items = lib.items(args)
268 # Confirm with user.
269 if not opts.yes and not _confirm(items, False):
270 return
271 art.clear(self._log, lib, args)
272
273 clear_cmd.func = clear_func
274
275 return [embed_cmd, extract_cmd, clear_cmd]
276
277 def process_album(self, album: Album) -> None:
278 """Automatically embed art after art has been set"""
279 if self.config["auto"] and ui.should_write():
280 max_width = self.config["maxwidth"].get(int)
281 art.embed_album(
282 self._log,
283 album,
284 max_width,
285 True,
286 self.config["compare_threshold"].get(int),
287 self.config["ifempty"].get(bool),
288 )
289 self.remove_artfile(album)
290
291 def remove_artfile(self, album: Album) -> None:
292 """Possibly delete the album art file for an album (if the
293 appropriate configuration option is enabled).
294 """
295 if self.config["remove_art_file"] and album.artpath:
296 if os.path.isfile(syspath(album.artpath)):
297 self._log.debug("Removing album art file for {}", album)
298 os.remove(syspath(album.artpath))
299 album.artpath = None
300 album.store()
301
302 def import_task_files(
303 self, session: ImportSession, task: ImportTask
304 ) -> None:
305 """Automatically clearart of imported files."""
306 for item in task.imported_items():
307 self._log.debug("clearart-on-import {.filepath}", item)
308 art.clear_item(item, self._log)