| 1 |
import json |
| 2 |
import os |
| 3 |
import re |
| 4 |
from pathlib import Path |
| 5 |
|
| 6 |
from django.apps import apps |
| 7 |
from django.conf import settings |
| 8 |
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse |
| 9 |
from django.template import Context, Engine |
| 10 |
from django.urls import translate_url |
| 11 |
from django.utils.formats import get_format |
| 12 |
from django.utils.http import url_has_allowed_host_and_scheme |
| 13 |
from django.utils.translation import check_for_language, get_language |
| 14 |
from django.utils.translation.trans_real import DjangoTranslation |
| 15 |
from django.views.generic import View |
| 16 |
|
| 17 |
LANGUAGE_QUERY_PARAMETER = "language" |
| 18 |
|
| 19 |
|
| 20 |
def builtin_template_path(name): |
| 21 |
""" |
| 22 |
Return a path to a builtin template. |
| 23 |
|
| 24 |
Avoid calling this function at the module level or in a class-definition |
| 25 |
because __file__ may not exist, e.g. in frozen environments. |
| 26 |
""" |
| 27 |
return Path(__file__).parent / "templates" / name |
| 28 |
|
| 29 |
|
| 30 |
def set_language(request): |
| 31 |
""" |
| 32 |
Redirect to a given URL while setting the chosen language in the language |
| 33 |
cookie. The URL and the language code need to be specified in the request |
| 34 |
parameters. |
| 35 |
|
| 36 |
Since this view changes how the user will see the rest of the site, it must |
| 37 |
only be accessed as a POST request. If called as a GET request, it will |
| 38 |
redirect to the page in the request (the 'next' parameter) without changing |
| 39 |
any state. |
| 40 |
""" |
| 41 |
next_url = request.POST.get("next", request.GET.get("next")) |
| 42 |
if ( |
| 43 |
next_url or request.accepts("text/html") |
| 44 |
) and not url_has_allowed_host_and_scheme( |
| 45 |
url=next_url, |
| 46 |
allowed_hosts={request.get_host()}, |
| 47 |
require_https=request.is_secure(), |
| 48 |
): |
| 49 |
next_url = request.META.get("HTTP_REFERER") |
| 50 |
if not url_has_allowed_host_and_scheme( |
| 51 |
url=next_url, |
| 52 |
allowed_hosts={request.get_host()}, |
| 53 |
require_https=request.is_secure(), |
| 54 |
): |
| 55 |
next_url = "/" |
| 56 |
response = HttpResponseRedirect(next_url) if next_url else HttpResponse(status=204) |
| 57 |
if request.method == "POST": |
| 58 |
lang_code = request.POST.get(LANGUAGE_QUERY_PARAMETER) |
| 59 |
if lang_code and check_for_language(lang_code): |
| 60 |
if next_url: |
| 61 |
next_trans = translate_url(next_url, lang_code) |
| 62 |
if next_trans != next_url: |
| 63 |
response = HttpResponseRedirect(next_trans) |
| 64 |
response.set_cookie( |
| 65 |
settings.LANGUAGE_COOKIE_NAME, |
| 66 |
lang_code, |
| 67 |
max_age=settings.LANGUAGE_COOKIE_AGE, |
| 68 |
path=settings.LANGUAGE_COOKIE_PATH, |
| 69 |
domain=settings.LANGUAGE_COOKIE_DOMAIN, |
| 70 |
secure=settings.LANGUAGE_COOKIE_SECURE, |
| 71 |
httponly=settings.LANGUAGE_COOKIE_HTTPONLY, |
| 72 |
samesite=settings.LANGUAGE_COOKIE_SAMESITE, |
| 73 |
) |
| 74 |
return response |
| 75 |
|
| 76 |
|
| 77 |
def get_formats(): |
| 78 |
"""Return all formats strings required for i18n to work.""" |
| 79 |
FORMAT_SETTINGS = ( |
| 80 |
"DATE_FORMAT", |
| 81 |
"DATETIME_FORMAT", |
| 82 |
"TIME_FORMAT", |
| 83 |
"YEAR_MONTH_FORMAT", |
| 84 |
"MONTH_DAY_FORMAT", |
| 85 |
"SHORT_DATE_FORMAT", |
| 86 |
"SHORT_DATETIME_FORMAT", |
| 87 |
"FIRST_DAY_OF_WEEK", |
| 88 |
"DECIMAL_SEPARATOR", |
| 89 |
"THOUSAND_SEPARATOR", |
| 90 |
"NUMBER_GROUPING", |
| 91 |
"DATE_INPUT_FORMATS", |
| 92 |
"TIME_INPUT_FORMATS", |
| 93 |
"DATETIME_INPUT_FORMATS", |
| 94 |
) |
| 95 |
return {attr: get_format(attr) for attr in FORMAT_SETTINGS} |
| 96 |
|
| 97 |
|
| 98 |
class JavaScriptCatalog(View): |
| 99 |
""" |
| 100 |
Return the selected language catalog as a JavaScript library. |
| 101 |
|
| 102 |
Receive the list of packages to check for translations in the `packages` |
| 103 |
kwarg either from the extra dictionary passed to the path() function or as |
| 104 |
a plus-sign delimited string from the request. Default is 'django.conf'. |
| 105 |
|
| 106 |
You can override the gettext domain for this view, but usually you don't |
| 107 |
want to do that as JavaScript messages go to the djangojs domain. This |
| 108 |
might be needed if you deliver your JavaScript source from Django templates. |
| 109 |
""" |
| 110 |
|
| 111 |
domain = "djangojs" |
| 112 |
packages = None |
| 113 |
|
| 114 |
def get(self, request, *args, **kwargs): |
| 115 |
locale = get_language() |
| 116 |
domain = kwargs.get("domain", self.domain) |
| 117 |
# If packages are not provided, default to all installed packages, as |
| 118 |
# DjangoTranslation without localedirs harvests them all. |
| 119 |
packages = kwargs.get("packages", "") |
| 120 |
packages = packages.split("+") if packages else self.packages |
| 121 |
paths = self.get_paths(packages) if packages else None |
| 122 |
self.translation = DjangoTranslation(locale, domain=domain, localedirs=paths) |
| 123 |
context = self.get_context_data(**kwargs) |
| 124 |
return self.render_to_response(context) |
| 125 |
|
| 126 |
def get_paths(self, packages): |
| 127 |
allowable_packages = { |
| 128 |
app_config.name: app_config for app_config in apps.get_app_configs() |
| 129 |
} |
| 130 |
app_configs = [ |
| 131 |
allowable_packages[p] for p in packages if p in allowable_packages |
| 132 |
] |
| 133 |
if len(app_configs) < len(packages): |
| 134 |
excluded = [p for p in packages if p not in allowable_packages] |
| 135 |
raise ValueError( |
| 136 |
"Invalid package(s) provided to JavaScriptCatalog: %s" |
| 137 |
% ",".join(excluded) |
| 138 |
) |
| 139 |
# paths of requested packages |
| 140 |
return [os.path.join(app.path, "locale") for app in app_configs] |
| 141 |
|
| 142 |
@property |
| 143 |
def _num_plurals(self): |
| 144 |
""" |
| 145 |
Return the number of plurals for this catalog language, or 2 if no |
| 146 |
plural string is available. |
| 147 |
""" |
| 148 |
match = re.search(r"nplurals=\s*(\d+)", self._plural_string or "") |
| 149 |
if match: |
| 150 |
return int(match[1]) |
| 151 |
return 2 |
| 152 |
|
| 153 |
@property |
| 154 |
def _plural_string(self): |
| 155 |
""" |
| 156 |
Return the plural string (including nplurals) for this catalog language, |
| 157 |
or None if no plural string is available. |
| 158 |
""" |
| 159 |
if "" in self.translation._catalog: |
| 160 |
for line in self.translation._catalog[""].split("\n"): |
| 161 |
if line.startswith("Plural-Forms:"): |
| 162 |
return line.split(":", 1)[1].strip() |
| 163 |
return None |
| 164 |
|
| 165 |
def get_plural(self): |
| 166 |
plural = self._plural_string |
| 167 |
if plural is not None: |
| 168 |
# This should be a compiled function of a typical plural-form: |
| 169 |
# Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : |
| 170 |
# n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2; |
| 171 |
plural = [ |
| 172 |
el.strip() |
| 173 |
for el in plural.split(";") |
| 174 |
if el.strip().startswith("plural=") |
| 175 |
][0].split("=", 1)[1] |
| 176 |
return plural |
| 177 |
|
| 178 |
def get_catalog(self): |
| 179 |
pdict = {} |
| 180 |
catalog = {} |
| 181 |
translation = self.translation |
| 182 |
seen_keys = set() |
| 183 |
while True: |
| 184 |
for key, value in translation._catalog.items(): |
| 185 |
if key == "" or key in seen_keys: |
| 186 |
continue |
| 187 |
if isinstance(key, str): |
| 188 |
catalog[key] = value |
| 189 |
elif isinstance(key, tuple): |
| 190 |
msgid, cnt = key |
| 191 |
pdict.setdefault(msgid, {})[cnt] = value |
| 192 |
else: |
| 193 |
raise TypeError(key) |
| 194 |
seen_keys.add(key) |
| 195 |
if translation._fallback: |
| 196 |
translation = translation._fallback |
| 197 |
else: |
| 198 |
break |
| 199 |
|
| 200 |
num_plurals = self._num_plurals |
| 201 |
for k, v in pdict.items(): |
| 202 |
catalog[k] = [v.get(i, "") for i in range(num_plurals)] |
| 203 |
return catalog |
| 204 |
|
| 205 |
def get_context_data(self, **kwargs): |
| 206 |
return { |
| 207 |
"catalog": self.get_catalog(), |
| 208 |
"formats": get_formats(), |
| 209 |
"plural": self.get_plural(), |
| 210 |
} |
| 211 |
|
| 212 |
def render_to_response(self, context, **response_kwargs): |
| 213 |
def indent(s): |
| 214 |
return s.replace("\n", "\n ") |
| 215 |
|
| 216 |
with builtin_template_path("i18n_catalog.js").open(encoding="utf-8") as fh: |
| 217 |
template = Engine().from_string(fh.read()) |
| 218 |
context["catalog_str"] = ( |
| 219 |
indent(json.dumps(context["catalog"], sort_keys=True, indent=2)) |
| 220 |
if context["catalog"] |
| 221 |
else None |
| 222 |
) |
| 223 |
context["formats_str"] = indent( |
| 224 |
json.dumps(context["formats"], sort_keys=True, indent=2) |
| 225 |
) |
| 226 |
|
| 227 |
return HttpResponse( |
| 228 |
template.render(Context(context)), 'text/javascript; charset="utf-8"' |
| 229 |
) |
| 230 |
|
| 231 |
|
| 232 |
class JSONCatalog(JavaScriptCatalog): |
| 233 |
""" |
| 234 |
Return the selected language catalog as a JSON object. |
| 235 |
|
| 236 |
Receive the same parameters as JavaScriptCatalog and return a response |
| 237 |
with a JSON object of the following format: |
| 238 |
|
| 239 |
{ |
| 240 |
"catalog": { |
| 241 |
# Translations catalog |
| 242 |
}, |
| 243 |
"formats": { |
| 244 |
# Language formats for date, time, etc. |
| 245 |
}, |
| 246 |
"plural": '...' # Expression for plural forms, or null. |
| 247 |
} |
| 248 |
""" |
| 249 |
|
| 250 |
def render_to_response(self, context, **response_kwargs): |
| 251 |
return JsonResponse(context) |