Skip to content

Commit

Permalink
[common] Respect user language in Orga backend
Browse files Browse the repository at this point in the history
  • Loading branch information
raphaelm committed May 25, 2017
1 parent 9fcaae4 commit e7dcb68
Showing 1 changed file with 65 additions and 0 deletions.
65 changes: 65 additions & 0 deletions src/pretalx/common/middleware.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
import pytz
from django.conf import settings
from django.core.exceptions import PermissionDenied
from django.shortcuts import redirect
from django.urls import resolve
from django.utils import translation, timezone
from django.utils.translation.trans_real import parse_accept_lang_header, language_code_re, \
get_supported_language_variant

from pretalx.event.models import Event
from pretalx.person.models import EventPermission
Expand Down Expand Up @@ -47,4 +52,64 @@ def __call__(self, request):
if hasattr(request, 'event') and not request.is_orga:
raise PermissionDenied()

self._select_locale(request)

return self.get_response(request)

def _select_locale(self, request):
supported = request.event.locales if hasattr(request, 'event') else settings.LANGUAGES
language = (
self._language_from_user(request, supported)
or self._language_from_browser(request, supported)
)
if hasattr(request, 'event'):
language = language or request.event.locale

translation.activate(language)
request.LANGUAGE_CODE = translation.get_language()

try:
if request.user.is_authenticated:
tzname = request.user.timezone
elif hasattr(request, 'event'):
tzname = request.event.timezone
else:
tzname = settings.TIME_ZONE
timezone.activate(pytz.timezone(tzname))
request.timezone = tzname
except pytz.UnknownTimeZoneError:
pass

def _language_from_browser(self, request, supported):
accept_value = request.META.get('HTTP_ACCEPT_LANGUAGE', '')
for accept_lang, unused in parse_accept_lang_header(accept_value):
if accept_lang == '*':
break

if not language_code_re.search(accept_lang):
continue

try:
val = get_supported_language_variant(accept_lang)
if val and val in supported:
return val
except LookupError:
continue

def _language_from_cookie(self, request, supported):
cookie_value = request.COOKIES.get(settings.LANGUAGE_COOKIE_NAME)
try:
cookie_value = get_supported_language_variant(cookie_value)
if cookie_value and cookie_value in supported:
return cookie_value
except LookupError:
pass

def _language_from_user(self, request, supported):
if request.user.is_authenticated:
try:
value = get_supported_language_variant(request.user.locale)
if value and value in supported:
return value
except LookupError:
pass

0 comments on commit e7dcb68

Please sign in to comment.