import logging
import re
from urllib.parse import urlparse

from django.conf import settings
from django.utils.cache import add_never_cache_headers
from django.utils.cache import patch_cache_control
from django.utils.cache import patch_response_headers

logger = logging.getLogger(__name__)

STAC_BASE = settings.STAC_BASE
STAC_BASE_V = settings.STAC_BASE_V


class CacheHeadersMiddleware:
    '''Middleware that adds appropriate cache headers to GET and HEAD methods.

    NOTE: /checker, /get-token, /metrics and /{healthcheck} endpoints are marked as never cache.
    '''

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.

        response = self.get_response(request)

        # Code to be executed for each request/response after
        # the view is called.
        # match /xxx or /api/stac/xxx
        # f.ex. /metrics, /checker, /api/stac/{healthcheck}, /api/stac/get-token
        if re.match(fr'^(/{STAC_BASE})?/\w+$', request.path):
            add_never_cache_headers(response)
        elif (
            request.method in ('GET', 'HEAD') and
            not request.path.startswith(urlparse(settings.STATIC_URL).path)
        ):
            logger.debug(
                "Patching cache headers for request %s %s",
                request.method,
                request.path,
                extra={"request": request}
            )
            patch_response_headers(response, settings.CACHE_MIDDLEWARE_SECONDS)
            patch_cache_control(response, public=True)

        return response

[((263, 290), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (280, 290), False, 'import logging\n'), ((1067, 1116), 're.match', 're.match', (['f"""^(/{STAC_BASE})?/\\\\w+$"""', 'request.path'], {}), "(f'^(/{STAC_BASE})?/\\\\w+$', request.path)\n", (1075, 1116), False, 'import re\n'), ((1130, 1163), 'django.utils.cache.add_never_cache_headers', 'add_never_cache_headers', (['response'], {}), '(response)\n', (1153, 1163), False, 'from django.utils.cache import add_never_cache_headers\n'), ((1533, 1600), 'django.utils.cache.patch_response_headers', 'patch_response_headers', (['response', 'settings.CACHE_MIDDLEWARE_SECONDS'], {}), '(response, settings.CACHE_MIDDLEWARE_SECONDS)\n', (1555, 1600), False, 'from django.utils.cache import patch_response_headers\n'), ((1613, 1655), 'django.utils.cache.patch_cache_control', 'patch_cache_control', (['response'], {'public': '(True)'}), '(response, public=True)\n', (1632, 1655), False, 'from django.utils.cache import patch_cache_control\n'), ((1269, 1298), 'urllib.parse.urlparse', 'urlparse', (['settings.STATIC_URL'], {}), '(settings.STATIC_URL)\n', (1277, 1298), False, 'from urllib.parse import urlparse\n')]