/ src / l10n.py.bak
l10n.py.bak
  1  """Localization helpers"""
  2  
  3  import logging
  4  import os
  5  import re
  6  import time
  7  
  8  import six
  9  from six.moves import range
 10  
 11  from bmconfigparser import config
 12  
 13  logger = logging.getLogger('default')
 14  
 15  DEFAULT_ENCODING = 'ISO8859-1'
 16  DEFAULT_LANGUAGE = 'en_US'
 17  DEFAULT_TIME_FORMAT = '%Y-%m-%d %H:%M:%S'
 18  
 19  try:
 20      import locale
 21      encoding = locale.getpreferredencoding(True) or DEFAULT_ENCODING
 22      language = (
 23          locale.getlocale()[0] or locale.getdefaultlocale()[0]
 24          or DEFAULT_LANGUAGE)
 25  except (ImportError, AttributeError):  # FIXME: it never happens
 26      logger.exception('Could not determine language or encoding')
 27      locale = None
 28      encoding = DEFAULT_ENCODING
 29      language = DEFAULT_LANGUAGE
 30  
 31  
 32  windowsLanguageMap = {
 33      "ar": "arabic",
 34      "cs": "czech",
 35      "da": "danish",
 36      "de": "german",
 37      "en": "english",
 38      "eo": "esperanto",
 39      "fr": "french",
 40      "it": "italian",
 41      "ja": "japanese",
 42      "nl": "dutch",
 43      "no": "norwegian",
 44      "pl": "polish",
 45      "pt": "portuguese",
 46      "ru": "russian",
 47      "sk": "slovak",
 48      "zh": "chinese",
 49      "zh_CN": "chinese-simplified",
 50      "zh_HK": "chinese-traditional",
 51      "zh_SG": "chinese-simplified",
 52      "zh_TW": "chinese-traditional"
 53  }
 54  
 55  
 56  time_format = config.safeGet(
 57      'bitmessagesettings', 'timeformat', DEFAULT_TIME_FORMAT)
 58  
 59  if not re.search(r'\d', time.strftime(time_format)):
 60      time_format = DEFAULT_TIME_FORMAT
 61  
 62  # It seems some systems lie about the encoding they use
 63  # so we perform comprehensive decoding tests
 64  elif six.PY2:
 65      try:
 66          # Check day names
 67          for i in range(7):
 68              time.strftime(
 69                  time_format, (0, 0, 0, 0, 0, 0, i, 0, 0)).decode(encoding)
 70          # Check month names
 71          for i in range(1, 13):
 72              time.strftime(
 73                  time_format, (0, i, 0, 0, 0, 0, 0, 0, 0)).decode(encoding)
 74          # Check AM/PM
 75          time.strftime(
 76              time_format, (0, 0, 0, 11, 0, 0, 0, 0, 0)).decode(encoding)
 77          time.strftime(
 78              time_format, (0, 0, 0, 13, 0, 0, 0, 0, 0)).decode(encoding)
 79          # Check DST
 80          time.strftime(
 81              time_format, (0, 0, 0, 0, 0, 0, 0, 0, 1)).decode(encoding)
 82      except Exception:  # TODO: write tests and determine exception types
 83          logger.exception('Could not decode locale formatted timestamp')
 84          # time_format = DEFAULT_TIME_FORMAT
 85          encoding = DEFAULT_ENCODING
 86  
 87  
 88  def setlocale(newlocale):
 89      """Set the locale"""
 90      try:
 91          locale.setlocale(locale.LC_ALL, newlocale)
 92      except AttributeError:  # locale is None
 93          pass
 94      # it looks like some stuff isn't initialised yet when this is called the
 95      # first time and its init gets the locale settings from the environment
 96      os.environ["LC_ALL"] = newlocale
 97  
 98  
 99  def formatTimestamp(timestamp=None):
100      """Return a formatted timestamp"""
101      # For some reason some timestamps are strings so we need to sanitize.
102      if timestamp is not None and not isinstance(timestamp, int):
103          try:
104              timestamp = int(timestamp)
105          except (ValueError, TypeError):
106              timestamp = None
107  
108      # timestamp can't be less than 0.
109      if timestamp is not None and timestamp < 0:
110          timestamp = None
111  
112      if timestamp is None:
113          timestring = time.strftime(time_format)
114      else:
115          # In case timestamp is too far in the future
116          try:
117              timestring = time.strftime(time_format, time.localtime(timestamp))
118          except ValueError:
119              timestring = time.strftime(time_format)
120  
121      if six.PY2:
122          return timestring.decode(encoding)
123      return timestring
124  
125  
126  def getTranslationLanguage():
127      """Return the user's language choice"""
128      userlocale = config.safeGet(
129          'bitmessagesettings', 'userlocale', 'system')
130      return userlocale if userlocale and userlocale != 'system' else language
131  
132  
133  def getWindowsLocale(posixLocale):
134      """
135      Get the Windows locale
136      Technically this converts the locale string from UNIX to Windows format,
137      because they use different ones in their
138      libraries. E.g. "en_EN.UTF-8" to "english".
139      """
140      if posixLocale in windowsLanguageMap:
141          return windowsLanguageMap[posixLocale]
142      if "." in posixLocale:
143          loc = posixLocale.split(".", 1)
144          if loc[0] in windowsLanguageMap:
145              return windowsLanguageMap[loc[0]]
146      if "_" in posixLocale:
147          loc = posixLocale.split("_", 1)
148          if loc[0] in windowsLanguageMap:
149              return windowsLanguageMap[loc[0]]
150      if posixLocale != DEFAULT_LANGUAGE:
151          return getWindowsLocale(DEFAULT_LANGUAGE)
152      return None