From fa86a258703bcf945b47bde9328e39855edc6b55 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ball=C3=B3=20Gy=C3=B6rgy?= Date: Sat, 2 Nov 2024 15:32:45 +0100 Subject: [PATCH] Make sure that image can be opened Checking for file extension does not ensure that the image file can be actually opened. Check if it can be loaded into a pixbuf, and convert it if necessary. --- cartridges/store/managers/cover_manager.py | 21 ++++++++++++++++----- cartridges/utils/save_cover.py | 8 -------- 2 files changed, 16 insertions(+), 13 deletions(-) diff --git a/cartridges/store/managers/cover_manager.py b/cartridges/store/managers/cover_manager.py index d5cbd194..28b4e1ba 100644 --- a/cartridges/store/managers/cover_manager.py +++ b/cartridges/store/managers/cover_manager.py @@ -19,10 +19,10 @@ # SPDX-License-Identifier: GPL-3.0-or-later from pathlib import Path -from typing import NamedTuple +from typing import NamedTuple, Optional import requests -from gi.repository import GdkPixbuf, Gio +from gi.repository import GdkPixbuf, Gio, GLib from requests.exceptions import HTTPError, SSLError from cartridges import shared @@ -128,9 +128,20 @@ def composite_cover( """ # Load source image - source = GdkPixbuf.Pixbuf.new_from_file( - str(convert_cover(image_path, resize=False)) - ) + try: + source = GdkPixbuf.Pixbuf.new_from_file( + str(image_path) + ) + except GLib.Error: + new_path = convert_cover(image_path, resize=False) + + if new_path: + source = GdkPixbuf.Pixbuf.new_from_file( + str(new_path) + ) + else: + return None + source_size = ImageSize(source.get_width(), source.get_height()) cover_size = ImageSize._make(shared.image_size) diff --git a/cartridges/utils/save_cover.py b/cartridges/utils/save_cover.py index 38c414ba..ac3fb92a 100644 --- a/cartridges/utils/save_cover.py +++ b/cartridges/utils/save_cover.py @@ -35,14 +35,6 @@ def convert_cover( if not cover_path and not pixbuf: return None - pixbuf_extensions = set() - for pixbuf_format in GdkPixbuf.Pixbuf.get_formats(): - for pixbuf_extension in pixbuf_format.get_extensions(): - pixbuf_extensions.add(pixbuf_extension) - - if not resize and cover_path and cover_path.suffix.lower()[1:] in pixbuf_extensions: - return cover_path - try: with Image.open(cover_path) as image: if getattr(image, "is_animated", False):