| 1 |
# Default locale mapping for the Facebook JS SDK |
| 2 |
# The list of supported locales is at |
| 3 |
# https://www.facebook.com/translations/FacebookLocales.xml |
| 4 |
from __future__ import annotations |
| 5 |
|
| 6 |
import os |
| 7 |
|
| 8 |
from django.http import HttpRequest |
| 9 |
from django.utils.translation import get_language, to_locale |
| 10 |
|
| 11 |
|
| 12 |
def _build_locale_table(filename_or_file): |
| 13 |
""" |
| 14 |
Parses the FacebookLocales.xml file and builds a dict relating every |
| 15 |
available language ('en, 'es, 'zh', ...) with a list of available regions |
| 16 |
for that language ('en' -> 'US', 'EN') and an (arbitrary) default region. |
| 17 |
""" |
| 18 |
# Require the XML parser module only if we want the default mapping |
| 19 |
from xml.dom.minidom import parse # nosec |
| 20 |
|
| 21 |
# Trusted source |
| 22 |
dom = parse(filename_or_file) # nosec |
| 23 |
|
| 24 |
reps = dom.getElementsByTagName("representation") |
| 25 |
locs = map(lambda r: r.childNodes[0].data, reps) |
| 26 |
|
| 27 |
locale_map = {} |
| 28 |
for loc in locs: |
| 29 |
lang, _, reg = loc.partition("_") |
| 30 |
lang_map = locale_map.setdefault(lang, {"regs": [], "default": reg}) |
| 31 |
lang_map["regs"].append(reg) |
| 32 |
|
| 33 |
# Default region overrides (arbitrary) |
| 34 |
locale_map["en"]["default"] = "US" |
| 35 |
# Special case: Use es_ES for Spain and es_LA for everything else |
| 36 |
locale_map["es"]["default"] = "LA" |
| 37 |
locale_map["zh"]["default"] = "CN" |
| 38 |
locale_map["fr"]["default"] = "FR" |
| 39 |
locale_map["pt"]["default"] = "PT" |
| 40 |
|
| 41 |
return locale_map |
| 42 |
|
| 43 |
|
| 44 |
def get_default_locale_callable(): |
| 45 |
""" |
| 46 |
Wrapper function so that the default mapping is only built when needed |
| 47 |
""" |
| 48 |
exec_dir = os.path.dirname(os.path.realpath(__file__)) |
| 49 |
xml_path = os.path.join(exec_dir, "data", "FacebookLocales.xml") |
| 50 |
|
| 51 |
fb_locales = _build_locale_table(xml_path) |
| 52 |
|
| 53 |
def default_locale(request: HttpRequest): |
| 54 |
""" |
| 55 |
Guess an appropriate FB locale based on the active Django locale. |
| 56 |
If the active locale is available, it is returned. Otherwise, |
| 57 |
it tries to return another locale with the same language. If there |
| 58 |
isn't one available, 'en_US' is returned. |
| 59 |
""" |
| 60 |
chosen = "en_US" |
| 61 |
language = get_language() |
| 62 |
if language: |
| 63 |
locale = to_locale(language) |
| 64 |
lang, _, reg = locale.partition("_") |
| 65 |
|
| 66 |
lang_map = fb_locales.get(lang) |
| 67 |
if lang_map is not None: |
| 68 |
if reg in lang_map["regs"]: |
| 69 |
chosen = f"{lang}_{reg}" |
| 70 |
else: |
| 71 |
chosen = f"{lang}_{lang_map['default']}" |
| 72 |
return chosen |
| 73 |
|
| 74 |
return default_locale |