| 1 |
"""Base material for download middlewares. |
| 2 |
|
| 3 |
Download middlewares capture :py:class:`django_downloadview.DownloadResponse` |
| 4 |
responses and may replace them with optimized download responses. |
| 5 |
|
| 6 |
""" |
| 7 |
|
| 8 |
import collections.abc |
| 9 |
import copy |
| 10 |
import os |
| 11 |
|
| 12 |
from django.conf import settings |
| 13 |
from django.core.exceptions import ImproperlyConfigured |
| 14 |
|
| 15 |
from django_downloadview.response import DownloadResponse |
| 16 |
from django_downloadview.utils import import_member |
| 17 |
|
| 18 |
|
| 19 |
#: Sentinel value to detect whether configuration is to be loaded from Django |
| 20 |
#: settings or not. |
| 21 |
AUTO_CONFIGURE = object() |
| 22 |
|
| 23 |
|
| 24 |
def is_download_response(response): |
| 25 |
"""Return ``True`` if ``response`` is a download response. |
| 26 |
|
| 27 |
Current implementation returns True if ``response`` is an instance of |
| 28 |
:py:class:`django_downloadview.response.DownloadResponse`. |
| 29 |
|
| 30 |
""" |
| 31 |
return isinstance(response, DownloadResponse) |
| 32 |
|
| 33 |
|
| 34 |
class BaseDownloadMiddleware: |
| 35 |
"""Base (abstract) Django middleware that handles download responses. |
| 36 |
|
| 37 |
Subclasses **must** implement :py:meth:`process_download_response` method. |
| 38 |
|
| 39 |
""" |
| 40 |
|
| 41 |
def __init__(self, get_response): |
| 42 |
self.get_response = get_response |
| 43 |
|
| 44 |
def __call__(self, request): |
| 45 |
response = self.get_response(request) |
| 46 |
return self.process_response(request, response) |
| 47 |
|
| 48 |
def is_download_response(self, response): |
| 49 |
"""Return True if ``response`` can be considered as a file download. |
| 50 |
|
| 51 |
By default, this method uses |
| 52 |
:py:func:`django_downloadview.middlewares.is_download_response`. |
| 53 |
Override this method if you want a different behaviour. |
| 54 |
|
| 55 |
""" |
| 56 |
return is_download_response(response) |
| 57 |
|
| 58 |
def process_response(self, request, response): |
| 59 |
"""Call `process_download_response()` if ``response`` is download.""" |
| 60 |
if self.is_download_response(response): |
| 61 |
return self.process_download_response(request, response) |
| 62 |
return response |
| 63 |
|
| 64 |
def process_download_response(self, request, response): |
| 65 |
"""Handle file download response.""" |
| 66 |
raise NotImplementedError() |
| 67 |
|
| 68 |
|
| 69 |
class RealDownloadMiddleware(BaseDownloadMiddleware): |
| 70 |
"""Download middleware that cannot handle virtual files.""" |
| 71 |
|
| 72 |
def is_download_response(self, response): |
| 73 |
"""Return True for DownloadResponse, except for "virtual" files. |
| 74 |
|
| 75 |
This implementation cannot handle files that live in memory or which |
| 76 |
are to be dynamically iterated over. So, we capture only responses |
| 77 |
whose file attribute have either an URL or a file name. |
| 78 |
|
| 79 |
""" |
| 80 |
return super().is_download_response(response) and bool( |
| 81 |
getattr(response.file, "url", None) or getattr(response.file, "name", None) |
| 82 |
) |
| 83 |
|
| 84 |
|
| 85 |
class DownloadDispatcher: |
| 86 |
def __init__(self, middlewares=AUTO_CONFIGURE): |
| 87 |
#: List of children middlewares. |
| 88 |
self.middlewares = middlewares |
| 89 |
if self.middlewares is AUTO_CONFIGURE: |
| 90 |
self.auto_configure_middlewares() |
| 91 |
|
| 92 |
def auto_configure_middlewares(self): |
| 93 |
"""Populate :attr:`middlewares` from |
| 94 |
``settings.DOWNLOADVIEW_MIDDLEWARES``.""" |
| 95 |
for key, import_string, kwargs in getattr( |
| 96 |
settings, "DOWNLOADVIEW_MIDDLEWARES", [] |
| 97 |
): |
| 98 |
factory = import_member(import_string) |
| 99 |
middleware = factory(**kwargs) |
| 100 |
self.middlewares.append((key, middleware)) |
| 101 |
|
| 102 |
def dispatch(self, request, response): |
| 103 |
"""Dispatches job to children middlewares.""" |
| 104 |
for key, middleware in self.middlewares: |
| 105 |
response = middleware.process_response(request, response) |
| 106 |
return response |
| 107 |
|
| 108 |
|
| 109 |
class DownloadDispatcherMiddleware(BaseDownloadMiddleware): |
| 110 |
"Download middleware that dispatches job to several middleware instances." |
| 111 |
|
| 112 |
def __init__(self, get_response, middlewares=AUTO_CONFIGURE): |
| 113 |
super().__init__(get_response) |
| 114 |
self.dispatcher = DownloadDispatcher(middlewares) |
| 115 |
|
| 116 |
def process_download_response(self, request, response): |
| 117 |
return self.dispatcher.dispatch(request, response) |
| 118 |
|
| 119 |
|
| 120 |
class SmartDownloadMiddleware(DownloadDispatcherMiddleware): |
| 121 |
"""Easy to configure download middleware.""" |
| 122 |
|
| 123 |
def __init__( |
| 124 |
self, |
| 125 |
get_response, |
| 126 |
backend_factory=AUTO_CONFIGURE, |
| 127 |
backend_options=AUTO_CONFIGURE, |
| 128 |
): |
| 129 |
"""Constructor.""" |
| 130 |
super().__init__(get_response, middlewares=[]) |
| 131 |
#: Callable (typically a class) to instantiate backend (typically a |
| 132 |
#: :class:`DownloadMiddleware` subclass). |
| 133 |
self.backend_factory = backend_factory |
| 134 |
if self.backend_factory is AUTO_CONFIGURE: |
| 135 |
self.auto_configure_backend_factory() |
| 136 |
#: List of positional or keyword arguments to instantiate backend |
| 137 |
#: instances. |
| 138 |
self.backend_options = backend_options |
| 139 |
if self.backend_options is AUTO_CONFIGURE: |
| 140 |
self.auto_configure_backend_options() |
| 141 |
|
| 142 |
def auto_configure_backend_factory(self): |
| 143 |
"Assign :attr:`backend_factory` from ``settings.DOWNLOADVIEW_BACKEND``" |
| 144 |
try: |
| 145 |
self.backend_factory = import_member(settings.DOWNLOADVIEW_BACKEND) |
| 146 |
except AttributeError: |
| 147 |
raise ImproperlyConfigured( |
| 148 |
"SmartDownloadMiddleware requires " "settings.DOWNLOADVIEW_BACKEND" |
| 149 |
) |
| 150 |
|
| 151 |
def auto_configure_backend_options(self): |
| 152 |
"""Populate :attr:`dispatcher` using :attr:`factory` and |
| 153 |
``settings.DOWNLOADVIEW_RULES``.""" |
| 154 |
try: |
| 155 |
options_list = copy.deepcopy(settings.DOWNLOADVIEW_RULES) |
| 156 |
except AttributeError: |
| 157 |
raise ImproperlyConfigured( |
| 158 |
"SmartDownloadMiddleware requires " "settings.DOWNLOADVIEW_RULES" |
| 159 |
) |
| 160 |
for key, options in enumerate(options_list): |
| 161 |
args = [] |
| 162 |
kwargs = {} |
| 163 |
if isinstance(options, collections.abc.Mapping): # Using kwargs. |
| 164 |
kwargs = options |
| 165 |
else: |
| 166 |
args = options |
| 167 |
if "backend" in kwargs: # Specific backend for this rule. |
| 168 |
factory = import_member(kwargs["backend"]) |
| 169 |
del kwargs["backend"] |
| 170 |
else: # Fallback to global backend. |
| 171 |
factory = self.backend_factory |
| 172 |
middleware_instance = factory(*args, **kwargs) |
| 173 |
self.dispatcher.middlewares.append((key, middleware_instance)) |
| 174 |
|
| 175 |
|
| 176 |
class NoRedirectionMatch(Exception): |
| 177 |
"""Response object does not match redirection rules.""" |
| 178 |
|
| 179 |
|
| 180 |
class ProxiedDownloadMiddleware(RealDownloadMiddleware): |
| 181 |
"""Base class for middlewares that use optimizations of reverse proxies.""" |
| 182 |
|
| 183 |
def __init__( |
| 184 |
self, get_response, source_dir=None, source_url=None, destination_url=None |
| 185 |
): |
| 186 |
"""Constructor.""" |
| 187 |
super().__init__(get_response) |
| 188 |
|
| 189 |
self.source_dir = source_dir |
| 190 |
self.source_url = source_url |
| 191 |
self.destination_url = destination_url |
| 192 |
|
| 193 |
def get_redirect_url(self, response): |
| 194 |
"""Return redirect URL for file wrapped into response.""" |
| 195 |
url = None |
| 196 |
file_url = "" |
| 197 |
if self.source_url: |
| 198 |
try: |
| 199 |
file_url = response.file.url |
| 200 |
except AttributeError: |
| 201 |
pass |
| 202 |
else: |
| 203 |
if file_url.startswith(self.source_url): |
| 204 |
file_url = file_url[len(self.source_url) :] |
| 205 |
url = file_url |
| 206 |
file_name = "" |
| 207 |
if url is None and self.source_dir: |
| 208 |
try: |
| 209 |
file_name = response.file.name |
| 210 |
except AttributeError: |
| 211 |
pass |
| 212 |
else: |
| 213 |
if file_name.startswith(self.source_dir): |
| 214 |
file_name = os.path.relpath(file_name, self.source_dir) |
| 215 |
url = file_name.replace(os.path.sep, "/") |
| 216 |
if url is None: |
| 217 |
message = ( |
| 218 |
"""Couldn't capture/convert file attributes into a """ |
| 219 |
"""redirection. """ |
| 220 |
"""``source_url`` is "%(source_url)s", """ |
| 221 |
"""file's URL is "%(file_url)s". """ |
| 222 |
"""``source_dir`` is "%(source_dir)s", """ |
| 223 |
"""file's name is "%(file_name)s". """ |
| 224 |
% { |
| 225 |
"source_url": self.source_url, |
| 226 |
"file_url": file_url, |
| 227 |
"source_dir": self.source_dir, |
| 228 |
"file_name": file_name, |
| 229 |
} |
| 230 |
) |
| 231 |
raise NoRedirectionMatch(message) |
| 232 |
return "/".join((self.destination_url.rstrip("/"), url.lstrip("/"))) |