Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
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

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