2016-03-06 08:01:39 +08:00
|
|
|
import itertools
|
2013-04-14 22:55:17 +08:00
|
|
|
import json
|
2009-12-23 01:58:49 +08:00
|
|
|
import os
|
2017-05-18 21:00:42 +08:00
|
|
|
import re
|
2017-01-26 21:25:15 +08:00
|
|
|
from urllib.parse import unquote
|
2009-12-23 01:58:49 +08:00
|
|
|
|
2013-12-24 19:25:17 +08:00
|
|
|
from django.apps import apps
|
2009-03-19 00:55:59 +08:00
|
|
|
from django.conf import settings
|
2017-02-25 14:48:20 +08:00
|
|
|
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
|
2015-02-23 02:14:05 +08:00
|
|
|
from django.template import Context, Engine
|
2015-12-30 23:51:16 +08:00
|
|
|
from django.urls import translate_url
|
2016-04-28 21:15:34 +08:00
|
|
|
from django.utils.formats import get_format
|
2019-08-14 23:39:21 +08:00
|
|
|
from django.utils.http import url_has_allowed_host_and_scheme
|
2015-01-28 20:35:27 +08:00
|
|
|
from django.utils.translation import (
|
2017-01-01 01:10:37 +08:00
|
|
|
LANGUAGE_SESSION_KEY, check_for_language, get_language,
|
2015-01-28 20:35:27 +08:00
|
|
|
)
|
2016-03-06 08:01:39 +08:00
|
|
|
from django.utils.translation.trans_real import DjangoTranslation
|
2016-03-08 04:52:08 +08:00
|
|
|
from django.views.generic import View
|
2005-11-04 12:59:46 +08:00
|
|
|
|
2015-06-05 22:10:28 +08:00
|
|
|
LANGUAGE_QUERY_PARAMETER = 'language'
|
|
|
|
|
2013-11-03 07:53:29 +08:00
|
|
|
|
2005-11-04 12:59:46 +08:00
|
|
|
def set_language(request):
|
|
|
|
"""
|
2017-12-02 20:00:30 +08:00
|
|
|
Redirect to a given URL while setting the chosen language in the session
|
|
|
|
(if enabled) and in a cookie. The URL and the language code need to be
|
|
|
|
specified in the request parameters.
|
2007-09-14 15:33:45 +08:00
|
|
|
|
|
|
|
Since this view changes how the user will see the rest of the site, it must
|
|
|
|
only be accessed as a POST request. If called as a GET request, it will
|
|
|
|
redirect to the page in the request (the 'next' parameter) without changing
|
|
|
|
any state.
|
2005-11-04 12:59:46 +08:00
|
|
|
"""
|
2019-12-22 04:18:14 +08:00
|
|
|
next_url = request.POST.get('next', request.GET.get('next'))
|
2019-08-14 23:39:21 +08:00
|
|
|
if (
|
2019-12-15 22:30:35 +08:00
|
|
|
(next_url or request.accepts('text/html')) and
|
2019-08-14 23:39:21 +08:00
|
|
|
not url_has_allowed_host_and_scheme(
|
2019-12-22 04:18:14 +08:00
|
|
|
url=next_url,
|
|
|
|
allowed_hosts={request.get_host()},
|
|
|
|
require_https=request.is_secure(),
|
2019-08-14 23:39:21 +08:00
|
|
|
)
|
|
|
|
):
|
2019-12-22 04:18:14 +08:00
|
|
|
next_url = request.META.get('HTTP_REFERER')
|
|
|
|
# HTTP_REFERER may be encoded.
|
|
|
|
next_url = next_url and unquote(next_url)
|
2019-08-14 23:39:21 +08:00
|
|
|
if not url_has_allowed_host_and_scheme(
|
2019-12-22 04:18:14 +08:00
|
|
|
url=next_url,
|
|
|
|
allowed_hosts={request.get_host()},
|
|
|
|
require_https=request.is_secure(),
|
2019-08-14 23:39:21 +08:00
|
|
|
):
|
2019-12-22 04:18:14 +08:00
|
|
|
next_url = '/'
|
|
|
|
response = HttpResponseRedirect(next_url) if next_url else HttpResponse(status=204)
|
2007-09-14 15:33:45 +08:00
|
|
|
if request.method == 'POST':
|
2015-06-05 22:10:28 +08:00
|
|
|
lang_code = request.POST.get(LANGUAGE_QUERY_PARAMETER)
|
2007-09-14 15:33:45 +08:00
|
|
|
if lang_code and check_for_language(lang_code):
|
2019-12-22 04:18:14 +08:00
|
|
|
if next_url:
|
|
|
|
next_trans = translate_url(next_url, lang_code)
|
|
|
|
if next_trans != next_url:
|
2017-02-25 14:48:20 +08:00
|
|
|
response = HttpResponseRedirect(next_trans)
|
2007-09-14 15:33:45 +08:00
|
|
|
if hasattr(request, 'session'):
|
2016-08-15 04:42:49 +08:00
|
|
|
# Storing the language in the session is deprecated.
|
|
|
|
# (RemovedInDjango40Warning)
|
2014-02-22 21:27:57 +08:00
|
|
|
request.session[LANGUAGE_SESSION_KEY] = lang_code
|
2017-12-02 20:00:30 +08:00
|
|
|
response.set_cookie(
|
|
|
|
settings.LANGUAGE_COOKIE_NAME, lang_code,
|
|
|
|
max_age=settings.LANGUAGE_COOKIE_AGE,
|
|
|
|
path=settings.LANGUAGE_COOKIE_PATH,
|
|
|
|
domain=settings.LANGUAGE_COOKIE_DOMAIN,
|
2019-04-01 17:29:10 +08:00
|
|
|
secure=settings.LANGUAGE_COOKIE_SECURE,
|
|
|
|
httponly=settings.LANGUAGE_COOKIE_HTTPONLY,
|
|
|
|
samesite=settings.LANGUAGE_COOKIE_SAMESITE,
|
2017-12-02 20:00:30 +08:00
|
|
|
)
|
2005-11-04 12:59:46 +08:00
|
|
|
return response
|
2005-12-04 20:06:16 +08:00
|
|
|
|
2013-04-14 22:55:17 +08:00
|
|
|
|
2009-12-23 01:58:49 +08:00
|
|
|
def get_formats():
|
2017-01-25 04:36:07 +08:00
|
|
|
"""Return all formats strings required for i18n to work."""
|
2009-12-31 06:12:16 +08:00
|
|
|
FORMAT_SETTINGS = (
|
|
|
|
'DATE_FORMAT', 'DATETIME_FORMAT', 'TIME_FORMAT',
|
2009-12-23 01:58:49 +08:00
|
|
|
'YEAR_MONTH_FORMAT', 'MONTH_DAY_FORMAT', 'SHORT_DATE_FORMAT',
|
|
|
|
'SHORT_DATETIME_FORMAT', 'FIRST_DAY_OF_WEEK', 'DECIMAL_SEPARATOR',
|
2009-12-31 06:12:16 +08:00
|
|
|
'THOUSAND_SEPARATOR', 'NUMBER_GROUPING',
|
|
|
|
'DATE_INPUT_FORMATS', 'TIME_INPUT_FORMATS', 'DATETIME_INPUT_FORMATS'
|
|
|
|
)
|
2017-04-27 16:50:48 +08:00
|
|
|
return {attr: get_format(attr) for attr in FORMAT_SETTINGS}
|
2005-12-04 20:06:16 +08:00
|
|
|
|
|
|
|
|
2013-04-14 22:55:17 +08:00
|
|
|
js_catalog_template = r"""
|
|
|
|
{% autoescape off %}
|
2015-03-21 01:31:17 +08:00
|
|
|
(function(globals) {
|
2005-12-04 20:06:16 +08:00
|
|
|
|
2013-04-14 22:55:17 +08:00
|
|
|
var django = globals.django || (globals.django = {});
|
2010-01-04 10:28:34 +08:00
|
|
|
|
2013-04-14 22:55:17 +08:00
|
|
|
{% if plural %}
|
2015-03-21 01:31:17 +08:00
|
|
|
django.pluralidx = function(n) {
|
2013-04-14 22:55:17 +08:00
|
|
|
var v={{ plural }};
|
|
|
|
if (typeof(v) == 'boolean') {
|
|
|
|
return v ? 1 : 0;
|
|
|
|
} else {
|
|
|
|
return v;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
{% else %}
|
2015-03-21 01:31:17 +08:00
|
|
|
django.pluralidx = function(count) { return (count == 1) ? 0 : 1; };
|
2013-04-14 22:55:17 +08:00
|
|
|
{% endif %}
|
2010-01-04 10:28:34 +08:00
|
|
|
|
2013-04-14 22:55:17 +08:00
|
|
|
/* gettext library */
|
2010-01-04 10:28:34 +08:00
|
|
|
|
2014-02-23 22:10:31 +08:00
|
|
|
django.catalog = django.catalog || {};
|
|
|
|
{% if catalog_str %}
|
|
|
|
var newcatalog = {{ catalog_str }};
|
|
|
|
for (var key in newcatalog) {
|
|
|
|
django.catalog[key] = newcatalog[key];
|
|
|
|
}
|
2013-04-14 22:55:17 +08:00
|
|
|
{% endif %}
|
|
|
|
|
2014-02-23 22:10:31 +08:00
|
|
|
if (!django.jsi18n_initialized) {
|
2015-03-21 01:31:17 +08:00
|
|
|
django.gettext = function(msgid) {
|
2014-02-23 22:10:31 +08:00
|
|
|
var value = django.catalog[msgid];
|
|
|
|
if (typeof(value) == 'undefined') {
|
|
|
|
return msgid;
|
|
|
|
} else {
|
|
|
|
return (typeof(value) == 'string') ? value : value[0];
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2015-03-21 01:31:17 +08:00
|
|
|
django.ngettext = function(singular, plural, count) {
|
2014-02-23 22:10:31 +08:00
|
|
|
var value = django.catalog[singular];
|
|
|
|
if (typeof(value) == 'undefined') {
|
|
|
|
return (count == 1) ? singular : plural;
|
|
|
|
} else {
|
2019-01-26 23:44:49 +08:00
|
|
|
return value.constructor === Array ? value[django.pluralidx(count)] : value;
|
2014-02-23 22:10:31 +08:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2015-03-21 01:31:17 +08:00
|
|
|
django.gettext_noop = function(msgid) { return msgid; };
|
2014-02-23 22:10:31 +08:00
|
|
|
|
2015-03-21 01:31:17 +08:00
|
|
|
django.pgettext = function(context, msgid) {
|
2014-02-23 22:10:31 +08:00
|
|
|
var value = django.gettext(context + '\x04' + msgid);
|
|
|
|
if (value.indexOf('\x04') != -1) {
|
|
|
|
value = msgid;
|
|
|
|
}
|
2010-01-04 10:28:34 +08:00
|
|
|
return value;
|
2014-02-23 22:10:31 +08:00
|
|
|
};
|
2005-12-04 20:06:16 +08:00
|
|
|
|
2015-03-21 01:31:17 +08:00
|
|
|
django.npgettext = function(context, singular, plural, count) {
|
2014-02-23 22:10:31 +08:00
|
|
|
var value = django.ngettext(context + '\x04' + singular, context + '\x04' + plural, count);
|
|
|
|
if (value.indexOf('\x04') != -1) {
|
|
|
|
value = django.ngettext(singular, plural, count);
|
|
|
|
}
|
|
|
|
return value;
|
|
|
|
};
|
|
|
|
|
2015-03-21 01:31:17 +08:00
|
|
|
django.interpolate = function(fmt, obj, named) {
|
2014-02-23 22:10:31 +08:00
|
|
|
if (named) {
|
|
|
|
return fmt.replace(/%\(\w+\)s/g, function(match){return String(obj[match.slice(2,-2)])});
|
|
|
|
} else {
|
|
|
|
return fmt.replace(/%s/g, function(match){return String(obj.shift())});
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
|
|
/* formatting library */
|
|
|
|
|
|
|
|
django.formats = {{ formats_str }};
|
|
|
|
|
2015-03-21 01:31:17 +08:00
|
|
|
django.get_format = function(format_type) {
|
2014-02-23 22:10:31 +08:00
|
|
|
var value = django.formats[format_type];
|
|
|
|
if (typeof(value) == 'undefined') {
|
|
|
|
return format_type;
|
|
|
|
} else {
|
|
|
|
return value;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
/* add to global namespace */
|
|
|
|
globals.pluralidx = django.pluralidx;
|
|
|
|
globals.gettext = django.gettext;
|
|
|
|
globals.ngettext = django.ngettext;
|
|
|
|
globals.gettext_noop = django.gettext_noop;
|
|
|
|
globals.pgettext = django.pgettext;
|
|
|
|
globals.npgettext = django.npgettext;
|
|
|
|
globals.interpolate = django.interpolate;
|
|
|
|
globals.get_format = django.get_format;
|
|
|
|
|
|
|
|
django.jsi18n_initialized = true;
|
|
|
|
}
|
2005-12-04 20:06:16 +08:00
|
|
|
|
2013-04-14 22:55:17 +08:00
|
|
|
}(this));
|
|
|
|
{% endautoescape %}
|
2005-12-04 20:06:16 +08:00
|
|
|
"""
|
|
|
|
|
2013-04-14 22:55:17 +08:00
|
|
|
|
2016-03-08 04:52:08 +08:00
|
|
|
class JavaScriptCatalog(View):
|
|
|
|
"""
|
|
|
|
Return the selected language catalog as a JavaScript library.
|
|
|
|
|
2017-01-25 04:36:07 +08:00
|
|
|
Receive the list of packages to check for translations in the `packages`
|
2020-05-05 02:33:35 +08:00
|
|
|
kwarg either from the extra dictionary passed to the path() function or as
|
|
|
|
a plus-sign delimited string from the request. Default is 'django.conf'.
|
2016-03-08 04:52:08 +08:00
|
|
|
|
|
|
|
You can override the gettext domain for this view, but usually you don't
|
|
|
|
want to do that as JavaScript messages go to the djangojs domain. This
|
|
|
|
might be needed if you deliver your JavaScript source from Django templates.
|
|
|
|
"""
|
|
|
|
domain = 'djangojs'
|
|
|
|
packages = None
|
|
|
|
|
|
|
|
def get(self, request, *args, **kwargs):
|
|
|
|
locale = get_language()
|
|
|
|
domain = kwargs.get('domain', self.domain)
|
|
|
|
# If packages are not provided, default to all installed packages, as
|
|
|
|
# DjangoTranslation without localedirs harvests them all.
|
2016-10-23 07:20:24 +08:00
|
|
|
packages = kwargs.get('packages', '')
|
|
|
|
packages = packages.split('+') if packages else self.packages
|
2016-03-08 04:52:08 +08:00
|
|
|
paths = self.get_paths(packages) if packages else None
|
|
|
|
self.translation = DjangoTranslation(locale, domain=domain, localedirs=paths)
|
|
|
|
context = self.get_context_data(**kwargs)
|
|
|
|
return self.render_to_response(context)
|
|
|
|
|
|
|
|
def get_paths(self, packages):
|
2017-06-02 07:08:59 +08:00
|
|
|
allowable_packages = {app_config.name: app_config for app_config in apps.get_app_configs()}
|
2016-03-08 04:52:08 +08:00
|
|
|
app_configs = [allowable_packages[p] for p in packages if p in allowable_packages]
|
2017-04-03 02:14:39 +08:00
|
|
|
if len(app_configs) < len(packages):
|
|
|
|
excluded = [p for p in packages if p not in allowable_packages]
|
|
|
|
raise ValueError(
|
|
|
|
'Invalid package(s) provided to JavaScriptCatalog: %s' % ','.join(excluded)
|
|
|
|
)
|
2016-03-08 04:52:08 +08:00
|
|
|
# paths of requested packages
|
|
|
|
return [os.path.join(app.path, 'locale') for app in app_configs]
|
|
|
|
|
2017-05-18 21:00:42 +08:00
|
|
|
@property
|
|
|
|
def _num_plurals(self):
|
|
|
|
"""
|
|
|
|
Return the number of plurals for this catalog language, or 2 if no
|
|
|
|
plural string is available.
|
|
|
|
"""
|
|
|
|
match = re.search(r'nplurals=\s*(\d+)', self._plural_string or '')
|
|
|
|
if match:
|
2020-05-11 04:03:39 +08:00
|
|
|
return int(match[1])
|
2017-05-18 21:00:42 +08:00
|
|
|
return 2
|
|
|
|
|
|
|
|
@property
|
|
|
|
def _plural_string(self):
|
|
|
|
"""
|
|
|
|
Return the plural string (including nplurals) for this catalog language,
|
|
|
|
or None if no plural string is available.
|
|
|
|
"""
|
2016-03-08 04:52:08 +08:00
|
|
|
if '' in self.translation._catalog:
|
|
|
|
for line in self.translation._catalog[''].split('\n'):
|
|
|
|
if line.startswith('Plural-Forms:'):
|
2017-05-18 21:00:42 +08:00
|
|
|
return line.split(':', 1)[1].strip()
|
|
|
|
return None
|
|
|
|
|
|
|
|
def get_plural(self):
|
|
|
|
plural = self._plural_string
|
2016-03-08 04:52:08 +08:00
|
|
|
if plural is not None:
|
|
|
|
# This should be a compiled function of a typical plural-form:
|
|
|
|
# Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 :
|
|
|
|
# n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;
|
|
|
|
plural = [el.strip() for el in plural.split(';') if el.strip().startswith('plural=')][0].split('=', 1)[1]
|
|
|
|
return plural
|
|
|
|
|
|
|
|
def get_catalog(self):
|
|
|
|
pdict = {}
|
2017-05-18 21:00:42 +08:00
|
|
|
num_plurals = self._num_plurals
|
2016-03-08 04:52:08 +08:00
|
|
|
catalog = {}
|
|
|
|
trans_cat = self.translation._catalog
|
|
|
|
trans_fallback_cat = self.translation._fallback._catalog if self.translation._fallback else {}
|
2017-05-20 19:28:20 +08:00
|
|
|
seen_keys = set()
|
2017-08-24 04:48:29 +08:00
|
|
|
for key, value in itertools.chain(trans_cat.items(), trans_fallback_cat.items()):
|
2017-05-20 19:28:20 +08:00
|
|
|
if key == '' or key in seen_keys:
|
2016-03-08 04:52:08 +08:00
|
|
|
continue
|
2016-12-29 23:27:49 +08:00
|
|
|
if isinstance(key, str):
|
2016-03-08 04:52:08 +08:00
|
|
|
catalog[key] = value
|
|
|
|
elif isinstance(key, tuple):
|
2017-05-18 21:00:42 +08:00
|
|
|
msgid, cnt = key
|
2016-03-08 04:52:08 +08:00
|
|
|
pdict.setdefault(msgid, {})[cnt] = value
|
|
|
|
else:
|
|
|
|
raise TypeError(key)
|
2017-05-20 19:28:20 +08:00
|
|
|
seen_keys.add(key)
|
2016-03-08 04:52:08 +08:00
|
|
|
for k, v in pdict.items():
|
2017-05-18 21:00:42 +08:00
|
|
|
catalog[k] = [v.get(i, '') for i in range(num_plurals)]
|
2016-03-08 04:52:08 +08:00
|
|
|
return catalog
|
|
|
|
|
|
|
|
def get_context_data(self, **kwargs):
|
|
|
|
return {
|
|
|
|
'catalog': self.get_catalog(),
|
|
|
|
'formats': get_formats(),
|
|
|
|
'plural': self.get_plural(),
|
|
|
|
}
|
|
|
|
|
|
|
|
def render_to_response(self, context, **response_kwargs):
|
|
|
|
def indent(s):
|
|
|
|
return s.replace('\n', '\n ')
|
|
|
|
|
|
|
|
template = Engine().from_string(js_catalog_template)
|
|
|
|
context['catalog_str'] = indent(
|
|
|
|
json.dumps(context['catalog'], sort_keys=True, indent=2)
|
|
|
|
) if context['catalog'] else None
|
|
|
|
context['formats_str'] = indent(json.dumps(context['formats'], sort_keys=True, indent=2))
|
|
|
|
|
2018-06-22 15:15:29 +08:00
|
|
|
return HttpResponse(template.render(Context(context)), 'text/javascript; charset="utf-8"')
|
2016-03-08 04:52:08 +08:00
|
|
|
|
|
|
|
|
|
|
|
class JSONCatalog(JavaScriptCatalog):
|
|
|
|
"""
|
|
|
|
Return the selected language catalog as a JSON object.
|
|
|
|
|
2017-01-25 04:36:07 +08:00
|
|
|
Receive the same parameters as JavaScriptCatalog and return a response
|
2016-03-08 04:52:08 +08:00
|
|
|
with a JSON object of the following format:
|
|
|
|
|
|
|
|
{
|
|
|
|
"catalog": {
|
|
|
|
# Translations catalog
|
|
|
|
},
|
|
|
|
"formats": {
|
|
|
|
# Language formats for date, time, etc.
|
|
|
|
},
|
|
|
|
"plural": '...' # Expression for plural forms, or null.
|
|
|
|
}
|
|
|
|
"""
|
|
|
|
def render_to_response(self, context, **response_kwargs):
|
2017-02-25 14:48:20 +08:00
|
|
|
return JsonResponse(context)
|