Coverage for website/utils/media/views.py: 57.78%
37 statements
« prev ^ index » next coverage.py v7.6.7, created at 2025-08-14 10:31 +0000
« prev ^ index » next coverage.py v7.6.7, created at 2025-08-14 10:31 +0000
1from datetime import timedelta
3from django.core import signing
4from django.core.cache import cache
5from django.core.exceptions import PermissionDenied
6from django.core.signing import BadSignature
7from django.http import Http404
8from django.shortcuts import redirect
9from django.utils import timezone
10from django.utils.module_loading import import_string
12from django_sendfile import sendfile
15def get_thumb_modified_time(storage, path):
16 storage_value = cache.get(
17 f"thumbnails_{path}", timezone.make_aware(timezone.datetime.min)
18 )
19 if storage_value.timestamp() <= 0:
20 try:
21 storage_value = storage.get_modified_time(path)
22 cache.set(f"thumbnails_{path}", storage_value, 60 * 60)
23 except: # noqa: E722
24 # File probably does not exist
25 pass
26 return storage_value
29def _get_signature_info(request):
30 if "sig" in request.GET: 30 ↛ 36line 30 didn't jump to line 36 because the condition on line 30 was always true
31 signature = request.GET.get("sig")
32 try:
33 return signing.loads(signature, max_age=timedelta(hours=3))
34 except BadSignature:
35 pass
36 raise PermissionDenied
39def private_media(request, request_path):
40 """Serve private media files.
42 :param request: the request
43 :return: the media file
44 """
45 # Get image information from signature
46 # raises PermissionDenied if bad signature
47 sig_info = _get_signature_info(request)
48 storage = import_string(sig_info["storage"])()
49 serve_path = sig_info["serve_path"]
51 if not storage.exists(serve_path) or not serve_path == request_path: 51 ↛ 53line 51 didn't jump to line 53 because the condition on line 51 was never true
52 # 404 if the file does not exist
53 raise Http404("Media not found.")
55 # Serve the file, or redirect to a signed bucket url in the case of S3
56 if hasattr(storage, "bucket"): 56 ↛ 57line 56 didn't jump to line 57 because the condition on line 56 was never true
57 serve_url = storage.url(sig_info["serve_path"])
58 return redirect(
59 f"{serve_url}",
60 permanent=False,
61 )
62 return sendfile(
63 request,
64 serve_path,
65 attachment=bool(sig_info.get("attachment", False)),
66 attachment_filename=sig_info.get("attachment", None),
67 )