|
| 1 | +# python |
| 2 | +import re |
| 3 | + |
| 4 | +from django.utils.deprecation import MiddlewareMixin |
| 5 | +from opaque_keys.edx.keys import CourseKey |
| 6 | +from openedx.core.djangoapps.content.course_overviews.models import CourseOverview |
| 7 | +from openedx.core.djangoapps.lang_pref import LANGUAGE_KEY |
| 8 | +from openedx.core.djangoapps.user_api.preferences.api import set_user_preference |
| 9 | + |
| 10 | + |
| 11 | +class CourseLanguageCookieMiddleware(MiddlewareMixin): |
| 12 | + """ |
| 13 | + Sets language preference cookie and user preference based on course language. |
| 14 | + """ |
| 15 | + |
| 16 | + COURSE_URL_REGEX = re.compile( |
| 17 | + r"^/courses/(?P<course_key>course-v1:[A-Za-z0-9._-]+(?:\+[A-Za-z0-9._-]+)+)(?:/|$)", |
| 18 | + re.IGNORECASE, |
| 19 | + ) |
| 20 | + COOKIE_NAME = "openedx-language-preference" |
| 21 | + |
| 22 | + def process_response(self, request, response): |
| 23 | + path = getattr(request, "path_info", request.path) |
| 24 | + match = self.COURSE_URL_REGEX.match(path) |
| 25 | + if not match: |
| 26 | + return response |
| 27 | + |
| 28 | + course_key_str = match.group("course_key") |
| 29 | + try: |
| 30 | + course_key = CourseKey.from_string(course_key_str) |
| 31 | + overview = CourseOverview.get_from_id(course_key) |
| 32 | + except Exception: # noqa: BLE001 |
| 33 | + return response |
| 34 | + |
| 35 | + language = getattr(overview, "language", None) |
| 36 | + response.set_cookie( |
| 37 | + self.COOKIE_NAME, |
| 38 | + language or "", |
| 39 | + max_age=60 * 60 * 24 * 180, |
| 40 | + httponly=False, |
| 41 | + samesite="Lax", |
| 42 | + ) |
| 43 | + |
| 44 | + # Set user preference if authenticated |
| 45 | + if language and hasattr(request, "user") and request.user.is_authenticated: |
| 46 | + set_user_preference(request.user, LANGUAGE_KEY, language) |
| 47 | + |
| 48 | + return response |
0 commit comments