예제 #1
0
파일: views.py 프로젝트: wpride/commcare-hq
def edit_sms_languages(request, domain):
    """
    Accepts same post body as corehq.apps.app_manager.views.edit_app_langs
    """
    with StandaloneTranslationDoc.get_locked_obj(domain, "sms",
        create=True) as tdoc:
        try:
            from corehq.apps.app_manager.views import validate_langs
            langs, rename, build = validate_langs(request, tdoc.langs,
                validate_build=False)
        except AssertionError:
            return HttpResponse(status=400)

        for old, new in rename.items():
            if old != new:
                tdoc.translations[new] = tdoc.translations[old]
                del tdoc.translations[old]

        for lang in langs:
            if lang not in tdoc.translations:
                tdoc.translations[lang] = {}

        for lang in tdoc.translations.keys():
            if lang not in langs:
                del tdoc.translations[lang]

        tdoc.langs = langs
        tdoc.save()
        return json_response(langs)
예제 #2
0
파일: views.py 프로젝트: wpride/commcare-hq
def sms_languages(request, domain):
    with StandaloneTranslationDoc.get_locked_obj(domain, "sms",
        create=True) as tdoc:
        if len(tdoc.langs) == 0:
            tdoc.langs = ["en"]
            tdoc.translations["en"] = {}
            tdoc.save()
    context = {
        "domain": domain,
        "always_deploy": True,
        "sms_langs": tdoc.langs,
        "bulk_upload": {
            "action": reverse("upload_sms_translations",
                              args=(domain,)),
            "download_url": reverse("download_sms_translations",
                                    args=(domain,)),
            "adjective": _("messaging translation"),
            "plural_noun": _("messaging translations"),
        },
    }
    context.update({
        "bulk_upload_form": get_bulk_upload_form(context),
    })

    return render(request, "sms/languages.html", context)
예제 #3
0
파일: views.py 프로젝트: wpride/commcare-hq
def upload_sms_translations(request, domain):
    try:
        workbook = WorkbookJSONReader(request.file)
        translations = workbook.get_worksheet(title='translations')

        with StandaloneTranslationDoc.get_locked_obj(domain, "sms") as tdoc:
            msg_ids = sorted(_MESSAGES.keys())
            result = {}
            for lang in tdoc.langs:
                result[lang] = {}

            for row in translations:
                for lang in tdoc.langs:
                    if row.get(lang):
                        msg_id = row["property"]
                        if msg_id in msg_ids:
                            result[lang][msg_id] = str(row[lang]).strip()

            tdoc.translations = result
            tdoc.save()
        messages.success(request, _("SMS Translations Updated."))
    except Exception:
        notify_exception(request, 'SMS Upload Translations Error')
        messages.error(request, _("Update failed. We're looking into it."))

    return HttpResponseRedirect(reverse('sms_languages', args=[domain]))
예제 #4
0
 def setUpClass(cls):
     super(TestContent, cls).setUpClass()
     cls.domain = 'test-content'
     cls.user = CommCareUser(phone_numbers=['9990000000000'], language='es')
     cls.translation_doc = StandaloneTranslationDoc(domain=cls.domain,
                                                    area='sms',
                                                    langs=['en', 'es'])
     cls.translation_doc.save()
예제 #5
0
파일: util.py 프로젝트: dimagi/commcare-hq
def get_or_create_translation_doc(domain):
    with StandaloneTranslationDoc.get_locked_obj(domain, 'sms', create=True) as tdoc:
        if len(tdoc.langs) == 0:
            tdoc.langs = ['en']
            tdoc.translations['en'] = {}
            tdoc.save()

        return tdoc
예제 #6
0
파일: util.py 프로젝트: xbryanc/commcare-hq
def get_or_create_translation_doc(domain):
    with StandaloneTranslationDoc.get_locked_obj(domain, 'sms', create=True) as tdoc:
        if len(tdoc.langs) == 0:
            tdoc.langs = ['en']
            tdoc.translations['en'] = {}
            tdoc.save()

        return tdoc
예제 #7
0
 def available_languages(self):
     """
     Returns a the list of language codes available for the domain, or
     [] if no languages are specified.
     """
     translation_doc = StandaloneTranslationDoc.get_obj(self.domain, "sms")
     if translation_doc and translation_doc.langs:
         return translation_doc.langs
     return []
예제 #8
0
 def available_languages(self):
     """
     Returns a the list of language codes available for the domain, or
     [] if no languages are specified.
     """
     translation_doc = StandaloneTranslationDoc.get_obj(self.domain, "sms")
     if translation_doc and translation_doc.langs:
         return translation_doc.langs
     return []
예제 #9
0
def get_message(msg_id, verified_number=None, context=None):
    default_msg = _MESSAGES.get(msg_id, "")

    if verified_number:
        tdoc = StandaloneTranslationDoc.get_obj(verified_number.domain, "sms")
    else:
        tdoc = None

    try:
        user_lang = verified_number.owner.get_language_code()
    except:
        user_lang = None

    def get_translation(lang):
        return tdoc.translations.get(lang, {}).get(msg_id, None)

    def domain_msg_user_lang():
        if tdoc and user_lang in tdoc.langs:
            return get_translation(user_lang)
        else:
            return None

    def domain_msg_domain_lang():
        if tdoc and tdoc.default_lang:
            return get_translation(tdoc.default_lang)
        else:
            return None

    def global_msg_user_lang():
        result = None
        if user_lang:
            with localize(user_lang):
                result = _(default_msg)
        return result if result != default_msg else None

    def global_msg_domain_lang():
        result = None
        if tdoc and tdoc.default_lang:
            with localize(tdoc.default_lang):
                result = _(default_msg)
        return result if result != default_msg else None

    msg = (
        domain_msg_user_lang() or
        domain_msg_domain_lang() or
        global_msg_user_lang() or
        global_msg_domain_lang() or
        default_msg
    )

    if context:
        msg = msg.format(*context)

    return msg
예제 #10
0
def get_message(msg_id, verified_number=None, context=None):
    default_msg = _MESSAGES.get(msg_id, "")

    if verified_number:
        tdoc = StandaloneTranslationDoc.get_obj(verified_number.domain, "sms")
    else:
        tdoc = None

    try:
        user_lang = verified_number.owner.get_language_code()
    except:
        user_lang = None

    def get_translation(lang):
        return tdoc.translations.get(lang, {}).get(msg_id, None)

    def domain_msg_user_lang():
        if tdoc and user_lang in tdoc.langs:
            return get_translation(user_lang)
        else:
            return None

    def domain_msg_domain_lang():
        if tdoc and tdoc.default_lang:
            return get_translation(tdoc.default_lang)
        else:
            return None

    def global_msg_user_lang():
        result = None
        if user_lang:
            with localize(user_lang):
                result = _(default_msg)
        return result if result != default_msg else None

    def global_msg_domain_lang():
        result = None
        if tdoc and tdoc.default_lang:
            with localize(tdoc.default_lang):
                result = _(default_msg)
        return result if result != default_msg else None

    msg = (domain_msg_user_lang() or domain_msg_domain_lang()
           or global_msg_user_lang() or global_msg_domain_lang()
           or default_msg)

    if context:
        msg = msg.format(*context)

    return msg
예제 #11
0
def get_domain_languages(domain):
    query = AppES().domain(domain).terms_aggregation("langs", "languages").size(0)
    app_languages = query.run().aggregations.languages.keys

    translation_doc = StandaloneTranslationDoc.get_obj(domain, "sms")
    sms_languages = translation_doc.langs if translation_doc else []

    domain_languages = []
    for lang_code in set(app_languages + sms_languages):
        name = langcodes.get_name(lang_code)
        label = u"{} ({})".format(lang_code, name) if name else lang_code
        domain_languages.append((lang_code, label))

    return sorted(domain_languages) or langcodes.get_all_langs_for_select()
예제 #12
0
def get_domain_languages(domain):
    query = (AppES().domain(domain).terms_aggregation('langs',
                                                      'languages').size(0))
    app_languages = query.run().aggregations.languages.keys

    translation_doc = StandaloneTranslationDoc.get_obj(domain, 'sms')
    sms_languages = translation_doc.langs if translation_doc else []

    domain_languages = []
    for lang_code in set(app_languages + sms_languages):
        name = langcodes.get_name(lang_code)
        label = u"{} ({})".format(lang_code, name) if name else lang_code
        domain_languages.append((lang_code, label))

    return sorted(domain_languages) or langcodes.get_all_langs_for_select()
예제 #13
0
 def get_translation_from_message_dict(message_dict, schedule,
                                       preferred_language_code):
     """
     :param message_dict: a dictionary of {language code: message}
     :param schedule: an instance of corehq.messaging.scheduling.models.Schedule
     :param preferred_language_code: the language code of the user's preferred language
     """
     lang_doc = StandaloneTranslationDoc.get_obj(schedule.domain, 'sms')
     return (Content.get_cleaned_message(message_dict,
                                         preferred_language_code)
             or Content.get_cleaned_message(message_dict,
                                            schedule.default_language_code)
             or (Content.get_cleaned_message(
                 message_dict, lang_doc.default_lang) if lang_doc else None)
             or Content.get_cleaned_message(message_dict, '*'))
예제 #14
0
def get_domain_languages(domain):
    query = (AppES()
             .domain(domain)
             .terms_facet('langs', 'languages')
             .size(0))
    app_languages = query.run().facets.languages.terms

    translation_doc = StandaloneTranslationDoc.get_obj(domain, 'sms')
    sms_languages = translation_doc.langs if translation_doc else []

    domain_languages = []
    for lang_code in set(app_languages + sms_languages):
        name = langcodes.get_name(lang_code)
        label = u"{} ({})".format(lang_code, name) if name else lang_code
        domain_languages.append((lang_code, label))

    return sorted(domain_languages) or langcodes.get_all_langs_for_select()
예제 #15
0
def get_domain_languages(domain):
    app_languages = [
        res['key'][1] for res in Application.get_db().view('languages/list',
                                                           startkey=[domain],
                                                           endkey=[domain, {}],
                                                           group='true').all()
    ]

    translation_doc = StandaloneTranslationDoc.get_obj(domain, 'sms')
    sms_languages = translation_doc.langs if translation_doc else []

    domain_languages = []
    for lang_code in set(app_languages + sms_languages):
        name = langcodes.get_name(lang_code)
        label = u"{} ({})".format(lang_code, name) if name else lang_code
        domain_languages.append((lang_code, label))

    return sorted(domain_languages) or langcodes.get_all_langs_for_select()
예제 #16
0
def get_domain_languages(domain):
    app_languages = [
        res["key"][1]
        for res in Application.get_db()
        .view("languages/list", startkey=[domain], endkey=[domain, {}], group="true")
        .all()
    ]

    translation_doc = StandaloneTranslationDoc.get_obj(domain, "sms")
    sms_languages = translation_doc.langs if translation_doc else []

    domain_languages = []
    for lang_code in set(app_languages + sms_languages):
        name = langcodes.get_name(lang_code)
        label = u"{} ({})".format(lang_code, name) if name else lang_code
        domain_languages.append((lang_code, label))

    return sorted(domain_languages) or langcodes.get_all_langs_for_select()
예제 #17
0
파일: views.py 프로젝트: wpride/commcare-hq
def download_sms_translations(request, domain):
    tdoc = StandaloneTranslationDoc.get_obj(domain, "sms")
    columns = ["property"] + tdoc.langs + ["default"]

    msg_ids = sorted(_MESSAGES.keys())
    rows = []
    for msg_id in msg_ids:
        rows.append([msg_id])

    for lang in tdoc.langs:
        for row in rows:
            row.append(tdoc.translations[lang].get(row[0], ""))

    for row in rows:
        row.append(_MESSAGES.get(row[0]))

    temp = StringIO()
    headers = (("translations", tuple(columns)),)
    data = (("translations", tuple(rows)),)
    export_raw(headers, data, temp)
    return export_response(temp, Format.XLS_2007, "translations")
예제 #18
0
def get_message(msg_id,
                verified_number=None,
                context=None,
                domain=None,
                language=None):
    """
    Translates the message according to the user's and domain's preferences.

    msg_id - one of the MSG_* constants above
    verified_number - pass in the PhoneNumber of a contact in order to
                      use this contact's domain and language to translate
    context - some messages require additional parameters; pass them as a
              tuple or list
    domain - if the contact doesn't have a verified number, pass the domain
             in here to use this domain's translation doc
    language - if the contact doesn't have a verified number, pass the language
               code in here to use this language
    """
    default_msg = _MESSAGES.get(msg_id, "")

    if domain:
        tdoc = StandaloneTranslationDoc.get_obj(domain, "sms")
    elif verified_number:
        tdoc = StandaloneTranslationDoc.get_obj(verified_number.domain, "sms")
    else:
        tdoc = None

    if language:
        user_lang = language
    else:
        try:
            user_lang = verified_number.owner.get_language_code()
        except:
            user_lang = None

    def get_translation(lang):
        return tdoc.translations.get(lang, {}).get(msg_id, None)

    def domain_msg_user_lang():
        if tdoc and user_lang in tdoc.langs:
            return get_translation(user_lang)
        else:
            return None

    def domain_msg_domain_lang():
        if tdoc and tdoc.default_lang:
            return get_translation(tdoc.default_lang)
        else:
            return None

    def global_msg_user_lang():
        result = None
        if user_lang:
            with localize(user_lang):
                result = _(default_msg)
        return result if result != default_msg else None

    def global_msg_domain_lang():
        result = None
        if tdoc and tdoc.default_lang:
            with localize(tdoc.default_lang):
                result = _(default_msg)
        return result if result != default_msg else None

    msg = (domain_msg_user_lang() or domain_msg_domain_lang()
           or global_msg_user_lang() or global_msg_domain_lang()
           or default_msg)

    if context:
        msg = msg.format(*context)

    return msg
예제 #19
0
 def project_languages(self):
     doc = StandaloneTranslationDoc.get_obj(self.domain, 'sms')
     return getattr(doc, 'langs', ['en'])
예제 #20
0
 def get_lang_doc(self, domain):
     return StandaloneTranslationDoc.get_obj(domain, 'sms')
예제 #21
0
def get_message(msg_id, verified_number=None, context=None, domain=None, language=None):
    """
    Translates the message according to the user's and domain's preferences.

    msg_id - one of the MSG_* constants above
    verified_number - pass in the PhoneNumber of a contact in order to
                      use this contact's domain and language to translate
    context - some messages require additional parameters; pass them as a
              tuple or list
    domain - if the contact doesn't have a verified number, pass the domain
             in here to use this domain's translation doc
    language - if the contact doesn't have a verified number, pass the language
               code in here to use this language
    """
    default_msg = _MESSAGES.get(msg_id, "")

    if domain:
        tdoc = StandaloneTranslationDoc.get_obj(domain, "sms")
    elif verified_number:
        tdoc = StandaloneTranslationDoc.get_obj(verified_number.domain, "sms")
    else:
        tdoc = None

    if language:
        user_lang = language
    else:
        try:
            user_lang = verified_number.owner.get_language_code()
        except:
            user_lang = None

    def get_translation(lang):
        return tdoc.translations.get(lang, {}).get(msg_id, None)

    def domain_msg_user_lang():
        if tdoc and user_lang in tdoc.langs:
            return get_translation(user_lang)
        else:
            return None

    def domain_msg_domain_lang():
        if tdoc and tdoc.default_lang:
            return get_translation(tdoc.default_lang)
        else:
            return None

    def global_msg_user_lang():
        result = None
        if user_lang:
            with localize(user_lang):
                result = _(default_msg)
        return result if result != default_msg else None

    def global_msg_domain_lang():
        result = None
        if tdoc and tdoc.default_lang:
            with localize(tdoc.default_lang):
                result = _(default_msg)
        return result if result != default_msg else None

    msg = (
        domain_msg_user_lang() or
        domain_msg_domain_lang() or
        global_msg_user_lang() or
        global_msg_domain_lang() or
        default_msg
    )

    if context:
        msg = msg.format(*context)

    return msg