Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Save images to product media from external URLs (#9329)
Krzysztof Wolski5763cb1ad22b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c5f9677fc9..e0245411a9 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -26,6 +26,7 @@ All notable, unreleased changes to this project will be documented in this file.- Add `HANDLE_CHECKOUTS` permission (only for apps)- Refactor app tokens - #9438 by @IKarbowiak- Store app tokens hashes instead of plain text.+- Save images to product media from external URLs - #9329 by @krzysztofwolski# 3.1.7diff --git a/saleor/graphql/core/tests/test_core.py b/saleor/graphql/core/tests/test_core.pyindex 44e78c877d..44e0efde14 100644--- a/saleor/graphql/core/tests/test_core.py+++ b/saleor/graphql/core/tests/test_core.py@@ -1,7 +1,7 @@import enumimport osfrom io import BytesIO-from unittest.mock import patch+from unittest.mock import Mock, patchimport django_filtersimport graphene@@ -29,8 +29,11 @@ from ..utils import (add_hash_to_file_name,clean_seo_fields,get_duplicated_values,+ get_filename_from_url,+ is_image_mimetype,snake_to_camel_case,validate_image_file,+ validate_image_url,validate_slug_and_generate_if_needed,)from . import ErrorTest@@ -319,6 +322,111 @@ def test_validate_image_file_invalid_file_extension():)+def test_get_filename_from_url_unique():+ # given+ file_format = "jpg"+ file_name = "lenna"+ url = f"http://example.com/{file_name}.{file_format}"++ # when+ result = get_filename_from_url(url)++ # then+ assert result.startswith(file_name)+ assert result.endswith(file_format)+ assert result != f"{file_name}.{file_format}"+++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_validate_image_url_valid_image_response(monkeypatch):+ # given+ valid_image_response_mock = Mock()+ valid_image_response_mock.headers = {"content-type": "image/jpeg"}+ monkeypatch.setattr(+ "saleor.graphql.core.utils.requests.head",+ Mock(return_value=valid_image_response_mock),+ )+ field = "image"+ dummy_url = "http://example.com/valid_url.jpg"++ # when+ result = validate_image_url(+ dummy_url,+ field,+ ProductErrorCode.INVALID,+ )++ # then+ assert result is None+++def test_validate_image_url_invalid_mimetype_response(monkeypatch):+ # given+ invalid_response_mock = Mock()+ invalid_response_mock.headers = {"content-type": "application/json"}+ monkeypatch.setattr(+ "saleor.graphql.core.utils.requests.head",+ Mock(return_value=invalid_response_mock),+ )+ field = "image"+ dummy_url = "http://example.com/invalid_url.json"++ # when+ with pytest.raises(ValidationError) as exc:+ validate_image_url(+ dummy_url,+ field,+ ProductErrorCode.INVALID,+ )++ # then+ assert exc.value.args[0][field].message == "Invalid file type."+++def test_validate_image_url_response_without_content_headers(monkeypatch):+ # given+ invalid_response_mock = Mock()+ invalid_response_mock.headers = {}+ monkeypatch.setattr(+ "saleor.graphql.core.utils.requests.head",+ Mock(return_value=invalid_response_mock),+ )+ field = "image"+ dummy_url = "http://example.com/broken_url"++ # when+ with pytest.raises(ValidationError) as exc:+ validate_image_url(+ dummy_url,+ field,+ ProductErrorCode.INVALID,+ )++ # then+ assert exc.value.args[0][field].message == "Invalid file type."++@pytest.mark.parametrize("value, count, product_indexes",[diff --git a/saleor/graphql/core/utils/__init__.py b/saleor/graphql/core/utils/__init__.pyindex f6915f38d0..c10d3d9564 100644--- a/saleor/graphql/core/utils/__init__.py+++ b/saleor/graphql/core/utils/__init__.py@@ -1,10 +1,13 @@import binascii+import mimetypesimport osimport secrets+from enum import Enumfrom typing import TYPE_CHECKING, Type, Unionfrom uuid import UUIDimport graphene+import requestsfrom django.core.exceptions import ValidationErrorfrom django.core.files.uploadedfile import SimpleUploadedFilefrom graphene import ObjectType@@ -43,7 +46,46 @@ def str_to_enum(name):return name.replace(" ", "_").replace("-", "_").upper()-def validate_image_file(file, field_name, error_class):+def is_image_mimetype(mimetype: str) -> bool:+ """Check if mimetype is image."""+ if mimetype is None:+ return False+ return mimetype.startswith("image/")+++def is_image_url(url: str) -> bool:+ """Check if file URL seems to be an image."""+ if url.endswith(".webp"):+ # webp is not recognized by mimetypes as image+ # https://bugs.python.org/issue38902+ return True+ filetype = mimetypes.guess_type(url)[0]+ return filetype is not None and is_image_mimetype(filetype)+++def validate_image_url(url: str, field_name: str, error_code: str) -> None:+ """Check if remote file has content type of image.++ Instead of the whole file, only the headers are fetched.+ """+ head = requests.head(url)+ header = head.headers+ content_type = header.get("content-type")+ if content_type is None or not is_image_mimetype(content_type):+ raise ValidationError(+ {field_name: ValidationError("Invalid file type.", code=error_code)}+ )+++def get_filename_from_url(url: str) -> str:+ """Prepare unique filename for file from URL to avoid overwritting."""+ file_name = os.path.basename(url)+ name, format = os.path.splitext(file_name)+ hash = secrets.token_hex(nbytes=4)+ return f"{name}_{hash}{format}"+++def validate_image_file(file, field_name, error_class) -> None:"""Validate if the file is an image."""if not file:raise ValidationError(@@ -53,7 +95,7 @@ def validate_image_file(file, field_name, error_class):)})- if not file.content_type.startswith("image/"):+ if not is_image_mimetype(file.content_type):raise ValidationError({field_name: ValidationError(diff --git a/saleor/graphql/product/mutations/products.py b/saleor/graphql/product/mutations/products.pyindex 54f950983e..a33da85b02 100644--- a/saleor/graphql/product/mutations/products.py+++ b/saleor/graphql/product/mutations/products.py@@ -3,7 +3,9 @@ from collections import defaultdictfrom typing import List, Tupleimport graphene+import requestsfrom django.core.exceptions import ObjectDoesNotExist, ValidationError+from django.core.files import Filefrom django.db import transactionfrom django.db.models import Exists, OuterRef, Qfrom django.utils.text import slugify@@ -52,7 +54,10 @@ from ...core.utils import (add_hash_to_file_name,clean_seo_fields,get_duplicated_values,+ get_filename_from_url,+ is_image_url,validate_image_file,+ validate_image_url,validate_slug_and_generate_if_needed,)from ...core.utils.reordering import perform_reordering@@ -1520,14 +1525,29 @@ class ProductMediaCreate(BaseMutation):image=image_data, alt=alt, type=ProductMediaTypes.IMAGE)create_product_thumbnails.delay(media.pk)- else:- oembed_data, media_type = get_oembed_data(media_url, "media_url")- media = product.media.create(- external_url=oembed_data["url"],- alt=oembed_data.get("title", alt),- type=media_type,- oembed_data=oembed_data,- )+ if 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.+ if is_image_url(media_url):+ validate_image_url(media_url, "media_url", ProductErrorCode.INVALID)+ filename = get_filename_from_url(media_url)+ image_data = requests.get(media_url, stream=True)+ image_file = File(image_data.raw, filename)+ media = product.media.create(+ image=image_file,+ alt=alt,+ type=ProductMediaTypes.IMAGE,+ )+ create_product_thumbnails.delay(media.pk)+ else:+ oembed_data, media_type = get_oembed_data(media_url, "media_url")+ media = product.media.create(+ external_url=oembed_data["url"],+ alt=oembed_data.get("title", alt),+ type=media_type,+ oembed_data=oembed_data,+ )info.context.plugins.product_updated(product)product = ChannelContext(node=product, channel_slug=None)