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
|
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
from django import http
|
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
|
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
|
2015-01-28 20:35:27 +08:00
|
|
|
from django.utils import six
|
2016-09-03 02:17:15 +08:00
|
|
|
from django.utils.encoding import force_text
|
2016-04-28 21:15:34 +08:00
|
|
|
from django.utils.formats import get_format
|
2016-04-06 22:11:23 +08:00
|
|
|
from django.utils.http import is_safe_url, urlunquote
|
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):
|
|
|
|
"""
|
|
|
|
Redirect to a given url while setting the chosen language in the
|
|
|
|
session or cookie. The url and the language code need to be
|
2007-09-14 15:33:45 +08:00
|
|
|
specified in the request parameters.
|
|
|
|
|
|
|
|
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
|
|
|
"""
|
2013-10-16 04:36:49 +08:00
|
|
|
next = request.POST.get('next', request.GET.get('next'))
|
2016-08-19 20:32:21 +08:00
|
|
|
if ((next or not request.is_ajax()) and
|
2016-07-27 11:45:07 +08:00
|
|
|
not is_safe_url(url=next, allowed_hosts={request.get_host()}, require_https=request.is_secure())):
|
2012-11-18 05:00:53 +08:00
|
|
|
next = request.META.get('HTTP_REFERER')
|
2016-04-06 22:11:23 +08:00
|
|
|
if next:
|
|
|
|
next = urlunquote(next) # HTTP_REFERER may be encoded.
|
2016-07-27 11:45:07 +08:00
|
|
|
if not is_safe_url(url=next, allowed_hosts={request.get_host()}, require_https=request.is_secure()):
|
2012-11-18 05:00:53 +08:00
|
|
|
next = '/'
|
2016-03-29 01:23:04 +08:00
|
|
|
response = http.HttpResponseRedirect(next) if next else http.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):
|
2016-03-29 01:23:04 +08:00
|
|
|
if next:
|
|
|
|
next_trans = translate_url(next, lang_code)
|
|
|
|
if next_trans != next:
|
|
|
|
response = http.HttpResponseRedirect(next_trans)
|
2007-09-14 15:33:45 +08:00
|
|
|
if hasattr(request, 'session'):
|
2014-02-22 21:27:57 +08:00
|
|
|
request.session[LANGUAGE_SESSION_KEY] = lang_code
|
2007-09-14 15:33:45 +08:00
|
|
|
else:
|
2016-03-29 06:33:29 +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,
|
|
|
|
)
|
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():
|
|
|
|
"""
|
2009-12-31 06:12:16 +08:00
|
|
|
Returns all formats strings required for i18n to work
|
2009-12-23 01:58:49 +08:00
|
|
|
"""
|
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'
|
|
|
|
)
|
2009-12-23 01:58:49 +08:00
|
|
|
result = {}
|
2016-04-28 21:15:34 +08:00
|
|
|
for attr in FORMAT_SETTINGS:
|
|
|
|
result[attr] = get_format(attr)
|
2013-04-14 22:55:17 +08:00
|
|
|
formats = {}
|
2010-01-04 10:28:34 +08:00
|
|
|
for k, v in result.items():
|
2016-12-29 23:27:49 +08:00
|
|
|
if isinstance(v, (int, str)):
|
2016-09-03 02:17:15 +08:00
|
|
|
formats[k] = force_text(v)
|
2010-01-04 10:28:34 +08:00
|
|
|
elif isinstance(v, (tuple, list)):
|
2016-09-03 02:17:15 +08:00
|
|
|
formats[k] = [force_text(value) for value in v]
|
2013-04-14 22:55:17 +08:00
|
|
|
return formats
|
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 {
|
|
|
|
return value[django.pluralidx(count)];
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
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
|
|
|
|
|
|
|
def render_javascript_catalog(catalog=None, plural=None):
|
2015-02-23 02:14:05 +08:00
|
|
|
template = Engine().from_string(js_catalog_template)
|
2016-01-24 00:47:07 +08:00
|
|
|
|
|
|
|
def indent(s):
|
|
|
|
return s.replace('\n', '\n ')
|
|
|
|
|
2013-04-14 22:55:17 +08:00
|
|
|
context = Context({
|
|
|
|
'catalog_str': indent(json.dumps(
|
|
|
|
catalog, sort_keys=True, indent=2)) if catalog else None,
|
|
|
|
'formats_str': indent(json.dumps(
|
|
|
|
get_formats(), sort_keys=True, indent=2)),
|
|
|
|
'plural': plural,
|
|
|
|
})
|
|
|
|
|
|
|
|
return http.HttpResponse(template.render(context), 'text/javascript')
|
|
|
|
|
2008-03-24 21:27:19 +08:00
|
|
|
|
2013-05-18 19:20:52 +08:00
|
|
|
def null_javascript_catalog(request, domain=None, packages=None):
|
|
|
|
"""
|
|
|
|
Returns "identity" versions of the JavaScript i18n functions -- i.e.,
|
|
|
|
versions that don't actually do anything.
|
|
|
|
"""
|
|
|
|
return render_javascript_catalog()
|
|
|
|
|
|
|
|
|
2016-03-08 04:52:08 +08:00
|
|
|
class JavaScriptCatalog(View):
|
|
|
|
"""
|
|
|
|
Return the selected language catalog as a JavaScript library.
|
|
|
|
|
|
|
|
Receives the list of packages to check for translations in the `packages`
|
|
|
|
kwarg either from the extra dictionary passed to the url() function or as a
|
|
|
|
plus-sign delimited string from the request. Default is 'django.conf'.
|
|
|
|
|
|
|
|
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):
|
|
|
|
allowable_packages = dict((app_config.name, app_config) for app_config in apps.get_app_configs())
|
|
|
|
app_configs = [allowable_packages[p] for p in packages if p in allowable_packages]
|
|
|
|
# paths of requested packages
|
|
|
|
return [os.path.join(app.path, 'locale') for app in app_configs]
|
|
|
|
|
|
|
|
def get_plural(self):
|
|
|
|
plural = None
|
|
|
|
if '' in self.translation._catalog:
|
|
|
|
for line in self.translation._catalog[''].split('\n'):
|
|
|
|
if line.startswith('Plural-Forms:'):
|
|
|
|
plural = line.split(':', 1)[1].strip()
|
|
|
|
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 = {}
|
|
|
|
maxcnts = {}
|
|
|
|
catalog = {}
|
|
|
|
trans_cat = self.translation._catalog
|
|
|
|
trans_fallback_cat = self.translation._fallback._catalog if self.translation._fallback else {}
|
|
|
|
for key, value in itertools.chain(six.iteritems(trans_cat), six.iteritems(trans_fallback_cat)):
|
|
|
|
if key == '' or key in catalog:
|
|
|
|
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):
|
|
|
|
msgid = key[0]
|
|
|
|
cnt = key[1]
|
|
|
|
maxcnts[msgid] = max(cnt, maxcnts.get(msgid, 0))
|
|
|
|
pdict.setdefault(msgid, {})[cnt] = value
|
|
|
|
else:
|
|
|
|
raise TypeError(key)
|
|
|
|
for k, v in pdict.items():
|
2016-12-09 22:07:25 +08:00
|
|
|
catalog[k] = [v.get(i, '') for i in range(maxcnts[k] + 1)]
|
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))
|
|
|
|
|
|
|
|
return http.HttpResponse(template.render(Context(context)), 'text/javascript')
|
|
|
|
|
|
|
|
|
|
|
|
class JSONCatalog(JavaScriptCatalog):
|
|
|
|
"""
|
|
|
|
Return the selected language catalog as a JSON object.
|
|
|
|
|
|
|
|
Receives the same parameters as JavaScriptCatalog and returns a response
|
|
|
|
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):
|
|
|
|
return http.JsonResponse(context)
|