|
1 | 1 | import base64 |
2 | | -import html |
3 | 2 | import logging |
4 | 3 | import pathlib |
5 | 4 | import uuid |
6 | | -from html.parser import HTMLParser |
7 | 5 |
|
8 | 6 | from django.conf import settings |
9 | | -from django.templatetags.static import static |
10 | 7 | from django.utils.functional import cached_property |
11 | | -from django.utils.html import format_html, html_safe |
12 | | -from django.utils.safestring import mark_safe |
13 | 8 | from storages.utils import safe_join |
14 | 9 |
|
15 | | -from s3file.middleware import S3FileMiddleware |
16 | | -from s3file.storages import get_aws_location, storage |
17 | | - |
18 | | -logger = logging.getLogger("s3file") |
19 | | - |
20 | | - |
21 | | -class InputToS3FileRewriter(HTMLParser): |
22 | | - """HTML parser that rewrites <input type="file"> to <s3-file> custom elements.""" |
23 | | - |
24 | | - def __init__(self): |
25 | | - super().__init__() |
26 | | - self.output = [] |
27 | | - |
28 | | - def handle_starttag(self, tag, attrs): |
29 | | - if tag == "input" and dict(attrs).get("type") == "file": |
30 | | - self.output.append("<s3-file") |
31 | | - for name, value in attrs: |
32 | | - if name != "type": |
33 | | - self.output.append( |
34 | | - f' {name}="{html.escape(value, quote=True)}"' |
35 | | - if value |
36 | | - else f" {name}" |
37 | | - ) |
38 | | - self.output.append(">") |
39 | | - else: |
40 | | - self.output.append(self.get_starttag_text()) |
41 | | - |
42 | | - def handle_endtag(self, tag): |
43 | | - self.output.append(f"</{tag}>") |
44 | | - |
45 | | - def handle_data(self, data): |
46 | | - self.output.append(data) |
47 | | - |
48 | | - def handle_startendtag(self, tag, attrs): |
49 | | - if tag == "input" and dict(attrs).get("type") == "file": |
50 | | - self.output.append("<s3-file") |
51 | | - for name, value in attrs: |
52 | | - if name != "type": |
53 | | - self.output.append( |
54 | | - f' {name}="{html.escape(value, quote=True)}"' |
55 | | - if value |
56 | | - else f" {name}" |
57 | | - ) |
58 | | - self.output.append(">") |
59 | | - else: |
60 | | - self.output.append(self.get_starttag_text()) |
61 | | - |
62 | | - def handle_comment(self, data): |
63 | | - # Preserve HTML comments in the output |
64 | | - self.output.append(f"<!--{data}-->") |
65 | | - |
66 | | - def handle_decl(self, decl): |
67 | | - # Preserve declarations such as <!DOCTYPE ...> in the output |
68 | | - self.output.append(f"<!{decl}>") |
69 | | - |
70 | | - def handle_pi(self, data): |
71 | | - # Preserve processing instructions such as <?xml ...?> in the output |
72 | | - self.output.append(f"<?{data}>") |
73 | | - |
74 | | - def handle_entityref(self, name): |
75 | | - # Preserve HTML entities like &, <, > |
76 | | - self.output.append(f"&{name};") |
77 | | - |
78 | | - def handle_charref(self, name): |
79 | | - # Preserve character references like ', ' |
80 | | - self.output.append(f"&#{name};") |
81 | | - |
82 | | - def get_html(self): |
83 | | - return "".join(self.output) |
84 | | - |
85 | | - |
86 | | -@html_safe |
87 | | -class Asset: |
88 | | - """A generic asset that can be included in a template.""" |
| 10 | +try: |
| 11 | + from django.forms import Script |
| 12 | +except ImportError: |
| 13 | + from django.forms.utils import flatatt |
| 14 | + from django.templatetags.static import static |
| 15 | + from django.utils.html import format_html, html_safe |
| 16 | + |
| 17 | + # Django < 6.0 backport |
| 18 | + @html_safe |
| 19 | + class MediaAsset: |
| 20 | + element_template = "{path}" |
| 21 | + |
| 22 | + def __init__(self, path, **attributes): |
| 23 | + self._path = path |
| 24 | + self.attributes = attributes |
| 25 | + |
| 26 | + def __eq__(self, other): |
| 27 | + return (self.__class__ is other.__class__ and self.path == other.path) or ( |
| 28 | + isinstance(other, str) and self._path == other |
| 29 | + ) |
89 | 30 |
|
90 | | - def __init__(self, path): |
91 | | - self.path = path |
| 31 | + def __hash__(self): |
| 32 | + return hash(self._path) |
92 | 33 |
|
93 | | - def __eq__(self, other): |
94 | | - return (self.__class__ is other.__class__ and self.path == other.path) or ( |
95 | | - other.__class__ is str and self.path == other |
96 | | - ) |
| 34 | + def __str__(self): |
| 35 | + return format_html( |
| 36 | + self.element_template, |
| 37 | + path=self.path, |
| 38 | + attributes=flatatt(self.attributes), |
| 39 | + ) |
97 | 40 |
|
98 | | - def __hash__(self): |
99 | | - return hash(self.path) |
| 41 | + def __repr__(self): |
| 42 | + return f"{type(self).__qualname__}({self._path!r})" |
100 | 43 |
|
101 | | - def __str__(self): |
102 | | - return self.absolute_path(self.path) |
| 44 | + @property |
| 45 | + def path(self): |
| 46 | + if self._path.startswith(("http://", "https://", "/")): |
| 47 | + return self._path |
| 48 | + return static(self._path) |
103 | 49 |
|
104 | | - def absolute_path(self, path): |
105 | | - if path.startswith(("http://", "https://", "/")): |
106 | | - return path |
107 | | - return static(path) |
| 50 | + class Script(MediaAsset): |
| 51 | + element_template = '<script src="{path}"{attributes}></script>' |
108 | 52 |
|
109 | | - def __repr__(self): |
110 | | - return f"{type(self).__qualname__}: {self.path!r}" |
| 53 | + def __init__(self, src, **attributes): |
| 54 | + super().__init__(src, **attributes) |
111 | 55 |
|
112 | 56 |
|
113 | | -class ESM(Asset): |
114 | | - """A JavaScript asset for ECMA Script Modules (ESM).""" |
| 57 | +from s3file.middleware import S3FileMiddleware |
| 58 | +from s3file.storages import get_aws_location, storage |
115 | 59 |
|
116 | | - def __str__(self): |
117 | | - path = super().__str__() |
118 | | - template = '<script src="{}" type="module"></script>' |
119 | | - return format_html(template, self.absolute_path(path)) |
| 60 | +logger = logging.getLogger("s3file") |
120 | 61 |
|
121 | 62 |
|
122 | 63 | class S3FileInputMixin: |
@@ -162,15 +103,12 @@ def build_attrs(self, *args, **kwargs): |
162 | 103 | ) |
163 | 104 | defaults.update(attrs) |
164 | 105 |
|
| 106 | + try: |
| 107 | + defaults["class"] += " s3file" |
| 108 | + except KeyError: |
| 109 | + defaults["class"] = "s3file" |
165 | 110 | return defaults |
166 | 111 |
|
167 | | - def render(self, name, value, attrs=None, renderer=None): |
168 | | - """Render the widget as a custom element for Safari compatibility.""" |
169 | | - html_output = str(super().render(name, value, attrs=attrs, renderer=renderer)) |
170 | | - parser = InputToS3FileRewriter() |
171 | | - parser.feed(html_output) |
172 | | - return mark_safe(parser.get_html()) # noqa: S308 |
173 | | - |
174 | 112 | def get_conditions(self, accept): |
175 | 113 | conditions = [ |
176 | 114 | {"bucket": self.bucket_name}, |
@@ -201,4 +139,4 @@ def upload_folder(self): |
201 | 139 | ) # S3 uses POSIX paths |
202 | 140 |
|
203 | 141 | class Media: |
204 | | - js = [ESM("s3file/js/s3file.js")] |
| 142 | + js = [Script("s3file/js/s3file.js", type="module")] |
0 commit comments