Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Fetch product media images asynchronously (#18971)
Marcin Wcisło114553593e43
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c3d4cfbb6e..f223cda08a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -28,6 +28,7 @@ All notable, unreleased changes to this project will be documented in this file.Important: digital products are still fully supported in Saleor. Only the legacy,undocumented digital content API has been removed, the supported approach is documented here: https://docs.saleor.io/recipes/digital-products+- Product media images from external URLs are now fetched asynchronously via background tasks in `productMediaCreate` and `productBulkCreate` mutations, improving response times. During download, the API returns HTTP 503 for the media image.### GraphQL APIdiff --git a/saleor/core/utils/__init__.py b/saleor/core/utils/__init__.pyindex 222ac50395..88e031c8c4 100644--- a/saleor/core/utils/__init__.py+++ b/saleor/core/utils/__init__.py@@ -1,13 +1,16 @@import socketfrom collections.abc import Iterable+from io import BytesIOfrom typing import TYPE_CHECKINGfrom urllib.parse import urljoin, urlparsefrom django.conf import settingsfrom django.contrib.sites.models import Site+from django.core.files import Filefrom django.db.models import Modelfrom django.utils.encoding import iri_to_urifrom django.utils.text import slugify+from requests import Responsefrom text_unidecode import unidecodeif TYPE_CHECKING:@@ -150,3 +153,19 @@ def prepare_unique_attribute_value_slug(attribute: "Attribute", slug: str):"slug", flat=True)return prepare_unique_slug(slug, value_slugs)+++def create_file_from_response(response: Response, filename: str) -> File:+ """Create a Django File object from an HTTP response.++ HTTP response should contain the file content. Response should use streaming.+ https://requests.readthedocs.io/en/latest/user/advanced/#body-content-workflow+ """+ # Create a BytesIO object to store the file content+ file_data = BytesIO()+ # Write the response content to the BytesIO object+ file_data.write(response.content)+ # Move the cursor to the beginning of the BytesIO object+ file_data.seek(0)+ # Create a Django File object from the BytesIO object+ return File(file_data, filename)diff --git a/saleor/core/utils/tests/test_validators.py b/saleor/core/utils/tests/test_validators.pynew file mode 100644index 0000000000..5de526f3aa--- /dev/null+++ b/saleor/core/utils/tests/test_validators.py@@ -0,0 +1,68 @@+import pytest++from ..validators import get_mime_type, is_image_mimetype, is_valid_image_content_type+++def test_is_image_mimetype_valid_mimetype():+ # given+ valid_mimetype = "image/jpeg"++ # when+ result = is_image_mimetype(valid_mimetype)++ # then+ assert result+++def test_is_image_mimetype_invalid_mimetype():+ # given+ invalid_mimetype = "application/javascript"++ # when+ result = is_image_mimetype(invalid_mimetype)++ # then+ assert not result+++ ("content_type", "is_valid"),+ [+ ("image/jpeg", True),+ ("image/jpg", True),+ ("image/png", True),+ ("image/gif", True),+ ("image/bmp", True),+ ("image/tiff", True),+ ("image/webp", True),+ ("image/avif", True),+ ("image/svg+xml", False),+ ("application/json", False),+ ("text/plain", False),+ ("application/pdf", False),+ (None, False),+ ],+)+def test_is_valid_image_content_type(content_type, is_valid):+ # when+ result = is_valid_image_content_type(content_type)++ # then+ assert result == is_valid+++ ("content_type_header", "expected_mime_type"),+ [+ (None, None),+ ("", ""),+ ("text/html; charset=utf-8", "text/html"),+ ("text/css; charset=UTF-8", "text/css"),+ ("image/jpeg", "image/jpeg"),+ (" image/png; charset=binary", "image/png"),+ (" Text/HTML ; Charset=UTF-8 ", "text/html"),+ ("APPLICATION/JSON;CHARSET=UTF-8", "application/json"),+ ],+)+def test_get_mime_type(content_type_header, expected_mime_type):+ assert get_mime_type(content_type_header) == expected_mime_typediff --git a/saleor/core/utils/validators.py b/saleor/core/utils/validators.pyindex c2d3d5b604..94f17ef41b 100644--- a/saleor/core/utils/validators.py+++ b/saleor/core/utils/validators.py@@ -30,3 +30,23 @@ def get_oembed_data(url: str) -> tuple[dict[str, Any], str]:def is_date_in_future(given_date):"""Return true when the date is in the future."""return given_date > datetime.datetime.now(tz=datetime.UTC).date()+++def get_mime_type(content_type_header: str | None) -> str | None:+ if content_type_header is None:+ return None+ return content_type_header.split(";", maxsplit=1)[0].strip().lower()+++def is_image_mimetype(mimetype: str | None) -> bool:+ """Check if mimetype is image."""+ if mimetype is None:+ return False+ return mimetype.startswith("image/")+++def is_valid_image_content_type(content_type: str | None) -> bool:+ """Check if content type is a valid image content type."""+ from ...thumbnail import MIME_TYPE_TO_PIL_IDENTIFIER++ return content_type is not None and content_type in MIME_TYPE_TO_PIL_IDENTIFIERdiff --git a/saleor/graphql/core/tests/test_file_validation.py b/saleor/graphql/core/tests/test_file_validation.pyindex be999bc824..250b89d6a1 100644--- a/saleor/graphql/core/tests/test_file_validation.py+++ b/saleor/graphql/core/tests/test_file_validation.py@@ -11,36 +11,11 @@ from ....product.error_codes import ProductErrorCodefrom ..validators.file import (clean_image_file,detect_mime_type,- get_mime_type,- is_image_mimetype,is_supported_image_mimetype,- is_valid_image_content_type,validate_upload_file,)-def test_is_image_mimetype_valid_mimetype():- # given- valid_mimetype = "image/jpeg"-- # when- result = is_image_mimetype(valid_mimetype)-- # then- assert result---def test_is_image_mimetype_invalid_mimetype():- # given- invalid_mimetype = "application/javascript"-- # when- result = is_image_mimetype(invalid_mimetype)-- # then- assert not result--def test_is_supported_image_mimetype_valid_mimetype():# givenvalid_mimetype = "image/jpeg"@@ -63,31 +38,6 @@ def test_is_supported_image_mimetype_invalid_mimetype():assert not result- ("content_type", "is_valid"),- [- ("image/jpeg", True),- ("image/jpg", True),- ("image/png", True),- ("image/gif", True),- ("image/bmp", True),- ("image/tiff", True),- ("image/webp", True),- ("image/avif", True),- ("application/json", False),- ("text/plain", False),- ("application/pdf", False),- (None, False),- ],-)-def test_is_valid_image_content_type(content_type, is_valid):- # when- result = is_valid_image_content_type(content_type)-- # then- assert result == is_valid--def test_clean_image_file():# givenimg_data = BytesIO()@@ -274,23 +224,6 @@ def test_clean_image_file_in_avif_format():clean_image_file({field: img}, field, ProductErrorCode)- ("content_type_header", "expected_mime_type"),- [- (None, None),- ("", ""),- ("text/html; charset=utf-8", "text/html"),- ("text/css; charset=UTF-8", "text/css"),- ("image/jpeg", "image/jpeg"),- (" image/png; charset=binary", "image/png"),- (" Text/HTML ; Charset=UTF-8 ", "text/html"),- ("APPLICATION/JSON;CHARSET=UTF-8", "application/json"),- ],-)-def test_get_mime_type(content_type_header, expected_mime_type):- assert get_mime_type(content_type_header) == expected_mime_type--@pytest.mark.parametrize(("filename", "mime_type"),[diff --git a/saleor/graphql/core/utils/__init__.py b/saleor/graphql/core/utils/__init__.pyindex 7ba8f65f4f..aa00fbaba7 100644--- a/saleor/graphql/core/utils/__init__.py+++ b/saleor/graphql/core/utils/__init__.py@@ -2,16 +2,13 @@ import binasciiimport osimport secretsfrom dataclasses import dataclass-from io import BytesIOfrom typing import Literal, NoReturn, overloadimport graphenefrom django.conf import settingsfrom django.core.exceptions import ValidationError-from django.core.files import Filefrom graphene import ObjectTypefrom graphql import GraphQLError-from requests import Responsefrom ....plugins.const import APP_ID_PREFIXfrom ....thumbnail import FILE_NAME_MAX_LENGTH@@ -172,22 +169,6 @@ def message_webhook_events(webhook_events: list[WebhookEventInfo]) -> str:return description-def create_file_from_response(response: Response, filename: str) -> File:- """Create a Django File object from an HTTP response.-- HTTP response should contain the file content. Response should use streaming.- https://requests.readthedocs.io/en/latest/user/advanced/#body-content-workflow- """- # Create a BytesIO object to store the file content- file_data = BytesIO()- # Write the response content to the BytesIO object- file_data.write(response.content)- # Move the cursor to the beginning of the BytesIO object- file_data.seek(0)- # Create a Django File object from the BytesIO object- return File(file_data, filename)--def validate_and_apply_search_rank_sorting(kwargs: dict,rank_sort_field,diff --git a/saleor/graphql/core/validators/file.py b/saleor/graphql/core/validators/file.pyindex 7a909e86e2..fb87dfa397 100644--- a/saleor/graphql/core/validators/file.py+++ b/saleor/graphql/core/validators/file.py@@ -87,19 +87,6 @@ def detect_mime_type(file_data) -> str:return mime_type-def get_mime_type(content_type_header: str | None) -> str | None:- if content_type_header is None:- return None- return content_type_header.split(";", maxsplit=1)[0].strip().lower()---def is_image_mimetype(mimetype: str | None) -> bool:- """Check if mimetype is image."""- if mimetype is None:- return False- return mimetype.startswith("image/")--def is_supported_image_mimetype(mimetype: str) -> bool:"""Check if mimetype is a mimetype that thumbnails support."""if mimetype is None:@@ -107,11 +94,6 @@ def is_supported_image_mimetype(mimetype: str) -> bool:return mimetype in MIME_TYPE_TO_PIL_IDENTIFIER.keys()-def is_valid_image_content_type(content_type: str | None) -> bool:- """Check if content type is a valid image content type."""- return content_type is not None and is_supported_image_mimetype(content_type)--def clean_image_file(cleaned_input, img_field_name, error_class):"""Extract and clean uploaded image file.diff --git a/saleor/graphql/product/bulk_mutations/product_bulk_create.py b/saleor/graphql/product/bulk_mutations/product_bulk_create.pyindex 16a0b579d2..df11795491 100644--- a/saleor/graphql/product/bulk_mutations/product_bulk_create.py+++ b/saleor/graphql/product/bulk_mutations/product_bulk_create.py@@ -2,25 +2,22 @@ import datetimefrom collections import defaultdictimport graphene-from django.conf import settingsfrom django.core.exceptions import ValidationError+from django.db import transactionfrom django.db.models import Ffrom django.utils.text import slugifyfrom graphene.utils.str_converters import to_camel_casefrom text_unidecode import unidecode-from ....core.exceptions import UnsupportedMediaProviderException-from ....core.http_client import HTTPClientfrom ....core.tracing import traced_atomic_transactionfrom ....core.utils import prepare_unique_slugfrom ....core.utils.editorjs import clean_editor_js-from ....core.utils.validators import get_oembed_datafrom ....discount.utils.promotion import mark_active_catalogue_promotion_rules_as_dirtyfrom ....permission.enums import ProductPermissionsfrom ....product import ProductMediaTypes, modelsfrom ....product.error_codes import ProductBulkCreateErrorCodefrom ....product.models import CollectionProduct-from ....thumbnail.utils import get_filename_from_url+from ....product.tasks import fetch_product_media_image_taskfrom ....warehouse.models import Warehousefrom ....webhook.event_types import WebhookEventAsyncTypefrom ....webhook.utils import get_webhooks_for_event@@ -41,19 +38,14 @@ from ...core.types import (ProductBulkCreateError,SeoInput,)-from ...core.utils import create_file_from_response, get_duplicated_values+from ...core.utils import get_duplicated_valuesfrom ...core.validators import clean_seo_fields-from ...core.validators.file import (- clean_image_file,- get_mime_type,- is_image_mimetype,- is_valid_image_content_type,-)+from ...core.validators.file import clean_image_filefrom ...meta.inputs import MetadataInput, MetadataInputDescriptionfrom ...plugins.dataloaders import get_plugin_manager_promisefrom ..mutations.product.product_create import ProductCreateInputfrom ..types import Product-from ..utils import ALT_CHAR_LIMIT+from ..utils import probe_media_url, validate_media_inputfrom .product_variant_bulk_create import (ProductVariantBulkCreate,ProductVariantBulkCreateInput,@@ -440,40 +432,23 @@ class ProductBulkCreate(BaseMutation):for index, media_input in enumerate(media_inputs):image = media_input.get("image")media_url = media_input.get("media_url")- # Replace null alt value with an empty string to satisfy DB constraintsalt = media_input.get("alt") or ""- media_input["alt"] = alt- if not image and not media_url:+ if error := validate_media_input(+ image, media_url, alt, ProductBulkCreateErrorCode+ ):+ error_message, error_code, field = error+ path = f"media.{index}.{field}" if field else f"media.{index}"index_error_map[product_index].append(ProductBulkCreateError(- path=f"media.{index}",- message="Image or external URL is required.",- code=ProductBulkCreateErrorCode.REQUIRED.value,- )- )- continue-- if image and media_url:- index_error_map[product_index].append(- ProductBulkCreateError(- path=f"media.{index}",- message="Either image or external URL is required.",- code=ProductBulkCreateErrorCode.DUPLICATED_INPUT_ITEM.value,+ path=path,+ message=error_message,+ code=error_code,))continue- if alt and len(alt) > ALT_CHAR_LIMIT:- index_error_map[product_index].append(- ProductBulkCreateError(- path=f"media.{index}.alt",- message=f"Alt field exceeds the character "- f"limit of {ALT_CHAR_LIMIT}.",- code=ProductBulkCreateErrorCode.INVALID.value,- )- )- continue+ media_input["alt"] = altif image:media_input["image"] = info.context.FILES.get(image)@@ -488,56 +463,24 @@ class ProductBulkCreate(BaseMutation):)continueelif media_url:- with HTTPClient.send_request(- "GET",- media_url,- stream=True,- allow_redirects=False,- timeout=settings.COMMON_REQUESTS_TIMEOUT,- ) as image_data:- mime_type = get_mime_type(image_data.headers.get("content-type"))- if is_image_mimetype(mime_type):- if is_valid_image_content_type(mime_type):- filename = get_filename_from_url(media_url, mime_type)- image_file = create_file_from_response(image_data, filename)- media_input["image"] = image_file- media_to_create.append(media_input)- else:- validation_error = ValidationError(- {- "media_url": ValidationError(- "Invalid file type.",- code=ProductBulkCreateErrorCode.INVALID.value,- )- }- )- cls.add_indexes_to_errors(- product_index,- validation_error,- index_error_map,- f"media.{index}",- )- continuetry:- oembed_data, supported_media_type = get_oembed_data(media_url)- oembed_data["supported_media_type"] = supported_media_type- except UnsupportedMediaProviderException as exc:- validation_error = ValidationError(- {- "media_url": ValidationError(- exc.message,- code=ProductBulkCreateErrorCode.UNSUPPORTED_MEDIA_PROVIDER.value,- )- }+ probe_result = probe_media_url(+ media_url, ProductBulkCreateErrorCode)+ except ValidationError as exc:cls.add_indexes_to_errors(product_index,- validation_error,+ exc,index_error_map,f"media.{index}",)continue- media_input["oembed_data"] = oembed_data+ if probe_result.is_image:+ media_input["external_url"] = media_url+ else:+ oembed_data = probe_result.oembed_data+ oembed_data["supported_media_type"] = probe_result.media_type+ media_input["oembed_data"] = oembed_datamedia_to_create.append(media_input)return media_to_create@@ -870,6 +813,9 @@ class ProductBulkCreate(BaseMutation):models.Product.objects.bulk_create(products_to_create)models.ProductMedia.objects.bulk_create(media_to_create)+ transaction.on_commit(+ lambda: cls.schedule_fetch_product_media_image_tasks(media_to_create)+ )models.ProductChannelListing.objects.bulk_create(listings_to_create)for product, attributes in attributes_to_save:@@ -880,6 +826,20 @@ class ProductBulkCreate(BaseMutation):return variants, updated_channels+ @classmethod+ def schedule_fetch_product_media_image_tasks(cls, media_to_create):+ """Schedule a task for each ProductMedia object that was created, has external URL set but has no image set yet."""+ media_to_fetch = (+ product_media+ for product_media in media_to_create+ if product_media.type == ProductMediaTypes.IMAGE+ and not product_media.image+ and product_media.external_url+ )++ for product_media in media_to_fetch:+ fetch_product_media_image_task.delay(product_media.pk)+@classmethoddef _save_m2m(cls, _info, instances_data):product_collections = []@@ -935,6 +895,17 @@ class ProductBulkCreate(BaseMutation):type=ProductMediaTypes.IMAGE,))+ elif not media_input.get("image") and media_input.get("external_url"):+ media_to_create.append(+ models.ProductMedia(+ external_url=media_input["external_url"],+ image=None,+ alt=alt,+ product=product,+ type=ProductMediaTypes.IMAGE,+ )+ )+if oembed_data := media_input.get("oembed_data"):media_to_create.append(models.ProductMedia(diff --git a/saleor/graphql/product/mutations/product/product_media_create.py b/saleor/graphql/product/mutations/product/product_media_create.pyindex b45449beb1..f104b64dac 100644--- a/saleor/graphql/product/mutations/product/product_media_create.py+++ b/saleor/graphql/product/mutations/product/product_media_create.py@@ -1,29 +1,19 @@import graphene-from django.conf import settingsfrom django.core.exceptions import ValidationError-from .....core.exceptions import UnsupportedMediaProviderException-from .....core.http_client import HTTPClient-from .....core.utils.validators import get_oembed_datafrom .....permission.enums import ProductPermissionsfrom .....product import ProductMediaTypes, modelsfrom .....product.error_codes import ProductErrorCode-from .....thumbnail.utils import get_filename_from_url+from .....product.tasks import fetch_product_media_image_taskfrom ....core import ResolveInfofrom ....core.context import ChannelContextfrom ....core.doc_category import DOC_CATEGORY_PRODUCTSfrom ....core.mutations import BaseMutationfrom ....core.types import BaseInputObjectType, ProductError, Upload-from ....core.utils import create_file_from_response-from ....core.validators.file import (- clean_image_file,- get_mime_type,- is_image_mimetype,- is_valid_image_content_type,-)+from ....core.validators.file import clean_image_filefrom ....plugins.dataloaders import get_plugin_manager_promisefrom ...types import Product, ProductMedia-from ...utils import ALT_CHAR_LIMIT+from ...utils import probe_media_url, validate_media_inputclass ProductMediaCreateInput(BaseInputObjectType):@@ -64,45 +54,38 @@ class ProductMediaCreate(BaseMutation):error_type_field = "product_errors"@classmethod- def validate_input(cls, data):- image = data.get("image")- media_url = data.get("media_url")- alt = data.get("alt")-- if not image and not media_url:+ def validate_input(cls, input):+ if not input.get("product"):raise ValidationError({- "input": ValidationError(- "Image or external URL is required.",+ "product": ValidationError(+ "Product ID is required.",code=ProductErrorCode.REQUIRED.value,)})- if image and media_url:- raise ValidationError(- {- "input": ValidationError(- "Either image or external URL is required.",- code=ProductErrorCode.DUPLICATED_INPUT_ITEM.value,- )- }- )- if alt and len(alt) > ALT_CHAR_LIMIT:+ @classmethod+ def perform_mutation( # type: ignore[override]+ cls, _root, info: ResolveInfo, /, *, input+ ):+ cls.validate_input(input)++ image = input.get("image")+ media_url = input.get("media_url")+ alt = input.get("alt") or ""++ if error := validate_media_input(image, media_url, alt, ProductErrorCode):+ error_message, error_code, _ = errorraise ValidationError({"input": ValidationError(- f"Alt field exceeds the character limit of {ALT_CHAR_LIMIT}.",- code=ProductErrorCode.INVALID.value,+ error_message,+ code=error_code,)})- @classmethod- def perform_mutation( # type: ignore[override]- cls, _root, info: ResolveInfo, /, *, input- ):- cls.validate_input(input)product = cls.get_node_or_error(info,input["product"],@@ -111,63 +94,31 @@ class ProductMediaCreate(BaseMutation):qs=models.Product.objects.all(),)- # Replace null alt value with an empty string to satisfy DB constraints- alt = input.get("alt") or ""- media_url = input.get("media_url")media = None- if img_data := input.get("image"):- input["image"] = info.context.FILES.get(img_data)+ if image:+ input["image"] = info.context.FILES.get(image)image_data = clean_image_file(input, "image", ProductErrorCode)media = product.media.create(image=image_data, alt=alt, type=ProductMediaTypes.IMAGE)- if media_url:+ elif media_url:# Remote URLs can point to the images or oembed data.- # In case of images, file is downloaded. Otherwise we keep only- # URL to remote media.- with HTTPClient.send_request(- "GET",- media_url,- stream=True,- allow_redirects=False,- timeout=settings.COMMON_REQUESTS_TIMEOUT,- ) as image_data:- mime_type = get_mime_type(image_data.headers.get("content-type"))- if is_image_mimetype(mime_type):- if not is_valid_image_content_type(mime_type):- raise ValidationError(- {- "media_url": ValidationError(- "Invalid file type.",- code=ProductErrorCode.INVALID.value,- )- }- )- filename = get_filename_from_url(media_url, mime_type)- image_file = create_file_from_response(image_data, filename)- media = product.media.create(- image=image_file,- alt=alt,- type=ProductMediaTypes.IMAGE,- )- if media is None:- try:- oembed_data, media_type = get_oembed_data(- media_url,- )- except UnsupportedMediaProviderException as exc:- raise ValidationError(- {- "media_url": ValidationError(- exc.message,- code=ProductErrorCode.UNSUPPORTED_MEDIA_PROVIDER.value,- )- }- ) from exc+ # In case of images, the image is fetched asynchronously by a task.+ # Otherwise we keep only URL to remote media.+ probe_result = probe_media_url(media_url, ProductErrorCode)+ if probe_result.is_image:+ media = product.media.create(+ external_url=media_url,+ alt=alt,+ type=ProductMediaTypes.IMAGE,+ )+ fetch_product_media_image_task.delay(media.pk)+ else:+ oembed_data = probe_result.oembed_datamedia = product.media.create(external_url=oembed_data["url"],alt=oembed_data.get("title", alt),- type=media_type,+ type=probe_result.media_type,oembed_data=oembed_data,)manager = get_plugin_manager_promise(info.context).get()diff --git a/saleor/graphql/product/tests/mutations/test_product_bulk_create.py b/saleor/graphql/product/tests/mutations/test_product_bulk_create.pyindex b713ae765c..a7fe7835a4 100644--- a/saleor/graphql/product/tests/mutations/test_product_bulk_create.py+++ b/saleor/graphql/product/tests/mutations/test_product_bulk_create.py@@ -9,6 +9,9 @@ import grapheneimport PILimport pytestfrom measurement.measures import Weight+from requests import RequestException+from requests.exceptions import InvalidSchema+from requests_hardened.ip_filter import InvalidIPAddressfrom .....attribute.tests.model_helpers import (get_product_attribute_values,@@ -985,7 +988,7 @@ def test_product_bulk_create_with_media_image_with_invalid_exif(assert len(error_1) == 1-@patch("saleor.graphql.product.bulk_mutations.product_bulk_create.HTTPClient")+@patch("saleor.graphql.product.utils.HTTPClient")@pytest.mark.vcrdef test_product_bulk_create_with_media_with_media_url(mock_HTTPClient,@@ -1084,9 +1087,9 @@ def test_product_bulk_create_with_media_with_media_url()-@patch("saleor.graphql.product.bulk_mutations.product_bulk_create.HTTPClient")+@patch("saleor.graphql.product.utils.HTTPClient")@patch(- "saleor.graphql.product.bulk_mutations.product_bulk_create.get_oembed_data",+ "saleor.graphql.product.utils.get_oembed_data",)def test_product_bulk_create_with_media_with_media_url_invalid_provider(mocked_get_oembed_data,@@ -1152,7 +1155,7 @@ def test_product_bulk_create_with_media_with_media_url_invalid_provider(return_value=False,)@patch(- "saleor.graphql.product.bulk_mutations.product_bulk_create.HTTPClient",+ "saleor.graphql.product.utils.HTTPClient",)def test_product_bulk_create_with_media_with_media_url_invalid_image_type(mocked_http_client,@@ -1216,7 +1219,7 @@ def test_product_bulk_create_with_media_with_media_url_invalid_image_type(assert len(error_1) == 1-@patch("saleor.graphql.product.bulk_mutations.product_bulk_create.HTTPClient")+@patch("saleor.graphql.product.utils.HTTPClient")def test_product_bulk_create_with_media_invalid_image_file_fetch_only_header(mock_HTTPClient,staff_api_client,@@ -1271,8 +1274,12 @@ def test_product_bulk_create_with_media_invalid_image_file_fetch_only_header(assert len(error_1) == 1+@patch(+ "saleor.graphql.product.bulk_mutations.product_bulk_create.fetch_product_media_image_task.delay"+)@pytest.mark.vcrdef test_product_bulk_create_with_media_image_file_is_fetched_only_once(+ mock_fetch_product_media_image_task,staff_api_client,product_type,category,@@ -1318,27 +1325,21 @@ def test_product_bulk_create_with_media_image_file_is_fetched_only_once(assert data["results"][0]["product"]["media"][0]["alt"] == altassert data["results"][0]["product"]["media"][0]["url"] != url- # Validate the image fileproduct = Product.objects.first()product_image = product.media.last()- assert product_image.image.file- img_name, format = os.path.splitext(expected_file_name)- file_name = product_image.image.name- assert file_name != expected_file_name- assert file_name.startswith(f"products/{img_name}")- assert file_name.endswith(format)-- # Open the image and validate its content- image_path = product_image.image.path- with PIL.Image.open(image_path) as img:- assert img.format == "PNG" # Ensure the image format is PNG- assert img.size[0] > 0 # Ensure the image has dimensions- assert img.size[1] > 0 # Ensure the image has dimensions---@patch("saleor.graphql.product.bulk_mutations.product_bulk_create.HTTPClient")++ assert bool(product_image.image) is False+ assert product_image.external_url is not None+ mock_fetch_product_media_image_task.assert_called_once_with(product_image.pk)+++@patch(+ "saleor.graphql.product.bulk_mutations.product_bulk_create.fetch_product_media_image_task.delay"+)+@patch("saleor.graphql.product.utils.HTTPClient")def test_product_bulk_create_with_no_extension_media_url(mock_HTTPClient,+ mock_fetch_product_media_image_task,staff_api_client,product_type,category,@@ -1377,13 +1378,12 @@ def test_product_bulk_create_with_no_extension_media_url(# thenassert not content["results"][0]["errors"]- # validate image file_, product_id = graphene.Node.from_global_id(content["results"][0]["product"]["id"])product_image = Product.objects.get(id=product_id).media.first()- assert product_image.image.name.startswith("products/image-path_")- assert product_image.image.name.endswith(".png")- with product_image.image.open("rb") as img:- assert img.read() == image_content++ assert bool(product_image.image) is False+ assert product_image.external_url is not None+ mock_fetch_product_media_image_task.assert_called_once_with(product_image.pk)def test_product_bulk_create_with_attributes(@@ -3316,7 +3316,7 @@ def test_product_bulk_create_with_media_when_alt_is_null(assert content["results"][0]["product"]["media"][0]["alt"] == ""-@patch("saleor.graphql.product.bulk_mutations.product_bulk_create.HTTPClient")+@patch("saleor.graphql.product.utils.HTTPClient")def test_product_bulk_create_with_media_url_when_alt_is_null(mock_HTTPClient,staff_api_client,@@ -3356,3 +3356,52 @@ def test_product_bulk_create_with_media_url_when_alt_is_null(# thenassert not content["results"][0]["errors"]assert content["results"][0]["product"]["media"][0]["alt"] == ""+++ "exception",+ [+ RequestException("Connection refused"),+ InvalidIPAddress("10.0.0.1"),+ InvalidSchema("No adapters found for url"),+ ],+)+@patch("saleor.graphql.product.utils.HTTPClient")+def test_product_bulk_create_with_media_url_request_exception(+ mock_HTTPClient,+ exception,+ staff_api_client,+ product_type,+ permission_manage_products,+):+ # given+ mock_HTTPClient.send_request.side_effect = exception+ products = [+ {+ "productType": graphene.Node.to_global_id("ProductType", product_type.pk),+ "name": "test name 1",+ "media": [+ {+ "alt": "some media",+ "mediaUrl": "https://www.example.com/image.jpg",+ }+ ],+ },+ ]++ # when+ response = staff_api_client.post_graphql(+ PRODUCT_BULK_CREATE_MUTATION,+ {"products": products},+ permissions=[permission_manage_products],+ )+ content = get_graphql_content(response)+ data = content["data"]["productBulkCreate"]++ # then+ assert data["count"] == 0+ assert len(data["results"][0]["errors"]) == 1+ error = data["results"][0]["errors"][0]+ assert error["code"] == ProductBulkCreateErrorCode.INVALID.name+ assert error["path"] == "media.0.mediaUrl"+ assert error["message"] == "Failed to fetch media from URL."diff --git a/saleor/graphql/product/tests/mutations/test_product_media_create.py b/saleor/graphql/product/tests/mutations/test_product_media_create.pyindex bb3737f837..caa338117d 100644--- a/saleor/graphql/product/tests/mutations/test_product_media_create.py+++ b/saleor/graphql/product/tests/mutations/test_product_media_create.py@@ -1,13 +1,13 @@import jsonimport os-from io import BytesIOfrom unittest.mock import Mock, patchimport graphene-import PILimport pytestfrom django.conf import settings-from PIL import Image+from requests import RequestException+from requests.exceptions import InvalidSchema+from requests_hardened.ip_filter import InvalidIPAddressfrom .....graphql.tests.utils import get_graphql_content, get_multipart_request_bodyfrom .....product import ProductMediaTypes@@ -38,6 +38,7 @@ PRODUCT_MEDIA_CREATE_QUERY = """errors {codefield+ message}}}@@ -109,7 +110,7 @@ def test_product_media_create_mutation_without_file(assert errors[0]["code"] == ProductErrorCode.REQUIRED.name-@patch("saleor.graphql.product.mutations.product.product_media_create.HTTPClient")+@patch("saleor.graphql.product.utils.HTTPClient")@pytest.mark.vcrdef test_product_media_create_mutation_with_media_url(mock_HTTPClient, staff_api_client, product, permission_manage_products, media_root@@ -204,7 +205,7 @@ def test_product_media_create_mutation_with_both_url_and_image(assert errors[0]["field"] == "input"-@patch("saleor.graphql.product.mutations.product.product_media_create.HTTPClient")+@patch("saleor.graphql.product.utils.HTTPClient")def test_product_media_create_mutation_with_unknown_url(mock_HTTPClient, staff_api_client, product, permission_manage_products, media_root):@@ -274,7 +275,7 @@ def test_invalid_product_media_create_mutation(assert product.media.count() == 0-@patch("saleor.graphql.product.mutations.product.product_media_create.HTTPClient")+@patch("saleor.graphql.product.utils.HTTPClient")def test_product_media_create_mutation_invalid_image_file_fetch_only_header(mock_HTTPClient, staff_api_client, product, permission_manage_products):@@ -322,9 +323,16 @@ def test_product_media_create_mutation_invalid_image_file_fetch_only_header(mock_response.headers.get.assert_called_once_with("content-type")+@patch(+ "saleor.graphql.product.mutations.product.product_media_create.fetch_product_media_image_task.delay"+)@pytest.mark.vcrdef test_product_media_create_mutation_valid_image_file_is_fetched_once(- staff_api_client, product, permission_manage_products, media_root+ mock_fetch_product_media_image_task,+ staff_api_client,+ product,+ permission_manage_products,+ media_root,):# givenexpected_file_name = "icon-dark.png"@@ -348,40 +356,33 @@ def test_product_media_create_mutation_valid_image_file_is_fetched_once(# thendata = content["data"]["productMediaCreate"]assert data["errors"] == []- assert data["product"]["media"][0]["url"] is not Noneassert data["product"]["media"][0]["type"] == ProductMediaTypes.IMAGEassert data["product"]["media"][0]["alt"] == expected_alt+ assert data["product"]["media"][0]["url"] != url- # Validate the image fileproduct.refresh_from_db()product_image = product.media.last()- assert product_image.image.file- img_name, format = os.path.splitext(expected_file_name)- file_name = product_image.image.name- assert file_name != expected_file_name- assert file_name.startswith(f"products/{img_name}")- assert file_name.endswith(format)- # Open the image and validate its content- image_path = product_image.image.path- with Image.open(image_path) as img:- assert img.format == "PNG" # Ensure the image format is PNG- assert img.size[0] > 0 # Ensure the image has dimensions- assert img.size[1] > 0 # Ensure the image has dimensions+ assert bool(product_image.image) is False+ assert product_image.external_url is not None+ mock_fetch_product_media_image_task.assert_called_once_with(product_image.pk)-@patch("saleor.graphql.product.mutations.product.product_media_create.HTTPClient")+@patch(+ "saleor.graphql.product.mutations.product.product_media_create.fetch_product_media_image_task.delay"+)+@patch("saleor.graphql.product.utils.HTTPClient")def test_product_media_create_mutation_with_no_extension_media_url(- mock_HTTPClient, staff_api_client, product, permission_manage_products, media_root+ mock_HTTPClient,+ mock_fetch_product_media_image_task,+ staff_api_client,+ product,+ permission_manage_products,+ media_root,):# givenmock_response = Mock()mock_response.headers.get = Mock(return_value="image/png")- # generate PNG image content- image_content = BytesIO()- PIL.Image.new("RGB", size=(100, 100)).save(image_content, format="PNG")- image_content = image_content.read()- mock_response.content = image_contentmock_HTTPClient.send_request.return_value.__enter__.return_value = mock_responsevariables = {"product": graphene.Node.to_global_id("Product", product.id),@@ -400,12 +401,11 @@ def test_product_media_create_mutation_with_no_extension_media_url(# thenassert not content["errors"]- # validate image fileproduct_image = product.media.last()- assert product_image.image.name.startswith("products/image-path_")- assert product_image.image.name.endswith(".png")- with product_image.image.open("rb") as img:- assert img.read() == image_content++ assert bool(product_image.image) is False+ assert product_image.external_url is not None+ mock_fetch_product_media_image_task.assert_called_once_with(product_image.pk)def test_product_media_create_mutation_alt_character_limit(@@ -464,9 +464,17 @@ def test_product_media_create_when_alt_is_null(assert content["product"]["media"][0]["alt"] == ""-@patch("saleor.graphql.product.mutations.product.product_media_create.HTTPClient")+@patch(+ "saleor.graphql.product.mutations.product.product_media_create.fetch_product_media_image_task.delay"+)+@patch("saleor.graphql.product.utils.HTTPClient")def test_product_media_create_with_media_url_when_alt_is_null(- mock_HTTPClient, staff_api_client, product, permission_manage_products, media_root+ mock_HTTPClient,+ mock_fetch_product_media_image_task,+ staff_api_client,+ product,+ permission_manage_products,+ media_root,):# givenimage_file, _ = create_image()@@ -492,3 +500,70 @@ def test_product_media_create_with_media_url_when_alt_is_null(# thenassert not content["errors"]assert content["product"]["media"][0]["alt"] == ""++ product_media = product.media.last()+ mock_fetch_product_media_image_task.assert_called_once_with(product_media.pk)+++ "exception",+ [+ RequestException("Connection refused"),+ InvalidIPAddress("10.0.0.1"),+ InvalidSchema("No adapters found for url"),+ ],+)+@patch("saleor.graphql.product.utils.HTTPClient")+def test_product_media_create_mutation_request_exception(+ mock_HTTPClient,+ exception,+ staff_api_client,+ product,+ permission_manage_products,+):+ # given+ mock_HTTPClient.send_request.side_effect = exception+ variables = {+ "product": graphene.Node.to_global_id("Product", product.id),+ "mediaUrl": "https://www.example.com/image.jpg",+ "alt": "some media",+ }++ # when+ response = staff_api_client.post_graphql(+ PRODUCT_MEDIA_CREATE_QUERY,+ variables=variables,+ permissions=[permission_manage_products],+ )+ content = get_graphql_content(response)++ # then+ assert len(content["data"]["productMediaCreate"]["errors"]) == 1+ error = content["data"]["productMediaCreate"]["errors"][0]+ assert error["code"] == ProductErrorCode.INVALID.name+ assert error["field"] == "mediaUrl"+ assert error["message"] == "Failed to fetch media from URL."+++def test_product_media_create_mutation_with_empty_product_id(+ staff_api_client, permission_manage_products+):+ # given+ staff_api_client.user.user_permissions.add(permission_manage_products)+ variables = {+ "product": "",+ "mediaUrl": "https://www.youtube.com/watch?v=dQw4w9WgXcQ",+ }++ # when+ response = staff_api_client.post_graphql(+ PRODUCT_MEDIA_CREATE_QUERY,+ variables=variables,+ )+ content = get_graphql_content(response)++ # then+ errors = content["data"]["productMediaCreate"]["errors"]+ assert len(errors) == 1+ assert errors[0]["field"] == "product"+ assert errors[0]["code"] == ProductErrorCode.REQUIRED.namediff --git a/saleor/graphql/product/tests/queries/test_product_query.py b/saleor/graphql/product/tests/queries/test_product_query.pyindex aa68c547a5..680c1a99a8 100644--- a/saleor/graphql/product/tests/queries/test_product_query.py+++ b/saleor/graphql/product/tests/queries/test_product_query.py@@ -2177,6 +2177,60 @@ def test_query_product_media_by_id_zero_size_value_original_image_returned()+def test_query_product_media_by_id_without_image_returns_thumbnail_proxy_url(+ user_api_client, product, channel_USD+):+ # given+ query = QUERY_PRODUCT_MEDIA_BY_ID+ media = product.media.create(image=None)+ media_id = graphene.Node.to_global_id("ProductMedia", media.pk)++ variables = {+ "productId": graphene.Node.to_global_id("Product", product.pk),+ "mediaId": media_id,+ "channel": channel_USD.slug,+ "size": 120,+ }++ # when+ response = user_api_client.post_graphql(query, variables)++ # then+ content = get_graphql_content(response)+ assert content["data"]["product"]["mediaById"]["id"]+ assert (+ content["data"]["product"]["mediaById"]["url"]+ == f"https://example.com/thumbnail/{media_id}/128/"+ )+++def test_query_product_media_by_id_without_image_zero_size_returns_original_image_proxy_url(+ user_api_client, product, channel_USD+):+ # given+ query = QUERY_PRODUCT_MEDIA_BY_ID+ media = product.media.create(image=None)+ media_id = graphene.Node.to_global_id("ProductMedia", media.pk)++ variables = {+ "productId": graphene.Node.to_global_id("Product", product.pk),+ "mediaId": media_id,+ "channel": channel_USD.slug,+ "size": 0,+ }++ # when+ response = user_api_client.post_graphql(query, variables)++ # then+ content = get_graphql_content(response)+ assert content["data"]["product"]["mediaById"]["id"]+ assert (+ content["data"]["product"]["mediaById"]["url"]+ == f"https://example.com/image/{media_id}/"+ )++QUERY_PRODUCT_IN_FEDERATION = """query GetProductInFederation($representations: [_Any!]!) {_entities(representations: $representations) {diff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.pyindex d51b9f6dab..a4956e6a5d 100644--- a/saleor/graphql/product/types/products.py+++ b/saleor/graphql/product/types/products.py@@ -16,7 +16,7 @@ from ....core.weight import convert_weight_to_default_weight_unitfrom ....permission.auth_filters import AuthorizationFiltersfrom ....permission.enums import OrderPermissions, ProductPermissionsfrom ....permission.utils import has_one_of_permissions-from ....product import models+from ....product import ProductMediaTypes, modelsfrom ....product.models import ALL_PRODUCTS_PERMISSIONSfrom ....product.utils import calculate_revenue_for_variantfrom ....product.utils.availability import (@@ -31,6 +31,7 @@ from ....tax.utils import ()from ....thumbnail.utils import (get_image_or_proxy_url,+ get_original_image_proxy_url,get_thumbnail_format,get_thumbnail_size,)@@ -2043,15 +2044,22 @@ class ProductMedia(ModelObjectType[models.ProductMedia]):size: int | None = None,format: str | None = None,) -> str | None | Promise[str]:- if root.external_url:+ if root.external_url and root.type != ProductMediaTypes.IMAGE:return root.external_url- if not root.image:- return None+ # Bypass proxy URL when image is already in-place and original size is+ # requested.+ if root.image and size == 0:+ return build_absolute_uri(root.image.url)+ # If image is not there yet and original size is requested return proxy URL for+ # original.if size == 0:- return build_absolute_uri(root.image.url)+ return build_absolute_uri(+ get_original_image_proxy_url(str(root.id), "ProductMedia")+ )+ # Else, return proxy URL for thumbnail.format = get_thumbnail_format(format)selected_size = get_thumbnail_size(size)diff --git a/saleor/graphql/product/utils.py b/saleor/graphql/product/utils.pyindex 28ac4c0bae..e86a65ca0e 100644--- a/saleor/graphql/product/utils.py+++ b/saleor/graphql/product/utils.py@@ -1,14 +1,25 @@from collections import defaultdictfrom collections.abc import Iterable+from dataclasses import dataclassfrom typing import TYPE_CHECKING, NamedTuplefrom uuid import UUIDimport graphene+import requests+from django.conf import settingsfrom django.core.exceptions import ValidationErrorfrom django.db import DatabaseError, transactionfrom django.db.utils import IntegrityError+from ...core.exceptions import UnsupportedMediaProviderException+from ...core.http_client import HTTPClientfrom ...core.tracing import traced_atomic_transaction+from ...core.utils.validators import (+ get_mime_type,+ get_oembed_data,+ is_image_mimetype,+ is_valid_image_content_type,+)from ...order import OrderStatusfrom ...order import models as order_modelsfrom ...warehouse.models import Stock@@ -26,6 +37,104 @@ logger = logging.getLogger(__name__)ALT_CHAR_LIMIT = 250+class MediaValidationError(NamedTuple):+ message: str+ code: str+ field: str+++def validate_media_input(+ image, media_url, alt, error_code_enum+) -> MediaValidationError | None:+ """Validate media input fields.++ Returns a MediaValidationError if validation fails, None otherwise.+ """+ if not image and not media_url:+ return MediaValidationError(+ message="Image or external URL is required.",+ code=error_code_enum.REQUIRED.value,+ field="",+ )+ if image and media_url:+ return MediaValidationError(+ message="Either image or external URL is required.",+ code=error_code_enum.DUPLICATED_INPUT_ITEM.value,+ field="",+ )+ if alt and len(alt) > ALT_CHAR_LIMIT:+ return MediaValidationError(+ message=f"Alt field exceeds the character limit of {ALT_CHAR_LIMIT}.",+ code=error_code_enum.INVALID.value,+ field="alt",+ )+ return None+++@dataclass+class MediaUrlProbeResult:+ """Result of probing a media URL."""++ is_image: bool+ oembed_data: dict+ media_type: str+++def probe_media_url(media_url: str, error_code_enum) -> MediaUrlProbeResult:+ """Probe a media URL to determine if it points to an image or oembed content.++ Returns a MediaUrlProbeResult indicating the type of media.+ Raises ValidationError if the URL points to an invalid image type+ or an unsupported media provider.+ """+ try:+ with HTTPClient.send_request(+ "GET",+ media_url,+ stream=True,+ allow_redirects=False,+ timeout=settings.COMMON_REQUESTS_TIMEOUT,+ ) as response:+ mime_type = get_mime_type(response.headers.get("content-type"))+ except requests.exceptions.RequestException as exc:+ raise ValidationError(+ {+ "media_url": ValidationError(+ "Failed to fetch media from URL.",+ code=error_code_enum.INVALID.value,+ )+ }+ ) from exc++ if is_image_mimetype(mime_type):+ if not is_valid_image_content_type(mime_type):+ raise ValidationError(+ {+ "media_url": ValidationError(+ "Invalid file type.",+ code=error_code_enum.INVALID.value,+ )+ }+ )+ return MediaUrlProbeResult(is_image=True, oembed_data={}, media_type="")++ try:+ oembed_data, media_type = get_oembed_data(media_url)+ except UnsupportedMediaProviderException as exc:+ raise ValidationError(+ {+ "media_url": ValidationError(+ "Unsupported media provider or incorrect URL.",+ code=error_code_enum.UNSUPPORTED_MEDIA_PROVIDER.value,+ )+ }+ ) from exc++ return MediaUrlProbeResult(+ is_image=False, oembed_data=oembed_data, media_type=media_type+ )++def get_used_attribute_values_for_variant(variant):"""Create a dict of attributes values for variant.diff --git a/saleor/product/tasks.py b/saleor/product/tasks.pyindex 7a9deffb3c..3d96ce1a76 100644--- a/saleor/product/tasks.py+++ b/saleor/product/tasks.py@@ -14,16 +14,33 @@ from ..attribute.models import Attributefrom ..celeryconf import appfrom ..core.db.connection import allow_writerfrom ..core.exceptions import PreorderAllocationError+from ..core.http_client import HTTPClient+from ..core.utils.validators import get_mime_typefrom ..discount import PromotionTypefrom ..discount.models import Promotion, PromotionRulefrom ..plugins.manager import get_plugins_manager+from ..product import ProductMediaTypesfrom ..warehouse.management import deactivate_preorder_for_variantfrom ..webhook.event_types import WebhookEventAsyncTypefrom ..webhook.utils import get_webhooks_for_eventfrom .lock_objects import product_qs_select_for_update-from .models import Product, ProductChannelListing, ProductType, ProductVariant+from .models import (+ Product,+ ProductChannelListing,+ ProductMedia,+ ProductType,+ ProductVariant,+)from .search import update_products_search_vectorfrom .utils.product import mark_products_in_channels_as_dirty+from .utils.tasks_utils import (+ create_image,+ update_product_media,+ validate_content_type_header,+ validate_image_exif,+ validate_image_mime_type,+ validate_status_code,+)from .utils.variant_prices import update_discounted_prices_for_promotionfrom .utils.variants import (fetch_variants_for_promotion_rules,@@ -341,3 +358,69 @@ def collection_product_updated_task(product_ids):webhooks = get_webhooks_for_event(WebhookEventAsyncType.PRODUCT_UPDATED)for product in products:manager.product_updated(product, webhooks=webhooks)+++def on_failure_fetch_product_media_image_task(self, exc, task_id, args, kwargs, einfo):+ product_media_id = args[0]+ logger.warning(+ "Failed to fetch image for product media with id: %s. Removing product media.",+ product_media_id,+ )+ ProductMedia.objects.filter(+ pk=product_media_id, type=ProductMediaTypes.IMAGE+ ).delete()+++ queue=settings.FETCH_IMAGES_QUEUE_NAME,+ max_retries=5,+ retry_backoff=True,+ default_retry_delay=1,+ autoretry_for=(IOError,),+ on_failure=on_failure_fetch_product_media_image_task,+)+@allow_writer()+def fetch_product_media_image_task(product_media_id: int):+ try:+ product_media = ProductMedia.objects.get(+ pk=product_media_id, type=ProductMediaTypes.IMAGE+ )+ except ProductMedia.DoesNotExist:+ logger.warning(+ "Product media with id: %s with type: %s does not exist.",+ product_media_id,+ ProductMediaTypes.IMAGE,+ )+ return++ if product_media.image:+ logger.error(+ "Product media with id: %s already has an image.",+ product_media_id,+ )+ return++ if not product_media.external_url:+ logger.error(+ "Product media with id: %s has neither an external "+ "URL nor an image. The object is in an invalid state and cannot be "+ "processed.",+ product_media_id,+ )+ return++ with HTTPClient.send_request(+ "GET",+ product_media.external_url,+ stream=True,+ allow_redirects=False,+ timeout=settings.COMMON_REQUESTS_TIMEOUT,+ ) as response:+ validate_status_code(response.status_code)+ mime_type = get_mime_type(response.headers.get("content-type"))+ validate_content_type_header(product_media, mime_type)+ image = create_image(product_media, mime_type, response)++ validate_image_mime_type(image)+ validate_image_exif(image)+ update_product_media(product_media, image)diff --git a/saleor/product/tests/fixtures/product_media.py b/saleor/product/tests/fixtures/product_media.pyindex ded9fc98e7..c4d4c2c00a 100644--- a/saleor/product/tests/fixtures/product_media.py+++ b/saleor/product/tests/fixtures/product_media.py@@ -13,3 +13,21 @@ def product_media_image(product, image, media_root):type=ProductMediaTypes.IMAGE,oembed_data="{}",)+++def product_media_image_not_yet_fetched(product):+ return ProductMedia.objects.create(+ product=product,+ type=ProductMediaTypes.IMAGE,+ external_url="https://example.com/image.jpg",+ )+++def product_media_video(product):+ return ProductMedia.objects.create(+ product=product,+ type=ProductMediaTypes.VIDEO,+ external_url="https://example.com/video.mp4",+ )diff --git a/saleor/product/tests/test_tasks.py b/saleor/product/tests/test_tasks.pyindex a1b0e39e4e..e6fe6b816f 100644--- a/saleor/product/tests/test_tasks.py+++ b/saleor/product/tests/test_tasks.py@@ -1,17 +1,27 @@import datetimeimport logging+from contextlib import contextmanagerfrom decimal import Decimal-from unittest.mock import patch+from io import BytesIO+from unittest.mock import MagicMock, patchimport pytestfrom django.utils import timezonefrom faker import Faker+from PIL import Image+from requests.exceptions import HTTPError, InvalidSchema, RequestExceptionfrom ...discount import PromotionType, RewardValueTypefrom ...discount.models import Promotion, PromotionRule-from ..models import Product, ProductChannelListing, ProductVariantChannelListing+from ..models import (+ Product,+ ProductChannelListing,+ ProductMedia,+ ProductVariantChannelListing,+)from ..tasks import (_get_preorder_variants_to_clean,+ fetch_product_media_image_task,mark_products_search_vector_as_dirty,recalculate_discounted_price_for_products_task,update_products_search_vector_task,@@ -21,6 +31,23 @@ from ..tasks import (from ..utils.variants import fetch_variants_for_promotion_rules+@contextmanager+def mock_http_response_for_product_task(+ status_code=200, content_type=None, content=None+):+ """Patch HTTPClient.send_request to return a response with the given attributes."""+ mock_response = MagicMock()+ mock_response.status_code = status_code+ mock_response.headers.get.return_value = content_type+ mock_response.content = content++ with patch("saleor.product.tasks.HTTPClient") as mock_client:+ mock_client.send_request.return_value.__enter__ = MagicMock(+ return_value=mock_response+ )+ yield mock_client++@patch("saleor.product.tasks.update_variant_relations_for_active_promotion_rules_task.""delay"@@ -335,3 +362,281 @@ def test_mark_products_search_vector_as_dirty(product_list):"search_index_dirty", flat=True))+++def test_fetch_product_media_image_already_has_image(product_media_image):+ # given+ assert product_media_image.image+ image = product_media_image.image++ # when+ fetch_product_media_image_task.apply(args=(product_media_image.pk,))++ # then+ product_media_image.refresh_from_db(fields=["image"])+ assert product_media_image.image == image+++def test_fetch_product_media_image_not_found():+ # given+ non_existent_id = -1+ assert not ProductMedia.objects.filter(pk=non_existent_id).exists()++ # when+ fetch_product_media_image_task.apply(args=(non_existent_id,))++ # then+ assert not ProductMedia.objects.filter(pk=non_existent_id).exists()+++def test_fetch_product_media_image_missing_external_url_and_image(+ product_media_image_not_yet_fetched,+):+ # given+ product_media = product_media_image_not_yet_fetched+ product_media.external_url = None+ product_media.save(update_fields=["external_url"])+ assert not product_media.image++ # when+ fetch_product_media_image_task.apply(args=(product_media.pk,))++ # then+ assert ProductMedia.objects.filter(pk=product_media.pk).exists()+++def test_fetch_product_media_image_wrong_type(product_media_video):+ # given+ product_media = product_media_video+ assert not product_media.image++ # when+ fetch_product_media_image_task.apply(args=(product_media.pk,))++ # then+ product_media.refresh_from_db()+ assert not product_media.image+++def test_fetch_product_media_image_non_image_content_type(+ product_media_image_not_yet_fetched,+ caplog,+):+ # given+ product_media = product_media_image_not_yet_fetched+ assert product_media.external_url+ assert not product_media.image++ # when+ with mock_http_response_for_product_task(+ status_code=200, content_type="text/plain"+ ):+ fetch_product_media_image_task.apply(args=(product_media.pk,))++ # then+ assert not ProductMedia.objects.filter(pk=product_media.pk).exists()+++def test_fetch_product_media_image_success(+ product_media_image_not_yet_fetched, media_root+):+ # given+ product_media = product_media_image_not_yet_fetched+ assert product_media.external_url+ assert not product_media.image++ image_buffer = BytesIO()+ Image.new("RGB", (1, 1)).save(image_buffer, format="JPEG")+ image_bytes = image_buffer.getvalue()++ # when+ with mock_http_response_for_product_task(+ status_code=200, content_type="image/jpeg", content=image_bytes+ ):+ fetch_product_media_image_task.apply(args=(product_media.pk,))++ # then+ product_media.refresh_from_db()+ assert product_media.external_url is None+ assert product_media.image+++def test_fetch_product_media_image_unsupported_image_content_type(+ product_media_image_not_yet_fetched,+ caplog,+):+ # given+ product_media = product_media_image_not_yet_fetched+ assert not product_media.image++ # when+ with mock_http_response_for_product_task(+ status_code=200, content_type="image/svg+xml"+ ):+ fetch_product_media_image_task.apply(args=(product_media.pk,))++ # then+ assert not ProductMedia.objects.filter(pk=product_media.pk).exists()+++def test_fetch_product_media_image_request_exception(+ product_media_image_not_yet_fetched,+):+ # given+ product_media = product_media_image_not_yet_fetched+ assert product_media.external_url+ assert not product_media.image++ # when+ with patch("saleor.product.tasks.HTTPClient") as mock_http_client:+ mock_http_client.send_request.side_effect = RequestException(+ "Connection timeout"+ )+ with pytest.raises(RequestException):+ # this call simulates a single attempt for executing the task+ # does not call .apply as otherwise on_failure hook would be called+ # and this results in removing ProductMedia object+ fetch_product_media_image_task(product_media.pk)++ # then+ assert ProductMedia.objects.filter(pk=product_media.pk).exists()+++def test_fetch_product_media_image_invalid_schema_exception(+ product_media_image_not_yet_fetched,+):+ # given+ product_media = product_media_image_not_yet_fetched+ assert product_media.external_url+ assert not product_media.image++ # when+ with patch("saleor.product.tasks.HTTPClient") as mock_http_client:+ mock_http_client.send_request.side_effect = InvalidSchema()+ with pytest.raises(InvalidSchema):+ # this call simulates a single attempt for executing the task+ fetch_product_media_image_task(product_media.pk)++ # then+ assert ProductMedia.objects.filter(pk=product_media.pk).exists()+++def test_fetch_product_media_image_invalid_schema_exception_on_failure_handler(+ product_media_image_not_yet_fetched,+):+ # given+ product_media = product_media_image_not_yet_fetched+ assert product_media.external_url+ assert not product_media.image++ # when+ with patch("saleor.product.tasks.HTTPClient") as mock_http_client:+ mock_http_client.send_request.side_effect = InvalidSchema()+ fetch_product_media_image_task.apply(args=(product_media.pk,))++ # then+ assert not ProductMedia.objects.filter(pk=product_media.pk).exists()+++def test_fetch_product_media_image_deleted_after_final_retry(+ product_media_image_not_yet_fetched,+):+ # given+ product_media = product_media_image_not_yet_fetched++ # when+ with patch("saleor.product.tasks.HTTPClient") as mock_http_client:+ mock_http_client.send_request.side_effect = RequestException(+ "Connection timeout"+ )+ # mind that .apply will execute retries and as well as hooks (like on_failure hook)+ fetch_product_media_image_task.apply(args=(product_media.pk,))++ # then+ assert not ProductMedia.objects.filter(pk=product_media.pk).exists()+++def test_fetch_product_media_image_invalid_exif(+ product_media_image_not_yet_fetched,+ caplog,+):+ # given+ product_media = product_media_image_not_yet_fetched+ assert not product_media.image++ image_buffer = BytesIO()+ Image.new("RGB", (1, 1)).save(image_buffer, format="JPEG")+ image_bytes = image_buffer.getvalue()++ # when+ with (+ mock_http_response_for_product_task(+ status_code=200, content_type="image/jpeg", content=image_bytes+ ),+ patch("saleor.product.utils.tasks_utils.Image.open") as mock_image_open,+ ):+ mock_pil_image = MagicMock()+ mock_pil_image.getexif.side_effect = SyntaxError("Invalid EXIF")+ mock_image_open.return_value = mock_pil_image++ fetch_product_media_image_task.apply(args=(product_media.pk,))++ # then+ assert not ProductMedia.objects.filter(pk=product_media.pk).exists()+++def test_fetch_product_media_image_invalid_metadata(+ product_media_image_not_yet_fetched,+ caplog,+):+ # given+ product_media = product_media_image_not_yet_fetched+ assert not product_media.image++ # when+ with mock_http_response_for_product_task(+ status_code=200, content_type="image/jpeg", content=b"not an image"+ ):+ fetch_product_media_image_task.apply(args=(product_media.pk,))++ # then+ assert not ProductMedia.objects.filter(pk=product_media.pk).exists()++[email protected]("status_code", [500, 502, 503])+def test_fetch_product_media_image_server_error_triggers_retry(+ product_media_image_not_yet_fetched,+ status_code,+):+ # given+ product_media = product_media_image_not_yet_fetched++ # when & then+ with mock_http_response_for_product_task(status_code=status_code):+ with pytest.raises(HTTPError):+ # this call simulates a single attempt for executing the task+ # does not call .apply as otherwise on_failure hook would be called+ # and this results in removing ProductMedia object+ fetch_product_media_image_task(product_media.pk)++ # then+ product_media.refresh_from_db()+ assert not product_media.image+ assert product_media.external_url++[email protected]("status_code", [100, 199, 300, 301, 401, 404, 499])+def test_fetch_product_media_image_client_error_does_not_retry(+ product_media_image_not_yet_fetched,+ caplog,+ status_code,+):+ # given+ product_media = product_media_image_not_yet_fetched++ # when+ with mock_http_response_for_product_task(status_code=status_code):+ fetch_product_media_image_task.apply(args=(product_media.pk,))++ # then+ assert not ProductMedia.objects.filter(pk=product_media.pk).exists()diff --git a/saleor/product/utils/tasks_utils.py b/saleor/product/utils/tasks_utils.pynew file mode 100644index 0000000000..7eab20f092--- /dev/null+++ b/saleor/product/utils/tasks_utils.py@@ -0,0 +1,59 @@+from typing import IO++from PIL import Image, UnidentifiedImageError+from requests.exceptions import HTTPError++from ...core.utils import create_file_from_response+from ...core.utils.validators import is_valid_image_content_type+from ...thumbnail.utils import ProcessedImage, get_filename_from_url+++def validate_status_code(status_code):+ if status_code >= 500:+ raise HTTPError(f"Retryable error (HTTP status: {status_code}).")++ if status_code < 200 or status_code >= 300:+ raise ValueError(f"Non-retryable error (HTTP status: {status_code}).")+++def validate_content_type_header(product_media, mime_type):+ if not is_valid_image_content_type(mime_type):+ raise ValueError(+ f"File from product media: {product_media.pk} does not have "+ f"valid image content-type: {mime_type}."+ )+++def create_image(product_media, mime_type, response):+ filename = get_filename_from_url(product_media.external_url, mime_type)+ return create_file_from_response(response, filename)+++def validate_image_mime_type(image: IO[bytes]):+ try:+ # Validate by reading MIME type from magic bytes.+ ProcessedImage.get_image_metadata_from_file(image)+ finally:+ image.seek(0)+++def validate_image_exif(image: IO[bytes]):+ try:+ # Validate by getting exif.+ pil_image_obj = Image.open(image)+ pil_image_obj.getexif()+ except (+ ValueError,+ TypeError,+ SyntaxError,+ UnidentifiedImageError,+ ) as exc:+ raise ValueError(exc) from exc+ finally:+ image.seek(0)+++def update_product_media(product_media, image):+ product_media.image = image+ product_media.external_url = None+ product_media.save(update_fields=["image", "external_url"])diff --git a/saleor/settings.py b/saleor/settings.pyindex 70b7739dab..7b81257b22 100644--- a/saleor/settings.py+++ b/saleor/settings.py@@ -1059,6 +1059,8 @@ DATA_MIGRATIONS_TASKS_QUEUE_NAME = os.environ.get("DATA_MIGRATIONS_TASKS_QUEUE_NAME", None)+FETCH_IMAGES_QUEUE_NAME = os.environ.get("FETCH_IMAGES_QUEUE_NAME", None)+# Lock time for request password reset mutation per user (seconds)RESET_PASSWORD_LOCK_TIME = parse(os.environ.get("RESET_PASSWORD_LOCK_TIME", "15 minutes")diff --git a/saleor/thumbnail/tests/test_views.py b/saleor/thumbnail/tests/test_views.pyindex 6790097fc8..0057a8b821 100644--- a/saleor/thumbnail/tests/test_views.py+++ b/saleor/thumbnail/tests/test_views.py@@ -3,6 +3,7 @@ from unittest.mock import patchimport graphenefrom PIL import Image+from ...product import ProductMediaTypesfrom .. import IconThumbnailFormat, ThumbnailFormatfrom ..models import Thumbnail@@ -199,6 +200,26 @@ def test_handle_thumbnail_view_no_image(client, category):assert response.status_code == 404+def test_handle_thumbnail_view_for_product_media_image_type_with_external_url_but_no_image(+ client, product+):+ # given+ size = 500+ product_media = product.media.create(+ image=None,+ type=ProductMediaTypes.IMAGE,+ external_url="https://example.com/image.jpg",+ )+ product_media_id = graphene.Node.to_global_id("ProductMedia", product_media.id)++ # when+ response = client.get(f"/thumbnail/{product_media_id}/{size}/")++ # then+ assert response.status_code == 503+ assert response["Retry-After"] == "60"++def test_handle_thumbnail_view_invalid_object_type(client, order):# givensize = 60@@ -413,3 +434,169 @@ def test_handle_thumbnail_view_for_app_installation_logo_default_thumbnail_existassert response.status_code == 302assert response.url == thumbnail.image.urlassert Thumbnail.objects.count() == thumbnail_count+++def test_handle_original_image_for_category(client, category_with_image, settings):+ # given+ category_id = graphene.Node.to_global_id("Category", category_with_image.id)++ # when+ response = client.get(f"/image/{category_id}/")++ # then+ assert response.status_code == 302+ assert (+ response.url == settings.MEDIA_URL + category_with_image.background_image.name+ )+++def test_handle_original_image_for_collection(client, collection_with_image, settings):+ # given+ collection_id = graphene.Node.to_global_id("Collection", collection_with_image.id)++ # when+ response = client.get(f"/image/{collection_id}/")++ # then+ assert response.status_code == 302+ assert (+ response.url == settings.MEDIA_URL + collection_with_image.background_image.name+ )+++def test_handle_original_image_for_user(+ client, staff_user, image, media_root, settings+):+ # given+ staff_user.avatar = image+ staff_user.save(update_fields=["avatar"])++ user_uuid = graphene.Node.to_global_id("User", staff_user.uuid)++ # when+ response = client.get(f"/image/{user_uuid}/")++ # then+ assert response.status_code == 302+ assert response.url == settings.MEDIA_URL + staff_user.avatar.name+++def test_handle_original_image_for_product_media(client, product_with_image, settings):+ # given+ product_media = product_with_image.media.first()+ product_media_id = graphene.Node.to_global_id("ProductMedia", product_media.id)++ # when+ response = client.get(f"/image/{product_media_id}/")++ # then+ assert response.status_code == 302+ assert response.url == settings.MEDIA_URL + product_media.image.name+++def test_handle_original_image_for_app(client, app, icon_image, media_root, settings):+ # given+ app.brand_logo_default = icon_image+ app.save(update_fields=["brand_logo_default"])++ app_uuid = graphene.Node.to_global_id("App", app.uuid)++ # when+ response = client.get(f"/image/{app_uuid}/")++ # then+ assert response.status_code == 302+ assert response.url == settings.MEDIA_URL + app.brand_logo_default.name+++def test_handle_original_image_for_app_installation(+ client, app_installation, icon_image, media_root, settings+):+ # given+ app_installation.brand_logo_default = icon_image+ app_installation.save(update_fields=["brand_logo_default"])++ uuid = graphene.Node.to_global_id("AppInstallation", app_installation.uuid)++ # when+ response = client.get(f"/image/{uuid}/")++ # then+ assert response.status_code == 302+ assert response.url == settings.MEDIA_URL + app_installation.brand_logo_default.name+++def test_handle_original_image_invalid_instance_id(client):+ # given+ instance_id = "invalid-id"++ # when+ response = client.get(f"/image/{instance_id}/")++ # then+ assert response.status_code == 404+++def test_handle_original_image_invalid_object_type(client, order):+ # given+ order_id = graphene.Node.to_global_id("Order", order.id)++ # when+ response = client.get(f"/image/{order_id}/")++ # then+ assert response.status_code == 404+++def test_handle_original_image_object_does_not_exist(client):+ # given+ category_id = graphene.Node.to_global_id("Category", 1)++ # when+ response = client.get(f"/image/{category_id}/")++ # then+ assert response.status_code == 404+++def test_handle_original_image_no_image(client, category):+ # given+ category_id = graphene.Node.to_global_id("Category", category.id)+ assert not category.background_image++ # when+ response = client.get(f"/image/{category_id}/")++ # then+ assert response.status_code == 404+++def test_handle_original_image_for_product_media_without_image(client, product):+ # given+ product_media = product.media.create(image=None)+ product_media_id = graphene.Node.to_global_id("ProductMedia", product_media.id)++ # when+ response = client.get(f"/image/{product_media_id}/")++ # then+ assert response.status_code == 404+++def test_handle_original_image_for_product_media_image_type_with_external_url_but_no_image(+ client, product+):+ # given+ product_media = product.media.create(+ image=None,+ type=ProductMediaTypes.IMAGE,+ external_url="https://example.com/image.jpg",+ )+ product_media_id = graphene.Node.to_global_id("ProductMedia", product_media.id)++ # when+ response = client.get(f"/image/{product_media_id}/")++ # then+ assert response.status_code == 503+ assert response["Retry-After"] == "60"diff --git a/saleor/thumbnail/utils.py b/saleor/thumbnail/utils.pyindex 745765f56f..32ab428681 100644--- a/saleor/thumbnail/utils.py+++ b/saleor/thumbnail/utils.py@@ -12,6 +12,7 @@ from django.core.files.storage import default_storagefrom django.urls import reversefrom PIL import Image+from ..product import ProductMediaTypesfrom . import (DEFAULT_THUMBNAIL_SIZE,FILE_NAME_MAX_LENGTH,@@ -50,6 +51,16 @@ def prepare_image_proxy_url(return reverse("thumbnail", kwargs=kwargs)+def get_original_image_proxy_url(+ instance_pk: str,+ object_type: str,+):+ instance_id = graphene.Node.to_global_id(object_type, instance_pk)+ kwargs = {"instance_id": instance_id}++ return reverse("original-image", kwargs=kwargs)++def get_thumbnail_size(size: int | None) -> int:"""Return the closest size to the given one of the available sizes."""if size is None:@@ -264,3 +275,12 @@ def get_filename_from_url(url: str, mime_type: str | None = None) -> str:name = name[:FILE_NAME_MAX_LENGTH]hash = secrets.token_hex(nbytes=4)return f"{name}_{hash}{format}"+++def is_product_media_image_pending(object_type: str, instance) -> bool:+ """Check if instance is a ProductMedia of IMAGE type with a pending image download."""+ return (+ object_type == "ProductMedia"+ and instance.type == ProductMediaTypes.IMAGE+ and instance.external_url+ )diff --git a/saleor/thumbnail/views.py b/saleor/thumbnail/views.pyindex 63b878037b..610f19265c 100644--- a/saleor/thumbnail/views.py+++ b/saleor/thumbnail/views.py@@ -4,6 +4,7 @@ from typing import NamedTuplefrom django.conf import settingsfrom django.core.exceptions import ObjectDoesNotExistfrom django.http import (+ HttpResponse,HttpResponseBadRequest,HttpResponseNotFound,HttpResponseRedirect,@@ -23,11 +24,14 @@ from .utils import (ProcessedIconImage,ProcessedImage,get_thumbnail_size,+ is_product_media_image_pending,prepare_thumbnail_file_name,)logger = logging.getLogger(__name__)+PENDING_IMAGE_RETRY_AFTER = "60"+class ModelData(NamedTuple):model: type[App | AppInstallation | Category | Collection | ProductMedia | User]@@ -93,20 +97,22 @@ def handle_thumbnail(request, instance_id: str, size: str, format: str | None =):return HttpResponseRedirect(thumbnail.image.url)+ pk_field = "uuid" if object_type in UUID_IDENTIFIABLE_TYPES else "id"try:- if object_type in UUID_IDENTIFIABLE_TYPES:- instance = model_data.model.objects.using(- settings.DATABASE_CONNECTION_REPLICA_NAME- ).get(uuid=pk) # type: ignore[misc]- else:- instance = model_data.model.objects.using(- settings.DATABASE_CONNECTION_REPLICA_NAME- ).get(id=pk)+ instance = model_data.model.objects.using(+ settings.DATABASE_CONNECTION_REPLICA_NAME+ ).get(**{pk_field: pk})except ObjectDoesNotExist:return HttpResponseNotFound("Instance with the given id cannot be found.")image = getattr(instance, model_data.image_field)if not bool(image):+ if is_product_media_image_pending(object_type, instance):+ return HttpResponse(+ "Image has not been fetched yet, try later.",+ status=503,+ headers={"Retry-After": PENDING_IMAGE_RETRY_AFTER},+ )return HttpResponseNotFound("There is no image for provided instance.")# prepare thumbnail@@ -142,3 +148,36 @@ def handle_thumbnail(request, instance_id: str, size: str, format: str | None =call_event(manager.thumbnail_created, thumbnail)return HttpResponseRedirect(thumbnail.image.url)+++def handle_original_image(request, instance_id: str):+ """Redirect to original image URL."""+ try:+ object_type, pk = from_global_id_or_error(instance_id, raise_error=True)+ except GraphQLError:+ return HttpResponseNotFound("Cannot find instance with the given id.")++ if object_type not in TYPE_TO_MODEL_DATA_MAPPING:+ return HttpResponseNotFound("Invalid instance type.")++ model_data = TYPE_TO_MODEL_DATA_MAPPING[object_type]++ pk_field = "uuid" if object_type in UUID_IDENTIFIABLE_TYPES else "id"+ try:+ instance = model_data.model.objects.using(+ settings.DATABASE_CONNECTION_REPLICA_NAME+ ).get(**{pk_field: pk})+ except ObjectDoesNotExist:+ return HttpResponseNotFound("Instance with the given id cannot be found.")++ image = getattr(instance, model_data.image_field)+ if not bool(image):+ if is_product_media_image_pending(object_type, instance):+ return HttpResponse(+ "Image has not been fetched yet, try later.",+ status=503,+ headers={"Retry-After": PENDING_IMAGE_RETRY_AFTER},+ )+ return HttpResponseNotFound("There is no image for provided instance.")++ return HttpResponseRedirect(image.url)diff --git a/saleor/urls.py b/saleor/urls.pyindex f00bfcadc1..53f88b9c5a 100644--- a/saleor/urls.py+++ b/saleor/urls.py@@ -12,7 +12,7 @@ from .plugins.views import (handle_plugin_per_channel_webhook,handle_plugin_webhook,)-from .thumbnail.views import handle_thumbnail+from .thumbnail.views import handle_original_image, handle_thumbnailurlpatterns = [re_path(@@ -44,6 +44,11 @@ urlpatterns = [handle_thumbnail,name="thumbnail",),+ re_path(+ (r"^image/(?P<instance_id>[.0-9A-Za-z_=\-]+)/$"),+ handle_original_image,+ name="original-image",+ ),re_path(r"^\.well-known/jwks.json$", jwks, name="jwks"),]