def init_localization():  # pragma: no cover
    """
    Application localization

    :return: gettext translator method
    :rtype: method
    """
    try:
        # Language message file
        lang_filename = os.path.join(
            os.path.abspath(os.path.dirname(__file__)),
            "LC_MESSAGES/%s.mo" % settings.get_config('Alignak-app', 'locale'))
        logger.info("Opening message file %s for locale %s", lang_filename,
                    settings.get_config('Alignak-app', 'locale'))
        translation = GNUTranslations(open(lang_filename, "rb"))
        translation.install()
        _ = translation.gettext
    except IOError:
        logger.warning(
            "Locale not found. Using default language messages (English)")
        null_translation = NullTranslations()
        null_translation.install()
        _ = null_translation.gettext
    except Exception as e:  # pragma: no cover - should not happen
        logger.error("Locale not found. Exception: %s", str(e))
        null_translation = NullTranslations()
        null_translation.install()
        _ = null_translation.gettext

    return _
Beispiel #2
0
def set_translators():
    global _lang_trans, lcdata
    # To test different translations invoke as
    # CALIBRE_OVERRIDE_LANG=de_DE.utf8 program
    lang = get_lang()
    t = buf = iso639 = None

    if 'CALIBRE_TEST_TRANSLATION' in os.environ:
        buf = load_po(
            os.path.expanduser(os.environ['CALIBRE_TEST_TRANSLATION']))

    if lang:
        mpath = get_lc_messages_path(lang)
        if buf is None and mpath and os.access(mpath + '.po', os.R_OK):
            buf = load_po(mpath + '.po')

        if mpath is not None:
            from zipfile import ZipFile
            with ZipFile(
                    P('localization/locales.zip', allow_user_override=False),
                    'r') as zf:
                if buf is None:
                    buf = io.BytesIO(zf.read(mpath + '/messages.mo'))
                if mpath == 'nds':
                    mpath = 'de'
                isof = mpath + '/iso639.mo'
                try:
                    iso639 = io.BytesIO(zf.read(isof))
                except:
                    pass  # No iso639 translations for this lang
                if buf is not None:
                    from calibre.utils.serialize import msgpack_loads
                    try:
                        lcdata = msgpack_loads(
                            zf.read(mpath + '/lcdata.calibre_msgpack'))
                    except:
                        pass  # No lcdata

    if buf is not None:
        t = GNUTranslations(buf)
        if iso639 is not None:
            iso639 = _lang_trans = GNUTranslations(iso639)
            t.add_fallback(iso639)

    if t is None:
        t = NullTranslations()

    try:
        set_translators.lang = t.info().get('language')
    except Exception:
        pass
    if is_py3:
        t.install(names=('ngettext', ))
    else:
        t.install(unicode=True, names=('ngettext', ))
    # Now that we have installed a translator, we have to retranslate the help
    # for the global prefs object as it was instantiated in get_lang(), before
    # the translator was installed.
    from calibre.utils.config_base import prefs
    prefs.retranslate_help()
Beispiel #3
0
def init_localization(app):
    """prepare l10n"""

    # -----
    # Application localization
    # -----
    try:
        # Language message file
        lang_filename = os.path.join(
            os.path.abspath(os.path.dirname(__file__)),
            "../locales/%s.mo" % app.config.get('locale', 'en_US')
        )
        print("Opening message file %s for locale %s"
              % (lang_filename, app.config.get('locale', 'en_US')))
        translation = GNUTranslations(open(lang_filename, "rb"))
        translation.install(True)
        _ = translation.gettext
    except IOError:
        print("Locale not found. Using default language messages (English)")
        null_translation = NullTranslations()
        null_translation.install()
        _ = null_translation.gettext
    except Exception as e:  # pragma: no cover - should not happen
        print("Locale not found. Exception: %s" % str(e))
        null_translation = NullTranslations()
        null_translation.install()
        _ = null_translation.gettext

    # Provide translation methods to templates
    app.config['_'] = _
    print(_("Language is English (default)..."))

    return _
def     flask_before_i18n_set_user_language(lng=None):
    # Get current request language
    if lng is None:
        lng = request.headers.get('Accept-Language')
    if lng is not None:
        lng = lng[0:2]  # Todo: check priority : en-US,en;q=0.5
    else:
        lng = 'en'
    setattr(request, 'i18n_language', lng)

    # Init i18n
    try:
        setlocale(LC_ALL, (lng, 'utf-8'))
    except:
        setlocale(LC_ALL, '')

    # Build translation filename
    if lng not in settings.FLASK_TRANSLATION_LNG:
        lng = settings.FLASK_TRANSLATION_LNG[0]
    filename = ''
    filename = join(filename, join(join(settings.FLASK_TRANSLATION_DIR, lng), 'LC_MESSAGES/messages.mo'))

    # Open translation file or use NullTranslation if fail
    try:
        trans = GNUTranslations(open(filename, 'rb'))
    except IOError:
        trans = NullTranslations()

    # Install i18n
    trans.install()
    setattr(request, 'i18n_engine', trans)
Beispiel #5
0
def set_translators():
    global _lang_trans, lcdata
    # To test different translations invoke as
    # CALIBRE_OVERRIDE_LANG=de_DE.utf8 program
    lang = get_lang()
    t = None

    if lang:
        buf = iso639 = None
        mpath = get_lc_messages_path(lang)
        if mpath and os.access(mpath + '.po', os.R_OK):
            from calibre.translations.msgfmt import make
            buf = cStringIO.StringIO()
            try:
                make(mpath + '.po', buf)
            except:
                print(('Failed to compile translations file: %s,'
                       ' ignoring') % (mpath + '.po'))
                buf = None
            else:
                buf = cStringIO.StringIO(buf.getvalue())

        if mpath is not None:
            from zipfile import ZipFile
            with ZipFile(
                    P('localization/locales.zip', allow_user_override=False),
                    'r') as zf:
                if buf is None:
                    buf = cStringIO.StringIO(zf.read(mpath + '/messages.mo'))
                if mpath == 'nds':
                    mpath = 'de'
                isof = mpath + '/iso639.mo'
                try:
                    iso639 = cStringIO.StringIO(zf.read(isof))
                except:
                    pass  # No iso639 translations for this lang
                if buf is not None:
                    try:
                        lcdata = cPickle.loads(
                            zf.read(mpath + '/lcdata.pickle'))
                    except:
                        pass  # No lcdata

        if buf is not None:
            t = GNUTranslations(buf)
            if iso639 is not None:
                iso639 = _lang_trans = GNUTranslations(iso639)
                t.add_fallback(iso639)

    if t is None:
        t = NullTranslations()

    t.install(unicode=True, names=('ngettext', ))
    # Now that we have installed a translator, we have to retranslate the help
    # for the global prefs object as it was instantiated in get_lang(), before
    # the translator was installed.
    from calibre.utils.config_base import prefs
    prefs.retranslate_help()
Beispiel #6
0
def set_translators():
    global _lang_trans, lcdata
    # To test different translations invoke as
    # CALIBRE_OVERRIDE_LANG=de_DE.utf8 program
    lang = get_lang()
    t = None

    if lang:
        buf = iso639 = None
        mpath = get_lc_messages_path(lang)
        if mpath and os.access(mpath + '.po', os.R_OK):
            from calibre.translations.msgfmt import make
            buf = cStringIO.StringIO()
            try:
                make(mpath + '.po', buf)
            except:
                print(('Failed to compile translations file: %s,'
                       ' ignoring') % (mpath + '.po'))
                buf = None
            else:
                buf = cStringIO.StringIO(buf.getvalue())

        if mpath is not None:
            from zipfile import ZipFile
            with ZipFile(
                    P('localization/locales.zip', allow_user_override=False),
                    'r') as zf:
                if buf is None:
                    buf = cStringIO.StringIO(zf.read(mpath + '/messages.mo'))
                if mpath == 'nds':
                    mpath = 'de'
                isof = mpath + '/iso639.mo'
                try:
                    iso639 = cStringIO.StringIO(zf.read(isof))
                except:
                    pass  # No iso639 translations for this lang
                if buf is not None:
                    try:
                        lcdata = cPickle.loads(
                            zf.read(mpath + '/lcdata.pickle'))
                    except:
                        pass  # No lcdata

        if buf is not None:
            t = GNUTranslations(buf)
            if iso639 is not None:
                iso639 = _lang_trans = GNUTranslations(iso639)
                t.add_fallback(iso639)

    if t is None:
        t = NullTranslations()

    t.install(unicode=True, names=('ngettext', ))
    # Now that we have installed a translator, we have to retranslate the help
    # for the global prefs object as it was instantiated in get_lang(), before
    # the translator was installed.
    from calibre.utils.config_base import prefs
    prefs.retranslate_help()
Beispiel #7
0
def set_translators():
    global _lang_trans, lcdata
    # To test different translations invoke as
    # CALIBRE_OVERRIDE_LANG=de_DE.utf8 program
    lang = get_lang()
    t = buf = iso639 = None

    if 'CALIBRE_TEST_TRANSLATION' in os.environ:
        buf = load_po(os.path.expanduser(os.environ['CALIBRE_TEST_TRANSLATION']))

    if lang:
        mpath = get_lc_messages_path(lang)
        if buf is None and mpath and os.access(mpath + '.po', os.R_OK):
            buf = load_po(mpath + '.po')

        if mpath is not None:
            from zipfile import ZipFile
            with ZipFile(P('localization/locales.zip',
                allow_user_override=False), 'r') as zf:
                if buf is None:
                    buf = io.BytesIO(zf.read(mpath + '/messages.mo'))
                if mpath == 'nds':
                    mpath = 'de'
                isof = mpath + '/iso639.mo'
                try:
                    iso639 = io.BytesIO(zf.read(isof))
                except:
                    pass  # No iso639 translations for this lang
                if buf is not None:
                    from calibre.utils.serialize import msgpack_loads
                    try:
                        lcdata = msgpack_loads(zf.read(mpath + '/lcdata.calibre_msgpack'))
                    except:
                        pass  # No lcdata

    if buf is not None:
        t = GNUTranslations(buf)
        if iso639 is not None:
            iso639 = _lang_trans = GNUTranslations(iso639)
            t.add_fallback(iso639)

    if t is None:
        t = NullTranslations()

    try:
        set_translators.lang = t.info().get('language')
    except Exception:
        pass
    if is_py3:
        t.install(names=('ngettext',))
    else:
        t.install(unicode=True, names=('ngettext',))
    # Now that we have installed a translator, we have to retranslate the help
    # for the global prefs object as it was instantiated in get_lang(), before
    # the translator was installed.
    from calibre.utils.config_base import prefs
    prefs.retranslate_help()
Beispiel #8
0
def set_translators():
    global _lang_trans
    # To test different translations invoke as
    # CALIBRE_OVERRIDE_LANG=de_DE.utf8 program
    lang = get_lang()
    t = None

    if lang:
        buf = iso639 = None
        mpath = get_lc_messages_path(lang)
        if mpath and os.access(mpath+'.po', os.R_OK):
            from calibre.translations.msgfmt import make
            buf = cStringIO.StringIO()
            try:
                make(mpath+'.po', buf)
            except:
                print (('Failed to compile translations file: %s,'
                        ' ignoring')%(mpath+'.po'))
                buf = None
            else:
                buf = cStringIO.StringIO(buf.getvalue())

        if mpath is not None:
            from zipfile import ZipFile
            with ZipFile(P('localization/locales.zip',
                allow_user_override=False), 'r') as zf:
                if buf is None:
                    buf = cStringIO.StringIO(zf.read(mpath + '/messages.mo'))
                if mpath == 'nds':
                    mpath = 'de'
                isof = mpath + '/iso639.mo'
                try:
                    iso639 = cStringIO.StringIO(zf.read(isof))
                except:
                    pass  # No iso639 translations for this lang

        if buf is not None:
            t = GNUTranslations(buf)
            if iso639 is not None:
                iso639 = _lang_trans = GNUTranslations(iso639)
                t.add_fallback(iso639)

    if t is None:
        t = NullTranslations()

    t.install(unicode=True, names=('ngettext',))
Beispiel #9
0
def set_translators():
    # To test different translations invoke as
    # CALIBRE_OVERRIDE_LANG=de_DE.utf8 program
    lang = get_lang()
    t = None

    if lang:
        buf = iso639 = None
        mpath = get_lc_messages_path(lang)
        if mpath and os.access(mpath + '.po', os.R_OK):
            from calibre.translations.msgfmt import make
            buf = cStringIO.StringIO()
            try:
                make(mpath + '.po', buf)
            except:
                print(('Failed to compile translations file: %s,'
                       ' ignoring') % (mpath + '.po'))
                buf = None
            else:
                buf = cStringIO.StringIO(buf.getvalue())

        if mpath is not None:
            from zipfile import ZipFile
            with ZipFile(
                    P('localization/locales.zip', allow_user_override=False),
                    'r') as zf:
                if buf is None:
                    buf = cStringIO.StringIO(zf.read(mpath + '/messages.mo'))
                if mpath == 'nds':
                    mpath = 'de'
                isof = mpath + '/iso639.mo'
                try:
                    iso639 = cStringIO.StringIO(zf.read(isof))
                except:
                    pass  # No iso639 translations for this lang

        if buf is not None:
            t = GNUTranslations(buf)
            if iso639 is not None:
                iso639 = GNUTranslations(iso639)
                t.add_fallback(iso639)

    if t is None:
        t = NullTranslations()

    t.install(unicode=True, names=('ngettext', ))
Beispiel #10
0
def init_localization(language):
    """prepare l10n"""

    try:
        # Language message file
        filename = os.path.join(os.path.abspath(os.path.dirname(__file__)),
                                "../res/%s.mo" % language)
        logger.info("Opening message file %s for locale %s", filename,
                    language)
        translation = GNUTranslations(open(filename, "rb"))
        translation.install()
    except IOError:
        logger.warning("Locale not found. Using default messages")
        logger.debug("Backtrace: %s", traceback.format_exc())
        default = NullTranslations()
        default.install()
    except Exception as e:
        logger.error("Locale not found. Exception: %s", str(e))
        logger.debug("Backtrace: %s", traceback.format_exc())
        default = NullTranslations()
        default.install()
    logger.info(_("Language is English (default)..."))
Beispiel #11
0
def set_app_config(config):
    """
    Update global application configuration
    """
    global bottle_app, app_config, _

    # Localization
    try:
        # Language message file
        filename = os.path.join(os.path.abspath(os.path.dirname(__file__)),
                                "res/%s.mo" % config.get('locale', 'en_US'))
        print("Opening message file %s for locale %s" %
              (filename, config.get('locale', 'en_US')))
        translation = GNUTranslations(open(filename, "rb"))
        translation.install()
        _ = translation.gettext
    except IOError:
        print("Locale not found. Using default language messages (English)")
        default = NullTranslations()
        default.install()
        _ = default.gettext
    except Exception as e:  # pragma: no cover - should not happen
        print("Locale not found. Exception: %s" % str(e))
        default = NullTranslations()
        default.install()
        _ = default.gettext
    print(_("Language is English (default)..."))

    app_config = config
    bottle_app.config.update(config)

    # Set logging options for the application
    set_console_logger(logger)

    # Store logs in a daily file, keeping 6 days along ... as default!
    set_file_logger(logger,
                    path=app_config.get('logs.dir', '/var/log/' +
                                        manifest['name'].lower()),
                    filename=app_config.get('logs.filename',
                                            manifest['name'].lower() + '.log'),
                    when=app_config.get('logs.when', 'D'),
                    interval=int(app_config.get('logs.interval', '1')),
                    backup_count=int(app_config.get('logs.backupCount', '6')))

    # Set application log level (default is INFO (20))
    print("Activate logs level: %d" % int(app_config.get('logs.level', '20')))
    logger.setLevel(int(app_config.get('logs.level', '20')))
    if app_config.get('debug',
                      '0') == '1':  # pragma: no cover - not testable easily...
        print("Activate DEBUG logs")
        logger.setLevel(DEBUG)

    logger.info(
        "--------------------------------------------------------------------------------"
    )
    logger.info("%s, version %s", manifest['name'], manifest['version'])
    logger.info("Copyright %s", manifest['copyright'])
    logger.info("License: %s", manifest['license'])
    logger.info(
        "--------------------------------------------------------------------------------"
    )
    logger.debug("Doc: %s", manifest['doc'])
    logger.debug("Release notes: %s", manifest['release'])
    logger.debug(
        "--------------------------------------------------------------------------------"
    )

    logger.info(
        "--------------------------------------------------------------------------------"
    )
    logger.info("%s, listening on %s:%d (debug mode: %s)",
                app_config.get('name', 'Test'),
                app_config.get('host', '127.0.0.1'),
                int(app_config.get('port', '5001')),
                app_config.get('debug', '0') == '1')
    logger.info("%s, using alignak backend on %s",
                app_config.get('name', 'Test'),
                app_config.get('alignak_backend', 'http://127.0.0.1:5000'))
    logger.info(
        "--------------------------------------------------------------------------------"
    )

    logger.debug("Application settings: ")
    for key, value in sorted(app_config.items()):
        logger.debug(" %s = %s", key, value)
    logger.debug(
        "--------------------------------------------------------------------------------"
    )
Beispiel #12
0
def set_app_config(config):
    '''
    Update global application configuration
    '''
    global bottle_app, app_config, _

    # Localization
    try:
        # Language message file
        filename = os.path.join(
            os.path.abspath(os.path.dirname(__file__)), "res/%s.mo" % config.get('locale', 'en_US')
        )
        print "Opening message file %s for locale %s" % (filename, config.get('locale', 'en_US'))
        translation = GNUTranslations(open(filename, "rb"))
        translation.install()
        _ = translation.gettext
    except IOError:
        print "Locale not found. Using default language messages (English)"
        default = NullTranslations()
        default.install()
        _ = default.gettext
    except Exception as e:  # pragma: no cover - should not happen
        print "Locale not found. Exception: %s" % str(e)
        default = NullTranslations()
        default.install()
        _ = default.gettext
    print _("Language is English (default)...")

    app_config = config
    bottle_app.config.update(config)

    # Set logging options for the application
    set_console_logger(logger)

    # Store logs in a daily file, keeping 6 days along ... as default!
    set_file_logger(
        logger,
        path=app_config.get('logs.dir', '/var/log'),
        filename=app_config.get('logs.filename', manifest['name'].lower() + '.log'),
        when=app_config.get('logs.when', 'D'),
        interval=int(app_config.get('logs.interval', '1')),
        backupCount=int(app_config.get('logs.backupCount', '6'))
    )

    # Set application log level (default is INFO (20))
    print "Activate logs level: %d" % int(app_config.get('logs.level', '20'))
    logger.setLevel(int(app_config.get('logs.level', '20')))
    if app_config.get('debug', '0') == '1':
        print "Activate DEBUG logs"
        logger.setLevel(DEBUG)

    logger.info(
        "--------------------------------------------------------------------------------"
    )
    logger.info("%s, version %s", manifest['name'], manifest['version'])
    logger.info("Copyright %s", manifest['copyright'])
    logger.info("License: %s", manifest['license'])
    logger.info(
        "--------------------------------------------------------------------------------"
    )
    logger.debug("Doc: %s", manifest['doc'])
    logger.debug("Release notes: %s", manifest['release'])
    logger.debug(
        "--------------------------------------------------------------------------------"
    )

    logger.debug("Application settings: ")
    for key, value in sorted(app_config.items()):
        logger.debug(" %s = %s", key, value)
    logger.debug(
        "--------------------------------------------------------------------------------"
    )