Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

i18n.py 11KB

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