| 1 |
"""Create freedesktop.org-compliant thumbnails for album folders |
| 2 |
|
| 3 |
This plugin is POSIX-only. |
| 4 |
Spec: standards.freedesktop.org/thumbnail-spec/latest/index.html |
| 5 |
""" |
| 6 |
|
| 7 |
from __future__ import annotations |
| 8 |
|
| 9 |
import ctypes |
| 10 |
import ctypes.util |
| 11 |
import os |
| 12 |
import shutil |
| 13 |
from hashlib import md5 |
| 14 |
from pathlib import PurePosixPath |
| 15 |
from typing import TYPE_CHECKING, Any |
| 16 |
|
| 17 |
from xdg import BaseDirectory |
| 18 |
|
| 19 |
from beets.plugins import BeetsPlugin |
| 20 |
from beets.ui import Subcommand |
| 21 |
from beets.util import bytestring_path, displayable_path, syspath |
| 22 |
from beets.util.artresizer import ArtResizer |
| 23 |
|
| 24 |
BASE_DIR = os.path.join(BaseDirectory.xdg_cache_home, "thumbnails") |
| 25 |
if TYPE_CHECKING: |
| 26 |
import optparse |
| 27 |
|
| 28 |
from beets.library import Album, Library |
| 29 |
|
| 30 |
|
| 31 |
NORMAL_DIR = bytestring_path(os.path.join(BASE_DIR, "normal")) |
| 32 |
LARGE_DIR = bytestring_path(os.path.join(BASE_DIR, "large")) |
| 33 |
|
| 34 |
|
| 35 |
class ThumbnailsPlugin(BeetsPlugin): |
| 36 |
def __init__(self) -> None: |
| 37 |
super().__init__() |
| 38 |
self.config.add({"auto": True, "force": False, "dolphin": False}) |
| 39 |
|
| 40 |
if self.config["auto"] and self._check_local_ok(): |
| 41 |
self.register_listener("art_set", self.process_album) |
| 42 |
|
| 43 |
def commands(self) -> list[Subcommand]: |
| 44 |
thumbnails_command = Subcommand( |
| 45 |
"thumbnails", help="Create album thumbnails" |
| 46 |
) |
| 47 |
thumbnails_command.parser.add_option( |
| 48 |
"-f", |
| 49 |
"--force", |
| 50 |
dest="force", |
| 51 |
action="store_true", |
| 52 |
default=False, |
| 53 |
help="force regeneration of thumbnails deemed fine (existing & " |
| 54 |
"recent enough)", |
| 55 |
) |
| 56 |
thumbnails_command.parser.add_option( |
| 57 |
"--dolphin", |
| 58 |
dest="dolphin", |
| 59 |
action="store_true", |
| 60 |
default=False, |
| 61 |
help="create Dolphin-compatible thumbnail information (for KDE)", |
| 62 |
) |
| 63 |
thumbnails_command.func = self.process_query |
| 64 |
|
| 65 |
return [thumbnails_command] |
| 66 |
|
| 67 |
def process_query( |
| 68 |
self, lib: Library, opts: optparse.Values, args: list[str] |
| 69 |
) -> None: |
| 70 |
self.config.set_args(opts) |
| 71 |
if self._check_local_ok(): |
| 72 |
for album in lib.albums(args): |
| 73 |
self.process_album(album) |
| 74 |
|
| 75 |
def _check_local_ok(self) -> bool: |
| 76 |
"""Check that everything is ready: |
| 77 |
- local capability to resize images |
| 78 |
- thumbnail dirs exist (create them if needed) |
| 79 |
- detect whether we'll use PIL or IM |
| 80 |
- detect whether we'll use GIO or Python to get URIs |
| 81 |
""" |
| 82 |
if not ArtResizer.shared.local: |
| 83 |
self._log.warning( |
| 84 |
"No local image resizing capabilities, " |
| 85 |
"cannot generate thumbnails" |
| 86 |
) |
| 87 |
return False |
| 88 |
|
| 89 |
for dir_ in (NORMAL_DIR, LARGE_DIR): |
| 90 |
if not os.path.exists(syspath(dir_)): |
| 91 |
os.makedirs(syspath(dir_)) |
| 92 |
|
| 93 |
if not ArtResizer.shared.can_write_metadata: |
| 94 |
raise RuntimeError( |
| 95 |
f"Thumbnails: ArtResizer backend {ArtResizer.shared.method}" |
| 96 |
f" unexpectedly cannot write image metadata." |
| 97 |
) |
| 98 |
self._log.debug("using {.shared.method} to write metadata", ArtResizer) |
| 99 |
|
| 100 |
uri_getter: URIGetter = GioURI() |
| 101 |
if not uri_getter.available: |
| 102 |
uri_getter = PathlibURI() |
| 103 |
self._log.debug("using {.name} to compute URIs", uri_getter) |
| 104 |
self.get_uri = uri_getter.uri |
| 105 |
|
| 106 |
return True |
| 107 |
|
| 108 |
def process_album(self, album: Album) -> None: |
| 109 |
"""Produce thumbnails for the album folder.""" |
| 110 |
self._log.debug("generating thumbnail for {}", album) |
| 111 |
|
| 112 |
artpath = album.artpath |
| 113 |
if not artpath: |
| 114 |
self._log.warning("album {} has no art", album) |
| 115 |
return |
| 116 |
|
| 117 |
if self.config["dolphin"]: |
| 118 |
self.make_dolphin_cover_thumbnail(album.path, artpath) |
| 119 |
|
| 120 |
size = ArtResizer.shared.get_size(artpath) |
| 121 |
if not size: |
| 122 |
self._log.warning( |
| 123 |
"problem getting the picture size for {.artpath}", album |
| 124 |
) |
| 125 |
return |
| 126 |
|
| 127 |
wrote = True |
| 128 |
if max(size) >= 256: |
| 129 |
wrote &= self.make_cover_thumbnail(album, artpath, 256, LARGE_DIR) |
| 130 |
wrote &= self.make_cover_thumbnail(album, artpath, 128, NORMAL_DIR) |
| 131 |
|
| 132 |
if wrote: |
| 133 |
self._log.info("wrote thumbnail for {}", album) |
| 134 |
else: |
| 135 |
self._log.info("nothing to do for {}", album) |
| 136 |
|
| 137 |
def make_cover_thumbnail( |
| 138 |
self, album: Album, artpath: bytes, size: int, target_dir: bytes |
| 139 |
) -> bool: |
| 140 |
"""Make a thumbnail of given size for `album` and put it in |
| 141 |
`target_dir`. |
| 142 |
""" |
| 143 |
target = os.path.join(target_dir, self.thumbnail_file_name(album.path)) |
| 144 |
|
| 145 |
if ( |
| 146 |
os.path.exists(syspath(target)) |
| 147 |
and os.stat(syspath(target)).st_mtime |
| 148 |
> os.stat(syspath(artpath)).st_mtime |
| 149 |
): |
| 150 |
if self.config["force"]: |
| 151 |
self._log.debug( |
| 152 |
"found a suitable {0}x{0} thumbnail for {1}, " |
| 153 |
"forcing regeneration", |
| 154 |
size, |
| 155 |
album, |
| 156 |
) |
| 157 |
else: |
| 158 |
self._log.debug( |
| 159 |
"{0}x{0} thumbnail for {1} exists and is recent enough", |
| 160 |
size, |
| 161 |
album, |
| 162 |
) |
| 163 |
return False |
| 164 |
resized = ArtResizer.shared.resize(size, artpath, target) |
| 165 |
self.add_tags(artpath, resized) |
| 166 |
shutil.move(syspath(resized), syspath(target)) |
| 167 |
return True |
| 168 |
|
| 169 |
def thumbnail_file_name(self, path: bytes) -> bytes: |
| 170 |
"""Compute the thumbnail file name |
| 171 |
See https://standards.freedesktop.org/thumbnail-spec/latest/x227.html |
| 172 |
""" |
| 173 |
uri = self.get_uri(path) |
| 174 |
hash_ = md5(uri.encode("utf-8")).hexdigest() |
| 175 |
return bytestring_path(f"{hash_}.png") |
| 176 |
|
| 177 |
def add_tags(self, artpath: bytes, image_path: bytes) -> None: |
| 178 |
"""Write required metadata to the thumbnail |
| 179 |
See https://standards.freedesktop.org/thumbnail-spec/latest/x142.html |
| 180 |
""" |
| 181 |
mtime = os.stat(syspath(artpath)).st_mtime |
| 182 |
metadata = { |
| 183 |
"Thumb::URI": self.get_uri(artpath), |
| 184 |
"Thumb::MTime": str(mtime), |
| 185 |
} |
| 186 |
try: |
| 187 |
ArtResizer.shared.write_metadata(image_path, metadata) |
| 188 |
except Exception: |
| 189 |
self._log.exception( |
| 190 |
"could not write metadata to {}", displayable_path(image_path) |
| 191 |
) |
| 192 |
|
| 193 |
def make_dolphin_cover_thumbnail( |
| 194 |
self, album_path: bytes, artpath: bytes |
| 195 |
) -> None: |
| 196 |
outfilename = os.path.join(album_path, b".directory") |
| 197 |
if os.path.exists(syspath(outfilename)): |
| 198 |
return |
| 199 |
artfile = os.path.split(artpath)[1] |
| 200 |
with open(syspath(outfilename), "w") as f: |
| 201 |
f.write("[Desktop Entry]\n") |
| 202 |
f.write(f"Icon=./{artfile.decode('utf-8')}") |
| 203 |
f.close() |
| 204 |
self._log.debug("Wrote file {}", displayable_path(outfilename)) |
| 205 |
|
| 206 |
|
| 207 |
class URIGetter: |
| 208 |
available = False |
| 209 |
name = "Abstract base" |
| 210 |
|
| 211 |
def uri(self, path: bytes) -> str: |
| 212 |
raise NotImplementedError() |
| 213 |
|
| 214 |
|
| 215 |
class PathlibURI(URIGetter): |
| 216 |
available = True |
| 217 |
name = "Python Pathlib" |
| 218 |
|
| 219 |
def uri(self, path: bytes) -> str: |
| 220 |
return PurePosixPath(os.fsdecode(path)).as_uri() |
| 221 |
|
| 222 |
|
| 223 |
def copy_c_string(c_string: Any) -> bytes | None: |
| 224 |
"""Copy a `ctypes.POINTER(ctypes.c_char)` value into a new Python |
| 225 |
string and return it. The old memory is then safe to free. |
| 226 |
""" |
| 227 |
# This is a pretty dumb way to get a string copy, but it seems to |
| 228 |
# work. A more surefire way would be to allocate a ctypes buffer and copy |
| 229 |
# the data with `memcpy` or somesuch. |
| 230 |
return ctypes.cast(c_string, ctypes.c_char_p).value |
| 231 |
|
| 232 |
|
| 233 |
class GioURI(URIGetter): |
| 234 |
"""Use gio URI function g_file_get_uri. Paths must be utf-8 encoded.""" |
| 235 |
|
| 236 |
name = "GIO" |
| 237 |
|
| 238 |
def __init__(self) -> None: |
| 239 |
self.libgio = self.get_library() |
| 240 |
self.available = bool(self.libgio) |
| 241 |
if self.libgio: |
| 242 |
self.libgio.g_type_init() # for glib < 2.36 |
| 243 |
|
| 244 |
self.libgio.g_file_new_for_path.argtypes = [ctypes.c_char_p] |
| 245 |
self.libgio.g_file_new_for_path.restype = ctypes.c_void_p |
| 246 |
|
| 247 |
self.libgio.g_file_get_uri.argtypes = [ctypes.c_void_p] |
| 248 |
self.libgio.g_file_get_uri.restype = ctypes.POINTER(ctypes.c_char) |
| 249 |
|
| 250 |
self.libgio.g_object_unref.argtypes = [ctypes.c_void_p] |
| 251 |
|
| 252 |
def get_library(self) -> ctypes.CDLL | None: |
| 253 |
lib_name = ctypes.util.find_library("gio-2") |
| 254 |
try: |
| 255 |
if not lib_name: |
| 256 |
return None |
| 257 |
return ctypes.cdll.LoadLibrary(lib_name) |
| 258 |
except OSError: |
| 259 |
return None |
| 260 |
|
| 261 |
def uri(self, path: bytes) -> str: |
| 262 |
libgio = self.libgio |
| 263 |
if libgio is None: |
| 264 |
raise RuntimeError("GIO library is unavailable") |
| 265 |
|
| 266 |
g_file_ptr = libgio.g_file_new_for_path(path) |
| 267 |
if not g_file_ptr: |
| 268 |
raise RuntimeError( |
| 269 |
f"No gfile pointer received for {displayable_path(path)}" |
| 270 |
) |
| 271 |
|
| 272 |
try: |
| 273 |
uri_ptr = libgio.g_file_get_uri(g_file_ptr) |
| 274 |
finally: |
| 275 |
libgio.g_object_unref(g_file_ptr) |
| 276 |
if not uri_ptr: |
| 277 |
libgio.g_free(uri_ptr) |
| 278 |
raise RuntimeError( |
| 279 |
f"No URI received from the gfile pointer for {displayable_path(path)}" |
| 280 |
) |
| 281 |
|
| 282 |
try: |
| 283 |
uri = copy_c_string(uri_ptr) |
| 284 |
finally: |
| 285 |
libgio.g_free(uri_ptr) |
| 286 |
|
| 287 |
if uri is None: |
| 288 |
raise RuntimeError("GIO returned NULL for filename") |
| 289 |
|
| 290 |
try: |
| 291 |
return os.fsdecode(uri) |
| 292 |
except UnicodeDecodeError: |
| 293 |
raise RuntimeError(f"Could not decode filename from GIO: {uri!r}") |