def upload(request): """Upload translated resource.""" try: slug = request.POST['slug'] code = request.POST['code'] part = request.POST['part'] except MultiValueDictKeyError: raise Http404 locale = get_object_or_404(Locale, code=code) project = get_object_or_404(Project, slug=slug) if ( not request.user.can_translate(project=project, locale=locale) or utils.readonly_exists(project, locale) ): return HttpResponseForbidden("Forbidden: You don't have permission to upload files") form = forms.UploadFileForm(request.POST, request.FILES) if form.is_valid(): f = request.FILES['uploadfile'] utils.handle_upload_content(slug, code, part, f, request.user) messages.success(request, 'Translations updated from uploaded file.') else: for field, errors in form.errors.items(): for error in errors: messages.error(request, error) return translate(request, code, slug, part)
def delete_translation(request): """Delete given translation.""" try: t = request.POST['translation'] except MultiValueDictKeyError as e: return HttpResponseBadRequest('Bad Request: {error}'.format(error=e)) translation = get_object_or_404(Translation, pk=t) project = translation.entity.resource.project locale = translation.locale # Read-only translations cannot be deleted if utils.readonly_exists(project, locale): return HttpResponseForbidden( "Forbidden: This string is in read-only mode") # Only privileged users or authors can delete translations if not translation.rejected or not (request.user.can_translate( locale, project) or request.user == translation.user or translation.approved): return HttpResponseForbidden( "Forbidden: You can't delete this translation.") translation.delete() return HttpResponse('ok')
def upload(request): """Upload translated resource.""" try: slug = request.POST['slug'] code = request.POST['code'] part = request.POST['part'] except MultiValueDictKeyError: raise Http404 locale = get_object_or_404(Locale, code=code) project = get_object_or_404(Project, slug=slug) if (not request.user.can_translate(project=project, locale=locale) or utils.readonly_exists(project, locale)): return HttpResponseForbidden( "You don't have permission to upload files.") form = forms.UploadFileForm(request.POST, request.FILES) if form.is_valid(): f = request.FILES['uploadfile'] utils.handle_upload_content(slug, code, part, f, request.user) messages.success(request, 'Translations updated from uploaded file.') else: for field, errors in form.errors.items(): for error in errors: messages.error(request, error) return translate(request, code, slug, part)
def upload(request): """Upload translated resource.""" try: slug = request.POST["slug"] code = request.POST["code"] part = request.POST["part"] except MultiValueDictKeyError: raise Http404 locale = get_object_or_404(Locale, code=code) project = get_object_or_404(Project.objects.visible_for(request.user), slug=slug) if not request.user.can_translate( project=project, locale=locale ) or utils.readonly_exists(project, locale): return HttpResponseForbidden("You don't have permission to upload files.") form = forms.UploadFileForm(request.POST, request.FILES) if form.is_valid(): f = request.FILES["uploadfile"] utils.handle_upload_content(slug, code, part, f, request.user) messages.success(request, "Translations updated from uploaded file.") else: for field, errors in form.errors.items(): for error in errors: messages.error(request, error) response = HttpResponse(content="", status=303) response["Location"] = reverse( "pontoon.translate", kwargs={"locale": code, "project": slug, "resource": part}, ) return response
def delete_translation(request): """Delete given translation.""" try: t = request.POST['translation'] except MultiValueDictKeyError as e: return HttpResponseBadRequest('Bad Request: {error}'.format(error=e)) translation = get_object_or_404(Translation, pk=t) project = translation.entity.resource.project locale = translation.locale # Read-only translations cannot be deleted if utils.readonly_exists(project, locale): return HttpResponseForbidden( "Forbidden: This string is in read-only mode" ) # Only privileged users or authors can delete translations if not translation.rejected or not ( request.user.can_translate(locale, project) or request.user == translation.user or translation.approved ): return HttpResponseForbidden( "Forbidden: You can't delete this translation." ) translation.delete() return HttpResponse('ok')
def reject_translation(request): """Reject given translation.""" try: t = request.POST['translation'] paths = request.POST.getlist('paths[]') except MultiValueDictKeyError as e: return HttpResponseBadRequest('Bad Request: {error}'.format(error=e)) translation = get_object_or_404(Translation, pk=t) project = translation.entity.resource.project locale = translation.locale # Read-only translations cannot be rejected if utils.readonly_exists(project, locale): return HttpResponseForbidden( "Forbidden: This string is in read-only mode" ) # Non-privileged users can only reject own unapproved translations if not request.user.can_translate(locale, project): if translation.user == request.user: if translation.approved is True: return HttpResponseForbidden( "Forbidden: Can't reject approved translations" ) else: return HttpResponseForbidden( "Forbidden: Can't reject translations from other users" ) # Check if translation was approved. We must do this before unapproving it. if translation.approved or translation.fuzzy: translation.entity.mark_changed(locale) TranslatedResource.objects.get( resource=translation.entity.resource, locale=locale ).calculate_stats() translation.rejected = True translation.rejected_user = request.user translation.rejected_date = timezone.now() translation.approved = False translation.approved_user = None translation.approved_date = None translation.fuzzy = False translation.save() latest_translation = translation.entity.translation_set.filter( locale=locale, plural_form=translation.plural_form, ).order_by('-approved', 'rejected', '-date')[0].serialize() TranslationMemoryEntry.objects.filter(translation=translation).delete() return JsonResponse({ 'translation': latest_translation, 'stats': TranslatedResource.objects.stats(project, paths, locale), })
def unreject_translation(request): """Unreject given translation.""" try: t = request.POST["translation"] paths = request.POST.getlist("paths[]") except MultiValueDictKeyError as e: return JsonResponse( { "status": False, "message": "Bad Request: {error}".format(error=e) }, status=400, ) translation = get_object_or_404(Translation, pk=t) project = translation.entity.resource.project locale = translation.locale # Read-only translations cannot be un-rejected if utils.readonly_exists(project, locale): return JsonResponse( { "status": False, "message": "Forbidden: This string is in read-only mode.", }, status=403, ) # Only privileged users or authors can un-reject translations if not (request.user.can_translate(locale, project) or request.user == translation.user or translation.approved): return JsonResponse( { "status": False, "message": "Forbidden: You can't unreject this translation.", }, status=403, ) translation.unreject(request.user) log_action( ActionLog.ActionType.TRANSLATION_UNREJECTED, request.user, translation=translation, ) active_translation = translation.entity.reset_active_translation( locale=locale, plural_form=translation.plural_form, ) return JsonResponse({ "translation": active_translation.serialize(), "stats": TranslatedResource.objects.stats(project, paths, locale), })
def approve_translation(request): """Approve given translation.""" try: t = request.POST['translation'] paths = request.POST.getlist('paths[]') except MultiValueDictKeyError as e: return HttpResponseBadRequest('Bad Request: {error}'.format(error=e)) translation = get_object_or_404(Translation, pk=t) project = translation.entity.resource.project locale = translation.locale user = request.user # Read-only translations cannot be approved if utils.readonly_exists(project, locale): return HttpResponseForbidden( "Forbidden: This translation is in read-only mode" ) if translation.approved: return HttpResponseForbidden( "Forbidden: This translation is already approved" ) # Only privileged users can approve translations if not user.can_translate(locale, project): return HttpResponseForbidden( "Forbidden: You don't have permission to approve this translation." ) # Check for errors. # Checks are disabled for the tutorial. use_checks = project.slug != 'tutorial' if use_checks and translation.errors.exists(): return HttpResponseForbidden( "Forbidden: There are errors with this translation." ) translation.approve(user) active_translation = translation.entity.reset_active_translation( locale=locale, plural_form=translation.plural_form, ) return JsonResponse({ 'translation': active_translation.serialize(), 'stats': TranslatedResource.objects.stats(project, paths, locale), })
def approve_translation(request): """Approve given translation.""" try: t = request.POST['translation'] paths = request.POST.getlist('paths[]') except MultiValueDictKeyError as e: return HttpResponseBadRequest('Bad Request: {error}'.format(error=e)) translation = get_object_or_404(Translation, pk=t) project = translation.entity.resource.project locale = translation.locale user = request.user # Read-only translations cannot be approved if utils.readonly_exists(project, locale): return HttpResponseForbidden( "Forbidden: This translation is in read-only mode" ) if translation.approved: return HttpResponseForbidden( "Forbidden: This translation is already approved" ) # Only privileged users can approve translations if not user.can_translate(locale, project): return HttpResponseForbidden( "Forbidden: You don't have permission to approve this translation." ) # Check for errors. # Checks are disabled for the tutorial. use_checks = project.slug != 'tutorial' if use_checks and translation.errors.exists(): return HttpResponseForbidden( "Forbidden: There are errors with this translation." ) translation.approve(user) active_translation = translation.entity.reset_active_translation( locale=locale, plural_form=translation.plural_form, ) return JsonResponse({ 'translation': active_translation.serialize(), 'stats': TranslatedResource.objects.stats(project, paths, locale), })
def delete_translation(request): """Delete given translation.""" try: translation_id = request.POST["translation"] except MultiValueDictKeyError as e: return JsonResponse( { "status": False, "message": "Bad Request: {error}".format(error=e) }, status=400, ) translation = get_object_or_404(Translation, pk=translation_id) entity = translation.entity project = entity.resource.project locale = translation.locale # Read-only translations cannot be deleted if utils.readonly_exists(project, locale): return JsonResponse( { "status": False, "message": "Forbidden: This string is in read-only mode.", }, status=403, ) # Only privileged users or authors can delete translations if not translation.rejected or not (request.user.can_translate( locale, project) or request.user == translation.user or translation.approved): return JsonResponse( { "status": False, "message": "Forbidden: You can't delete this translation.", }, status=403, ) translation.delete() log_action( ActionLog.ActionType.TRANSLATION_DELETED, request.user, entity=entity, locale=locale, ) return JsonResponse({"status": True})
def unreject_translation(request): """Unreject given translation.""" try: t = request.POST['translation'] paths = request.POST.getlist('paths[]') except MultiValueDictKeyError as e: return JsonResponse( { 'status': False, 'message': 'Bad Request: {error}'.format(error=e), }, status=400) translation = get_object_or_404(Translation, pk=t) project = translation.entity.resource.project locale = translation.locale # Read-only translations cannot be un-rejected if utils.readonly_exists(project, locale): return JsonResponse( { 'status': False, 'message': 'Forbidden: This string is in read-only mode.', }, status=403) # Only privileged users or authors can un-reject translations if not (request.user.can_translate(locale, project) or request.user == translation.user or translation.approved): return JsonResponse( { 'status': False, 'message': "Forbidden: You can't unreject this translation.", }, status=403) translation.unreject(request.user) active_translation = translation.entity.reset_active_translation( locale=locale, plural_form=translation.plural_form, ) return JsonResponse({ 'translation': active_translation.serialize(), 'stats': TranslatedResource.objects.stats(project, paths, locale), })
def reject_translation(request): """Reject given translation.""" try: t = request.POST['translation'] paths = request.POST.getlist('paths[]') except MultiValueDictKeyError as e: return JsonResponse({ 'status': False, 'message': 'Bad Request: {error}'.format(error=e), }, status=400) translation = get_object_or_404(Translation, pk=t) project = translation.entity.resource.project locale = translation.locale # Read-only translations cannot be rejected if utils.readonly_exists(project, locale): return JsonResponse({ 'status': False, 'message': 'Forbidden: This string is in read-only mode.', }, status=403) # Non-privileged users can only reject own unapproved translations if not request.user.can_translate(locale, project): if translation.user == request.user: if translation.approved is True: return JsonResponse({ 'status': False, 'message': "Forbidden: You can't reject approved translations.", }, status=403) else: return JsonResponse({ 'status': False, 'message': "Forbidden: You can't reject translations from other users.", }, status=403) translation.reject(request.user) active_translation = translation.entity.reset_active_translation( locale=locale, plural_form=translation.plural_form, ) return JsonResponse({ 'translation': active_translation.serialize(), 'stats': TranslatedResource.objects.stats(project, paths, locale), })
def delete_translation(request): """Delete given translation.""" try: t = request.POST['translation'] except MultiValueDictKeyError as e: return JsonResponse( { 'status': False, 'message': 'Bad Request: {error}'.format(error=e), }, status=400) translation = get_object_or_404(Translation, pk=t) project = translation.entity.resource.project locale = translation.locale # Read-only translations cannot be deleted if utils.readonly_exists(project, locale): return JsonResponse( { 'status': False, 'message': 'Forbidden: This string is in read-only mode.', }, status=403) # Only privileged users or authors can delete translations if not translation.rejected or not (request.user.can_translate( locale, project) or request.user == translation.user or translation.approved): return JsonResponse( { 'status': False, 'message': "Forbidden: You can't delete this translation.", }, status=403) translation.delete() return JsonResponse({ 'status': True, })
def reject_translation(request): """Reject given translation.""" try: t = request.POST['translation'] paths = request.POST.getlist('paths[]') except MultiValueDictKeyError as e: return HttpResponseBadRequest('Bad Request: {error}'.format(error=e)) translation = get_object_or_404(Translation, pk=t) project = translation.entity.resource.project locale = translation.locale # Read-only translations cannot be rejected if utils.readonly_exists(project, locale): return HttpResponseForbidden( "Forbidden: This string is in read-only mode" ) # Non-privileged users can only reject own unapproved translations if not request.user.can_translate(locale, project): if translation.user == request.user: if translation.approved is True: return HttpResponseForbidden( "Forbidden: Can't reject approved translations" ) else: return HttpResponseForbidden( "Forbidden: Can't reject translations from other users" ) translation.reject(request.user) active_translation = translation.entity.reset_active_translation( locale=locale, plural_form=translation.plural_form, ) return JsonResponse({ 'translation': active_translation.serialize(), 'stats': TranslatedResource.objects.stats(project, paths, locale), })
def unreject_translation(request): """Unreject given translation.""" try: t = request.POST['translation'] paths = request.POST.getlist('paths[]') except MultiValueDictKeyError as e: return HttpResponseBadRequest('Bad Request: {error}'.format(error=e)) translation = Translation.objects.get(pk=t) project = translation.entity.resource.project locale = translation.locale # Read-only translations cannot be un-rejected if utils.readonly_exists(project, locale): return HttpResponseForbidden( "Forbidden: This string is in read-only mode" ) # Only privileged users or authors can un-reject translations if not ( request.user.can_translate(locale, project) or request.user == translation.user or translation.approved ): return HttpResponseForbidden( "Forbidden: You can't unreject this translation." ) translation.unreject(request.user) latest_translation = translation.entity.translation_set.filter( locale=locale, plural_form=translation.plural_form, ).order_by('-approved', 'rejected', '-date')[0].serialize() return JsonResponse({ 'translation': latest_translation, 'stats': TranslatedResource.objects.stats(project, paths, locale), })
def unreject_translation(request): """Unreject given translation.""" try: t = request.POST['translation'] paths = request.POST.getlist('paths[]') except MultiValueDictKeyError as e: return HttpResponseBadRequest('Bad Request: {error}'.format(error=e)) translation = get_object_or_404(Translation, pk=t) project = translation.entity.resource.project locale = translation.locale # Read-only translations cannot be un-rejected if utils.readonly_exists(project, locale): return HttpResponseForbidden( "Forbidden: This string is in read-only mode" ) # Only privileged users or authors can un-reject translations if not ( request.user.can_translate(locale, project) or request.user == translation.user or translation.approved ): return HttpResponseForbidden( "Forbidden: You can't unreject this translation." ) translation.unreject(request.user) active_translation = translation.entity.reset_active_translation( locale=locale, plural_form=translation.plural_form, ) return JsonResponse({ 'translation': active_translation.serialize(), 'stats': TranslatedResource.objects.stats(project, paths, locale), })
def delete_translation(request): """Delete given translation.""" try: t = request.POST['translation'] except MultiValueDictKeyError as e: return JsonResponse({ 'status': False, 'message': 'Bad Request: {error}'.format(error=e), }, status=400) translation = get_object_or_404(Translation, pk=t) project = translation.entity.resource.project locale = translation.locale # Read-only translations cannot be deleted if utils.readonly_exists(project, locale): return JsonResponse({ 'status': False, 'message': 'Forbidden: This string is in read-only mode.', }, status=403) # Only privileged users or authors can delete translations if not translation.rejected or not ( request.user.can_translate(locale, project) or request.user == translation.user or translation.approved ): return JsonResponse({ 'status': False, 'message': "Forbidden: You can't delete this translation.", }, status=403) translation.delete() return JsonResponse({ 'status': True, })
def update_translation(request): """Update entity translation for the specified locale and user. Note that this view is also used to approve a translation by the old Translate app. Once we migrate to Translate.Next, we'll want to rework this view to remove the bits about approving a translation, because that has been delegated to the `approve_translation` view. """ try: entity = request.POST['entity'] string = request.POST['translation'] locale = request.POST['locale'] plural_form = request.POST['plural_form'] original = request.POST['original'] ignore_warnings = request.POST.get('ignore_warnings', 'false') == 'true' approve = request.POST.get('approve', 'false') == 'true' force_suggestions = request.POST.get('force_suggestions', 'false') == 'true' paths = request.POST.getlist('paths[]') except MultiValueDictKeyError as e: return HttpResponseBadRequest('Bad Request: {error}'.format(error=e)) try: e = Entity.objects.get(pk=entity) except Entity.DoesNotExist as error: log.error(str(error)) return HttpResponse("error") try: locale = Locale.objects.get(code=locale) except Locale.DoesNotExist as error: log.error(str(error)) return HttpResponse("error") if plural_form == "-1": plural_form = None user = request.user project = e.resource.project # Read-only translations cannot saved if utils.readonly_exists(project, locale): return HttpResponseForbidden( "Forbidden: This string is in read-only mode" ) try: use_ttk_checks = UserProfile.objects.get(user=user).quality_checks except UserProfile.DoesNotExist as error: use_ttk_checks = True # Disable checks for tutorial project. if project.slug == 'tutorial': use_ttk_checks = False now = timezone.now() can_translate = ( request.user.can_translate(project=project, locale=locale) and (not force_suggestions or approve) ) translations = Translation.objects.filter( entity=e, locale=locale, plural_form=plural_form) same_translations = translations.filter(string=string).order_by( '-active', 'rejected', '-date' ) # If same translation exists in the DB, don't save it again. if utils.is_same(same_translations, can_translate): return JsonResponse({ 'same': True, }) failed_checks = run_checks( e, locale.code, original, string, use_ttk_checks, ) if are_blocking_checks(failed_checks, ignore_warnings): return JsonResponse({ 'failedChecks': failed_checks, }) # Translations exist if len(translations) > 0: # Same translation exists if len(same_translations) > 0: t = same_translations[0] # If added by privileged user, approve and unfuzzy it if can_translate and (t.fuzzy or not t.approved): if not t.active: translations.filter(active=True).update(active=False) t.active = True t.approved = True t.fuzzy = False t.rejected = False t.rejected_user = None t.rejected_date = None if t.approved_user is None: t.approved_user = user t.approved_date = now t.save() t.warnings.all().delete() t.errors.all().delete() save_failed_checks(t, failed_checks) return JsonResponse({ 'type': 'updated', 'translation': t.serialize(), 'stats': TranslatedResource.objects.stats(project, paths, locale), }) # Different translation added else: t = Translation( entity=e, locale=locale, plural_form=plural_form, string=string, user=user, date=now, approved=can_translate, ) if can_translate: t.approved_user = user t.approved_date = now t.save() save_failed_checks(t, failed_checks) active_translation = e.reset_active_translation( locale=locale, plural_form=plural_form, ) return JsonResponse({ 'type': 'added', 'translation': active_translation.serialize(), 'stats': TranslatedResource.objects.stats(project, paths, locale), }) # No translations saved yet else: t = Translation( entity=e, locale=locale, plural_form=plural_form, string=string, user=user, date=now, active=True, approved=can_translate, ) if can_translate: t.approved_user = user t.approved_date = now t.save() save_failed_checks(t, failed_checks) return JsonResponse({ 'type': 'saved', 'translation': t.serialize(), 'stats': TranslatedResource.objects.stats(project, paths, locale), })
def approve_translation(request): """Approve given translation.""" try: t = request.POST['translation'] ignore_warnings = request.POST.get('ignore_warnings', 'false') == 'true' paths = request.POST.getlist('paths[]') except MultiValueDictKeyError as e: return JsonResponse( { 'status': False, 'message': 'Bad Request: {error}'.format(error=e), }, status=400) translation = get_object_or_404(Translation, pk=t) entity = translation.entity project = entity.resource.project locale = translation.locale user = request.user # Read-only translations cannot be approved if utils.readonly_exists(project, locale): return JsonResponse( { 'status': False, 'message': 'Forbidden: This string is in read-only mode.', }, status=403) if translation.approved: return JsonResponse( { 'status': False, 'message': 'Forbidden: This translation is already approved.', }, status=403) # Only privileged users can approve translations if not user.can_translate(locale, project): return JsonResponse( { 'status': False, 'message': "Forbidden: You don't have permission to approve this translation.", }, status=403) # Check for errors. # Checks are disabled for the tutorial. use_checks = project.slug != 'tutorial' if use_checks: failed_checks = run_checks( entity, locale.code, entity.string, translation.string, user.profile.quality_checks, ) if are_blocking_checks(failed_checks, ignore_warnings): return JsonResponse({ 'string': translation.string, 'failedChecks': failed_checks, }) translation.approve(user) active_translation = translation.entity.reset_active_translation( locale=locale, plural_form=translation.plural_form, ) return JsonResponse({ 'translation': active_translation.serialize(), 'stats': TranslatedResource.objects.stats(project, paths, locale), })
def batch_edit_translations(request): """Perform an action on a list of translations. Available actions are defined in `ACTIONS_FN_MAP`. Arguments to this view are defined in `models.BatchActionsForm`. """ form = forms.BatchActionsForm(request.POST) if not form.is_valid(): return HttpResponseBadRequest(form.errors.as_json()) locale = get_object_or_404(Locale, code=form.cleaned_data['locale']) entities = Entity.objects.filter(pk__in=form.cleaned_data['entities']) if not entities.exists(): return JsonResponse({'count': 0}) # Batch editing is only available to translators. Check if user has # translate permissions for all of the projects in passed entities. # Also make sure projects are not enabled in read-only mode for a locale. projects_pk = entities.values_list('resource__project__pk', flat=True) projects = Project.objects.filter(pk__in=projects_pk.distinct()) for project in projects: if ( not request.user.can_translate(project=project, locale=locale) or readonly_exists(projects, locale) ): return HttpResponseForbidden( "Forbidden: You don't have permission for batch editing" ) # Find all impacted active translations, including plural forms. active_translations = Translation.objects.filter( active=True, locale=locale, entity__in=entities, ) # Execute the actual action. action_function = ACTIONS_FN_MAP[form.cleaned_data['action']] action_status = action_function( form, request.user, active_translations, locale, ) if action_status.get('error'): return JsonResponse(action_status) invalid_translation_count = len(action_status.get('invalid_translation_pks', [])) if action_status['count'] == 0: return JsonResponse({ 'count': 0, 'invalid_translation_count': invalid_translation_count, }) update_stats(action_status['translated_resources'], locale) mark_changed_translation(action_status['changed_entities'], locale) # Update latest translation. if action_status['latest_translation_pk']: Translation.objects.get( pk=action_status['latest_translation_pk'] ).update_latest_translation() update_translation_memory( action_status['changed_translation_pks'], project, locale ) return JsonResponse({ 'count': action_status['count'], 'invalid_translation_count': invalid_translation_count, })
def update_translation(request): """Update entity translation for the specified locale and user.""" try: entity = request.POST['entity'] string = request.POST['translation'] locale = request.POST['locale'] plural_form = request.POST['plural_form'] original = request.POST['original'] ignore_warnings = request.POST.get('ignore_warnings', 'false') == 'true' approve = request.POST.get('approve', 'false') == 'true' force_suggestions = request.POST.get('force_suggestions', 'false') == 'true' paths = request.POST.getlist('paths[]') except MultiValueDictKeyError as e: return HttpResponseBadRequest('Bad Request: {error}'.format(error=e)) try: e = Entity.objects.get(pk=entity) except Entity.DoesNotExist as error: log.error(str(error)) return HttpResponse("error") try: locale = Locale.objects.get(code=locale) except Locale.DoesNotExist as error: log.error(str(error)) return HttpResponse("error") if plural_form == "-1": plural_form = None user = request.user project = e.resource.project # Read-only translations cannot saved if utils.readonly_exists(project, locale): return HttpResponseForbidden( "Forbidden: This string is in read-only mode" ) try: use_ttk_checks = UserProfile.objects.get(user=user).quality_checks except UserProfile.DoesNotExist as error: use_ttk_checks = True # Disable checks for tutorial project. if project.slug == 'tutorial': use_ttk_checks = False now = timezone.now() can_translate = ( request.user.can_translate(project=project, locale=locale) and (not force_suggestions or approve) ) translations = Translation.objects.filter( entity=e, locale=locale, plural_form=plural_form) same_translations = translations.filter(string=string).order_by( '-approved', 'rejected', '-date' ) # If same translation exists in the DB, don't save it again. if utils.is_same(same_translations, can_translate): return JsonResponse({ 'same': True, }) failed_checks = run_checks( e, locale.code, original, string, use_ttk_checks, ) if are_blocking_checks(failed_checks, ignore_warnings): return JsonResponse({ 'failedChecks': failed_checks, }) # Translations exist if len(translations) > 0: if len(same_translations) > 0: t = same_translations[0] # If added by privileged user, approve and unfuzzy it if can_translate and (t.fuzzy or not t.approved): translations.update( approved=False, approved_user=None, approved_date=None, rejected=True, rejected_user=request.user, rejected_date=timezone.now(), fuzzy=False, ) t.approved = True t.fuzzy = False t.rejected = False t.rejected_user = None t.rejected_date = None if t.approved_user is None: t.approved_user = user t.approved_date = now # If added by non-privileged user and fuzzy, unfuzzy it elif t.fuzzy: t.approved = False t.approved_user = None t.approved_date = None t.fuzzy = False t.save() t.warnings.all().delete() t.errors.all().delete() save_failed_checks(t, failed_checks) return JsonResponse({ 'type': 'updated', 'translation': t.serialize(), 'stats': TranslatedResource.objects.stats(project, paths, locale), }) # Different translation added else: if can_translate: translations.update(approved=False, approved_user=None, approved_date=None) translations.update(fuzzy=False) t = Translation( entity=e, locale=locale, user=user, string=string, plural_form=plural_form, date=now, approved=can_translate) if can_translate: t.approved_user = user t.approved_date = now t.save() save_failed_checks(t, failed_checks) # Return active (approved or latest) translation try: active = translations.filter(approved=True).latest("date") except Translation.DoesNotExist: active = translations.latest("date") return JsonResponse({ 'type': 'added', 'translation': active.serialize(), 'stats': TranslatedResource.objects.stats(project, paths, locale), }) # No translations saved yet else: t = Translation( entity=e, locale=locale, user=user, string=string, plural_form=plural_form, date=now, approved=can_translate) if can_translate: t.approved_user = user t.approved_date = now t.save() save_failed_checks(t, failed_checks) return JsonResponse({ 'type': 'saved', 'translation': t.serialize(), 'stats': TranslatedResource.objects.stats(project, paths, locale), })
def update_translation(request): """Update entity translation for the specified locale and user. Note that this view is also used to approve a translation by the old Translate app. Once we migrate to Translate.Next, we'll want to rework this view to remove the bits about approving a translation, because that has been delegated to the `approve_translation` view. """ try: entity = request.POST["entity"] string = request.POST["translation"] locale = request.POST["locale"] plural_form = request.POST["plural_form"] original = request.POST["original"] ignore_warnings = request.POST.get("ignore_warnings", "false") == "true" approve = request.POST.get("approve", "false") == "true" force_suggestions = request.POST.get("force_suggestions", "false") == "true" paths = request.POST.getlist("paths[]") except MultiValueDictKeyError as e: return JsonResponse( { "status": False, "message": "Bad Request: {error}".format(error=e) }, status=400, ) try: e = Entity.objects.get(pk=entity) except Entity.DoesNotExist as e: return JsonResponse( { "status": False, "message": "Bad Request: {error}".format(error=e) }, status=400, ) try: locale = Locale.objects.get(code=locale) except Locale.DoesNotExist as e: return JsonResponse( { "status": False, "message": "Bad Request: {error}".format(error=e) }, status=400, ) if plural_form == "-1": plural_form = None user = request.user project = e.resource.project # Read-only translations cannot saved if utils.readonly_exists(project, locale): return JsonResponse( { "status": False, "message": "Forbidden: This string is in read-only mode.", }, status=403, ) now = timezone.now() can_translate = request.user.can_translate( project=project, locale=locale) and (not force_suggestions or approve) translations = Translation.objects.filter(entity=e, locale=locale, plural_form=plural_form) same_translations = translations.filter(string=string).order_by( "-active", "rejected", "-date") # If same translation exists in the DB, don't save it again. if utils.is_same(same_translations, can_translate): return JsonResponse({"same": True}) # Check for errors. # Checks are disabled for the tutorial. use_checks = project.slug != "tutorial" failed_checks = None if use_checks: failed_checks = run_checks( e, locale.code, original, string, user.profile.quality_checks, ) if are_blocking_checks(failed_checks, ignore_warnings): return JsonResponse({"failedChecks": failed_checks}) # Translations exist if len(translations) > 0: # Same translation exists if len(same_translations) > 0: t = same_translations[0] # If added by privileged user, approve and unfuzzy it if can_translate and (t.fuzzy or not t.approved): if not t.active: translations.filter(active=True).update(active=False) t.active = True t.approved = True t.fuzzy = False t.rejected = False t.rejected_user = None t.rejected_date = None if t.approved_user is None: t.approved_user = user t.approved_date = now t.save(failed_checks=failed_checks) log_action("translation:approved", user, translation=t) return JsonResponse({ "type": "updated", "translation": t.serialize(), "stats": TranslatedResource.objects.stats(project, paths, locale), }) # Different translation added else: t = Translation( entity=e, locale=locale, plural_form=plural_form, string=string, user=user, date=now, approved=can_translate, ) if can_translate: t.approved_user = user t.approved_date = now t.save(failed_checks=failed_checks) log_action("translation:created", user, translation=t) active_translation = e.reset_active_translation( locale=locale, plural_form=plural_form, ) return JsonResponse({ "type": "added", "translation": active_translation.serialize(), "stats": TranslatedResource.objects.stats(project, paths, locale), }) # No translations saved yet else: t = Translation( entity=e, locale=locale, plural_form=plural_form, string=string, user=user, date=now, active=True, approved=can_translate, ) if can_translate: t.approved_user = user t.approved_date = now t.save(failed_checks=failed_checks) log_action("translation:created", user, translation=t) return JsonResponse({ "type": "saved", "translation": t.serialize(), "stats": TranslatedResource.objects.stats(project, paths, locale), })
def batch_edit_translations(request): """Perform an action on a list of translations. Available actions are defined in `ACTIONS_FN_MAP`. Arguments to this view are defined in `models.BatchActionsForm`. """ form = forms.BatchActionsForm(request.POST) if not form.is_valid(): return HttpResponseBadRequest(form.errors.as_json()) locale = get_object_or_404(Locale, code=form.cleaned_data['locale']) entities = Entity.objects.filter(pk__in=form.cleaned_data['entities']) if not entities.exists(): return JsonResponse({'count': 0}) # Batch editing is only available to translators. Check if user has # translate permissions for all of the projects in passed entities. # Also make sure projects are not enabled in read-only mode for a locale. projects_pk = entities.values_list('resource__project__pk', flat=True) projects = Project.objects.filter(pk__in=projects_pk.distinct()) for project in projects: if (not request.user.can_translate(project=project, locale=locale) or readonly_exists(projects, locale)): return HttpResponseForbidden( "Forbidden: You don't have permission for batch editing") # Find all impacted active translations, including plural forms. active_translations = Translation.objects.filter( active=True, locale=locale, entity__in=entities, ) # Execute the actual action. action_function = ACTIONS_FN_MAP[form.cleaned_data['action']] action_status = action_function( form, request.user, active_translations, locale, ) if action_status.get('error'): return JsonResponse(action_status) invalid_translation_count = len( action_status.get('invalid_translation_pks', [])) if action_status['count'] == 0: return JsonResponse({ 'count': 0, 'invalid_translation_count': invalid_translation_count, }) update_stats(action_status['translated_resources'], locale) mark_changed_translation(action_status['changed_entities'], locale) # Update latest translation. if action_status['latest_translation_pk']: Translation.objects.get(pk=action_status['latest_translation_pk'] ).update_latest_translation() update_translation_memory(action_status['changed_translation_pks'], project, locale) return JsonResponse({ 'count': action_status['count'], 'invalid_translation_count': invalid_translation_count, })
def create_translation(request): """ Create a new translation. """ form = forms.CreateTranslationForm(request.POST) if not form.is_valid(): problems = [] for field, errors in form.errors.items(): problems.append('Error validating field `{0}`: "{1}"'.format( field, " ".join(errors))) return JsonResponse({ "status": False, "message": "\n".join(problems) }, status=400) entity = form.cleaned_data["entity"] string = form.cleaned_data["translation"] locale = form.cleaned_data["locale"] plural_form = form.cleaned_data["plural_form"] original = form.cleaned_data["original"] ignore_warnings = form.cleaned_data["ignore_warnings"] approve = form.cleaned_data["approve"] force_suggestions = form.cleaned_data["force_suggestions"] resources = form.cleaned_data["paths"] project = entity.resource.project # Read-only translations cannot saved if utils.readonly_exists(project, locale): return JsonResponse( { "status": False, "message": "Forbidden: This string is in read-only mode.", }, status=403, ) translations = Translation.objects.filter(entity=entity, locale=locale, plural_form=plural_form) same_translations = translations.filter(string=string) # If same translation exists in the DB, don't save it again. if same_translations: return JsonResponse({"status": False, "same": True}) # Look for failed checks. # Checks are disabled for the tutorial. use_checks = project.slug != "tutorial" user = request.user failed_checks = None if use_checks: failed_checks = run_checks( entity, locale.code, original, string, user.profile.quality_checks, ) if are_blocking_checks(failed_checks, ignore_warnings): return JsonResponse({ "status": False, "failedChecks": failed_checks }) now = timezone.now() can_translate = user.can_translate( project=project, locale=locale) and (not force_suggestions or approve) translation = Translation( entity=entity, locale=locale, plural_form=plural_form, string=string, user=user, date=now, approved=can_translate, ) if can_translate: translation.approved_user = user translation.approved_date = now translation.save(failed_checks=failed_checks) log_action("translation:created", user, translation=translation) if translations: translation = entity.reset_active_translation( locale=locale, plural_form=plural_form, ) return JsonResponse({ "status": True, "translation": translation.serialize(), "stats": TranslatedResource.objects.stats(project, resources, locale), })
def update_translation(request): """Update entity translation for the specified locale and user. Note that this view is also used to approve a translation by the old Translate app. Once we migrate to Translate.Next, we'll want to rework this view to remove the bits about approving a translation, because that has been delegated to the `approve_translation` view. """ try: entity = request.POST['entity'] string = request.POST['translation'] locale = request.POST['locale'] plural_form = request.POST['plural_form'] original = request.POST['original'] ignore_warnings = request.POST.get('ignore_warnings', 'false') == 'true' approve = request.POST.get('approve', 'false') == 'true' force_suggestions = request.POST.get('force_suggestions', 'false') == 'true' paths = request.POST.getlist('paths[]') except MultiValueDictKeyError as e: return JsonResponse( { 'status': False, 'message': 'Bad Request: {error}'.format(error=e), }, status=400) try: e = Entity.objects.get(pk=entity) except Entity.DoesNotExist as e: return JsonResponse( { 'status': False, 'message': 'Bad Request: {error}'.format(error=e), }, status=400) try: locale = Locale.objects.get(code=locale) except Locale.DoesNotExist as e: return JsonResponse( { 'status': False, 'message': 'Bad Request: {error}'.format(error=e), }, status=400) if plural_form == "-1": plural_form = None user = request.user project = e.resource.project # Read-only translations cannot saved if utils.readonly_exists(project, locale): return JsonResponse( { 'status': False, 'message': 'Forbidden: This string is in read-only mode.', }, status=403) now = timezone.now() can_translate = (request.user.can_translate(project=project, locale=locale) and (not force_suggestions or approve)) translations = Translation.objects.filter(entity=e, locale=locale, plural_form=plural_form) same_translations = translations.filter(string=string).order_by( '-active', 'rejected', '-date') # If same translation exists in the DB, don't save it again. if utils.is_same(same_translations, can_translate): return JsonResponse({ 'same': True, }) # Check for errors. # Checks are disabled for the tutorial. use_checks = project.slug != 'tutorial' if use_checks: failed_checks = run_checks( e, locale.code, original, string, user.profile.quality_checks, ) if are_blocking_checks(failed_checks, ignore_warnings): return JsonResponse({ 'failedChecks': failed_checks, }) # Translations exist if len(translations) > 0: # Same translation exists if len(same_translations) > 0: t = same_translations[0] # If added by privileged user, approve and unfuzzy it if can_translate and (t.fuzzy or not t.approved): if not t.active: translations.filter(active=True).update(active=False) t.active = True t.approved = True t.fuzzy = False t.rejected = False t.rejected_user = None t.rejected_date = None if t.approved_user is None: t.approved_user = user t.approved_date = now t.save(failed_checks=failed_checks) return JsonResponse({ 'type': 'updated', 'translation': t.serialize(), 'stats': TranslatedResource.objects.stats(project, paths, locale), }) # Different translation added else: t = Translation( entity=e, locale=locale, plural_form=plural_form, string=string, user=user, date=now, approved=can_translate, ) if can_translate: t.approved_user = user t.approved_date = now t.save(failed_checks=failed_checks) active_translation = e.reset_active_translation( locale=locale, plural_form=plural_form, ) return JsonResponse({ 'type': 'added', 'translation': active_translation.serialize(), 'stats': TranslatedResource.objects.stats(project, paths, locale), }) # No translations saved yet else: t = Translation( entity=e, locale=locale, plural_form=plural_form, string=string, user=user, date=now, active=True, approved=can_translate, ) if can_translate: t.approved_user = user t.approved_date = now t.save(failed_checks=failed_checks) return JsonResponse({ 'type': 'saved', 'translation': t.serialize(), 'stats': TranslatedResource.objects.stats(project, paths, locale), })
def approve_translation(request): """Approve given translation.""" try: t = request.POST["translation"] ignore_warnings = request.POST.get("ignore_warnings", "false") == "true" paths = request.POST.getlist("paths[]") except MultiValueDictKeyError as e: return JsonResponse( { "status": False, "message": "Bad Request: {error}".format(error=e) }, status=400, ) translation = get_object_or_404(Translation, pk=t) entity = translation.entity project = entity.resource.project locale = translation.locale user = request.user # Read-only translations cannot be approved if utils.readonly_exists(project, locale): return JsonResponse( { "status": False, "message": "Forbidden: This string is in read-only mode.", }, status=403, ) if translation.approved: return JsonResponse( { "status": False, "message": "Forbidden: This translation is already approved.", }, status=403, ) # Only privileged users can approve translations if not user.can_translate(locale, project): return JsonResponse( { "status": False, "message": "Forbidden: You don't have permission to approve this translation.", }, status=403, ) # Check for errors. # Checks are disabled for the tutorial. use_checks = project.slug != "tutorial" if use_checks: failed_checks = run_checks( entity, locale.code, entity.string, translation.string, user.profile.quality_checks, ) if are_blocking_checks(failed_checks, ignore_warnings): return JsonResponse({ "string": translation.string, "failedChecks": failed_checks }) translation.approve(user) log_action("translation:approved", user, translation=translation) active_translation = translation.entity.reset_active_translation( locale=locale, plural_form=translation.plural_form, ) return JsonResponse({ "translation": active_translation.serialize(), "stats": TranslatedResource.objects.stats(project, paths, locale), })
def reject_translation(request): """Reject given translation.""" try: t = request.POST["translation"] paths = request.POST.getlist("paths[]") except MultiValueDictKeyError as e: return JsonResponse( { "status": False, "message": "Bad Request: {error}".format(error=e) }, status=400, ) translation = get_object_or_404(Translation, pk=t) project = translation.entity.resource.project locale = translation.locale # Read-only translations cannot be rejected if utils.readonly_exists(project, locale): return JsonResponse( { "status": False, "message": "Forbidden: This string is in read-only mode.", }, status=403, ) # Non-privileged users can only reject own unapproved translations if not request.user.can_translate(locale, project): if translation.user == request.user: if translation.approved is True: return JsonResponse( { "status": False, "message": "Forbidden: You can't reject approved translations.", }, status=403, ) else: return JsonResponse( { "status": False, "message": "Forbidden: You can't reject translations from other users.", }, status=403, ) translation.reject(request.user) log_action("translation:rejected", request.user, translation=translation) active_translation = translation.entity.reset_active_translation( locale=locale, plural_form=translation.plural_form, ) return JsonResponse({ "translation": active_translation.serialize(), "stats": TranslatedResource.objects.stats(project, paths, locale), })
def approve_translation(request): """Approve given translation.""" try: t = request.POST['translation'] ignore_warnings = request.POST.get('ignore_warnings', 'false') == 'true' paths = request.POST.getlist('paths[]') except MultiValueDictKeyError as e: return JsonResponse({ 'status': False, 'message': 'Bad Request: {error}'.format(error=e), }, status=400) translation = get_object_or_404(Translation, pk=t) entity = translation.entity project = entity.resource.project locale = translation.locale user = request.user # Read-only translations cannot be approved if utils.readonly_exists(project, locale): return JsonResponse({ 'status': False, 'message': 'Forbidden: This string is in read-only mode.', }, status=403) if translation.approved: return JsonResponse({ 'status': False, 'message': 'Forbidden: This translation is already approved.', }, status=403) # Only privileged users can approve translations if not user.can_translate(locale, project): return JsonResponse({ 'status': False, 'message': "Forbidden: You don't have permission to approve this translation.", }, status=403) # Check for errors. # Checks are disabled for the tutorial. use_checks = project.slug != 'tutorial' if use_checks: failed_checks = run_checks( entity, locale.code, entity.string, translation.string, user.profile.quality_checks, ) if are_blocking_checks(failed_checks, ignore_warnings): return JsonResponse({ 'string': translation.string, 'failedChecks': failed_checks, }) translation.approve(user) active_translation = translation.entity.reset_active_translation( locale=locale, plural_form=translation.plural_form, ) return JsonResponse({ 'translation': active_translation.serialize(), 'stats': TranslatedResource.objects.stats(project, paths, locale), })
def batch_edit_translations(request): """Perform an action on a list of translations. Available actions are defined in `ACTIONS_FN_MAP`. Arguments to this view are defined in `models.BatchActionsForm`. """ form = forms.BatchActionsForm(request.POST) if not form.is_valid(): return JsonResponse( { "status": False, "message": "{error}".format( error=form.errors.as_json(escape_html=True) ), }, status=400, ) locale = get_object_or_404(Locale, code=form.cleaned_data["locale"]) entities = Entity.objects.filter(pk__in=form.cleaned_data["entities"]) if not entities.exists(): return JsonResponse({"count": 0}) # Batch editing is only available to translators. Check if user has # translate permissions for all of the projects in passed entities. # Also make sure projects are not enabled in read-only mode for a locale. projects_pk = entities.values_list("resource__project__pk", flat=True) projects = Project.objects.filter(pk__in=projects_pk.distinct()) for project in projects: if not request.user.can_translate( project=project, locale=locale ) or readonly_exists(projects, locale): return JsonResponse( { "status": False, "message": "Forbidden: You don't have permission for batch editing.", }, status=403, ) # Find all impacted active translations, including plural forms. active_translations = Translation.objects.filter( active=True, locale=locale, entity__in=entities, ) # Execute the actual action. action_function = ACTIONS_FN_MAP[form.cleaned_data["action"]] action_status = action_function(form, request.user, active_translations, locale,) if action_status.get("error"): return JsonResponse(action_status) invalid_translation_count = len(action_status.get("invalid_translation_pks", [])) if action_status["count"] == 0: return JsonResponse( {"count": 0, "invalid_translation_count": invalid_translation_count} ) tr_pks = [tr.pk for tr in action_status["translated_resources"]] TranslatedResource.objects.filter(pk__in=tr_pks).update_stats() mark_changed_translation(action_status["changed_entities"], locale) # Reset term translations for entities belonging to the Terminology project changed_entity_pks = [entity.pk for entity in action_status["changed_entities"]] terminology_entities = Entity.objects.filter( pk__in=changed_entity_pks, resource__project__slug="terminology", ) for e in terminology_entities: e.reset_term_translation(locale) # Update latest translation. if action_status["latest_translation_pk"]: Translation.objects.get( pk=action_status["latest_translation_pk"] ).update_latest_translation() update_translation_memory(action_status["changed_translation_pks"], project, locale) return JsonResponse( { "count": action_status["count"], "invalid_translation_count": invalid_translation_count, } )
def create_translation(request): """ Create a new translation. """ form = forms.CreateTranslationForm(request.POST) if not form.is_valid(): problems = [] for field, errors in form.errors.items(): problems.append( 'Error validating field `{}`: "{}"'.format(field, " ".join(errors)) ) return JsonResponse( {"status": False, "message": "\n".join(problems)}, status=400 ) entity = form.cleaned_data["entity"] string = form.cleaned_data["translation"] locale = form.cleaned_data["locale"] plural_form = form.cleaned_data["plural_form"] original = form.cleaned_data["original"] ignore_warnings = form.cleaned_data["ignore_warnings"] approve = form.cleaned_data["approve"] force_suggestions = form.cleaned_data["force_suggestions"] paths = form.cleaned_data["paths"] machinery_sources = form.cleaned_data["machinery_sources"] project = entity.resource.project # Read-only translations cannot saved if utils.readonly_exists(project, locale): return JsonResponse( { "status": False, "message": "Forbidden: This string is in read-only mode.", }, status=403, ) translations = Translation.objects.filter( entity=entity, locale=locale, plural_form=plural_form, ) same_translations = translations.filter(string=string) # If same translation exists in the DB, don't save it again. if same_translations: return JsonResponse({"status": False, "same": True}) # Look for failed checks. # Checks are disabled for the tutorial. use_checks = project.slug != "tutorial" user = request.user first_contribution = user.is_new_contributor(locale) failed_checks = None if use_checks: failed_checks = run_checks( entity, locale.code, original, string, user.profile.quality_checks, ) if are_blocking_checks(failed_checks, ignore_warnings): return JsonResponse({"status": False, "failedChecks": failed_checks}) now = timezone.now() can_translate = user.can_translate(project=project, locale=locale) and ( not force_suggestions or approve ) translation = Translation( entity=entity, locale=locale, plural_form=plural_form, string=string, user=user, date=now, approved=can_translate, machinery_sources=machinery_sources, ) if can_translate: translation.approved_user = user translation.approved_date = now translation.save(failed_checks=failed_checks) log_action(ActionLog.ActionType.TRANSLATION_CREATED, user, translation=translation) if translations: translation = entity.reset_active_translation( locale=locale, plural_form=plural_form, ) # When user makes their first contribution to the team, notify team managers if first_contribution: desc = """ <a href="{user_href}">{user}</a> has made their first contribution to <a href="{locale_href}">{locale} ({locale_code})</a>. Please welcome them to the team, and make sure to <a href="{review_href}">review their suggestions</a>. """.format( user=user.name_or_email, user_href=reverse( "pontoon.contributors.contributor.username", kwargs={ "username": user.username, }, ), locale=locale.name, locale_code=locale.code, locale_href=reverse( "pontoon.teams.team", kwargs={ "locale": locale.code, }, ), review_href=reverse( "pontoon.translate", kwargs={ "locale": locale.code, "project": project.slug, "resource": entity.resource.path, }, ) + f"?string={entity.pk}", ) for manager in locale.managers_group.user_set.filter( profile__new_contributor_notifications=True ): notify.send( sender=manager, recipient=manager, verb="has reviewed suggestions", # Triggers render of description only description=desc, ) return JsonResponse( { "status": True, "translation": translation.serialize(), "stats": TranslatedResource.objects.stats(project, paths, locale), } )