def resolve_best_langstring_entries(langstring, target_locale=None): if langstring is None or langstring is models.LangString.EMPTY: return [] entries = [] if target_locale: target_locale = to_known_locale_code(target_locale) entry = langstring.closest_entry(target_locale) if entry: entries.append(entry) if entry.is_machine_translated: entry = langstring.closest_entry( entry.locale.machine_translated_from, filter_errors=False) assert entry, "closest original entry not found" entries.append(entry) else: entries.append(langstring.first_original()) return entries # use request's idea of target_locale lsentries = langstring.best_entries_in_request_with_originals() lp = LanguagePreferenceCollection.getCurrent() for entry in lsentries: entries.append( LangStringEntry( locale_code=entry.locale.base_locale, error_code=entry.error_code, translated_from_locale_code=entry.locale.machine_translated_from, # noqa: E501 supposed_understood=not lp.find_locale( entry.locale.base_locale).translate_to_locale, value=entry.value or '', ) ) return entries
def resolve_langstring(langstring, locale_code): """If locale_code is None, return the best lang based on user prefs, otherwise respect the locale_code to return the right translation. If no translation found, fallback to best lang behavior. """ if langstring is None: return None entries = langstring.entries if not entries: return None try: if locale_code: locale_code = to_known_locale_code(locale_code) closest = langstring.closest_entry(locale_code) if closest: return closest.value english = langstring.closest_entry('en') if english: return english.value return langstring.best_lang( LanguagePreferenceCollection.getCurrent(), False).value except Exception: # Anything that goes wrong with clean_input, return the original return langstring.first_original().value
def _maybe_translate(post, locale, request): if request.authenticated_userid == Everyone: # anonymous cannot trigger translations return if locale: lpc = LanguagePreferenceCollectionWithDefault(locale) else: lpc = LanguagePreferenceCollection.getCurrent(request) for ls in (post.body, post.subject): source_locale = ls.first_original().locale_code pref = lpc.find_locale(source_locale) target_locale = pref.translate_to_locale if not target_locale: continue target_locale = target_locale.code if not ls.closest_entry(target_locale): post.maybe_translate(lpc)