Commits

Hector Garcia committed 125e164

Added ability to redirect geolocated requests from Catalonia through django GeoIP.

Comments (0)

Files changed (1)

localeurl/middleware.py

 
     def process_request(self, request):
         locale, path = utils.strip_path(request.path_info)
+
         # Make localeurl work with django_language cookie
         lang_cookie = request.COOKIES.get(settings.LANGUAGE_COOKIE_NAME, False)
         locale = request.COOKIES.get(settings.LANGUAGE_COOKIE_NAME, locale)
+
         # Force certain urls to a given language
         forced_lang_dict = getattr(settings, 'FORCE_LOCALEURL_LANG', dict())
         patterns = filter(lambda x: x in forced_lang_dict, request.path.split('/'))
         if patterns:
             locale = forced_lang_dict[patterns[0]]
-        if localeurl_settings.USE_ACCEPT_LANGUAGE and not lang_cookie:
-            accept_langs = filter(lambda x: x, [utils.supported_language(lang[0])
-                                                for lang in
-                                                parse_accept_lang_header(
-                        request.META.get('HTTP_ACCEPT_LANGUAGE', ''))])
-            if accept_langs:
-                locale = accept_langs[0]
+
+        # Try to geolocate if not forced URL and lang cookie not set
+        if not patterns and not lang_cookie:
+            from django.contrib.gis.utils import GeoIP
+            geolocated = False
+            geo = GeoIP()
+            try: # Use only in devel envs, to test fake ips
+                ip = settings.GEOIP_FAKE_REMOTE_ADDR
+            except AttributeError:
+                ip = request.META.get('HTTP_X_REAL_IP', None)
+            if ip is not None and ip not in settings.INTERNAL_IPS:
+                ccode = geo.city(ip)['country_code'].lower()
+                region = geo.city(ip)['region'].lower()
+                if ccode == 'es' and region == '56': # Catalunya
+                    locale = 'ca'
+                    geolocated = True
+            if localeurl_settings.USE_ACCEPT_LANGUAGE and not geolocated:
+                accept_langs = filter(lambda x: x, [utils.supported_language(lang[0])
+                                                    for lang in
+                                                    parse_accept_lang_header(
+                            request.META.get('HTTP_ACCEPT_LANGUAGE', ''))])
+                if accept_langs:
+                    locale = accept_langs[0]
+
         locale_path = utils.locale_path(path, locale)
         if locale_path != request.path_info:
             if request.META.get("QUERY_STRING", ""):