Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Add brand field to app manifest (#12361)

Przemysław Ładad48b93a15616
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 77d9d3d6bd..2d80ffe8c9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -35,6 +35,7 @@ All notable, unreleased changes to this project will be documented in this file.
- Add `enable_account_confirmation_by_email` to `SiteSettings` model and allow to update it via `shopSettingsUpdate` mutation - #12781 by @SzymJ
- [Preview] Add `OrderBulkCreate` mutation - #12269 by @zedzior
- [Preview] Add `ORDER_BULK_CREATED` event, which is sent for successfully imported orders - #12536 by @zedzior
+- Add `brand` optional field with brand data (initially logo image) to `Manifest`, `AppInstallation` and `App` - #12361 by @przlada
### Saleor Apps
diff --git a/saleor/app/__init__.py b/saleor/app/__init__.py
index e69de29bb2..1f36c81d53 100644
--- a/saleor/app/__init__.py
+++ b/saleor/app/__init__.py
@@ -0,0 +1 @@
+default_app_config = "saleor.app.app.AppConfig"
diff --git a/saleor/app/app.py b/saleor/app/app.py
new file mode 100644
index 0000000000..0964a60ca3
--- /dev/null
+++ b/saleor/app/app.py
@@ -0,0 +1,22 @@
+from django.apps import AppConfig as DjangoAppConfig
+from django.db.models.signals import post_delete
+
+
+class AppConfig(DjangoAppConfig):
+ name = "saleor.app"
+
+ def ready(self):
+ from .models import App, AppInstallation
+ from .signals import delete_brand_images
+
+ # preventing duplicate signals
+ post_delete.connect(
+ delete_brand_images,
+ sender=App,
+ dispatch_uid="delete_app_brand_images",
+ )
+ post_delete.connect(
+ delete_brand_images,
+ sender=AppInstallation,
+ dispatch_uid="delete_app_installation_brand_images",
+ )
diff --git a/saleor/app/installation_utils.py b/saleor/app/installation_utils.py
index 3dc70d4b78..e66360ed0e 100644
--- a/saleor/app/installation_utils.py
+++ b/saleor/app/installation_utils.py
@@ -1,19 +1,39 @@
+import logging
+import time
+from io import BytesIO
+from typing import Optional, Union
+
import requests
+from celery.exceptions import MaxRetriesExceededError
+from celery.utils.log import get_task_logger
from django.conf import settings
from django.contrib.sites.models import Site
+from django.core.exceptions import ObjectDoesNotExist, ValidationError
+from django.core.files import File
+from django.core.files.storage import default_storage
+from django.db import DatabaseError
from django.urls import reverse
from requests import HTTPError, Response
from ..app.headers import AppHeaders, DeprecatedAppHeaders
+from ..celeryconf import app
from ..core.utils import build_absolute_uri
from ..permission.enums import get_permission_names
from ..plugins.manager import PluginsManager
+from ..thumbnail import ICON_MIME_TYPES
+from ..thumbnail.utils import get_filename_from_url
+from ..thumbnail.validators import validate_icon_image
from ..webhook.models import Webhook, WebhookEvent
+from .error_codes import AppErrorCode
from .manifest_validations import clean_manifest_data
from .models import App, AppExtension, AppInstallation
from .types import AppExtensionTarget, AppType
-REQUEST_TIMEOUT = 25
+REQUEST_TIMEOUT = 20
+MAX_ICON_FILE_SIZE = 1024 * 1024 * 10 # 10MB
+
+logger = logging.getLogger(__name__)
+task_logger = get_task_logger(__name__)
class AppInstallationError(HTTPError):
@@ -51,6 +71,120 @@ def send_app_token(target_url: str, token: str):
validate_app_install_response(response)
+def fetch_icon_image(
+ url: str, *, max_file_size=MAX_ICON_FILE_SIZE, timeout=REQUEST_TIMEOUT
+) -> File:
+ filename = get_filename_from_url(url)
+ size_error_msg = f"File too big. Maximal icon image file size is {max_file_size}."
+ code = AppErrorCode.INVALID.value
+ fetch_start = time.monotonic()
+ try:
+ with requests.get(
+ url, stream=True, timeout=timeout, allow_redirects=False
+ ) as res:
+ res.raise_for_status()
+ content_type = res.headers.get("content-type")
+ if content_type not in ICON_MIME_TYPES:
+ raise ValidationError("Invalid file type.", code=code)
+ try:
+ if int(res.headers.get("content-length", 0)) > max_file_size:
+ raise ValidationError(size_error_msg, code=code)
+ except (ValueError, TypeError):
+ pass
+ content = BytesIO()
+ for chunk in res.iter_content(chunk_size=File.DEFAULT_CHUNK_SIZE):
+ content.write(chunk)
+ if content.tell() > max_file_size:
+ raise ValidationError(size_error_msg, code=code)
+ if (time.monotonic() - fetch_start) > timeout:
+ raise ValidationError(
+ "Timeout occurred while reading image file.",
+ code=AppErrorCode.MANIFEST_URL_CANT_CONNECT.value,
+ )
+ content.seek(0)
+ image_file = File(content, filename)
+ except requests.RequestException:
+ code = AppErrorCode.MANIFEST_URL_CANT_CONNECT.value
+ raise ValidationError("Unable to fetch image.", code=code)
+
+ validate_icon_image(image_file, code)
+ return image_file
+
+
+def fetch_brand_data(manifest_data, timeout=REQUEST_TIMEOUT):
+ brand_data = manifest_data.get("brand")
+ if not brand_data:
+ return None
+ try:
+ logo_url = brand_data["logo"]["default"]
+ logo_file = fetch_icon_image(logo_url, timeout=timeout)
+ brand_data["logo"]["default"] = logo_file
+ except ValidationError as error:
+ msg = "Fetching brand data failed for app:%r error:%r"
+ logger.info(msg, manifest_data["id"], error, extra={"brand_data": brand_data})
+ brand_data = None
+ return brand_data
+
+
+def _set_brand_data(brand_obj: Optional[Union[App, AppInstallation]], logo: File):
+ if not brand_obj:
+ return
+ try:
+ brand_obj.refresh_from_db()
+ except ObjectDoesNotExist:
+ return
+ try:
+ if not brand_obj.brand_logo_default:
+ brand_obj.brand_logo_default.save(logo.name, logo, save=False)
+ brand_obj.save(update_fields=["brand_logo_default"])
+ except DatabaseError:
+ # If object was already deleted from DB, remove created image
+ default_storage.delete(brand_obj.brand_logo_default.name)
+
+
[email protected](bind=True, retry_backoff=2700, retry_kwargs={"max_retries": 5})
+def fetch_brand_data_task(
+ self, brand_data: dict, *, app_installation_id=None, app_id=None
+):
+ """Task to fetch app's brand data. Last retry delayed 24H."""
+ app = App.objects.filter(id=app_id).first()
+ app_inst = AppInstallation.objects.filter(id=app_installation_id).first()
+ if not app_inst or (app_inst and app_inst.brand_logo_default):
+ if not app or (app and app.brand_logo_default):
+ # App and AppInstall deleted or brand data already fetched
+ return
+ try:
+ logo_img = fetch_icon_image(brand_data["logo"]["default"])
+ _set_brand_data(app_inst, logo_img)
+ _set_brand_data(app, logo_img)
+ except ValidationError as error:
+ extra = {
+ "app_id": app_id,
+ "app_installation_id": app_installation_id,
+ "brand_data": brand_data,
+ }
+ task_logger.info("Fetching brand data failed. Error: %r", error, extra=extra)
+ try:
+ countdown = self.retry_backoff * (2**self.request.retries)
+ raise self.retry(countdown=countdown, **self.retry_kwargs)
+ except MaxRetriesExceededError:
+ task_logger.info("Fetching brand data exceeded retry limit.", extra=extra)
+
+
+def fetch_brand_data_async(
+ manifest_data: dict,
+ *,
+ app_installation: Optional[AppInstallation] = None,
+ app: Optional[App] = None
+):
+ if brand_data := manifest_data.get("brand"):
+ app_id = app.pk if app else None
+ app_installation_id = app_installation.pk if app_installation else None
+ fetch_brand_data_task.delay(
+ brand_data, app_installation_id=app_installation_id, app_id=app_id
+ )
+
+
def install_app(app_installation: AppInstallation, activate: bool = False):
response = requests.get(
app_installation.manifest_url, timeout=REQUEST_TIMEOUT, allow_redirects=False
@@ -120,7 +254,9 @@ def install_app(app_installation: AppInstallation, activate: bool = False):
try:
send_app_token(target_url=manifest_data.get("tokenTargetUrl"), token=token)
except requests.RequestException as e:
+ fetch_brand_data_async(manifest_data, app_installation=app_installation)
app.delete()
raise e
PluginsManager(plugins=settings.PLUGINS).app_installed(app)
+ fetch_brand_data_async(manifest_data, app=app)
return app, token
diff --git a/saleor/app/management/commands/install_app.py b/saleor/app/management/commands/install_app.py
index caea182593..e32208c08e 100644
--- a/saleor/app/management/commands/install_app.py
+++ b/saleor/app/management/commands/install_app.py
@@ -57,6 +57,6 @@ class Command(BaseCommand):
app_job.delete()
except Exception as e:
app_job.status = JobStatus.FAILED
- app_job.save()
+ app_job.save(update_fields=["status"])
raise e
return json.dumps({"auth_token": token})
diff --git a/saleor/app/manifest_validations.py b/saleor/app/manifest_validations.py
index b39c67fb6b..c77f994248 100644
--- a/saleor/app/manifest_validations.py
+++ b/saleor/app/manifest_validations.py
@@ -21,7 +21,7 @@ from ..webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
from ..webhook.validators import custom_headers_validator
from .error_codes import AppErrorCode
from .types import AppExtensionMount, AppExtensionTarget
-from .validators import AppURLValidator
+from .validators import AppURLValidator, brand_validator
logger = logging.getLogger(__name__)
@@ -133,6 +133,11 @@ def clean_manifest_data(manifest_data, raise_for_saleor_version=False):
except ValidationError as e:
errors["author"].append(e)
+ try:
+ brand_validator(manifest_data.get("brand"))
+ except ValidationError as e:
+ errors["brand"].append(e)
+
saleor_permissions = get_permissions().annotate(
formated_codename=Concat("content_type__app_label", Value("."), "codename")
)
diff --git a/saleor/app/migrations/0025_auto_20230420_1544.py b/saleor/app/migrations/0025_auto_20230420_1544.py
new file mode 100644
index 0000000000..073ae0708d
--- /dev/null
+++ b/saleor/app/migrations/0025_auto_20230420_1544.py
@@ -0,0 +1,24 @@
+# Generated by Django 3.2.18 on 2023-04-20 15:44
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("app", "0024_auto_20230412_1343"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="app",
+ name="brand_logo_default",
+ field=models.ImageField(blank=True, null=True, upload_to="app-brand-data"),
+ ),
+ migrations.AddField(
+ model_name="appinstallation",
+ name="brand_logo_default",
+ field=models.ImageField(
+ blank=True, null=True, upload_to="app-installation-brand-data"
+ ),
+ ),
+ ]
diff --git a/saleor/app/models.py b/saleor/app/models.py
index fec4314fdf..c58820e907 100644
--- a/saleor/app/models.py
+++ b/saleor/app/models.py
@@ -62,6 +62,9 @@ class App(ModelWithMetadata):
audience = models.CharField(blank=True, null=True, max_length=256)
is_installed = models.BooleanField(default=True)
author = models.CharField(blank=True, null=True, max_length=60)
+ brand_logo_default = models.ImageField(
+ upload_to="app-brand-data", blank=True, null=True
+ )
objects = AppManager()
class Meta(ModelWithMetadata.Meta):
@@ -170,6 +173,9 @@ class AppInstallation(Job):
related_name="app_installation_set",
related_query_name="app_installation",
)
+ brand_logo_default = models.ImageField(
+ upload_to="app-installation-brand-data", blank=True, null=True
+ )
def set_message(self, message: str, truncate=True):
if truncate:
diff --git a/saleor/app/signals.py b/saleor/app/signals.py
new file mode 100644
index 0000000000..8e2abb63ee
--- /dev/null
+++ b/saleor/app/signals.py
@@ -0,0 +1,6 @@
+from ..core.tasks import delete_from_storage_task
+
+
+def delete_brand_images(sender, instance, **kwargs):
+ if img := instance.brand_logo_default:
+ delete_from_storage_task.delay(img.name)
diff --git a/saleor/app/tasks.py b/saleor/app/tasks.py
index 92560f9ab2..925aa15b1b 100644
--- a/saleor/app/tasks.py
+++ b/saleor/app/tasks.py
@@ -45,4 +45,4 @@ def install_app_task(job_id, activate=False):
logger.warning("Failed to install app. Error: %s", e)
app_installation.message = "Unknown error. Contact with app support."
app_installation.status = JobStatus.FAILED
- app_installation.save()
+ app_installation.save(update_fields=["message", "status"])
diff --git a/saleor/app/tests/test_installation_utils.py b/saleor/app/tests/test_installation_utils.py
index 8aaee982e1..1e6af911b5 100644
--- a/saleor/app/tests/test_installation_utils.py
+++ b/saleor/app/tests/test_installation_utils.py
@@ -4,7 +4,11 @@ from unittest.mock import ANY, Mock, patch
import graphene
import pytest
import requests
+from celery.exceptions import Retry
from django.core.exceptions import ValidationError
+from django.core.files import File
+from django.core.files.base import ContentFile
+from django.db import DatabaseError
from freezegun import freeze_time
from ... import __version__
@@ -13,7 +17,10 @@ from ...webhook.event_types import WebhookEventAsyncType
from ...webhook.payloads import generate_meta, generate_requestor
from ..error_codes import AppErrorCode
from ..installation_utils import (
+ MAX_ICON_FILE_SIZE,
AppInstallationError,
+ fetch_brand_data_task,
+ fetch_icon_image,
install_app,
validate_app_install_response,
)
@@ -168,6 +175,29 @@ def test_install_app_with_empty_author(app_manifest, app_installation, monkeypat
assert errors[0].code == AppErrorCode.INVALID.value
+def test_install_app_with_brand_data(app_manifest, app_installation, monkeypatch):
+ # given
+ brand_data = {"logo": {"default": "https://example.com/logo.png"}}
+ app_manifest["brand"] = brand_data
+ mocked_get_response = Mock()
+ mocked_get_response.json.return_value = app_manifest
+ monkeypatch.setattr(requests, "get", Mock(return_value=mocked_get_response))
+ monkeypatch.setattr("saleor.app.installation_utils.send_app_token", Mock())
+ mocked_fetch_brand_data_task = Mock()
+ monkeypatch.setattr(
+ "saleor.app.installation_utils.fetch_brand_data_task.delay",
+ mocked_fetch_brand_data_task,
+ )
+
+ # when
+ app, _ = install_app(app_installation, activate=True)
+
+ # then
+ mocked_fetch_brand_data_task.assert_called_once_with(
+ brand_data, app_installation_id=None, app_id=app.id
+ )
+
+
@freeze_time("2022-05-12 12:00:00")
@patch("saleor.plugins.webhook.plugin.get_webhooks_for_event")
@patch("saleor.plugins.webhook.plugin.trigger_webhooks_async")
@@ -575,3 +605,202 @@ def test_install_app_lack_of_token_target_url_in_manifest_data(
error_dict = excinfo.value.error_dict
assert "tokenTargetUrl" in error_dict
assert error_dict["tokenTargetUrl"][0].message == "Field required."
+
+
+def image_response_mock():
+ content_chunks = [b"fake ", b"image ", b"content"]
+ mock_response = Mock()
+ mock_response.status_code = 200
+ mock_response.content = b"".join(content_chunks)
+ mock_response.headers = {
+ "content-type": "image/png",
+ "content-length": str(len(mock_response.content)),
+ }
+ mock_response.iter_content.return_value = iter(content_chunks)
+ return mock_response
+
+
+@patch("saleor.app.installation_utils.validate_icon_image")
+@patch("saleor.app.installation_utils.requests.get")
+def test_fetch_icon_image(
+ mock_get_request, mock_validate_icon_image, image_response_mock
+):
+ # given
+ image_file_format = "png"
+ image_url = f"https://example.com/logo.{image_file_format}"
+ mock_get_request.return_value.__enter__.return_value = image_response_mock
+
+ # when
+ image_file = fetch_icon_image(image_url)
+
+ # then
+ mock_get_request.assert_called_once_with(
+ image_url, stream=True, timeout=ANY, allow_redirects=False
+ )
+ mock_validate_icon_image.assert_called_once_with(image_file, ANY)
+ assert isinstance(image_file, File)
+ assert image_file.read() == image_response_mock.content
+ assert image_file.name.endswith(image_file_format)
+
+
+@patch("saleor.app.installation_utils.validate_icon_image")
+@patch("saleor.app.installation_utils.requests.get")
+def test_fetch_icon_image_invalid_type(
+ mock_get_request, mock_validate_icon_image, image_response_mock
+):
+ mock_get_request.return_value.__enter__.return_value = image_response_mock
+ image_response_mock.headers["content-type"] = "text/html"
+
+ with pytest.raises(ValidationError) as error:
+ fetch_icon_image("https://example.com/logo.png")
+ assert error.value.code == AppErrorCode.INVALID.value
+ mock_validate_icon_image.assert_not_called()
+
+
+@patch("saleor.app.installation_utils.requests.get")
+def test_fetch_icon_image_content_length(mock_get_request, image_response_mock):
+ mock_get_request.return_value.__enter__.return_value = image_response_mock
+ image_response_mock.headers["content-length"] = MAX_ICON_FILE_SIZE + 1
+
+ with pytest.raises(ValidationError) as error:
+ fetch_icon_image("https://example.com/logo.png")
+ assert error.value.code == AppErrorCode.INVALID.value
+ assert "File too big. Maximal icon image file size is" in error.value.message
+
+
+@patch("saleor.app.installation_utils.requests.get")
+def test_fetch_icon_image_file_too_big(mock_get_request, image_response_mock):
+ def content_chunks():
+ while True:
+ yield b"0" * 1024
+
+ mock_get_request.return_value.__enter__.return_value = image_response_mock
+ image_response_mock.iter_content.return_value = content_chunks()
+
+ with pytest.raises(ValidationError) as error:
+ fetch_icon_image("https://example.com/logo.png")
+ assert error.value.code == AppErrorCode.INVALID.value
+ assert "File too big. Maximal icon image file size is" in error.value.message
+
+
+@patch("saleor.app.installation_utils.requests.get")
+def test_fetch_icon_image_network_error(mock_get_request):
+ mock_get_request.side_effect = requests.RequestException
+ with pytest.raises(ValidationError) as error:
+ fetch_icon_image("https://example.com/logo.png")
+ assert error.value.code == AppErrorCode.MANIFEST_URL_CANT_CONNECT.value
+
+
[email protected]("app_object", ["app", "app_installation"])
+@patch("saleor.app.installation_utils.fetch_icon_image")
+def test_fetch_brand_data_task(
+ mock_fetch_icon_image, app_object, app_installation, app, media_root
+):
+ # given
+ logo_url = "https://example.com/logo.png"
+ fake_img_content = b"these are bytes"
+ logo_img = ContentFile(fake_img_content, "logo.png")
+ mock_fetch_icon_image.return_value = logo_img
+
+ # when
+ fetch_brand_data_task(
+ {"logo": {"default": logo_url}},
+ app_installation_id=None if app_object == "app" else app_installation.id,
+ app_id=None if app_object != "app" else app.id,
+ )
+
+ # then
+ app.refresh_from_db()
+ app_installation.refresh_from_db()
+ mock_fetch_icon_image.assert_called_once_with(logo_url)
+ if app_object == "app":
+ assert app.brand_logo_default.read() == fake_img_content
+ assert bool(app_installation.brand_logo_default) is False
+ else:
+ assert app_installation.brand_logo_default.read() == fake_img_content
+ assert bool(app.brand_logo_default) is False
+
+
+@patch("saleor.app.installation_utils.fetch_icon_image")
+def test_fetch_brand_data_task_terminated(
+ mock_fetch_icon_image, app_installation, app, media_root
+):
+ app.delete(), app_installation.delete()
+ fetch_brand_data_task({}, app_installation_id=app_installation.id, app_id=app.id)
+ mock_fetch_icon_image.assert_not_called()
+
+
+@patch("saleor.app.installation_utils.fetch_icon_image")
+def test_fetch_brand_data_task_terminated_when_brand_data_fetched(
+ mock_fetch_icon_image, app_installation, app, media_root
+):
+ app_installation.delete()
+ app.brand_logo_default.save("logo.png", ContentFile(b"bytes"))
+ fetch_brand_data_task({}, app_installation_id=app_installation.id, app_id=app.id)
+ mock_fetch_icon_image.assert_not_called()
+
+
+@patch("saleor.app.installation_utils.fetch_icon_image")
+def test_fetch_brand_data_task_retry(
+ mock_fetch_icon_image, app_installation, app, media_root
+):
+ # given
+ brand_data = {"logo": {"default": "https://example.com/logo.png"}}
+ mock_fetch_icon_image.side_effect = ValidationError("Fetch image error")
+
+ # when
+ with pytest.raises(Retry):
+ fetch_brand_data_task(
+ brand_data, app_installation_id=app_installation.id, app_id=app.id
+ )
+
+
+@patch("saleor.app.installation_utils.fetch_icon_image")
+def test_fetch_brand_data_task_saving_brand_data(
+ mock_fetch_icon_image, app_installation, app, media_root
+):
+ # given
+ brand_data = {"logo": {"default": "https://example.com/logo.png"}}
+ fake_img_content = b"these are bytes"
+ logo_img = ContentFile(fake_img_content, "logo.png")
+
+ def fake_fetch_icon_image(*args, **kwargs):
+ # AppInstallation deleted during brand data fetching
+ app_installation.delete()
+ return logo_img
+
+ mock_fetch_icon_image.side_effect = fake_fetch_icon_image
+
+ # when
+ fetch_brand_data_task(
+ brand_data, app_installation_id=app_installation.id, app_id=app.id
+ )
+
+ # then
+ app.refresh_from_db()
+ assert app.brand_logo_default.read() == fake_img_content
+
+
+@patch("saleor.app.installation_utils.AppInstallation.save", side_effect=DatabaseError)
+@patch("saleor.app.installation_utils.default_storage.delete")
+@patch("saleor.app.installation_utils.fetch_icon_image")
+def test_fetch_brand_data_task_saving_deleted_object(
+ mock_fetch_icon_image,
+ mock_storage_delete,
+ _mock_app_installation_save,
+ app_installation,
+ media_root,
+):
+ # given
+ brand_data = {"logo": {"default": "https://example.com/logo.png"}}
+ file_name = "logo.png"
+ mock_fetch_icon_image.return_value = ContentFile(b"these are bytes", file_name)
+
+ # when
+ fetch_brand_data_task(brand_data, app_installation_id=app_installation.id)
+
+ # then
+ mock_storage_delete.assert_called_once_with(
+ f"app-installation-brand-data/{file_name}"
+ )
diff --git a/saleor/app/tests/test_validators.py b/saleor/app/tests/test_validators.py
index 2303a9fa97..ce4ad7f58b 100644
--- a/saleor/app/tests/test_validators.py
+++ b/saleor/app/tests/test_validators.py
@@ -9,6 +9,7 @@ from ..manifest_validations import (
clean_required_saleor_version,
parse_version,
)
+from ..validators import brand_validator
def test_validate_url():
@@ -66,3 +67,23 @@ def test_clean_required_saleor_version_raise_for_saleor_version():
@pytest.mark.parametrize("author,cleaned", [(None, None), (" Acme Ltd ", "Acme Ltd")])
def test_clean_author(author, cleaned):
assert clean_author(author) == cleaned
+
+
+def test_brand_validator_required_fields():
+ with pytest.raises(ValidationError) as error:
+ brand_validator({"logo": {}})
+ assert error.value.code == AppErrorCode.REQUIRED.value
+
+
+ "url",
+ [
+ "example.com/logo.png",
+ "https://exmple.com/logo",
+ "https://exmple.com/logo.jpg",
+ ],
+)
+def test_brand_validator_with_invalid_logo_url(url):
+ with pytest.raises(ValidationError) as error:
+ brand_validator({"logo": {"default": url}})
+ assert error.value.code == AppErrorCode.INVALID_URL_FORMAT.value
diff --git a/saleor/app/validators.py b/saleor/app/validators.py
index f009bb180a..d8b4253a09 100644
--- a/saleor/app/validators.py
+++ b/saleor/app/validators.py
@@ -1,7 +1,12 @@
+import mimetypes
import re
+from django.core.exceptions import ValidationError
from django.core.validators import URLValidator
+from ..thumbnail import ICON_MIME_TYPES
+from .error_codes import AppErrorCode
+
class AppURLValidator(URLValidator):
validator = URLValidator
@@ -15,3 +20,27 @@ class AppURLValidator(URLValidator):
r"\Z",
re.IGNORECASE,
)
+
+
+image_url_validator = AppURLValidator(
+ message="Incorrect value for field: logo.default.",
+ code=AppErrorCode.INVALID_URL_FORMAT.value,
+)
+
+
+def brand_validator(brand):
+ if brand is None:
+ return
+ try:
+ logo_url = brand["logo"]["default"]
+ except (TypeError, KeyError):
+ raise ValidationError(
+ "Missing required field: logo.default.", code=AppErrorCode.REQUIRED.value
+ )
+ image_url_validator(logo_url)
+ filetype = mimetypes.guess_type(logo_url)[0]
+ if filetype not in ICON_MIME_TYPES:
+ raise ValidationError(
+ "Invalid file type for field: logo.default.",
+ code=AppErrorCode.INVALID_URL_FORMAT.value,
+ )
diff --git a/saleor/graphql/app/dataloaders.py b/saleor/graphql/app/dataloaders.py
index 4247364877..812c3be91d 100644
--- a/saleor/graphql/app/dataloaders.py
+++ b/saleor/graphql/app/dataloaders.py
@@ -10,7 +10,7 @@ from ...app.models import App, AppExtension, AppToken
from ...core.auth import get_token_from_request
from ...core.utils.lazyobjects import unwrap_lazy
from ..core import SaleorContext
-from ..core.dataloaders import DataLoader
+from ..core.dataloaders import BaseThumbnailBySizeAndFormatLoader, DataLoader
class AppByIdLoader(DataLoader):
@@ -102,6 +102,18 @@ class AppByTokenLoader(DataLoader):
return [apps.get(authed_apps.get(key)) for key in keys]
+class ThumbnailByAppIdSizeAndFormatLoader(BaseThumbnailBySizeAndFormatLoader):
+ context_key = "thumbnail_by_app_size_and_format"
+ model_name = "app"
+
+
+class ThumbnailByAppInstallationIdSizeAndFormatLoader(
+ BaseThumbnailBySizeAndFormatLoader
+):
+ context_key = "thumbnail_by_app_installation_size_and_format"
+ model_name = "app_installation"
+
+
def promise_app(context: SaleorContext) -> Promise[Optional[App]]:
auth_token = get_token_from_request(context)
if not auth_token or len(auth_token) != 30:
diff --git a/saleor/graphql/app/mutations/app_fetch_manifest.py b/saleor/graphql/app/mutations/app_fetch_manifest.py
index 4f44c3c326..51f883b385 100644
--- a/saleor/graphql/app/mutations/app_fetch_manifest.py
+++ b/saleor/graphql/app/mutations/app_fetch_manifest.py
@@ -3,7 +3,7 @@ import requests
from django.core.exceptions import ValidationError
from ....app.error_codes import AppErrorCode
-from ....app.installation_utils import REQUEST_TIMEOUT
+from ....app.installation_utils import REQUEST_TIMEOUT, fetch_brand_data
from ....app.manifest_validations import clean_manifest_data, clean_manifest_url
from ....permission.enums import AppPermission
from ...core import types as grapqhl_types
@@ -13,6 +13,8 @@ from ...core.mutations import BaseMutation
from ...core.types import AppError
from ..types import Manifest
+FETCH_BRAND_DATA_TIMEOUT = 5
+
class AppFetchManifest(BaseMutation):
manifest = graphene.Field(Manifest)
@@ -77,11 +79,15 @@ class AppFetchManifest(BaseMutation):
audience=cleaned_data.get("audience"),
required_saleor_version=cleaned_data.get("requiredSaleorVersion"),
author=cleaned_data.get("author"),
+ brand=cleaned_data.get("brand"),
)
@classmethod
def clean_manifest_data(cls, info, manifest_data):
clean_manifest_data(manifest_data)
+ manifest_data["brand"] = fetch_brand_data(
+ manifest_data, timeout=FETCH_BRAND_DATA_TIMEOUT
+ )
manifest_data["permissions"] = [
grapqhl_types.Permission(
diff --git a/saleor/graphql/app/tests/mutations/test_app_fetch_manifest.py b/saleor/graphql/app/tests/mutations/test_app_fetch_manifest.py
index c8c8b88eb0..f5513d2a2e 100644
--- a/saleor/graphql/app/tests/mutations/test_app_fetch_manifest.py
+++ b/saleor/graphql/app/tests/mutations/test_app_fetch_manifest.py
@@ -1,14 +1,23 @@
+import base64
+from io import BytesIO
from unittest.mock import Mock
import pytest
import requests
+from PIL import Image
from .....app.error_codes import AppErrorCode
+from .....thumbnail import IconThumbnailFormat
from ....tests.utils import assert_no_permission, get_graphql_content
from ...enums import AppExtensionMountEnum, AppExtensionTargetEnum
+from ...mutations.app_fetch_manifest import FETCH_BRAND_DATA_TIMEOUT
APP_FETCH_MANIFEST_MUTATION = """
-mutation AppFetchManifest($manifest_url: String!){
+mutation AppFetchManifest(
+ $manifest_url: String!
+ $size: Int
+ $format: IconThumbnailFormatEnum
+) {
appFetchManifest(manifestUrl:$manifest_url){
manifest{
identifier
@@ -41,6 +50,11 @@ mutation AppFetchManifest($manifest_url: String!){
name
}
}
+ brand{
+ logo{
+ default(size: $size, format: $format)
+ }
+ }
}
errors{
field
@@ -84,6 +98,7 @@ def test_app_fetch_manifest(staff_api_client, staff_user, permission_manage_apps
"MANAGE_USERS",
}
assert manifest["requiredSaleorVersion"] is None
+ assert manifest["brand"] is None
@pytest.mark.vcr
@@ -733,3 +748,82 @@ def test_app_fetch_manifest_with_empty_author(
assert len(errors) == 1
assert errors[0]["field"] == "author"
assert errors[0]["code"] == AppErrorCode.INVALID.name
+
+
+ "format,expected_format,size",
+ [
+ (None, "png", None),
+ (IconThumbnailFormat.WEBP, "webp", 120),
+ (IconThumbnailFormat.ORIGINAL, "png", 0),
+ ],
+)
+def test_app_fetch_manifest_with_brand_data(
+ format,
+ expected_format,
+ size,
+ staff_api_client,
+ app_manifest,
+ permission_manage_apps,
+ icon_image,
+ monkeypatch,
+):
+ # given
+ logo_url = "http://localhost:3000/logo.png"
+ app_manifest["brand"] = {"logo": {"default": logo_url}}
+ mocked_get_response = Mock()
+ mocked_get_response.json.return_value = app_manifest
+ monkeypatch.setattr(requests, "get", Mock(return_value=mocked_get_response))
+ mock_fetch_icon_image = Mock(return_value=icon_image)
+ monkeypatch.setattr(
+ "saleor.app.installation_utils.fetch_icon_image", mock_fetch_icon_image
+ )
+
+ # when
+ response = staff_api_client.post_graphql(
+ APP_FETCH_MANIFEST_MUTATION,
+ variables={
+ "manifest_url": "http://localhost:3000/manifest",
+ "size": size,
+ "format": format.upper() if format else None,
+ },
+ permissions=[permission_manage_apps],
+ )
+
+ # then
+ mock_fetch_icon_image.assert_called_once_with(
+ logo_url, timeout=FETCH_BRAND_DATA_TIMEOUT
+ )
+ content = get_graphql_content(response)
+ manifest = content["data"]["appFetchManifest"]["manifest"]
+ assert len(content["data"]["appFetchManifest"]["errors"]) == 0
+ # decode and check icon thumbnail from data url
+ data_url_prefix, base64_icon = manifest["brand"]["logo"]["default"].split(",", 1)
+ assert data_url_prefix == f"data:image/{expected_format};base64"
+ icon_thumbnail = BytesIO(base64.b64decode(base64_icon.encode()))
+ with Image.open(icon_thumbnail) as image:
+ assert image.format == expected_format.upper()
+
+
+def test_app_fetch_manifest_with_invalid_brand_data(
+ staff_api_client, app_manifest, permission_manage_apps, monkeypatch
+):
+ # given
+ app_manifest["brand"] = {"logo": {"default": "wrong-url.png"}}
+ mocked_get_response = Mock()
+ mocked_get_response.json.return_value = app_manifest
+ monkeypatch.setattr(requests, "get", Mock(return_value=mocked_get_response))
+
+ # when
+ response = staff_api_client.post_graphql(
+ APP_FETCH_MANIFEST_MUTATION,
+ variables={"manifest_url": "http://localhost:3000/manifest"},
+ permissions=[permission_manage_apps],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ errors = content["data"]["appFetchManifest"]["errors"]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "brand"
+ assert errors[0]["code"] == AppErrorCode.INVALID_URL_FORMAT.name
diff --git a/saleor/graphql/app/tests/queries/test_app.py b/saleor/graphql/app/tests/queries/test_app.py
index ea39f13b67..28d32bc8a6 100644
--- a/saleor/graphql/app/tests/queries/test_app.py
+++ b/saleor/graphql/app/tests/queries/test_app.py
@@ -5,6 +5,8 @@ from freezegun import freeze_time
from .....app.models import App
from .....app.types import AppType
from .....core.jwt import create_access_token_for_app, jwt_decode
+from .....thumbnail import IconThumbnailFormat
+from .....thumbnail.models import Thumbnail
from ....tests.utils import assert_no_permission, get_graphql_content
QUERY_APP = """
@@ -43,6 +45,11 @@ QUERY_APP = """
code
}
}
+ brand{
+ logo{
+ default
+ }
+ }
metafield(key: "test")
metafields(keys: ["test"])
metadata{
@@ -108,6 +115,7 @@ def test_app_query(
assert app_data["configurationUrl"] == app.configuration_url
assert app_data["appUrl"] == app.app_url
assert app_data["author"] == app.author
+ assert app_data["brand"] is None
if app_type == "external":
assert app_data["accessToken"] == create_access_token_for_app(
app, staff_api_client.user
@@ -335,7 +343,7 @@ def test_app_query_pending_installation(staff_api_client, app):
QUERY_APP_AVAILABLE_FOR_STAFF_WITHOUT_MANAGE_APPS = """
- query ($id: ID){
+ query ($id: ID, $size: Int, $format: IconThumbnailFormatEnum){
app(id: $id){
id
created
@@ -353,6 +361,11 @@ QUERY_APP_AVAILABLE_FOR_STAFF_WITHOUT_MANAGE_APPS = """
configurationUrl
appUrl
accessToken
+ brand{
+ logo{
+ default(size: $size, format: $format)
+ }
+ }
extensions{
id
label
@@ -445,6 +458,83 @@ def test_app_query_access_token_with_audience(
assert decoded_token["aud"] == app.audience
+ "format",
+ (
+ None,
+ IconThumbnailFormat.WEBP,
+ IconThumbnailFormat.ORIGINAL,
+ ),
+)
[email protected]("thumbnail_exists", (True, False))
+def test_app_query_logo_thumbnail_with_size_and_format_url_returned(
+ thumbnail_exists,
+ format,
+ staff_api_client,
+ app,
+ site_settings,
+ icon_image,
+ media_root,
+):
+ # given
+ app.brand_logo_default = icon_image
+ app.save()
+ id = graphene.Node.to_global_id("App", app.id)
+ media_id = graphene.Node.to_global_id("App", app.uuid)
+ domain = site_settings.site.domain
+ if thumbnail_exists:
+ thumbnail = Thumbnail.objects.create(
+ app=app,
+ size=128,
+ format=format or IconThumbnailFormat.ORIGINAL,
+ image=icon_image,
+ )
+ expected_url = f"http://{domain}/media/{thumbnail.image.name}"
+ else:
+ expected_url = f"http://{domain}/thumbnail/{media_id}/128/"
+ if format not in [None, IconThumbnailFormat.ORIGINAL]:
+ expected_url += f"{format}/"
+ variables = {"id": id, "size": 120, "format": format.upper() if format else None}
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_APP_AVAILABLE_FOR_STAFF_WITHOUT_MANAGE_APPS,
+ variables,
+ )
+ # then
+ content = get_graphql_content(response)
+ thumbnail_url = content["data"]["app"]["brand"]["logo"]["default"]
+ assert thumbnail_url == expected_url
+
+
+ "format",
+ (
+ None,
+ IconThumbnailFormat.WEBP,
+ IconThumbnailFormat.ORIGINAL,
+ ),
+)
+def test_app_query_logo_thumbnail_with_zero_size_value_original_image_url_returned(
+ format, staff_api_client, app, site_settings, icon_image, media_root
+):
+ # given
+ app.brand_logo_default = icon_image
+ app.save()
+ id = graphene.Node.to_global_id("App", app.id)
+ domain = site_settings.site.domain
+ expected_url = f"http://{domain}/media/{app.brand_logo_default.name}"
+ variables = {"id": id, "size": 0, "format": format.upper() if format else None}
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_APP_AVAILABLE_FOR_STAFF_WITHOUT_MANAGE_APPS,
+ variables,
+ )
+ # then
+ content = get_graphql_content(response)
+ thumbnail_url = content["data"]["app"]["brand"]["logo"]["default"]
+ assert thumbnail_url == expected_url
+
+
def test_app_query_for_normal_user(
user_api_client, permission_manage_users, permission_manage_staff, app
):
diff --git a/saleor/graphql/app/tests/queries/test_apps_installations.py b/saleor/graphql/app/tests/queries/test_apps_installations.py
index 78650d0cbe..cd6052ce2f 100644
--- a/saleor/graphql/app/tests/queries/test_apps_installations.py
+++ b/saleor/graphql/app/tests/queries/test_apps_installations.py
@@ -1,5 +1,8 @@
import graphene
+import pytest
+from .....thumbnail import IconThumbnailFormat
+from .....thumbnail.models import Thumbnail
from ....tests.utils import assert_no_permission, get_graphql_content
APPS_INSTALLATION_QUERY = """
@@ -45,3 +48,105 @@ def test_apps_installation_by_app_missing_permission(app_api_client):
def test_apps_installation_missing_permission(staff_api_client):
response = staff_api_client.post_graphql(APPS_INSTALLATION_QUERY)
assert_no_permission(response)
+
+
+APPS_INSTALLATION_QUERY_WITH_LOGO = """
+query ($size: Int, $format: IconThumbnailFormatEnum) {
+ appsInstallations {
+ id
+ brand {
+ logo {
+ default(format: $format, size: $size)
+ }
+ }
+ }
+}
+"""
+
+
+ "format",
+ (
+ None,
+ IconThumbnailFormat.WEBP,
+ IconThumbnailFormat.ORIGINAL,
+ ),
+)
[email protected]("thumbnail_exists", (True, False))
+def test_apps_installations_query_logo_thumbnail_with_size_and_format_url_returned(
+ thumbnail_exists,
+ format,
+ app_installation,
+ staff_api_client,
+ permission_manage_apps,
+ site_settings,
+ icon_image,
+ media_root,
+):
+ # given
+ app_installation.brand_logo_default = icon_image
+ app_installation.save()
+ media_id = graphene.Node.to_global_id("AppInstallation", app_installation.uuid)
+ domain = site_settings.site.domain
+ if thumbnail_exists:
+ thumbnail = Thumbnail.objects.create(
+ app_installation=app_installation,
+ size=128,
+ format=format or IconThumbnailFormat.ORIGINAL,
+ image=icon_image,
+ )
+ expected_url = f"http://{domain}/media/{thumbnail.image.name}"
+ else:
+ expected_url = f"http://{domain}/thumbnail/{media_id}/128/"
+ if format not in [None, IconThumbnailFormat.ORIGINAL]:
+ expected_url += f"{format}/"
+ variables = {"size": 120, "format": format.upper() if format else None}
+ # when
+ response = staff_api_client.post_graphql(
+ APPS_INSTALLATION_QUERY_WITH_LOGO,
+ variables,
+ permissions=[permission_manage_apps],
+ )
+ content = get_graphql_content(response)
+ installations = content["data"]["appsInstallations"]
+ # then
+ assert len(installations) == 1
+ thumbnail_url = installations[0]["brand"]["logo"]["default"]
+ assert thumbnail_url == expected_url
+
+
+ "format",
+ (
+ None,
+ IconThumbnailFormat.WEBP,
+ IconThumbnailFormat.ORIGINAL,
+ ),
+)
+def test_apps_installations_query_logo_thumbnail_original_image_url_returned(
+ format,
+ app_installation,
+ staff_api_client,
+ permission_manage_apps,
+ site_settings,
+ icon_image,
+ media_root,
+):
+ # given
+ app_installation.brand_logo_default = icon_image
+ app_installation.save()
+ domain = site_settings.site.domain
+ expected_url = f"http://{domain}/media/{app_installation.brand_logo_default.name}"
+ variables = {"size": 0, "format": format.upper() if format else None}
+ # when
+ response = staff_api_client.post_graphql(
+ APPS_INSTALLATION_QUERY_WITH_LOGO,
+ variables,
+ permissions=[permission_manage_apps],
+ )
+ content = get_graphql_content(response)
+ installations = content["data"]["appsInstallations"]
+ # then
+ assert len(installations) == 1
+ thumbnail_url = installations[0]["brand"]["logo"]["default"]
+ assert thumbnail_url == expected_url
diff --git a/saleor/graphql/app/types.py b/saleor/graphql/app/types.py
index df2e10ab13..55e84aa874 100644
--- a/saleor/graphql/app/types.py
+++ b/saleor/graphql/app/types.py
@@ -1,4 +1,5 @@
-from typing import List, Union
+import base64
+from typing import List, Optional, Type, Union
import graphene
@@ -6,9 +7,18 @@ from ...app import models
from ...app.types import AppExtensionTarget
from ...core.exceptions import PermissionDenied
from ...core.jwt import JWT_THIRDPARTY_ACCESS_TYPE
+from ...core.utils import build_absolute_uri
from ...permission.auth_filters import AuthorizationFilters
from ...permission.enums import AppPermission
from ...permission.utils import message_one_of_permissions_required
+from ...thumbnail import PIL_IDENTIFIER_TO_MIME_TYPE
+from ...thumbnail.utils import (
+ ProcessedIconImage,
+ get_icon_thumbnail_format,
+ get_image_or_proxy_url,
+ get_thumbnail_format,
+ get_thumbnail_size,
+)
from ..account.utils import is_owner_or_has_one_of_perms
from ..core import ResolveInfo, SaleorContext
from ..core.connection import CountableConnection
@@ -17,12 +27,20 @@ from ..core.descriptions import (
ADDED_IN_35,
ADDED_IN_38,
ADDED_IN_313,
+ ADDED_IN_314,
DEPRECATED_IN_3X_FIELD,
PREVIEW_FEATURE,
)
from ..core.doc_category import DOC_CATEGORY_APPS
from ..core.federation import federated_entity, resolve_federation_references
-from ..core.types import BaseObjectType, Job, ModelObjectType, NonNullList, Permission
+from ..core.types import (
+ BaseObjectType,
+ IconThumbnailField,
+ Job,
+ ModelObjectType,
+ NonNullList,
+ Permission,
+)
from ..core.utils import from_global_id_or_error
from ..meta.types import ObjectWithMetadata
from ..utils import format_permissions_for_display, get_user_or_app_from_context
@@ -33,6 +51,9 @@ from .dataloaders import (
AppByIdLoader,
AppExtensionByAppIdLoader,
AppTokensByAppIdLoader,
+ DataLoader,
+ ThumbnailByAppIdSizeAndFormatLoader,
+ ThumbnailByAppInstallationIdSizeAndFormatLoader,
app_promise_callback,
)
from .enums import AppExtensionMountEnum, AppExtensionTargetEnum, AppTypeEnum
@@ -42,6 +63,9 @@ from .resolvers import (
resolve_app_extension_url,
)
+# Maximal thumbnail size for manifest preview
+MANIFEST_THUMBNAIL_MAX_SIZE = 512
+
def has_required_permission(app: models.App, context: SaleorContext):
requester = get_user_or_app_from_context(context)
@@ -227,6 +251,131 @@ class AppManifestRequiredSaleorVersion(BaseObjectType):
doc_category = DOC_CATEGORY_APPS
+class AppManifestBrandLogo(BaseObjectType):
+ default = IconThumbnailField(
+ graphene.String,
+ required=True,
+ description="Data URL with a base64 encoded logo image."
+ + ADDED_IN_314
+ + PREVIEW_FEATURE,
+ )
+
+ class Meta:
+ doc_category = DOC_CATEGORY_APPS
+ description = (
+ "Represents the app's manifest brand data." + ADDED_IN_314 + PREVIEW_FEATURE
+ )
+
+ @staticmethod
+ def resolve_default(
+ root,
+ _info: ResolveInfo,
+ *,
+ size: Optional[int] = None,
+ format: Optional[str] = None
+ ):
+ format = get_icon_thumbnail_format(format)
+ # limit thumbnail max size as it is transferred
+ # as text and used for preview purposes only
+ if size == 0:
+ size = MANIFEST_THUMBNAIL_MAX_SIZE
+ size = min(get_thumbnail_size(size), MANIFEST_THUMBNAIL_MAX_SIZE)
+
+ logo_img = root["default"]
+ # prepare thumbnail on the fly
+ processed_image = ProcessedIconImage(logo_img, size, format)
+ thumbnail, thumbnail_format = processed_image.create_thumbnail()
+ mimetype = PIL_IDENTIFIER_TO_MIME_TYPE[thumbnail_format]
+
+ thumbnail_str = base64.b64encode(thumbnail.read()).decode()
+ return f"data:{mimetype};base64,{thumbnail_str}"
+
+
+class AppBrandLogo(BaseObjectType):
+ default = IconThumbnailField(
+ graphene.String,
+ required=True,
+ description="URL to the default logo image." + ADDED_IN_314 + PREVIEW_FEATURE,
+ )
+
+ class Meta:
+ doc_category = DOC_CATEGORY_APPS
+ description = (
+ "Represents the app's brand logo data." + ADDED_IN_314 + PREVIEW_FEATURE
+ )
+
+ @staticmethod
+ def resolve_default(
+ root: Union[models.App, models.AppInstallation],
+ info: ResolveInfo,
+ *,
+ size: Optional[int] = None,
+ format: Optional[str] = None,
+ ):
+ if not root.brand_logo_default:
+ return None
+ if size == 0:
+ return build_absolute_uri(root.brand_logo_default.url)
+
+ format = get_thumbnail_format(format)
+ selected_size = get_thumbnail_size(size)
+
+ if isinstance(root, models.App):
+ object_type = "App"
+ dataloader: Type[DataLoader] = ThumbnailByAppIdSizeAndFormatLoader
+ elif isinstance(root, models.AppInstallation):
+ object_type = "AppInstallation"
+ dataloader = ThumbnailByAppInstallationIdSizeAndFormatLoader
+ else:
+ return None
+
+ def _resolve_logo(thumbnail):
+ url = get_image_or_proxy_url(
+ thumbnail, str(root.uuid), object_type, selected_size, format
+ )
+ return build_absolute_uri(url)
+
+ return (
+ dataloader(info.context)
+ .load((root.id, selected_size, format))
+ .then(_resolve_logo)
+ )
+
+
+class AppBrand(BaseObjectType):
+ logo = graphene.Field(
+ AppBrandLogo,
+ required=True,
+ description="App's logos details." + ADDED_IN_314 + PREVIEW_FEATURE,
+ )
+
+ class Meta:
+ description = (
+ "Represents the app's brand data." + ADDED_IN_314 + PREVIEW_FEATURE
+ )
+ doc_category = DOC_CATEGORY_APPS
+
+ @staticmethod
+ def resolve_logo(
+ root: Union[models.App, models.AppInstallation], _info: ResolveInfo
+ ):
+ return root
+
+
+class AppManifestBrand(BaseObjectType):
+ logo = graphene.Field(
+ AppManifestBrandLogo,
+ required=True,
+ description="App's logos details." + ADDED_IN_314 + PREVIEW_FEATURE,
+ )
+
+ class Meta:
+ description = (
+ "Represents the app's manifest brand data." + ADDED_IN_314 + PREVIEW_FEATURE
+ )
+ doc_category = DOC_CATEGORY_APPS
+
+
class Manifest(BaseObjectType):
identifier = graphene.String(required=True)
version = graphene.String(required=True)
@@ -269,6 +418,10 @@ class Manifest(BaseObjectType):
author = graphene.String(
description=("The App's author name." + ADDED_IN_313 + PREVIEW_FEATURE)
)
+ brand = graphene.Field(
+ AppManifestBrand,
+ description="App's brand data." + ADDED_IN_314 + PREVIEW_FEATURE,
+ )
class Meta:
description = "The manifest definition."
@@ -366,6 +519,9 @@ class App(ModelObjectType[models.App]):
description="App's dashboard extensions." + ADDED_IN_31,
required=True,
)
+ brand = graphene.Field(
+ AppBrand, description="App's brand data." + ADDED_IN_314 + PREVIEW_FEATURE
+ )
class Meta:
description = "Represents app data."
@@ -431,6 +587,11 @@ class App(ModelObjectType[models.App]):
check_permission_for_access_to_meta(root, info, app)
return ObjectWithMetadata.resolve_metafields(root, info, keys=keys)
+ @staticmethod
+ def resolve_brand(root: models.App, _info: ResolveInfo):
+ if root.brand_logo_default:
+ return root
+
class AppCountableConnection(CountableConnection):
class Meta:
@@ -442,8 +603,16 @@ class AppInstallation(ModelObjectType[models.AppInstallation]):
id = graphene.GlobalID(required=True)
app_name = graphene.String(required=True)
manifest_url = graphene.String(required=True)
+ brand = graphene.Field(
+ AppBrand, description="App's brand data." + ADDED_IN_314 + PREVIEW_FEATURE
+ )
class Meta:
model = models.AppInstallation
description = "Represents ongoing installation of app."
interfaces = [graphene.relay.Node, Job]
+
+ @staticmethod
+ def resolve_brand(root: models.AppInstallation, _info: ResolveInfo):
+ if root.brand_logo_default:
+ return root
diff --git a/saleor/graphql/core/dataloaders.py b/saleor/graphql/core/dataloaders.py
index 71aced6561..b38877ba34 100644
--- a/saleor/graphql/core/dataloaders.py
+++ b/saleor/graphql/core/dataloaders.py
@@ -1,10 +1,13 @@
-from typing import Generic, Iterable, List, TypeVar, Union
+from collections import defaultdict
+from typing import DefaultDict, Generic, Iterable, List, Optional, Tuple, TypeVar, Union
import opentracing
import opentracing.tags
from promise import Promise
from promise.dataloader import DataLoader as BaseLoader
+from ...thumbnail.models import Thumbnail
+from ...thumbnail.utils import get_thumbnail_format
from . import SaleorContext
from .context import get_database_connection_name
@@ -50,3 +53,26 @@ class DataLoader(BaseLoader, Generic[K, R]):
def batch_load(self, keys: Iterable[K]) -> Union[Promise[List[R]], List[R]]:
raise NotImplementedError()
+
+
+class BaseThumbnailBySizeAndFormatLoader(
+ DataLoader[Tuple[int, int, Optional[str]], Thumbnail]
+):
+ model_name: str
+
+ def batch_load(self, keys: Iterable[Tuple[int, int, Optional[str]]]):
+ model_name = self.model_name.lower()
+ instance_ids = [id for id, _, _ in keys]
+ lookup = {f"{model_name}_id__in": instance_ids}
+ thumbnails = Thumbnail.objects.using(self.database_connection_name).filter(
+ **lookup
+ )
+ thumbnails_by_instance_id_size_and_format_map: DefaultDict[
+ Tuple[int, int, Optional[str]], Thumbnail
+ ] = defaultdict()
+ for thumbnail in thumbnails:
+ format = get_thumbnail_format(thumbnail.format)
+ thumbnails_by_instance_id_size_and_format_map[
+ (getattr(thumbnail, f"{model_name}_id"), thumbnail.size, format)
+ ] = thumbnail
+ return [thumbnails_by_instance_id_size_and_format_map.get(key) for key in keys]
diff --git a/saleor/graphql/core/enums.py b/saleor/graphql/core/enums.py
index bcdc635dae..829562349c 100644
--- a/saleor/graphql/core/enums.py
+++ b/saleor/graphql/core/enums.py
@@ -28,7 +28,7 @@ from ...plugins import error_codes as plugin_error_codes
from ...product import error_codes as product_error_codes
from ...shipping import error_codes as shipping_error_codes
from ...site import error_codes as site_error_codes
-from ...thumbnail import ThumbnailFormat
+from ...thumbnail import IconThumbnailFormat, ThumbnailFormat
from ...warehouse import error_codes as warehouse_error_codes
from ...webhook import error_codes as webhook_error_codes
from ..notifications import error_codes as external_notifications_error_codes
@@ -110,6 +110,11 @@ PermissionEnum.doc_category = DOC_CATEGORY_USERS
TimePeriodTypeEnum = to_enum(TimePeriodType)
ThumbnailFormatEnum = to_enum(ThumbnailFormat)
+IconThumbnailFormatEnum = to_enum(
+ IconThumbnailFormat,
+ type_name="IconThumbnailFormatEnum",
+ description=IconThumbnailFormat.__doc__,
+)
# unit enums
MeasurementUnitsEnum = to_enum(MeasurementUnits)
diff --git a/saleor/graphql/core/tests/test_core.py b/saleor/graphql/core/tests/test_core.py
index 66b6f087f8..9085f93893 100644
--- a/saleor/graphql/core/tests/test_core.py
+++ b/saleor/graphql/core/tests/test_core.py
@@ -13,6 +13,7 @@ from micawber import ProviderException, ProviderRegistry
from ....core.utils.validators import get_oembed_data
from ....product import ProductMediaTypes
from ....product.models import Product, ProductChannelListing
+from ....thumbnail import FILE_NAME_MAX_LENGTH
from ...tests.utils import get_graphql_content, get_graphql_content_from_response
from ...utils import requestor_is_superuser
from ...utils.filters import filter_range_field, reporting_period_to_date
@@ -21,7 +22,6 @@ from ..filters import EnumFilter
from ..mutations import BaseMutation, ModelWithExtRefMutation
from ..types import FilterInputObjectType
from ..utils import (
- FILE_NAME_MAX_LENGTH,
add_hash_to_file_name,
ext_ref_to_global_id_or_error,
get_duplicated_values,
diff --git a/saleor/graphql/core/tests/test_file_validation.py b/saleor/graphql/core/tests/test_file_validation.py
index 7b06cc4466..83867980b7 100644
--- a/saleor/graphql/core/tests/test_file_validation.py
+++ b/saleor/graphql/core/tests/test_file_validation.py
@@ -7,65 +7,14 @@ from django.core.files.uploadedfile import SimpleUploadedFile
from PIL import Image
from ....product.error_codes import ProductErrorCode
-from ...core.utils import FILE_NAME_MAX_LENGTH
from ..validators.file import (
clean_image_file,
- get_filename_from_url,
is_image_mimetype,
is_supported_image_mimetype,
validate_image_url,
)
-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_get_filename_from_url_with_long_name_is_trimmed():
- # given
- file_format = "jpg"
- file_name = "2Fvar2Ffolders2Fbj2F61gtb14j7rz474yd15tnkzjh0000gn2FT2Fa"
- assert len(file_name) > FILE_NAME_MAX_LENGTH
- url = f"http://example.com/{file_name}.{file_format}"
-
- # when
- result = get_filename_from_url(url)
-
- # then
- assert result.startswith(file_name[:FILE_NAME_MAX_LENGTH])
- assert result.endswith(file_format)
- assert result != f"{file_name}.{file_format}"
- assert len(result.split("_")[0]) == FILE_NAME_MAX_LENGTH
-
-
-def test_get_filename_from_url_with_short_name_is_not_trimmed():
- # given
- file_format = "jpg"
- file_name = "short"
- assert len(file_name) < FILE_NAME_MAX_LENGTH
- 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}"
- assert len(result.split("_")[0]) < FILE_NAME_MAX_LENGTH
-
-
def test_is_image_mimetype_valid_mimetype():
# given
valid_mimetype = "image/jpeg"
diff --git a/saleor/graphql/core/types/__init__.py b/saleor/graphql/core/types/__init__.py
index 221573adf8..f1a53531b3 100644
--- a/saleor/graphql/core/types/__init__.py
+++ b/saleor/graphql/core/types/__init__.py
@@ -22,6 +22,7 @@ from .common import (
File,
GiftCardError,
GiftCardSettingsError,
+ IconThumbnailField,
Image,
IntRangeInput,
InvoiceError,
@@ -161,4 +162,5 @@ __all__ = [
"IntFilterInput",
"DateFilterInput",
"DateTimeFilterInput",
+ "IconThumbnailField",
]
diff --git a/saleor/graphql/core/types/common.py b/saleor/graphql/core/types/common.py
index a7adee81f4..f336abe2f3 100644
--- a/saleor/graphql/core/types/common.py
+++ b/saleor/graphql/core/types/common.py
@@ -30,6 +30,7 @@ from ..descriptions import (
ADDED_IN_312,
ADDED_IN_314,
DEPRECATED_IN_3X_FIELD,
+ PREVIEW_FEATURE,
)
from ..enums import (
AccountErrorCode,
@@ -44,6 +45,7 @@ from ..enums import (
ExternalNotificationTriggerErrorCode,
GiftCardErrorCode,
GiftCardSettingsErrorCode,
+ IconThumbnailFormatEnum,
InvoiceErrorCode,
JobStatusEnum,
LanguageCodeEnum,
@@ -836,6 +838,16 @@ class ThumbnailField(graphene.Field):
super().__init__(of_type, *args, **kwargs)
+class IconThumbnailField(ThumbnailField):
+ format = IconThumbnailFormatEnum(
+ default_value="ORIGINAL",
+ description=(
+ "The format of the image. When not provided, format of the original "
+ "image will be used." + ADDED_IN_314 + PREVIEW_FEATURE
+ ),
+ )
+
+
class MediaInput(graphene.InputObjectType):
alt = graphene.String(description="Alt text for a product media.")
image = Upload(
diff --git a/saleor/graphql/core/utils/__init__.py b/saleor/graphql/core/utils/__init__.py
index a6ba01ec32..72309fca83 100644
--- a/saleor/graphql/core/utils/__init__.py
+++ b/saleor/graphql/core/utils/__init__.py
@@ -9,10 +9,9 @@ from graphene import ObjectType
from graphql.error import GraphQLError
from ....plugins.const import APP_ID_PREFIX
+from ....thumbnail import FILE_NAME_MAX_LENGTH
from ..validators import validate_if_int_or_uuid
-FILE_NAME_MAX_LENGTH = 55
-
def snake_to_camel_case(name):
"""Convert snake_case variable name to camelCase."""
diff --git a/saleor/graphql/core/validators/file.py b/saleor/graphql/core/validators/file.py
index ac24cb1c8d..e54aa53c51 100644
--- a/saleor/graphql/core/validators/file.py
+++ b/saleor/graphql/core/validators/file.py
@@ -1,13 +1,12 @@
import mimetypes
import os
-import secrets
import requests
from django.core.exceptions import ValidationError
from PIL import Image, UnidentifiedImageError
from ....thumbnail import MIME_TYPE_TO_PIL_IDENTIFIER
-from ..utils import FILE_NAME_MAX_LENGTH, add_hash_to_file_name
+from ..utils import add_hash_to_file_name
Image.init()
@@ -50,15 +49,6 @@ def validate_image_url(url: str, field_name: str, error_code: str) -> None:
)
-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)
- name = name[:FILE_NAME_MAX_LENGTH]
- hash = secrets.token_hex(nbytes=4)
- return f"{name}_{hash}{format}"
-
-
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.py
index f4a94ec491..12ab149977 100644
--- a/saleor/graphql/product/bulk_mutations/product_bulk_create.py
+++ b/saleor/graphql/product/bulk_mutations/product_bulk_create.py
@@ -19,6 +19,7 @@ from ....permission.enums import ProductPermissions
from ....product import ProductMediaTypes, models
from ....product.error_codes import ProductBulkCreateErrorCode
from ....product.tasks import update_products_discounted_prices_task
+from ....thumbnail.utils import get_filename_from_url
from ....warehouse.models import Warehouse
from ...attribute.types import AttributeValueInput
from ...attribute.utils import AttributeAssignmentMixin
@@ -39,12 +40,7 @@ from ...core.types import (
)
from ...core.utils import get_duplicated_values
from ...core.validators import clean_seo_fields
-from ...core.validators.file import (
- clean_image_file,
- get_filename_from_url,
- is_image_url,
- validate_image_url,
-)
+from ...core.validators.file import clean_image_file, is_image_url, validate_image_url
from ...meta.mutations import MetadataInput
from ...plugins.dataloaders import get_plugin_manager_promise
from ..mutations.product.product_create import ProductCreateInput
diff --git a/saleor/graphql/product/dataloaders/products.py b/saleor/graphql/product/dataloaders/products.py
index 865808ec47..3a0ae7800a 100644
--- a/saleor/graphql/product/dataloaders/products.py
+++ b/saleor/graphql/product/dataloaders/products.py
@@ -17,9 +17,7 @@ from ....product.models import (
ProductVariantChannelListing,
VariantMedia,
)
-from ....thumbnail.models import Thumbnail
-from ....thumbnail.utils import get_thumbnail_format
-from ...core.dataloaders import DataLoader
+from ...core.dataloaders import BaseThumbnailBySizeAndFormatLoader, DataLoader
ProductIdAndChannelSlug = Tuple[int, str]
VariantIdAndChannelSlug = Tuple[int, str]
@@ -649,29 +647,6 @@ class CategoryChildrenByCategoryIdLoader(DataLoader):
return [parent_to_children_mapping.get(key, []) for key in keys]
-class BaseThumbnailBySizeAndFormatLoader(
- DataLoader[Tuple[int, int, Optional[str]], Thumbnail]
-):
- model_name: str
-
- def batch_load(self, keys: Iterable[Tuple[int, int, Optional[str]]]):
- model_name = self.model_name.lower()
- instance_ids = [id for id, _, _ in keys]
- lookup = {f"{model_name}_id__in": instance_ids}
- thumbnails = Thumbnail.objects.using(self.database_connection_name).filter(
- **lookup
- )
- thumbnails_by_instance_id_size_and_format_map: DefaultDict[
- Tuple[int, int, Optional[str]], Thumbnail
- ] = defaultdict()
- for thumbnail in thumbnails:
- format = get_thumbnail_format(thumbnail.format)
- thumbnails_by_instance_id_size_and_format_map[
- (getattr(thumbnail, f"{model_name}_id"), thumbnail.size, format)
- ] = thumbnail
- return [thumbnails_by_instance_id_size_and_format_map.get(key) for key in keys]
-
-
class ThumbnailByCategoryIdSizeAndFormatLoader(BaseThumbnailBySizeAndFormatLoader):
context_key = "thumbnail_by_category_size_and_format"
model_name = "category"
diff --git a/saleor/graphql/product/mutations/product/product_media_create.py b/saleor/graphql/product/mutations/product/product_media_create.py
index fa63223c89..539c035da8 100644
--- a/saleor/graphql/product/mutations/product/product_media_create.py
+++ b/saleor/graphql/product/mutations/product/product_media_create.py
@@ -7,17 +7,13 @@ from .....core.utils.validators import get_oembed_data
from .....permission.enums import ProductPermissions
from .....product import ProductMediaTypes, models
from .....product.error_codes import ProductErrorCode
+from .....thumbnail.utils import get_filename_from_url
from ....channel import ChannelContext
from ....core import ResolveInfo
from ....core.doc_category import DOC_CATEGORY_PRODUCTS
from ....core.mutations import BaseMutation
from ....core.types import BaseInputObjectType, ProductError, Upload
-from ....core.validators.file import (
- clean_image_file,
- get_filename_from_url,
- is_image_url,
- validate_image_url,
-)
+from ....core.validators.file import clean_image_file, is_image_url, validate_image_url
from ....plugins.dataloaders import get_plugin_manager_promise
from ...types import Product, ProductMedia
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 933018c637..8b9598c102 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -2861,6 +2861,15 @@ type App implements Node & ObjectWithMetadata @doc(category: "Apps") {
Added in Saleor 3.1.
"""
extensions: [AppExtension!]!
+
+ """
+ App's brand data.
+
+ Added in Saleor 3.14.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ brand: AppBrand
}
interface ObjectWithMetadata {
@@ -3038,6 +3047,62 @@ enum AppExtensionTargetEnum @doc(category: "Apps") {
APP_PAGE
}
+"""
+Represents the app's brand data.
+
+Added in Saleor 3.14.
+
+Note: this API is currently in Feature Preview and can be subject to changes at later point.
+"""
+type AppBrand @doc(category: "Apps") {
+ """
+ App's logos details.
+
+ Added in Saleor 3.14.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ logo: AppBrandLogo!
+}
+
+"""
+Represents the app's brand logo data.
+
+Added in Saleor 3.14.
+
+Note: this API is currently in Feature Preview and can be subject to changes at later point.
+"""
+type AppBrandLogo @doc(category: "Apps") {
+ """
+ URL to the default logo image.
+
+ Added in Saleor 3.14.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ default(
+ """
+ Desired longest side the image in pixels. Defaults to 4096. Images are never cropped. Pass 0 to retrieve the original size (not recommended).
+ """
+ size: Int
+
+ """
+ The format of the image. When not provided, format of the original image will be used.
+
+ Added in Saleor 3.14.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ format: IconThumbnailFormatEnum = ORIGINAL
+ ): String!
+}
+
+"""Thumbnail formats for icon images."""
+enum IconThumbnailFormatEnum {
+ ORIGINAL
+ WEBP
+}
+
type EventDeliveryCountableConnection {
"""Pagination data for this connection."""
pageInfo: PageInfo!
@@ -12726,6 +12791,15 @@ type AppInstallation implements Node & Job @doc(category: "Apps") {
message: String
appName: String!
manifestUrl: String!
+
+ """
+ App's brand data.
+
+ Added in Saleor 3.14.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ brand: AppBrand
}
type AppCountableConnection @doc(category: "Apps") {
@@ -25428,6 +25502,15 @@ type Manifest @doc(category: "Apps") {
Note: this API is currently in Feature Preview and can be subject to changes at later point.
"""
author: String
+
+ """
+ App's brand data.
+
+ Added in Saleor 3.14.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ brand: AppManifestBrand
}
type AppManifestExtension @doc(category: "Apps") {
@@ -25484,6 +25567,56 @@ type AppManifestRequiredSaleorVersion @doc(category: "Apps") {
satisfied: Boolean!
}
+"""
+Represents the app's manifest brand data.
+
+Added in Saleor 3.14.
+
+Note: this API is currently in Feature Preview and can be subject to changes at later point.
+"""
+type AppManifestBrand @doc(category: "Apps") {
+ """
+ App's logos details.
+
+ Added in Saleor 3.14.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ logo: AppManifestBrandLogo!
+}
+
+"""
+Represents the app's manifest brand data.
+
+Added in Saleor 3.14.
+
+Note: this API is currently in Feature Preview and can be subject to changes at later point.
+"""
+type AppManifestBrandLogo @doc(category: "Apps") {
+ """
+ Data URL with a base64 encoded logo image.
+
+ Added in Saleor 3.14.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ default(
+ """
+ Desired longest side the image in pixels. Defaults to 4096. Images are never cropped. Pass 0 to retrieve the original size (not recommended).
+ """
+ size: Int
+
+ """
+ The format of the image. When not provided, format of the original image will be used.
+
+ Added in Saleor 3.14.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ format: IconThumbnailFormatEnum = ORIGINAL
+ ): String!
+}
+
"""
Activate the app.
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index 1abb4cfbf5..e5d6f182ec 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -1965,6 +1965,14 @@ def image():
return SimpleUploadedFile("product.jpg", img_data.getvalue())
+def icon_image():
+ img_data = BytesIO()
+ image = Image.new("RGB", size=(1, 1))
+ image.save(img_data, format="PNG")
+ return SimpleUploadedFile("logo.png", img_data.getvalue())
+
+
@pytest.fixture
def image_list():
img_data_1 = BytesIO()
diff --git a/saleor/thumbnail/__init__.py b/saleor/thumbnail/__init__.py
index 9145345f38..8e04b2bc5a 100644
--- a/saleor/thumbnail/__init__.py
+++ b/saleor/thumbnail/__init__.py
@@ -5,6 +5,8 @@ THUMBNAIL_SIZES = [32, 64, 128, 256, 512, 1024, 2048, 4096]
DEFAULT_THUMBNAIL_SIZE = 4096
+FILE_NAME_MAX_LENGTH = 55
+
class ThumbnailFormat:
ORIGINAL = "original"
@@ -18,6 +20,8 @@ class ThumbnailFormat:
]
+ALLOWED_THUMBNAIL_FORMATS = {ThumbnailFormat.AVIF, ThumbnailFormat.WEBP}
+
# PIL-supported file formats as found here:
# https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html
# Dict structure: {<mime-type>: <PIL-identifier>}
@@ -38,3 +42,24 @@ MIME_TYPE_TO_PIL_IDENTIFIER = {
"image/x-xpm": "XPM",
"image/webp": "WEBP",
}
+PIL_IDENTIFIER_TO_MIME_TYPE = {v: k for k, v in MIME_TYPE_TO_PIL_IDENTIFIER.items()}
+
+
+# Icon images
+ICON_MIME_TYPES = ["image/png"]
+MIN_ICON_SIZE = 256
+
+
+class IconThumbnailFormat:
+ """Thumbnail formats for icon images."""
+
+ ORIGINAL = "original"
+ WEBP = "webp"
+
+ CHOICES = [
+ (ORIGINAL, "Original"),
+ (WEBP, "WebP"),
+ ]
+
+
+ALLOWED_ICON_THUMBNAIL_FORMATS = {IconThumbnailFormat.WEBP}
diff --git a/saleor/thumbnail/migrations/0003_auto_20230412_1943.py b/saleor/thumbnail/migrations/0003_auto_20230412_1943.py
new file mode 100644
index 0000000000..708d0fda3b
--- /dev/null
+++ b/saleor/thumbnail/migrations/0003_auto_20230412_1943.py
@@ -0,0 +1,36 @@
+# Generated by Django 3.2.18 on 2023-04-12 19:43
+
+import django.db.models.deletion
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("app", "0025_auto_20230420_1544"),
+ ("thumbnail", "0002_alter_thumbnail_format"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="thumbnail",
+ name="app",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="thumbnails",
+ to="app.app",
+ ),
+ ),
+ migrations.AddField(
+ model_name="thumbnail",
+ name="app_installation",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="thumbnails",
+ to="app.appinstallation",
+ ),
+ ),
+ ]
diff --git a/saleor/thumbnail/models.py b/saleor/thumbnail/models.py
index cc0f472bfe..22972e5b69 100644
--- a/saleor/thumbnail/models.py
+++ b/saleor/thumbnail/models.py
@@ -2,6 +2,7 @@ from django.core.exceptions import ValidationError
from django.db import models
from ..account.models import User
+from ..app.models import App, AppInstallation
from ..product.models import Category, Collection, ProductMedia
from . import THUMBNAIL_SIZES, ThumbnailFormat
@@ -44,3 +45,13 @@ class Thumbnail(models.Model):
user = models.ForeignKey(
User, null=True, blank=True, on_delete=models.CASCADE, related_name="thumbnails"
)
+ app = models.ForeignKey(
+ App, null=True, blank=True, on_delete=models.CASCADE, related_name="thumbnails"
+ )
+ app_installation = models.ForeignKey(
+ AppInstallation,
+ null=True,
+ blank=True,
+ on_delete=models.CASCADE,
+ related_name="thumbnails",
+ )
diff --git a/saleor/thumbnail/tests/test_utils.py b/saleor/thumbnail/tests/test_utils.py
index 698afbb06a..ef80ee7eb1 100644
--- a/saleor/thumbnail/tests/test_utils.py
+++ b/saleor/thumbnail/tests/test_utils.py
@@ -4,10 +4,11 @@ import graphene
import pytest
from django.core.files import File
-from .. import ThumbnailFormat
+from .. import FILE_NAME_MAX_LENGTH, ThumbnailFormat
from ..models import Thumbnail
from ..utils import (
ProcessedImage,
+ get_filename_from_url,
get_image_or_proxy_url,
get_thumbnail_size,
prepare_image_proxy_url,
@@ -112,3 +113,52 @@ def test_processed_image_preprocess_method_called(category_with_image, thumb_for
# then
preprocess_mock.assert_called_once()
+
+
+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_get_filename_from_url_with_long_name_is_trimmed():
+ # given
+ file_format = "jpg"
+ file_name = "2Fvar2Ffolders2Fbj2F61gtb14j7rz474yd15tnkzjh0000gn2FT2Fa"
+ assert len(file_name) > FILE_NAME_MAX_LENGTH
+ url = f"http://example.com/{file_name}.{file_format}"
+
+ # when
+ result = get_filename_from_url(url)
+
+ # then
+ assert result.startswith(file_name[:FILE_NAME_MAX_LENGTH])
+ assert result.endswith(file_format)
+ assert result != f"{file_name}.{file_format}"
+ assert len(result.split("_")[0]) == FILE_NAME_MAX_LENGTH
+
+
+def test_get_filename_from_url_with_short_name_is_not_trimmed():
+ # given
+ file_format = "jpg"
+ file_name = "short"
+ assert len(file_name) < FILE_NAME_MAX_LENGTH
+ 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}"
+ assert len(result.split("_")[0]) < FILE_NAME_MAX_LENGTH
diff --git a/saleor/thumbnail/tests/test_validators.py b/saleor/thumbnail/tests/test_validators.py
new file mode 100644
index 0000000000..dd44aacc6e
--- /dev/null
+++ b/saleor/thumbnail/tests/test_validators.py
@@ -0,0 +1,79 @@
+from io import BytesIO
+from unittest.mock import Mock
+
+import pytest
+from django.core.exceptions import ValidationError
+from PIL import Image, UnidentifiedImageError
+
+from .. import MIN_ICON_SIZE
+from ..validators import (
+ validate_icon_image,
+ validate_image_exif,
+ validate_image_format,
+ validate_image_size,
+)
+
+
+def image_factory():
+ def factory(format="JPEG", size=(1, 1)):
+ image = Image.new("RGB", size=size)
+ image.format = format
+ return image
+
+ return factory
+
+
+def test_validate_image_format(image_factory):
+ validate_image_format(image_factory(), "invalid")
+
+
+def test_validate_image_format_when_not_allowed(image_factory):
+ image, error_code = image_factory(), "invalid"
+ with pytest.raises(ValidationError) as err:
+ validate_image_format(image, error_code, allowed_mimetypes=[])
+ assert err.value.code == error_code
+
+
+def test_validate_image_exif(image_factory):
+ image, error_code = image_factory(), "invalid"
+ image.getexif = Mock(side_effect=UnidentifiedImageError)
+ with pytest.raises(ValidationError) as err:
+ validate_image_exif(image, error_code)
+ assert err.value.code == error_code
+
+
+def test_validate_image_size(image_factory):
+ image, error_code = image_factory(), "invalid"
+ validate_image_size(image, error_code, 1, None, True)
+
+
+ "size,min_size,max_size,square_required",
+ [
+ ((1, 1), 10, None, False),
+ ((2, 2), None, 1, False),
+ ((1, 2), None, None, True),
+ ],
+)
+def test_validate_image_size_with_invalid_image(
+ image_factory, size, min_size, max_size, square_required
+):
+ image = image_factory(size=size)
+ error_code = "invalid"
+ with pytest.raises(ValidationError) as err:
+ validate_image_size(image, error_code, min_size, max_size, square_required)
+ assert err.value.code == error_code
+
+
+def test_validate_icon_image(image_factory):
+ img_data, image = BytesIO(), image_factory(size=(MIN_ICON_SIZE, MIN_ICON_SIZE))
+ image.save(img_data, format="PNG")
+ validate_icon_image(img_data, "invalid")
+
+
+def test_validate_icon_image_with_invalid_image():
+ img_data, error_code = BytesIO(b"data"), "invalid"
+ with pytest.raises(ValidationError) as err:
+ validate_icon_image(img_data, error_code)
+ assert err.value.code == error_code
diff --git a/saleor/thumbnail/tests/test_views.py b/saleor/thumbnail/tests/test_views.py
index d70f7ceef7..8a32caf60f 100644
--- a/saleor/thumbnail/tests/test_views.py
+++ b/saleor/thumbnail/tests/test_views.py
@@ -1,6 +1,7 @@
import graphene
+from PIL import Image
-from .. import ThumbnailFormat
+from .. import IconThumbnailFormat, ThumbnailFormat
from ..models import Thumbnail
@@ -208,10 +209,10 @@ def test_handle_thumbnail_view_invalid_object_type(client, order):
assert response.status_code == 404
-def test_handle_thumbnail_view_invalid_format(client, order):
+def test_handle_thumbnail_view_invalid_format(client, category):
# given
size = 60
- category_id = graphene.Node.to_global_id("Order", order.id)
+ category_id = graphene.Node.to_global_id("Category", category.id)
# when
response = client.get(f"/thumbnail/{category_id}/{size}/XYZ/")
@@ -220,6 +221,17 @@ def test_handle_thumbnail_view_invalid_format(client, order):
assert response.status_code == 404
+def test_handle_icon_thumbnail_view_invalid_format(client, app):
+ # given
+ app_uuid = graphene.Node.to_global_id("App", app.uuid)
+
+ # when
+ response = client.get(f"/thumbnail/{app_uuid}/60/XYZ/")
+
+ # then
+ assert response.status_code == 404
+
+
def test_handle_thumbnail_view_invalid_instance_id(client, category):
# given
size = 60
@@ -242,3 +254,118 @@ def test_handle_thumbnail_view_object_does_not_exists(client):
# then
assert response.status_code == 404
+
+
+def test_handle_icon_thumbnail_view_with_format(
+ client, app, icon_image, media_root, settings
+):
+ # given
+ app.brand_logo_default = icon_image
+ app.save(update_fields=["brand_logo_default"])
+
+ size = 60
+ format = IconThumbnailFormat.WEBP
+ app_uuid = graphene.Node.to_global_id("App", app.uuid)
+ thumbnail_count = Thumbnail.objects.count()
+
+ # when
+ response = client.get(f"/thumbnail/{app_uuid}/{size}/{format}/")
+
+ # then
+ assert response.status_code == 302
+ file_path, _ = app.brand_logo_default.name.rsplit(".")
+ assert (
+ response.url
+ == settings.MEDIA_URL + f"thumbnails/{file_path}_thumbnail_64.{format.lower()}"
+ )
+ assert Thumbnail.objects.count() == thumbnail_count + 1
+
+ thumbnail = Thumbnail.objects.last()
+ with Image.open(thumbnail.image) as image:
+ assert image.format == "WEBP"
+
+
+def test_handle_thumbnail_view_for_app_logo_default(
+ client, app, icon_image, media_root, settings
+):
+ # given
+ app.brand_logo_default = icon_image
+ app.save(update_fields=["brand_logo_default"])
+
+ size = 200
+ uuid = graphene.Node.to_global_id("App", app.uuid)
+ thumbnail_count = Thumbnail.objects.count()
+
+ # when
+ response = client.get(f"/thumbnail/{uuid}/{size}/")
+
+ # then
+ assert response.status_code == 302
+ file_path, ext = app.brand_logo_default.name.rsplit(".")
+ assert (
+ response.url
+ == settings.MEDIA_URL + f"thumbnails/{file_path}_thumbnail_256.{ext}"
+ )
+ assert Thumbnail.objects.count() == thumbnail_count + 1
+
+
+def test_handle_thumbnail_view_for_app_logo_default_thumbnail_exist(
+ client, app, icon_image, media_root, settings
+):
+ # given
+ size = 128
+ thumbnail = Thumbnail.objects.create(app=app, size=128, image=icon_image)
+ uuid = graphene.Node.to_global_id("App", app.uuid)
+ thumbnail_count = Thumbnail.objects.count()
+
+ # when
+ response = client.get(f"/thumbnail/{uuid}/{size}/")
+
+ # then
+ assert response.status_code == 302
+ assert response.url == thumbnail.image.url
+ assert Thumbnail.objects.count() == thumbnail_count
+
+
+def test_handle_thumbnail_view_for_app_installation_logo_default(
+ client, app_installation, icon_image, media_root, settings
+):
+ # given
+ app_installation.brand_logo_default = icon_image
+ app_installation.save(update_fields=["brand_logo_default"])
+
+ size = 200
+ uuid = graphene.Node.to_global_id("AppInstallation", app_installation.uuid)
+ thumbnail_count = Thumbnail.objects.count()
+
+ # when
+ response = client.get(f"/thumbnail/{uuid}/{size}/")
+
+ # then
+ assert response.status_code == 302
+ file_path, ext = app_installation.brand_logo_default.name.rsplit(".")
+ assert (
+ response.url
+ == settings.MEDIA_URL + f"thumbnails/{file_path}_thumbnail_256.{ext}"
+ )
+ assert Thumbnail.objects.count() == thumbnail_count + 1
+
+
+def test_handle_thumbnail_view_for_app_installation_logo_default_thumbnail_exist(
+ client, app_installation, icon_image, media_root, settings
+):
+ # given
+ size = 128
+ thumbnail = Thumbnail.objects.create(
+ app_installation=app_installation, size=128, image=icon_image
+ )
+ uuid = graphene.Node.to_global_id("AppInstallation", app_installation.uuid)
+ thumbnail_count = Thumbnail.objects.count()
+
+ # when
+ response = client.get(f"/thumbnail/{uuid}/{size}/")
+
+ # then
+ assert response.status_code == 302
+ assert response.url == thumbnail.image.url
+ assert Thumbnail.objects.count() == thumbnail_count
diff --git a/saleor/thumbnail/utils.py b/saleor/thumbnail/utils.py
index 4a3604b843..e92a249b2c 100644
--- a/saleor/thumbnail/utils.py
+++ b/saleor/thumbnail/utils.py
@@ -1,16 +1,21 @@
+import os
+import secrets
from io import BytesIO
-from typing import TYPE_CHECKING, Optional
+from typing import TYPE_CHECKING, Optional, Union
import graphene
import magic
+from django.core.files import File
from django.core.files.storage import default_storage
from django.urls import reverse
from PIL import Image
from . import (
DEFAULT_THUMBNAIL_SIZE,
+ FILE_NAME_MAX_LENGTH,
MIME_TYPE_TO_PIL_IDENTIFIER,
THUMBNAIL_SIZES,
+ IconThumbnailFormat,
ThumbnailFormat,
)
@@ -67,6 +72,13 @@ def get_thumbnail_format(format: Optional[str]) -> Optional[str]:
return format
+def get_icon_thumbnail_format(format: Optional[str]) -> Optional[str]:
+ """Return the icon thumbnail format if it's supported, otherwise None."""
+ if not format or format.lower() == IconThumbnailFormat.ORIGINAL:
+ return None
+ return format
+
+
def prepare_thumbnail_file_name(
file_name: str, size: int, format: Optional[str]
) -> str:
@@ -94,12 +106,12 @@ class ProcessedImage:
def __init__(
self,
- image_path: str,
+ image_source: Union[str, File],
size: int,
format: Optional[str] = None,
storage=default_storage,
):
- self.image_path = image_path
+ self.image_source = image_source
self.size = size
self.format = format.upper() if format else None
self.storage = storage
@@ -107,15 +119,17 @@ class ProcessedImage:
def create_thumbnail(self):
image, image_format = self.retrieve_image()
image, save_kwargs = self.preprocess(image, image_format)
- image_file = self.process_image(
+ image_file, thumbnail_format = self.process_image(
image=image,
save_kwargs=save_kwargs,
)
- return image_file
+ return image_file, thumbnail_format
def retrieve_image(self):
- """Return a PIL Image instance stored at `image_path`."""
- image = self.storage.open(self.image_path, "rb")
+ """Return a PIL Image instance stored at `image_source`."""
+ image = self.image_source
+ if isinstance(self.image_source, str):
+ image = self.storage.open(self.image_source, "rb")
image_format = self.get_image_metadata_from_file(image)
return (Image.open(image), image_format)
@@ -220,4 +234,18 @@ class ProcessedImage:
(self.size, self.size),
)
image.save(image_file, **save_kwargs)
- return image_file
+ image_file.seek(0)
+ return image_file, save_kwargs["format"]
+
+
+class ProcessedIconImage(ProcessedImage):
+ LOSSLESS_WEBP = True
+
+
+def get_filename_from_url(url: str) -> str:
+ """Prepare a unique filename for file from the URL to avoid overwriting."""
+ file_name = os.path.basename(url)
+ name, format = os.path.splitext(file_name)
+ name = name[:FILE_NAME_MAX_LENGTH]
+ hash = secrets.token_hex(nbytes=4)
+ return f"{name}_{hash}{format}"
diff --git a/saleor/thumbnail/validators.py b/saleor/thumbnail/validators.py
new file mode 100644
index 0000000000..4352c9a4df
--- /dev/null
+++ b/saleor/thumbnail/validators.py
@@ -0,0 +1,72 @@
+from typing import Collection, Optional
+
+from django.core.exceptions import ValidationError
+from PIL import Image, UnidentifiedImageError
+
+from . import (
+ ICON_MIME_TYPES,
+ MIME_TYPE_TO_PIL_IDENTIFIER,
+ MIN_ICON_SIZE,
+ PIL_IDENTIFIER_TO_MIME_TYPE,
+)
+
+
+def validate_image_format(
+ img: Image,
+ error_code: str,
+ allowed_mimetypes: Collection[str] = MIME_TYPE_TO_PIL_IDENTIFIER,
+):
+ image_mimetype = PIL_IDENTIFIER_TO_MIME_TYPE.get(img.format)
+ if not image_mimetype or image_mimetype not in allowed_mimetypes:
+ msg = f"Invalid file format. Only: {', '.join(allowed_mimetypes)} are supported"
+ raise ValidationError(msg, code=error_code)
+
+
+def validate_image_exif(img: Image, error_code: str):
+ try:
+ img.getexif()
+ except (SyntaxError, TypeError, UnidentifiedImageError) as e:
+ raise ValidationError(
+ "Invalid file. The following error was raised during the attempt "
+ f"of getting the exchangeable image file data: {str(e)}.",
+ code=error_code,
+ )
+
+
+def validate_image_size(
+ img: Image,
+ error_code: str,
+ min_size: Optional[int] = None,
+ max_size: Optional[int] = None,
+ square_required=False,
+):
+ if min_size and img.size < (min_size, min_size):
+ msg = f"Invalid file. Minimal accepted image size is {min_size}x{min_size}."
+ raise ValidationError(msg, code=error_code)
+ if max_size and img.size > (max_size, max_size):
+ msg = f"Invalid file. Maximal accepted image size is {max_size}x{max_size}."
+ raise ValidationError(msg, code=error_code)
+ if square_required and img.size[0] != img.size[1]:
+ msg = "Invalid file. Image must be square"
+ raise ValidationError(msg, code=error_code)
+
+
+def validate_icon_image(image_file, error_code: str):
+ file_pos = image_file.tell()
+ try:
+ with Image.open(image_file) as image:
+ validate_image_format(image, error_code, ICON_MIME_TYPES)
+ validate_image_size(image, error_code, MIN_ICON_SIZE, square_required=True)
+ except (
+ SyntaxError,
+ TypeError,
+ UnidentifiedImageError,
+ Image.DecompressionBombError,
+ ) as e:
+ raise ValidationError(
+ "Invalid file. The following error was raised during the attempt "
+ f"of opening the file: {str(e)}",
+ code=error_code,
+ )
+ finally:
+ image_file.seek(file_pos)
diff --git a/saleor/thumbnail/views.py b/saleor/thumbnail/views.py
index 963687ab8c..bb49eeac1c 100644
--- a/saleor/thumbnail/views.py
+++ b/saleor/thumbnail/views.py
@@ -6,22 +6,36 @@ from django.http import HttpResponseNotFound, HttpResponseRedirect
from graphql.error import GraphQLError
from ..account.models import User
+from ..app.models import App, AppInstallation
from ..core.utils.events import call_event
from ..graphql.core.utils import from_global_id_or_error
from ..plugins.manager import get_plugins_manager
from ..product.models import Category, Collection, ProductMedia
from ..thumbnail.models import Thumbnail
-from . import ThumbnailFormat
-from .utils import ProcessedImage, get_thumbnail_size, prepare_thumbnail_file_name
+from . import ALLOWED_ICON_THUMBNAIL_FORMATS, ALLOWED_THUMBNAIL_FORMATS
+from .utils import (
+ ProcessedIconImage,
+ ProcessedImage,
+ get_thumbnail_size,
+ prepare_thumbnail_file_name,
+)
ModelData = namedtuple("ModelData", ["model", "image_field", "thumbnail_field"])
+ICON_TYPE_TO_MODEL_DATA_MAPPING = {
+ "App": ModelData(App, "brand_logo_default", "app"),
+ "AppInstallation": ModelData(
+ AppInstallation, "brand_logo_default", "app_installation"
+ ),
+}
TYPE_TO_MODEL_DATA_MAPPING = {
"User": ModelData(User, "avatar", "user"),
"Category": ModelData(Category, "background_image", "category"),
"Collection": ModelData(Collection, "background_image", "collection"),
"ProductMedia": ModelData(ProductMedia, "image", "product_media"),
+ **ICON_TYPE_TO_MODEL_DATA_MAPPING,
}
+UUID_IDENTIFIABLE_TYPES = ["User", "App", "AppInstallation"]
def handle_thumbnail(
@@ -32,11 +46,6 @@ def handle_thumbnail(
If the provided size is not in the available resolution list, the thumbnail with
the closest available size is created and returned, if it does not exist.
"""
- # check formats
- format = format.lower() if format else None
- if format and format not in {ThumbnailFormat.AVIF, ThumbnailFormat.WEBP}:
- return HttpResponseNotFound("Unsupported image format.")
-
# try to find corresponding instance based on given instance_id
try:
object_type, pk = from_global_id_or_error(instance_id, raise_error=True)
@@ -46,6 +55,14 @@ def handle_thumbnail(
if object_type not in TYPE_TO_MODEL_DATA_MAPPING.keys():
return HttpResponseNotFound("Invalid instance type.")
+ # check formats
+ format = format.lower() if format else None
+ if object_type in ICON_TYPE_TO_MODEL_DATA_MAPPING:
+ if format and format not in ALLOWED_ICON_THUMBNAIL_FORMATS:
+ return HttpResponseNotFound("Unsupported icon image format.")
+ elif format and format not in ALLOWED_THUMBNAIL_FORMATS:
+ return HttpResponseNotFound("Unsupported image format.")
+
try:
size_px = get_thumbnail_size(int(size))
except ValueError:
@@ -53,8 +70,8 @@ def handle_thumbnail(
# return the thumbnail if it's already exist
model_data = TYPE_TO_MODEL_DATA_MAPPING[object_type]
- if object_type == "User":
- instance_id_lookup = "user__uuid"
+ if object_type in UUID_IDENTIFIABLE_TYPES:
+ instance_id_lookup = model_data.thumbnail_field + "__uuid"
else:
instance_id_lookup = model_data.thumbnail_field + "_id"
@@ -64,7 +81,7 @@ def handle_thumbnail(
return HttpResponseRedirect(thumbnail.image.url)
try:
- if object_type == "User":
+ if object_type in UUID_IDENTIFIABLE_TYPES:
instance = model_data.model.objects.get(uuid=pk)
else:
instance = model_data.model.objects.get(id=pk)
@@ -76,8 +93,13 @@ def handle_thumbnail(
return HttpResponseNotFound("There is no image for provided instance.")
# prepare thumbnail
- processed_image = ProcessedImage(image.name, size_px, format)
- thumbnail_file = processed_image.create_thumbnail()
+ if object_type in ICON_TYPE_TO_MODEL_DATA_MAPPING:
+ processed_image: ProcessedImage = ProcessedIconImage(
+ image.name, size_px, format
+ )
+ else:
+ processed_image = ProcessedImage(image.name, size_px, format)
+ thumbnail_file, _ = processed_image.create_thumbnail()
thumbnail_file_name = prepare_thumbnail_file_name(image.name, size_px, format)