Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Use the original SVG file as thumbnail (#2422)
Olga Bulat507d7401a774
diff --git a/api/api/utils/image_proxy/__init__.py b/api/api/utils/image_proxy/__init__.pynew file mode 100644index 000000000..2b83eda90--- /dev/null+++ b/api/api/utils/image_proxy/__init__.py@@ -0,0 +1,128 @@+import logging+from typing import Literal+from urllib.parse import urlparse++from django.conf import settings+from django.http import HttpResponse+from rest_framework.exceptions import UnsupportedMediaType++import django_redis+import requests+import sentry_sdk++from api.utils.image_proxy.exception import UpstreamThumbnailException+from api.utils.image_proxy.extension import get_image_extension+from api.utils.image_proxy.photon import get_photon_request_params+from api.utils.tallies import get_monthly_timestamp+++parent_logger = logging.getLogger(__name__)++HEADERS = {+ "User-Agent": settings.OUTBOUND_USER_AGENT_TEMPLATE.format(+ purpose="ThumbnailGeneration"+ )+}++PHOTON_TYPES = {"gif", "jpg", "jpeg", "png", "webp"}+ORIGINAL_TYPES = {"svg"}++PHOTON = "photon"+ORIGINAL = "original"+THUMBNAIL_STRATEGY = Literal["photon_proxy", "original"]+++def get_request_params_for_extension(+ ext: str,+ headers: dict[str, str],+ image_url: str,+ parsed_image_url: urlparse,+ is_full_size: bool,+ is_compressed: bool,+) -> tuple[str, dict[str, str], dict[str, str]]:+ """+ Get the request params (url, params, headers) for the thumbnail proxy.+ If the image type is supported by photon, we use photon, and compute the necessary+ request params, if the file can be cached and returned as is (SVG), we do that,+ otherwise we raise UnsupportedMediaType exception.+ """+ if ext in PHOTON_TYPES:+ return get_photon_request_params(+ parsed_image_url, is_full_size, is_compressed, headers+ )+ elif ext in ORIGINAL_TYPES:+ return image_url, {}, headers+ raise UnsupportedMediaType(+ f"Image extension {ext} is not supported by the thumbnail proxy."+ )+++def get(+ image_url: str,+ media_identifier: str,+ accept_header: str = "image/*",+ is_full_size: bool = False,+ is_compressed: bool = True,+) -> HttpResponse:+ """+ Proxy an image through Photon if its file type is supported, else return the+ original image if the file type is SVG. Otherwise, raise an exception.+ """+ logger = parent_logger.getChild("get")+ tallies = django_redis.get_redis_connection("tallies")+ month = get_monthly_timestamp()++ image_extension = get_image_extension(image_url, media_identifier)++ headers = {"Accept": accept_header} | HEADERS++ parsed_image_url = urlparse(image_url)+ domain = parsed_image_url.netloc++ upstream_url, params, headers = get_request_params_for_extension(+ image_extension,+ headers,+ image_url,+ parsed_image_url,+ is_full_size,+ is_compressed,+ )++ try:+ upstream_response = requests.get(+ upstream_url,+ timeout=15,+ params=params,+ headers=headers,+ )+ tallies.incr(f"thumbnail_response_code:{month}:{upstream_response.status_code}")+ tallies.incr(+ f"thumbnail_response_code_by_domain:{domain}:"+ f"{month}:{upstream_response.status_code}"+ )+ upstream_response.raise_for_status()+ except Exception as exc:+ exception_name = f"{exc.__class__.__module__}.{exc.__class__.__name__}"+ key = f"thumbnail_error:{exception_name}:{domain}:{month}"+ count = tallies.incr(key)+ if count <= settings.THUMBNAIL_ERROR_INITIAL_ALERT_THRESHOLD or (+ count % settings.THUMBNAIL_ERROR_REPEATED_ALERT_FREQUENCY == 0+ ):+ sentry_sdk.capture_exception(exc)+ if isinstance(exc, requests.exceptions.HTTPError):+ tallies.incr(+ f"thumbnail_http_error:{domain}:{month}:{exc.response.status_code}:{exc.response.text}"+ )+ raise UpstreamThumbnailException(f"Failed to render thumbnail. {exc}")++ res_status = upstream_response.status_code+ content_type = upstream_response.headers.get("Content-Type")+ logger.debug(+ f"Image proxy response status: {res_status}, content-type: {content_type}"+ )++ return HttpResponse(+ upstream_response.content,+ status=res_status,+ content_type=content_type,+ )diff --git a/api/api/utils/image_proxy/exception.py b/api/api/utils/image_proxy/exception.pynew file mode 100644index 000000000..903de58e9--- /dev/null+++ b/api/api/utils/image_proxy/exception.py@@ -0,0 +1,8 @@+from rest_framework import status+from rest_framework.exceptions import APIException+++class UpstreamThumbnailException(APIException):+ status_code = status.HTTP_424_FAILED_DEPENDENCY+ default_detail = "Could not render thumbnail due to upstream provider error."+ default_code = "upstream_photon_failure"diff --git a/api/api/utils/image_proxy/extension.py b/api/api/utils/image_proxy/extension.pynew file mode 100644index 000000000..ae74d7f09--- /dev/null+++ b/api/api/utils/image_proxy/extension.py@@ -0,0 +1,58 @@+from os.path import splitext+from urllib.parse import urlparse++import django_redis+import requests+import sentry_sdk++from api.utils.image_proxy.exception import UpstreamThumbnailException+++def get_image_extension(image_url: str, media_identifier: str) -> str | None:+ cache = django_redis.get_redis_connection("default")+ key = f"media:{media_identifier}:thumb_type"++ ext = _get_file_extension_from_url(image_url)++ if not ext:+ # If the extension is not present in the URL, try to get it from the redis cache+ ext = cache.get(key)+ ext = ext.decode("utf-8") if ext else None++ if not ext:+ # If the extension is still not present, try getting it from the content type+ try:+ response = requests.head(image_url, timeout=10)+ response.raise_for_status()+ except Exception as exc:+ sentry_sdk.capture_exception(exc)+ raise UpstreamThumbnailException(+ "Failed to render thumbnail due to inability to check media "+ f"type. {exc}"+ )+ else:+ if response.headers and "Content-Type" in response.headers:+ content_type = response.headers["Content-Type"]+ ext = _get_file_extension_from_content_type(content_type)+ else:+ ext = None++ cache.set(key, ext if ext else "unknown")+ return ext+++def _get_file_extension_from_url(image_url: str) -> str:+ """Return the image extension if present in the URL."""+ parsed = urlparse(image_url)+ _, ext = splitext(parsed.path)+ return ext[1:].lower() # remove the leading dot+++def _get_file_extension_from_content_type(content_type: str) -> str | None:+ """+ Return the image extension if present in the Response's content type+ header.+ """+ if content_type and "/" in content_type:+ return content_type.split("/")[1]+ return Nonediff --git a/api/api/utils/image_proxy/photon.py b/api/api/utils/image_proxy/photon.pynew file mode 100644index 000000000..639839c85--- /dev/null+++ b/api/api/utils/image_proxy/photon.py@@ -0,0 +1,43 @@+from django.conf import settings+++def get_photon_request_params(+ parsed_image_url,+ is_full_size: bool,+ is_compressed: bool,+ headers: dict,+):+ """+ Photon options documented here:+ https://developer.wordpress.com/docs/photon/api/+ """+ params = {}++ if not is_full_size:+ params["w"] = settings.THUMBNAIL_WIDTH_PX++ if is_compressed:+ params["quality"] = settings.THUMBNAIL_QUALITY++ if parsed_image_url.query:+ # No need to URL encode this string because requests will already+ # pass the `params` object to `urlencode` before it appends it to the+ # request URL.+ params["q"] = parsed_image_url.query++ if parsed_image_url.scheme == "https":+ # Photon defaults to HTTP without this parameter+ # which will cause some providers to fail (if they+ # do not serve over HTTP and do not have a redirect)+ params["ssl"] = "true"++ # Photon excludes the protocol, so we need to reconstruct the url + port + path+ # to send as the "path" of the Photon request+ domain = parsed_image_url.netloc+ path = parsed_image_url.path+ upstream_url = f"{settings.PHOTON_ENDPOINT}{domain}{path}"++ if settings.PHOTON_AUTH_KEY:+ headers["X-Photon-Authentication"] = settings.PHOTON_AUTH_KEY++ return upstream_url, params, headersdiff --git a/api/api/utils/photon.py b/api/api/utils/photon.pydeleted file mode 100644index 1e161736c..000000000--- a/api/api/utils/photon.py+++ /dev/null@@ -1,178 +0,0 @@-import logging-from os.path import splitext-from urllib.parse import urlparse--from django.conf import settings-from django.http import HttpResponse-from rest_framework import status-from rest_framework.exceptions import APIException, UnsupportedMediaType--import django_redis-import requests-import sentry_sdk--from api.utils.tallies import get_monthly_timestamp---parent_logger = logging.getLogger(__name__)---class UpstreamThumbnailException(APIException):- status_code = status.HTTP_424_FAILED_DEPENDENCY- default_detail = "Could not render thumbnail due to upstream provider error."- default_code = "upstream_photon_failure"---ALLOWED_TYPES = {"gif", "jpg", "jpeg", "png", "webp"}--HEADERS = {- "User-Agent": settings.OUTBOUND_USER_AGENT_TEMPLATE.format(- purpose="ThumbnailGeneration"- )-}---def _get_file_extension_from_url(image_url: str) -> str:- """Return the image extension if present in the URL."""- parsed = urlparse(image_url)- _, ext = splitext(parsed.path)- return ext[1:].lower() # remove the leading dot---def _get_file_extension_from_content_type(content_type: str) -> str | None:- """- Return the image extension if present in the Response's content type- header.- """- if content_type and "/" in content_type:- return content_type.split("/")[1]- return None---def check_image_type(image_url: str, media_obj) -> None:- cache = django_redis.get_redis_connection("default")- key = f"media:{media_obj.identifier}:thumb_type"-- ext = _get_file_extension_from_url(image_url)-- if not ext:- # If the extension is not present in the URL, try to get it from the redis cache- ext = cache.get(key)- ext = ext.decode("utf-8") if ext else None-- if not ext:- # If the extension is still not present, try getting it from the content type- try:- response = requests.head(image_url, timeout=10)- response.raise_for_status()- except Exception as exc:- sentry_sdk.capture_exception(exc)- raise UpstreamThumbnailException(- "Failed to render thumbnail due to inability to check media "- f"type. {exc}"- )- else:- if response.headers and "Content-Type" in response.headers:- content_type = response.headers["Content-Type"]- ext = _get_file_extension_from_content_type(content_type)- else:- ext = None-- cache.set(key, ext if ext else "unknown")-- if ext not in ALLOWED_TYPES:- raise UnsupportedMediaType(ext)---def _get_photon_params(image_url, is_full_size, is_compressed):- """- Photon options documented here:- https://developer.wordpress.com/docs/photon/api/- """- params = {}-- if not is_full_size:- params["w"] = settings.THUMBNAIL_WIDTH_PX-- if is_compressed:- params["quality"] = settings.THUMBNAIL_QUALITY-- parsed_image_url = urlparse(image_url)-- if parsed_image_url.query:- # No need to URL encode this string because requests will already- # pass the `params` object to `urlencode` before it appends it to the- # request URL.- params["q"] = parsed_image_url.query-- if parsed_image_url.scheme == "https":- # Photon defaults to HTTP without this parameter- # which will cause some providers to fail (if they- # do not serve over HTTP and do not have a redirect)- params["ssl"] = "true"-- return params, parsed_image_url---def get(- image_url: str,- accept_header: str = "image/*",- is_full_size: bool = False,- is_compressed: bool = True,-) -> HttpResponse:- logger = parent_logger.getChild("get")- tallies = django_redis.get_redis_connection("tallies")- month = get_monthly_timestamp()-- params, parsed_image_url = _get_photon_params(- image_url, is_full_size, is_compressed- )-- # Photon excludes the protocol, so we need to reconstruct the url + port + path- # to send as the "path" of the Photon request- domain = parsed_image_url.netloc- path = parsed_image_url.path- upstream_url = f"{settings.PHOTON_ENDPOINT}{domain}{path}"-- headers = {"Accept": accept_header} | HEADERS- if settings.PHOTON_AUTH_KEY:- headers["X-Photon-Authentication"] = settings.PHOTON_AUTH_KEY-- try:- upstream_response = requests.get(- upstream_url,- timeout=15,- params=params,- headers=headers,- )- tallies.incr(f"thumbnail_response_code:{month}:{upstream_response.status_code}")- tallies.incr(- f"thumbnail_response_code_by_domain:{domain}:"- f"{month}:{upstream_response.status_code}"- )- upstream_response.raise_for_status()- except Exception as exc:- exception_name = f"{exc.__class__.__module__}.{exc.__class__.__name__}"- key = f"thumbnail_error:{exception_name}:{domain}:{month}"- count = tallies.incr(key)- if count <= settings.THUMBNAIL_ERROR_INITIAL_ALERT_THRESHOLD or (- count % settings.THUMBNAIL_ERROR_REPEATED_ALERT_FREQUENCY == 0- ):- sentry_sdk.capture_exception(exc)- if isinstance(exc, requests.exceptions.HTTPError):- tallies.incr(- f"thumbnail_http_error:{domain}:{month}:{exc.response.status_code}:{exc.response.text}"- )- raise UpstreamThumbnailException(f"Failed to render thumbnail. {exc}")-- res_status = upstream_response.status_code- content_type = upstream_response.headers.get("Content-Type")- logger.debug(- f"Image proxy response status: {res_status}, content-type: {content_type}"- )-- return HttpResponse(- upstream_response.content,- status=res_status,- content_type=content_type,- )diff --git a/api/api/views/media_views.py b/api/api/views/media_views.pyindex 6a6d69fea..def37d283 100644--- a/api/api/views/media_views.py+++ b/api/api/views/media_views.py@@ -9,7 +9,7 @@ from rest_framework.viewsets import ReadOnlyModelViewSetfrom api.controllers import search_controllerfrom api.models import ContentProviderfrom api.serializers.provider_serializers import ProviderSerializer-from api.utils import photon+from api.utils import image_proxyfrom api.utils.pagination import StandardPagination@@ -164,10 +164,9 @@ class MediaViewSet(ReadOnlyModelViewSet):serializer = self.get_serializer(data=request.query_params)serializer.is_valid(raise_exception=True)- photon.check_image_type(image_url, media_obj)-- return photon.get(+ return image_proxy.get(image_url,+ media_obj.identifier,accept_header=request.headers.get("Accept", "image/*"),**serializer.validated_data,)diff --git a/api/test/unit/utils/test_photon.py b/api/test/unit/utils/test_image_proxy.pysimilarity index 83%rename from api/test/unit/utils/test_photon.pyrename to api/test/unit/utils/test_image_proxy.pyindex 7ea41252b..655c84f49 100644--- a/api/test/unit/utils/test_photon.py+++ b/api/test/unit/utils/test_image_proxy.py@@ -10,18 +10,14 @@ import pookimport pytestimport requests-from api.utils.photon import (- HEADERS,- UpstreamThumbnailException,- _get_file_extension_from_url,- check_image_type,-)-from api.utils.photon import get as photon_get+from api.utils.image_proxy import HEADERS, UpstreamThumbnailException, extension+from api.utils.image_proxy import get as photon_getfrom api.utils.tallies import get_monthly_timestampPHOTON_URL_FOR_TEST_IMAGE = f"{settings.PHOTON_ENDPOINT}subdomain.example.com/path_part1/part2/image_dot_jpg.jpg"TEST_IMAGE_URL = PHOTON_URL_FOR_TEST_IMAGE.replace(settings.PHOTON_ENDPOINT, "http://")+TEST_MEDIA_IDENTIFIER = "123"UA_HEADER = HEADERS["User-Agent"]@@ -31,6 +27,11 @@ UA_HEADER = HEADERS["User-Agent"]# this will get the tests working.MOCK_BODY = "mock response body"+SVG_BODY = """<?xml version="1.0" encoding="UTF-8"?>+<svg version="1.1" xmlns="http://www.w3.org/2000/svg">+<text x="10" y="10" fill="white">SVG</text>+</svg>"""+@pytest.fixturedef auth_key():@@ -59,13 +60,31 @@ def test_get_successful_no_auth_key_default_args(mock_image_data):.mock)- res = photon_get(TEST_IMAGE_URL)+ res = photon_get(TEST_IMAGE_URL, TEST_MEDIA_IDENTIFIER)assert res.content == MOCK_BODY.encode()assert res.status_code == 200assert mock_get.matched+def test_get_successful_original_svg_no_auth_key_default_args(mock_image_data):+ mock_get: pook.Mock = (+ pook.get(TEST_IMAGE_URL.replace(".jpg", ".svg"))+ .header("User-Agent", UA_HEADER)+ .header("Accept", "image/*")+ .reply(200)+ .body(SVG_BODY)+ .mock+ )++ res = photon_get(TEST_IMAGE_URL.replace(".jpg", ".svg"), TEST_MEDIA_IDENTIFIER)++ assert res.content == SVG_BODY.encode()+ assert res.status_code == 200+ assert mock_get.matched++@pook.ondef test_get_successful_with_auth_key_default_args(mock_image_data, auth_key):mock_get: pook.Mock = (@@ -84,7 +103,7 @@ def test_get_successful_with_auth_key_default_args(mock_image_data, auth_key):.mock)- res = photon_get(TEST_IMAGE_URL)+ res = photon_get(TEST_IMAGE_URL, TEST_MEDIA_IDENTIFIER)assert res.content == MOCK_BODY.encode()assert res.status_code == 200@@ -107,7 +126,7 @@ def test_get_successful_no_auth_key_not_compressed(mock_image_data):.mock)- res = photon_get(TEST_IMAGE_URL, is_compressed=False)+ res = photon_get(TEST_IMAGE_URL, TEST_MEDIA_IDENTIFIER, is_compressed=False)assert res.content == MOCK_BODY.encode()assert res.status_code == 200@@ -130,7 +149,7 @@ def test_get_successful_no_auth_key_full_size(mock_image_data):.mock)- res = photon_get(TEST_IMAGE_URL, is_full_size=True)+ res = photon_get(TEST_IMAGE_URL, TEST_MEDIA_IDENTIFIER, is_full_size=True)assert res.content == MOCK_BODY.encode()assert res.status_code == 200@@ -148,7 +167,9 @@ def test_get_successful_no_auth_key_full_size_not_compressed(mock_image_data):.mock)- res = photon_get(TEST_IMAGE_URL, is_full_size=True, is_compressed=False)+ res = photon_get(+ TEST_IMAGE_URL, TEST_MEDIA_IDENTIFIER, is_full_size=True, is_compressed=False+ )assert res.content == MOCK_BODY.encode()assert res.status_code == 200@@ -172,7 +193,7 @@ def test_get_successful_no_auth_key_png_only(mock_image_data):.mock)- res = photon_get(TEST_IMAGE_URL, accept_header="image/png")+ res = photon_get(TEST_IMAGE_URL, TEST_MEDIA_IDENTIFIER, accept_header="image/png")assert res.content == MOCK_BODY.encode()assert res.status_code == 200@@ -200,7 +221,7 @@ def test_get_successful_forward_query_params(mock_image_data):url_with_params = f"{TEST_IMAGE_URL}?{params}"- res = photon_get(url_with_params)+ res = photon_get(url_with_params, TEST_MEDIA_IDENTIFIER)assert res.content == MOCK_BODY.encode()assert res.status_code == 200@@ -235,7 +256,7 @@ def test_get_successful_records_response_code(mock_image_data, redis):.mock)- photon_get(TEST_IMAGE_URL)+ photon_get(TEST_IMAGE_URL, TEST_MEDIA_IDENTIFIER)month = get_monthly_timestamp()assert redis.get(f"thumbnail_response_code:{month}:200") == b"1"assert (@@ -290,7 +311,7 @@ def test_get_exception_handles_error(redis.set(key, count_start)with pytest.raises(UpstreamThumbnailException):- photon_get(TEST_IMAGE_URL)+ photon_get(TEST_IMAGE_URL, TEST_MEDIA_IDENTIFIER)assert_func = (capture_exception.assert_called_once@@ -331,7 +352,7 @@ def test_get_http_exception_handles_error(redis.set(key, count_start)with pytest.raises(UpstreamThumbnailException):- photon_get(TEST_IMAGE_URL)+ photon_get(TEST_IMAGE_URL, TEST_MEDIA_IDENTIFIER)assert_func = (capture_exception.assert_called_once@@ -369,7 +390,7 @@ def test_get_successful_https_image_url_sends_ssl_parameter(mock_image_data):.mock)- res = photon_get(https_url)+ res = photon_get(https_url, TEST_MEDIA_IDENTIFIER)assert res.content == MOCK_BODY.encode()assert res.status_code == 200@@ -383,7 +404,7 @@ def test_get_unsuccessful_request_raises_custom_exception():with pytest.raises(UpstreamThumbnailException, match=r"Failed to render thumbnail."):- photon_get(TEST_IMAGE_URL)+ photon_get(TEST_IMAGE_URL, TEST_MEDIA_IDENTIFIER)assert mock_get.matched@@ -404,34 +425,34 @@ def test_get_unsuccessful_request_raises_custom_exception():],)def test__get_extension_from_url(image_url, expected_ext):- assert _get_file_extension_from_url(image_url) == expected_ext+ assert extension._get_file_extension_from_url(image_url) == expected_ext@pytest.mark.django_db[email protected]("image_type", ["apng", "svg", "bmp"])-def test_check_image_type_raises_by_not_allowed_types(image_type):[email protected]("image_type", ["apng", "tiff", "bmp"])+def test_photon_get_raises_by_not_allowed_types(image_type):image_url = TEST_IMAGE_URL.replace(".jpg", f".{image_type}")image = ImageFactory.create(url=image_url)with pytest.raises(UnsupportedMediaType):- check_image_type(image_url, image)+ photon_get(image_url, image.identifier)@pytest.mark.django_db@pytest.mark.parametrize("headers, expected_cache_val",[- ({"Content-Type": "image/svg+xml"}, b"svg+xml"),+ ({"Content-Type": "image/tiff"}, b"tiff"),(None, b"unknown"),],)-def test_check_image_type_saves_image_type_to_cache(redis, headers, expected_cache_val):+def test_photon_get_saves_image_type_to_cache(redis, headers, expected_cache_val):image_url = TEST_IMAGE_URL.replace(".jpg", "")image = ImageFactory.create(url=image_url)with mock.patch("requests.head") as mock_head, pytest.raises(UnsupportedMediaType):mock_head.return_value.headers = headers- check_image_type(image_url, image)+ photon_get(image_url, image.identifier)key = f"media:{image.identifier}:thumb_type"assert redis.get(key) == expected_cache_val