1import mimetypes
2import os
3from email.utils import parsedate
4from io import BytesIO
5
6from plain.http import (
7 FileResponse,
8 NotFoundError404,
9 NotModifiedResponse,
10 RedirectResponse,
11 Response,
12 StreamingResponse,
13)
14from plain.http.response import ResponseHeaders
15from plain.runtime import settings
16from plain.urls import reverse
17from plain.utils.http import http_date
18from plain.views import View
19
20from .compile import get_compiled_path
21from .finders import _iter_assets
22from .manifest import AssetsManifest, get_manifest
23
24
25class AssetView(View):
26 """
27 Serve an asset file directly.
28
29 This class could be subclassed to further tweak the responses or behavior.
30 """
31
32 def get_manifest(self) -> AssetsManifest:
33 """Get the assets manifest. Override in tests to provide a custom manifest."""
34 return get_manifest()
35
36 def get_url_path(self) -> str | None:
37 return self.url_kwargs["path"]
38
39 def get(self) -> Response:
40 url_path = self.get_url_path()
41
42 if not url_path:
43 raise NotFoundError404("Asset path not found")
44
45 # Make a trailing slash work, but we don't expect it
46 url_path = url_path.rstrip("/")
47
48 # If a CDN is configured, redirect compiled assets there
49 if settings.ASSETS_CDN_URL and (
50 cdn_response := self.get_cdn_redirect_response(url_path)
51 ):
52 return cdn_response
53
54 if settings.DEBUG:
55 absolute_path = self.get_debug_asset_path(url_path)
56 else:
57 absolute_path = self.get_asset_path(url_path)
58
59 if settings.ASSETS_REDIRECT_ORIGINAL and (
60 redirect_response := self.get_redirect_response(url_path)
61 ):
62 return redirect_response
63
64 # check_asset_path validates and raises if path is invalid
65 # After this point, absolute_path is guaranteed to be a valid str
66 self.check_asset_path(absolute_path)
67 # Type guard: absolute_path is now str (check_asset_path raises if None/invalid)
68 assert absolute_path is not None
69
70 if encoded_path := self.get_encoded_path(absolute_path):
71 absolute_path = encoded_path
72
73 if range_response := self.get_range_response(absolute_path):
74 return range_response
75
76 if not_modified_response := self.get_conditional_response(absolute_path):
77 return not_modified_response
78
79 content_type, _ = mimetypes.guess_type(absolute_path)
80
81 response = FileResponse(
82 open(absolute_path, "rb"), # noqa: SIM115 — FileResponse takes ownership and closes it
83 filename=os.path.basename(absolute_path),
84 content_type=content_type,
85 )
86 response.headers = self.update_headers(response.headers, absolute_path)
87 return response
88
89 def get_asset_path(self, path: str) -> str:
90 """Get the path to the compiled asset"""
91 compiled_path = os.path.abspath(get_compiled_path())
92 asset_path = os.path.join(compiled_path, path)
93
94 # Make sure we don't try to escape the compiled assets path
95 if not os.path.commonpath([compiled_path, asset_path]) == compiled_path:
96 raise NotFoundError404("Asset not found")
97
98 return asset_path
99
100 def get_debug_asset_path(self, path: str) -> str | None:
101 """Make a "live" check to find the uncompiled asset in the filesystem"""
102 for asset in _iter_assets():
103 if asset.url_path == path:
104 return asset.absolute_path
105 return None
106
107 def check_asset_path(self, path: str | None) -> None:
108 if not path:
109 raise NotFoundError404("Asset not found")
110
111 if not os.path.exists(path):
112 raise NotFoundError404("Asset not found")
113
114 if os.path.isdir(path):
115 raise NotFoundError404("Asset is a directory")
116
117 def get_last_modified(self, path: str) -> str | None:
118 return _get_last_modified(path)
119
120 def get_etag(self, path: str) -> str:
121 return _get_etag(path)
122
123 def get_size(self, path: str) -> int:
124 return _get_size(path)
125
126 def update_headers(self, headers: ResponseHeaders, path: str) -> ResponseHeaders:
127 headers.setdefault("Access-Control-Allow-Origin", "*")
128
129 # Always vary on Accept-Encoding
130 vary = headers.get("Vary")
131 if not vary:
132 headers["Vary"] = "Accept-Encoding"
133 elif vary != "*" and "Accept-Encoding" not in vary:
134 headers["Vary"] = vary + ", Accept-Encoding"
135
136 # If the file is compressed, tell the browser
137 if encoding := mimetypes.guess_type(path)[1]:
138 headers.setdefault("Content-Encoding", encoding)
139
140 is_immutable = self.is_immutable(path)
141
142 if is_immutable:
143 max_age = 10 * 365 * 24 * 60 * 60 # 10 years
144 headers.setdefault("Cache-Control", f"max-age={max_age}, immutable")
145 elif settings.DEBUG:
146 # In development, cache for 1 second to avoid re-fetching the same file
147 headers.setdefault("Cache-Control", "max-age=0")
148 else:
149 # Tell the browser to cache the file for 60 seconds if nothing else
150 headers.setdefault("Cache-Control", "max-age=60")
151
152 if not is_immutable:
153 if last_modified := self.get_last_modified(path):
154 headers.setdefault("Last-Modified", last_modified)
155 if etag := self.get_etag(path):
156 headers.setdefault("ETag", etag)
157
158 if "Content-Disposition" in headers:
159 # This header messes up Safari...
160 # https://github.com/evansd/whitenoise/commit/93657cf88e14b919cb726864814617a6a639e507
161 # At some point, should probably look at not using FileResponse at all?
162 del headers["Content-Disposition"]
163
164 return headers
165
166 def is_immutable(self, path: str) -> bool:
167 """
168 Determine whether an asset is immutable (fingerprinted).
169
170 Checks if the path is a fingerprinted path in the manifest.
171 Also handles compressed variants (e.g., main.abc1234.css.gz).
172 """
173 # Convert absolute path to URL-relative path for manifest lookup
174 compiled_path = os.path.abspath(get_compiled_path())
175 if path.startswith(compiled_path):
176 url_path = os.path.relpath(path, compiled_path)
177 else:
178 url_path = path
179
180 manifest = self.get_manifest()
181
182 # Check the path directly, then without compression extension
183 if manifest.is_immutable(url_path):
184 return True
185 if url_path.endswith((".gz", ".br")):
186 return manifest.is_immutable(url_path[:-3])
187 return False
188
189 def get_encoded_path(self, path: str) -> str | None:
190 """
191 If the client supports compression, return the path to the compressed file.
192 Otherwise, return the original path.
193 """
194 accept_encoding = self.request.headers.get("Accept-Encoding")
195 if not accept_encoding:
196 return None
197
198 if "br" in accept_encoding:
199 br_path = path + ".br"
200 if os.path.exists(br_path):
201 return br_path
202
203 if "gzip" in accept_encoding:
204 gzip_path = path + ".gz"
205 if os.path.exists(gzip_path):
206 return gzip_path
207 return None
208
209 def get_redirect_response(self, path: str) -> RedirectResponse | None:
210 """If the asset is not found, try to redirect to the fingerprinted path"""
211 compiled_url_path = self.get_manifest().resolve(path)
212
213 if not compiled_url_path or compiled_url_path == path:
214 # Don't need to redirect if there is no compiled path,
215 # or we're already looking at it (not fingerprinted).
216 return None
217
218 # Import here to avoid circular import (urls.py imports AssetView)
219 from .urls import AssetsRouter
220
221 return RedirectResponse(
222 redirect_to=reverse(
223 f"{AssetsRouter.namespace}:asset", path=compiled_url_path
224 ),
225 status_code=302,
226 headers={
227 "Cache-Control": "max-age=60", # Can cache this for a short time, but the fingerprinted path can change
228 },
229 )
230
231 def get_cdn_redirect_response(self, path: str) -> RedirectResponse | None:
232 """Redirect to CDN URL for compiled assets.
233
234 Assets not in the manifest (e.g., page assets) are not redirected
235 and will be served locally.
236 """
237 manifest = self.get_manifest()
238
239 if path not in manifest:
240 return None
241
242 final_path = manifest.resolve(path) or path
243 is_immutable = manifest.is_immutable(path)
244
245 if is_immutable:
246 status_code = 301
247 cache_control = "max-age=31536000, immutable"
248 else:
249 status_code = 302
250 cache_control = "max-age=60"
251
252 cdn_url = f"{settings.ASSETS_CDN_URL.rstrip('/')}/{final_path.lstrip('/')}"
253 return RedirectResponse(
254 redirect_to=cdn_url,
255 status_code=status_code,
256 allow_external=True,
257 headers={"Cache-Control": cache_control},
258 )
259
260 def get_conditional_response(self, path: str) -> NotModifiedResponse | None:
261 """
262 Support conditional requests (HTTP 304 response) based on ETag and Last-Modified headers.
263 """
264 if self.request.headers.get("If-None-Match") == self.get_etag(path):
265 return self._not_modified_response(path)
266
267 if "If-Modified-Since" in self.request.headers:
268 if_modified_since = parsedate(self.request.headers["If-Modified-Since"])
269 last_modified = parsedate(self.get_last_modified(path))
270 if (
271 if_modified_since
272 and last_modified
273 and if_modified_since >= last_modified
274 ):
275 return self._not_modified_response(path)
276 return None
277
278 def _not_modified_response(self, path: str) -> NotModifiedResponse:
279 response = NotModifiedResponse()
280 response.headers = self.update_headers(response.headers, path)
281 if not settings.ASSETS_LOG_304:
282 response.log_access = False
283 return response
284
285 def get_range_response(self, path: str) -> Response | None:
286 """
287 Support range requests (HTTP 206 response).
288 """
289 range_header = self.request.headers.get("HTTP_RANGE")
290 if not range_header:
291 return None
292
293 file_size = self.get_size(path)
294
295 if not range_header.startswith("bytes="):
296 return Response(
297 status_code=416, headers={"Content-Range": f"bytes */{file_size}"}
298 )
299
300 range_values = range_header.split("=")[1].split("-")
301 start = int(range_values[0]) if range_values[0] else 0
302 end = int(range_values[1]) if range_values[1] else float("inf")
303
304 if start >= file_size:
305 return Response(
306 status_code=416, headers={"Content-Range": f"bytes */{file_size}"}
307 )
308
309 end = int(min(end, file_size - 1))
310
311 with open(path, "rb") as f:
312 f.seek(start)
313 content = f.read(end - start + 1)
314
315 response = StreamingResponse(BytesIO(content), status_code=206)
316 response.headers = self.update_headers(response.headers, path)
317 response.headers["Content-Range"] = f"bytes {start}-{end}/{file_size}"
318 response.headers["Content-Length"] = str(end - start + 1)
319 return response
320
321
322# Deliberately uncached: these validators are only consulted for
323# non-fingerprinted assets, which can change on disk while the process runs.
324def _get_last_modified(path: str) -> str | None:
325 try:
326 mtime = os.path.getmtime(path)
327 except OSError:
328 return None
329 if not mtime:
330 return None
331 return http_date(mtime)
332
333
334def _get_etag(path: str) -> str:
335 try:
336 mtime = os.path.getmtime(path)
337 except OSError:
338 mtime = 0.0
339 return f'"{int(mtime):x}-{_get_size(path):x}"'
340
341
342def _get_size(path: str) -> int:
343 return os.path.getsize(path)