def collections(self): features = self.features() lang = translation.to_language(translation.get_language()) locale = Q(locale='') | Q(locale=lang) promos = (CollectionPromo.objects.filter(locale) .filter(collection_feature__in=features) .transform(CollectionPromo.transformer)) groups = sorted_groupby(promos, 'collection_feature_id') # We key by feature_id and locale, so we can favor locale specific # promos. promo_dict = {} for feature_id, v in groups: promo = v.next() key = (feature_id, translation.to_language(promo.locale)) promo_dict[key] = promo rv = {} # If we can, we favor locale specific collections. for feature in features: key = (feature.id, lang) if key not in promo_dict: key = (feature.id, '') if key not in promo_dict: continue # We only want to see public add-ons on the front page. c = promo_dict[key].collection c.public_addons = c.addons.all() & Addon.objects.public() rv[feature] = c return rv
def test_to_language(self): """ Test the to_language function """ from django.utils.translation.trans_real import to_language self.assertEqual(to_language('en_US'), 'en-us') self.assertEqual(to_language('sr_Lat'), 'sr-lat')
def test_to_language(self): """ Test the to_language function """ from django.utils.translation.trans_real import to_language self.assertEqual(to_language("en_US"), "en-us") self.assertEqual(to_language("sr_Lat"), "sr-lat")
def to_language(locale): """Like Django's to_language, but en_US comes out as en-US.""" if '_' in locale: return to_language(trans_real.to_language(locale)) if '-' in locale: idx = locale.find('-') return locale[:idx].lower() + '-' + locale[idx + 1:].upper() return trans_real.to_language(locale)
def to_language(locale): """Like django's to_language, but en_US comes out as en-US.""" # A locale looks like en_US or fr. if '_' in locale: return to_language(trans_real.to_language(locale)) # Django returns en-us but we want to see en-US. elif '-' in locale: lang, region = locale.split('-') return '%s-%s' % (lang, region.upper()) else: return trans_real.to_language(locale)
def translation_from_string(self, instance, lang, string): """Create, save, and return a Translation from a string.""" try: trans = getattr(instance, self.field.name) trans_id = getattr(instance, self.field.attname) if trans is None and trans_id is not None: # This locale doesn't have a translation set, but there are # translations in another locale, so we have an id already. translation = self.model.new(string, lang, id=trans_id) elif to_language(trans.locale) == lang.lower(): # Replace the translation in the current language. trans.localized_string = string translation = trans else: # We already have a translation in a different language. translation = self.model.new(string, lang, id=trans.id) except AttributeError: # Create a brand new translation. translation = self.model.new(string, lang) # A new translation has been created and it might need to be saved. # This adds the translation to the queue of translation that need # to be saved for this instance. add_translation(make_key(instance), translation) return translation
def translation_from_dict(self, instance, lang, dict_): """ Create Translations from a {'locale': 'string'} mapping. If one of the locales matches lang, that Translation will be returned. """ from olympia.amo.utils import to_language as amo_to_language rv = None for locale, string in dict_.items(): loc = amo_to_language(locale) if loc not in settings.AMO_LANGUAGES: continue # The Translation is created and saved in here. trans = self.translation_from_string(instance, locale, string) # Set the Translation on the object because translation_from_string # doesn't expect Translations to be created but not attached. self.__set__(instance, trans) # If we're setting the current locale, set it to the object so # callers see the expected effect. if to_language(locale) == lang: rv = trans return rv
def details(request, addon_id, addon): # Name, Slug, Summary, Description, Privacy Policy, # Homepage URL, Support URL, Support Email. form_basic = AppDetailsBasicForm(request.POST or None, instance=addon, request=request) form_cats = CategoryForm(request.POST or None, product=addon, request=request) form_devices = DeviceTypeForm(request.POST or None, addon=addon) form_icon = AppFormMedia(request.POST or None, request.FILES or None, instance=addon, request=request) form_previews = PreviewFormSet(request.POST or None, prefix='files', queryset=addon.get_previews()) # For empty webapp-locale (or no-locale) fields that have # form-locale values, duplicate them to satisfy the requirement. form_locale = request.COOKIES.get("current_locale", "") app_locale = to_language(addon.default_locale) for name, value in request.POST.items(): if value: if name.endswith(form_locale): basename = name[:-len(form_locale)] else: basename = name + '_' othername = basename + app_locale if not request.POST.get(othername, None): request.POST[othername] = value forms = { 'form_basic': form_basic, 'form_devices': form_devices, 'form_cats': form_cats, 'form_icon': form_icon, 'form_previews': form_previews, } if request.POST and all(f.is_valid() for f in forms.itervalues()): addon = form_basic.save(addon) form_devices.save(addon) form_cats.save() form_icon.save(addon) for preview in form_previews.forms: preview.save(addon) tasks.generate_image_assets.delay(addon) checklist = AppSubmissionChecklist.objects.get(addon=addon) if waffle.switch_is_active('disabled-payments'): checklist.update(details=True, payments=True) addon.mark_done() return redirect('submit.app.done', addon.app_slug) else: checklist.update(details=True) return redirect('submit.app.payments', addon.app_slug) ctx = { 'step': 'details', 'addon': addon, } ctx.update(forms) return jingo.render(request, 'submit/details.html', ctx)
def set_locale_field_defaults(self): locale = to_language(default_locale(self.instance)) for field_name, field in self.fields.items(): if isinstance(field, _TransField): field.set_default_values(field_name=field_name, parent_form=self, default_locale=locale)
def translation_from_string(self, instance, lang, string): """Create, save, and return a Translation from a string.""" trans_id = instance.__dict__.get(self.field.attname) if trans_id is None: # We don't have a translation for this field in any language, # create a brand new one. translation = self.field.related_model.new(string, lang) else: try: trans = getattr(instance, self.field.name) except (AttributeError, instance.DoesNotExist): trans = None if trans is not None and to_language(trans.locale) == lang.lower(): # Replace the translation in the current language. trans.localized_string = string translation = trans else: # We either could not find a translation (but know that one # already exist, because trans_id is set) or are looking to # create one in a different language anyway. translation = self.field.related_model.new( string, lang, id=trans_id) # A new translation has been created and it might need to be saved. # This adds the translation to the queue of translation that need # to be saved for this instance. add_translation(make_key(instance), translation) return translation
def translation_from_dict(self, instance, lang, dict_): """ Create Translations from a {'locale': 'string'} mapping. If one of the locales matches lang, that Translation will be returned. """ from amo.utils import to_language as amo_to_language rv = None for locale, string in dict_.items(): loc = amo_to_language(locale) if loc not in settings.AMO_LANGUAGES + settings.HIDDEN_LANGUAGES: continue # The Translation is created and saved in here. trans = self.translation_from_string(instance, locale, string) # Set the Translation on the object because translation_from_string # doesn't expect Translations to be created but not attached. self.__set__(instance, trans) # If we're setting the current locale, set it to the object so # callers see the expected effect. if to_language(locale) == lang: rv = trans return rv
def details(request, addon_id, addon): # Name, Slug, Summary, Description, Privacy Policy, # Homepage URL, Support URL, Support Email. form_basic = AppDetailsBasicForm(request.POST or None, instance=addon, request=request) form_cats = CategoryForm(request.POST or None, product=addon, request=request) form_devices = DeviceTypeForm(request.POST or None, addon=addon) form_icon = AppFormMedia(request.POST or None, request.FILES or None, instance=addon, request=request) form_previews = PreviewFormSet(request.POST or None, prefix='files', queryset=addon.get_previews()) # For empty webapp-locale (or no-locale) fields that have # form-locale values, duplicate them to satisfy the requirement. form_locale = request.COOKIES.get("current_locale", "") app_locale = to_language(addon.default_locale) for name, value in request.POST.items(): if value: if name.endswith(form_locale): basename = name[:-len(form_locale)] else: basename = name + '_' othername = basename + app_locale if not request.POST.get(othername, None): request.POST[othername] = value forms = { 'form_basic': form_basic, 'form_devices': form_devices, 'form_cats': form_cats, 'form_icon': form_icon, 'form_previews': form_previews, } if request.POST and all(f.is_valid() for f in forms.itervalues()): addon = form_basic.save(addon) form_devices.save(addon) form_cats.save() form_icon.save(addon) for preview in form_previews.forms: preview.save(addon) tasks.generate_image_assets.delay(addon) AppSubmissionChecklist.objects.get(addon=addon).update(details=True) addon.mark_done() return redirect('submit.app.done', addon.app_slug) ctx = { 'step': 'details', 'addon': addon, } ctx.update(forms) return jingo.render(request, 'submit/details.html', ctx)
def set_locale_field_defaults(self): locale = to_language(default_locale(self.instance)) for field_name, field in self.fields.items(): if isinstance(field, _TransField): field.set_default_values( field_name=field_name, parent_form=self, default_locale=locale)
def find_languages(locale_path): """generates supported languages list from mo directory""" dirs = os.listdir(locale_path) langs = [] for lang in dirs: if data.langcode_re.match(lang) and os.path.isdir(os.path.join(locale_path, lang)): langs.append((trans_real.to_language(lang), data.languages.get(lang, (lang,))[0])) return langs
def clean(self): if self.locale == '': self.locale = 'en-US' # convert locale codes (en_US) to lang code (en-us) self.locale = to_language(self.locale) if self.locale.lower() not in settings.LANGUAGES_LOWERED: raise ValidationError("Not a valid language")
def details(request, addon_id, addon): # Name, Slug, Description, Privacy Policy, Homepage URL, Support URL, # Support Email. form_basic = AppDetailsBasicForm(request.POST or None, instance=addon, request=request) form_cats = CategoryForm(request.POST or None, product=addon, request=request) form_icon = AppFormMedia(request.POST or None, request.FILES or None, instance=addon, request=request) form_previews = PreviewFormSet(request.POST or None, prefix="files", queryset=addon.get_previews()) # For empty webapp-locale (or no-locale) fields that have # form-locale values, duplicate them to satisfy the requirement. form_locale = request.COOKIES.get("current_locale", "") app_locale = to_language(addon.default_locale) for name, value in request.POST.items(): if value: if name.endswith(form_locale): basename = name[: -len(form_locale)] else: basename = name + "_" othername = basename + app_locale if not request.POST.get(othername, None): request.POST[othername] = value forms = {"form_basic": form_basic, "form_cats": form_cats, "form_icon": form_icon, "form_previews": form_previews} if request.POST and all(f.is_valid() for f in forms.itervalues()): addon = form_basic.save(addon) form_cats.save() form_icon.save(addon) for preview in form_previews.forms: preview.save(addon) # If this is an incomplete app from the legacy submission flow, it may # not have device types set yet - so assume it works everywhere. if not addon.device_types: for device in amo.DEVICE_TYPES: addon.addondevicetype_set.create(device_type=device) AppSubmissionChecklist.objects.get(addon=addon).update(details=True) if addon.needs_payment(): # Paid apps get STATUS_NULL until payment information and content # ratings entered. addon.update(status=amo.STATUS_NULL, highest_status=amo.STATUS_PENDING) # Mark as pending in special regions (i.e., China). # By default, the column is set to pending when the row is inserted. # But we need to set a nomination date so we know to list the app # in the China Review Queue now (and sort it by that date too). for region in mkt.regions.SPECIAL_REGIONS: addon.geodata.set_nominated_date(region, save=True) log.info(u"[Webapp:%s] Setting nomination date to " u"now for region (%s)." % (addon, region.slug)) record_action("app-submitted", request, {"app-id": addon.pk}) return redirect("submit.app.done", addon.app_slug) ctx = {"step": "details", "addon": addon} ctx.update(forms) return render(request, "submit/details.html", ctx)
def extract_language_options(self) -> None: locale_path = f"{settings.DEPLOY_ROOT}/locale" output_path = f"{locale_path}/language_options.json" data: Dict[str, List[Dict[str, Any]]] = {"languages": []} try: locales = self.get_locales() except CalledProcessError: # In case we are not under a Git repo, fallback to getting the # locales using listdir(). locales = os.listdir(locale_path) locales.append("en") locales = list(set(locales)) for locale in locales: if locale == "en": data["languages"].append({ "name": "English", "name_local": "English", "code": "en", "locale": "en", }) continue lc_messages_path = os.path.join(locale_path, locale, "LC_MESSAGES") if not os.path.exists(lc_messages_path): # Not a locale. continue info: Dict[str, Any] = {} code = to_language(locale) percentage = self.get_translation_percentage(locale_path, locale) try: name = LANG_INFO[code]["name"] name_local = LANG_INFO[code]["name_local"] except KeyError: # Fallback to getting the name from PO file. filename = self.get_po_filename(locale_path, locale) name = self.get_name_from_po_file(filename, locale) with override_language(code): name_local = _(name) info["name"] = name info["name_local"] = name_local info["code"] = code info["locale"] = locale info["percent_translated"] = percentage data["languages"].append(info) with open(output_path, "w") as writer: json.dump(data, writer, indent=2, sort_keys=True) writer.write("\n")
def supported_langs(): """Return a list of locales supported adapting to live translation state. """ from django.conf import settings if settings.LIVE_TRANSLATION: try: from pootle_language.models import Language return [(trans_real.to_language(language.code), language.fullname) for language in Language.objects.exclude(code='template')] except Exception: pass return settings.LANGUAGES
def render(self, name, value, attrs=None): from .fields import switch attrs = self.build_attrs(attrs) lang = to_language(value.locale) attrs.update(lang=lang) # Use rsplit to drop django's name_idx numbering. (name_0 => name) name = '%s_%s' % (name.rsplit('_', 1)[0], lang) # Make sure we don't get a Linkified/Purified Translation. We don't # want people editing a bleached value. if value.__class__ != Translation: value = switch(value, Translation) return super(_TransWidget, self).render(name, value, attrs)
def extract_language_options(self) -> None: locale_path = f"{settings.DEPLOY_ROOT}/locale" output_path = f"{locale_path}/language_options.json" data: Dict[str, List[Dict[str, Any]]] = {'languages': []} try: locales = self.get_locales() except CalledProcessError: # In case we are not under a Git repo, fallback to getting the # locales using listdir(). locales = os.listdir(locale_path) locales.append('en') locales = list(set(locales)) for locale in locales: if locale == 'en': data['languages'].append({ 'name': 'English', 'name_local': 'English', 'code': 'en', 'locale': 'en', }) continue lc_messages_path = os.path.join(locale_path, locale, 'LC_MESSAGES') if not os.path.exists(lc_messages_path): # Not a locale. continue info: Dict[str, Any] = {} code = to_language(locale) percentage = self.get_translation_percentage(locale_path, locale) try: name = LANG_INFO[code]['name'] name_local = LANG_INFO[code]['name_local'] except KeyError: # Fallback to getting the name from PO file. filename = self.get_po_filename(locale_path, locale) name = self.get_name_from_po_file(filename, locale) with override_language(code): name_local = _(name) info['name'] = name info['name_local'] = name_local info['code'] = code info['locale'] = locale info['percent_translated'] = percentage data['languages'].append(info) with open(output_path, 'w') as writer: json.dump(data, writer, indent=2, sort_keys=True) writer.write('\n')
def extract_language_options(self): # type: () -> None locale_path = u"{}/locale".format(settings.STATIC_ROOT) output_path = u"{}/language_options.json".format(locale_path) data = {'languages': []} # type: Dict[str, List[Dict[str, Any]]] try: locales = self.get_locales() except CalledProcessError: # In case we are not under a Git repo, fallback to getting the # locales using listdir(). locales = os.listdir(locale_path) locales.append(u'en') locales = list(set(locales)) for locale in locales: if locale == 'en': data['languages'].append({ 'name': 'English', 'name_local': 'English', 'code': 'en', 'locale': 'en', }) continue lc_messages_path = os.path.join(locale_path, locale, 'LC_MESSAGES') if not os.path.exists(lc_messages_path): # Not a locale. continue info = {} # type: Dict[str, Any] code = to_language(locale) percentage = self.get_translation_percentage(locale_path, locale) try: name = LANG_INFO[code]['name'] name_local = LANG_INFO[code]['name_local'] except KeyError: # Fallback to getting the name from PO file. filename = self.get_po_filename(locale_path, locale) name = self.get_name_from_po_file(filename, locale) name_local = with_language(name, code) info['name'] = name info['name_local'] = name_local info['code'] = code info['locale'] = locale info['percent_translated'] = percentage data['languages'].append(info) with open(output_path, 'w') as writer: ujson.dump(data, writer, indent=2)
def extract_language_options(self) -> None: locale_path = "{}/locale".format(settings.STATIC_ROOT) output_path = "{}/language_options.json".format(locale_path) data = {'languages': []} # type: Dict[str, List[Dict[str, Any]]] try: locales = self.get_locales() except CalledProcessError: # In case we are not under a Git repo, fallback to getting the # locales using listdir(). locales = os.listdir(locale_path) locales.append('en') locales = list(set(locales)) for locale in locales: if locale == 'en': data['languages'].append({ 'name': 'English', 'name_local': 'English', 'code': 'en', 'locale': 'en', }) continue lc_messages_path = os.path.join(locale_path, locale, 'LC_MESSAGES') if not os.path.exists(lc_messages_path): # Not a locale. continue info = {} # type: Dict[str, Any] code = to_language(locale) percentage = self.get_translation_percentage(locale_path, locale) try: name = LANG_INFO[code]['name'] name_local = LANG_INFO[code]['name_local'] except KeyError: # Fallback to getting the name from PO file. filename = self.get_po_filename(locale_path, locale) name = self.get_name_from_po_file(filename, locale) name_local = with_language(name, code) info['name'] = name info['name_local'] = name_local info['code'] = code info['locale'] = locale info['percent_translated'] = percentage data['languages'].append(info) with open(output_path, 'w') as writer: ujson.dump(data, writer, indent=2) writer.write('\n')
def find_languages(locale_path): """Generate supported languages list from the :param:`locale_path` directory. """ dirs = os.listdir(locale_path) langs = [] for lang in dirs: append_lang = (data.langcode_re.match(lang) and os.path.isdir(os.path.join(locale_path, lang))) if append_lang: langs.append((trans_real.to_language(lang), data.languages.get(lang, (lang, ))[0])) return langs
def supported_langs(): """returns list of locales supported adapting to live translation state""" from django.conf import settings if settings.LIVE_TRANSLATION: try: # hackish: we import PootleProfile to force a failure when # first initializing the PootleProfile model, this way # Language is never created before PootleProfile and all # ManyToMany relations work fine from pootle_language.models import Language return [(trans_real.to_language(language.code), language.fullname) for language in Language.objects.exclude(code='template')] except Exception: pass return settings.LANGUAGES
def translation_from_string(self, instance, lang, string): """Create, save, and return a Translation from a string.""" try: trans = getattr(instance, self.field.name) trans_id = getattr(instance, self.field.attname) if trans is None and trans_id is not None: # This locale doesn't have a translation set, but there are # translations in another locale, so we have an id already. return self.model.new(string, lang, id=trans_id) elif to_language(trans.locale) == lang.lower(): # Replace the translation in the current language. trans.localized_string = string trans.save() return trans else: # We already have a translation in a different language. return self.model.new(string, lang, id=trans.id) except AttributeError: # Create a brand new translation. return self.model.new(string, lang)
def translation_from_string(self, instance, lang, string): """Create, save, and return a Translation from a string.""" try: trans = getattr(instance, self.field.name) trans_id = getattr(instance, self.field.attname) if trans is None and trans_id is not None: # This locale doesn't have a translation set, but there are # translations in another locale, so we have an id already. translation = self.model.new(string, lang, id=trans_id) elif to_language(trans.locale) == lang.lower(): # Replace the translation in the current language. trans.localized_string = string translation = trans else: # We already have a translation in a different language. translation = self.model.new(string, lang, id=trans.id) except AttributeError: # Create a brand new translation. translation = self.model.new(string, lang) save_on_signal(instance, translation) return translation
def process_request(self, request): "Set language for the current user" lang = settings.ANAF_LANGUAGES_DEFAULT if request.user.username: try: user = request.user.profile conf = ModuleSetting.get('language', user=user)[0] lang = conf.value except IndexError: pass except AttributeError: pass else: try: conf = ModuleSetting.get( 'language', user__isnull=True, strict=True)[0] lang = conf.value except IndexError: pass lang = to_language(lang) request.session['django_language'] = lang
def full_clean(self): locale = to_language(default_locale(self.instance)) for field in self.fields.values(): field.default_locale = locale return super(TranslationFormMixin, self).full_clean()
def details(request, addon_id, addon): # Name, Slug, Summary, Description, Privacy Policy, # Homepage URL, Support URL, Support Email. form_basic = AppDetailsBasicForm(request.POST or None, instance=addon, request=request) form_cats = CategoryForm(request.POST or None, product=addon, request=request) form_icon = AppFormMedia(request.POST or None, request.FILES or None, instance=addon, request=request) form_previews = PreviewFormSet(request.POST or None, prefix='files', queryset=addon.get_previews()) # For empty webapp-locale (or no-locale) fields that have # form-locale values, duplicate them to satisfy the requirement. form_locale = request.COOKIES.get("current_locale", "") app_locale = to_language(addon.default_locale) for name, value in request.POST.items(): if value: if name.endswith(form_locale): basename = name[:-len(form_locale)] else: basename = name + '_' othername = basename + app_locale if not request.POST.get(othername, None): request.POST[othername] = value forms = { 'form_basic': form_basic, 'form_cats': form_cats, 'form_icon': form_icon, 'form_previews': form_previews, } if request.POST and all(f.is_valid() for f in forms.itervalues()): addon = form_basic.save(addon) form_cats.save() form_icon.save(addon) for preview in form_previews.forms: preview.save(addon) # If this is an incomplete app from the legacy submission flow, it may # not have device types set yet - so assume it works everywhere. if not addon.device_types: for device in amo.DEVICE_TYPES: addon.addondevicetype_set.create(device_type=device) tasks.generate_image_assets.delay(addon) AppSubmissionChecklist.objects.get(addon=addon).update(details=True) make_public = (amo.PUBLIC_IMMEDIATELY if form_basic.cleaned_data.get('publish') else amo.PUBLIC_WAIT) # Free apps get pushed for review. if addon.premium_type == amo.ADDON_FREE: # The developer doesn't want the app published immediately upon # review. addon.update(status=amo.STATUS_PENDING, make_public=make_public) else: # Paid apps get STATUS_NULL until payment information has been # entered. addon.update(status=amo.STATUS_NULL, highest_status=amo.STATUS_PENDING, make_public=make_public) # Mark the app as excluded in regions that don't support payments. for region in mkt.regions.ALL_REGIONS: if not region.has_payments: AddonExcludedRegion.objects.get_or_create( addon=addon, region=region.id) return redirect('submit.app.done', addon.app_slug) ctx = { 'step': 'details', 'addon': addon, } ctx.update(forms) return jingo.render(request, 'submit/details.html', ctx)
def language_ascii(self): return settings.LANGUAGES[translation.to_language(self.default_locale)]
def default_filename(locale, domain): from django.utils.translation.trans_real import to_language return os.path.join(to_language(locale), '%s.js' % domain)
def details(request, addon_id, addon): # Name, Slug, Description, Privacy Policy, Homepage URL, Support URL, # Support Email. form_basic = AppDetailsBasicForm(request.POST or None, instance=addon, request=request) form_cats = CategoryForm(request.POST or None, product=addon, request=request) form_icon = AppFormMedia(request.POST or None, request.FILES or None, instance=addon, request=request) form_previews = PreviewFormSet(request.POST or None, prefix='files', queryset=addon.get_previews()) # For empty webapp-locale (or no-locale) fields that have # form-locale values, duplicate them to satisfy the requirement. form_locale = request.COOKIES.get('current_locale', '') app_locale = to_language(addon.default_locale) for name, value in request.POST.items(): if value: if name.endswith(form_locale): basename = name[:-len(form_locale)] else: basename = name + '_' othername = basename + app_locale if not request.POST.get(othername, None): request.POST[othername] = value forms = { 'form_basic': form_basic, 'form_cats': form_cats, 'form_icon': form_icon, 'form_previews': form_previews, } if request.POST and all(f.is_valid() for f in forms.itervalues()): addon = form_basic.save(addon) form_cats.save() form_icon.save(addon) for preview in form_previews.forms: preview.save(addon) # If this is an incomplete app from the legacy submission flow, it may # not have device types set yet - so assume it works everywhere. if not addon.device_types: for device in mkt.DEVICE_TYPES: addon.addondevicetype_set.create(device_type=device) AppSubmissionChecklist.objects.get(addon=addon).update(details=True) if addon.needs_payment(): # Paid apps get STATUS_NULL until payment information and content # ratings entered. addon.update(status=mkt.STATUS_NULL, highest_status=mkt.STATUS_PENDING) record_action('app-submitted', request, {'app-id': addon.pk}) return redirect('submit.app.done', addon.app_slug) ctx = { 'step': 'details', 'addon': addon, } ctx.update(forms) return render(request, 'submit/details.html', ctx)
def legacy_filename(locale, domain, output_format="js"): from django.utils.translation.trans_real import to_language return os.path.join(to_language(locale), "%s.%s" % (domain, output_format))
def default_filename(locale, domain, output_format='js'): from django.utils.translation.trans_real import to_language return os.path.join(to_language(locale), '%s.%s' % (domain, output_format))
def details(request, addon_id, addon): # Name, Slug, Description, Privacy Policy, Homepage URL, Support URL, # Support Email. form_basic = AppDetailsBasicForm(request.POST or None, instance=addon, request=request) form_cats = CategoryForm(request.POST or None, product=addon, request=request) form_icon = AppFormMedia(request.POST or None, request.FILES or None, instance=addon, request=request) form_previews = PreviewFormSet(request.POST or None, prefix='files', queryset=addon.get_previews()) # For empty webapp-locale (or no-locale) fields that have # form-locale values, duplicate them to satisfy the requirement. form_locale = request.COOKIES.get('current_locale', '') app_locale = to_language(addon.default_locale) for name, value in request.POST.items(): if value: if name.endswith(form_locale): basename = name[:-len(form_locale)] else: basename = name + '_' othername = basename + app_locale if not request.POST.get(othername, None): request.POST[othername] = value forms = { 'form_basic': form_basic, 'form_cats': form_cats, 'form_icon': form_icon, 'form_previews': form_previews, } if request.POST and all(f.is_valid() for f in forms.itervalues()): addon = form_basic.save(addon) form_cats.save() form_icon.save(addon) for preview in form_previews.forms: preview.save(addon) # If this is an incomplete app from the legacy submission flow, it may # not have device types set yet - so assume it works everywhere. if not addon.device_types: for device in amo.DEVICE_TYPES: addon.addondevicetype_set.create(device_type=device) AppSubmissionChecklist.objects.get(addon=addon).update(details=True) make_public = (amo.PUBLIC_IMMEDIATELY if form_basic.cleaned_data.get('publish') else amo.PUBLIC_WAIT) # Free apps get pushed for review. if addon.premium_type == amo.ADDON_FREE: # The developer doesn't want the app published immediately upon # review. addon.update(status=amo.STATUS_PENDING, make_public=make_public) else: # Paid apps get STATUS_NULL until payment information has been # entered. addon.update(status=amo.STATUS_NULL, highest_status=amo.STATUS_PENDING, make_public=make_public) # Mark the app as excluded in regions that don't support payments. for region in mkt.regions.ALL_REGIONS: if not region.has_payments: AddonExcludedRegion.objects.get_or_create(addon=addon, region=region.id) record_action('app-submitted', request, {'app-id': addon.pk}) return redirect('submit.app.done', addon.app_slug) ctx = { 'step': 'details', 'addon': addon, } ctx.update(forms) return jingo.render(request, 'submit/details.html', ctx)
def set_default_locale(self): locale = to_language(default_locale(self.instance)) for field in self.fields.values(): field.default_locale = locale field.widget.default_locale = locale
def details(request, addon_id, addon): # Name, Slug, Description, Privacy Policy, Homepage URL, Support URL, # Support Email. form_basic = AppDetailsBasicForm(request.POST or None, instance=addon, request=request) form_cats = CategoryForm(request.POST or None, product=addon, request=request) form_icon = AppFormMedia(request.POST or None, request.FILES or None, instance=addon, request=request) form_previews = PreviewFormSet(request.POST or None, prefix='files', queryset=addon.get_previews()) # For empty webapp-locale (or no-locale) fields that have # form-locale values, duplicate them to satisfy the requirement. form_locale = request.COOKIES.get('current_locale', '') app_locale = to_language(addon.default_locale) for name, value in request.POST.items(): if value: if name.endswith(form_locale): basename = name[:-len(form_locale)] else: basename = name + '_' othername = basename + app_locale if not request.POST.get(othername, None): request.POST[othername] = value forms = { 'form_basic': form_basic, 'form_cats': form_cats, 'form_icon': form_icon, 'form_previews': form_previews, } if request.POST and all(f.is_valid() for f in forms.itervalues()): addon = form_basic.save(addon) form_cats.save() form_icon.save(addon) for preview in form_previews.forms: preview.save(addon) # If this is an incomplete app from the legacy submission flow, it may # not have device types set yet - so assume it works everywhere. if not addon.device_types: for device in amo.DEVICE_TYPES: addon.addondevicetype_set.create(device_type=device) AppSubmissionChecklist.objects.get(addon=addon).update(details=True) # `make_public` if the developer doesn't want the app published # immediately upon review. make_public = (amo.PUBLIC_IMMEDIATELY if form_basic.cleaned_data.get('publish') else amo.PUBLIC_WAIT) if addon.premium_type == amo.ADDON_FREE: if waffle.switch_is_active('iarc'): # Free apps get STATUS_NULL until content ratings has been # entered. # TODO: set to STATUS_PENDING once app gets an IARC rating. addon.update(make_public=make_public) else: addon.update(status=amo.STATUS_PENDING, make_public=make_public) else: # Paid apps get STATUS_NULL until payment information and content # ratings has been entered. addon.update(status=amo.STATUS_NULL, make_public=make_public, highest_status=amo.STATUS_PENDING) record_action('app-submitted', request, {'app-id': addon.pk}) return redirect('submit.app.done', addon.app_slug) ctx = { 'step': 'details', 'addon': addon, } ctx.update(forms) return jingo.render(request, 'submit/details.html', ctx)
def details(request, addon_id, addon): # Name, Slug, Description, Privacy Policy, Homepage URL, Support URL, # Support Email. form_basic = AppDetailsBasicForm(request.POST or None, instance=addon, request=request) form_cats = CategoryForm(request.POST or None, product=addon, request=request) form_icon = AppFormMedia(request.POST or None, request.FILES or None, instance=addon, request=request) form_previews = PreviewFormSet(request.POST or None, prefix='files', queryset=addon.get_previews()) # For empty webapp-locale (or no-locale) fields that have # form-locale values, duplicate them to satisfy the requirement. form_locale = request.COOKIES.get('current_locale', '') app_locale = to_language(addon.default_locale) for name, value in request.POST.items(): if value: if name.endswith(form_locale): basename = name[:-len(form_locale)] else: basename = name + '_' othername = basename + app_locale if not request.POST.get(othername, None): request.POST[othername] = value forms = { 'form_basic': form_basic, 'form_cats': form_cats, 'form_icon': form_icon, 'form_previews': form_previews, } if request.POST and all(f.is_valid() for f in forms.itervalues()): addon = form_basic.save(addon) form_cats.save() form_icon.save(addon) for preview in form_previews.forms: preview.save(addon) # If this is an incomplete app from the legacy submission flow, it may # not have device types set yet - so assume it works everywhere. if not addon.device_types: for device in mkt.DEVICE_TYPES: addon.addondevicetype_set.create(device_type=device) AppSubmissionChecklist.objects.get(addon=addon).update(details=True) if addon.needs_payment(): # Paid apps get STATUS_NULL until payment information and content # ratings entered. addon.update(status=mkt.STATUS_NULL, highest_status=mkt.STATUS_PENDING) # Mark as pending in special regions (i.e., China). # By default, the column is set to pending when the row is inserted. # But we need to set a nomination date so we know to list the app # in the China Review Queue now (and sort it by that date too). for region in mkt.regions.SPECIAL_REGIONS: addon.geodata.set_nominated_date(region, save=True) log.info(u'[Webapp:%s] Setting nomination date to ' u'now for region (%s).' % (addon, region.slug)) record_action('app-submitted', request, {'app-id': addon.pk}) return redirect('submit.app.done', addon.app_slug) ctx = { 'step': 'details', 'addon': addon, } ctx.update(forms) return render(request, 'submit/details.html', ctx)
def trans_widgets(trans_id, widget): translations = (Translation.objects.filter(id=trans_id) .filter(localized_string__isnull=False) .values_list('locale', 'localized_string')) return [(to_language(locale), widget(locale, val)) for locale, val in translations if val is not None]
def details(request, addon_id, addon): # Name, Slug, Description, Privacy Policy, Homepage URL, Support URL, # Support Email. form_basic = AppDetailsBasicForm(request.POST or None, instance=addon, request=request) form_cats = CategoryForm(request.POST or None, product=addon, request=request) form_icon = AppFormMedia(request.POST or None, request.FILES or None, instance=addon, request=request) form_previews = PreviewFormSet(request.POST or None, prefix='files', queryset=addon.get_previews()) # For empty webapp-locale (or no-locale) fields that have # form-locale values, duplicate them to satisfy the requirement. form_locale = request.COOKIES.get('current_locale', '') app_locale = to_language(addon.default_locale) for name, value in request.POST.items(): if value: if name.endswith(form_locale): basename = name[:-len(form_locale)] else: basename = name + '_' othername = basename + app_locale if not request.POST.get(othername, None): request.POST[othername] = value forms = { 'form_basic': form_basic, 'form_cats': form_cats, 'form_icon': form_icon, 'form_previews': form_previews, } if request.POST and all(f.is_valid() for f in forms.itervalues()): addon = form_basic.save(addon) form_cats.save() form_icon.save(addon) for preview in form_previews.forms: preview.save(addon) # If this is an incomplete app from the legacy submission flow, it may # not have device types set yet - so assume it works everywhere. if not addon.device_types: for device in amo.DEVICE_TYPES: addon.addondevicetype_set.create(device_type=device) AppSubmissionChecklist.objects.get(addon=addon).update(details=True) # `publish_type` if the developer doesn't want the app published # immediately upon review. publish_type = (amo.PUBLISH_IMMEDIATE if form_basic.cleaned_data.get('publish') else amo.PUBLISH_PRIVATE) if addon.premium_type == amo.ADDON_FREE: if waffle.switch_is_active('iarc'): # Free apps get STATUS_NULL until content ratings has been # entered. # TODO: set to STATUS_PENDING once app gets an IARC rating. addon.update(publish_type=publish_type) else: addon.update(status=amo.STATUS_PENDING, publish_type=publish_type) else: # Paid apps get STATUS_NULL until payment information and content # ratings has been entered. addon.update(status=amo.STATUS_NULL, publish_type=publish_type, highest_status=amo.STATUS_PENDING) # Mark as pending in special regions (i.e., China). # By default, the column is set to pending when the row is inserted. # But we need to set a nomination date so we know to list the app # in the China Review Queue now (and sort it by that date too). for region in mkt.regions.SPECIAL_REGIONS: addon.geodata.set_nominated_date(region, save=True) log.info(u'[Webapp:%s] Setting nomination date to ' u'now for region (%s).' % (addon, region.slug)) record_action('app-submitted', request, {'app-id': addon.pk}) return redirect('submit.app.done', addon.app_slug) ctx = { 'step': 'details', 'addon': addon, } ctx.update(forms) return render(request, 'submit/details.html', ctx)
def widget(locale, value): locale = to_language(locale) value = jinja2.escape(value) attrs_ = dict(id='trans_%s_%s' % (name, locale), **attrs) return textarea.format(name=name, locale=locale, attrs=flatatt(attrs_), value=value)