def handle_translate(request, translation, this_unit_url, next_unit_url): """Save translation or suggestion to database and backend.""" # Antispam protection antispam = AntispamForm(request.POST) if not antispam.is_valid(): # Silently redirect to next entry return HttpResponseRedirect(next_unit_url) form = TranslationForm( request.user, translation, None, request.POST ) if not form.is_valid(): show_form_errors(request, form) return None unit = form.cleaned_data['unit'] go_next = True if 'suggest' in request.POST: go_next = perform_suggestion(unit, form, request) elif not request.user.has_perm('unit.edit', unit): messages.error( request, _('Insufficient privileges for saving translations.') ) else: go_next = perform_translation(unit, form, request) # Redirect to next entry if go_next: return HttpResponseRedirect(next_unit_url) return HttpResponseRedirect(this_unit_url)
def save_zen(request, project, subproject, lang): ''' Save handler for zen mode. ''' translation = get_translation(request, project, subproject, lang) user_locked = translation.is_user_locked(request.user) form = TranslationForm(translation, None, request.POST) if not can_translate(request.user, translation): messages.error( request, _('You don\'t have privileges to save translations!') ) elif not form.is_valid(): messages.error(request, _('Failed to save translation!')) elif not user_locked: unit = form.cleaned_data['unit'] perform_translation(unit, form, request) return render( request, 'zen-response.html', {}, )
def handle_translate(translation, request, user_locked, this_unit_url, next_unit_url): ''' Saves translation or suggestion to database and backend. ''' # Antispam protection antispam = AntispamForm(request.POST) if not antispam.is_valid(): # Silently redirect to next entry return HttpResponseRedirect(next_unit_url) # Check whether translation is not outdated translation.check_sync() form = TranslationForm(translation, None, request.POST) if not form.is_valid(): return unit = form.cleaned_data['unit'] go_next = True if 'suggest' in request.POST: go_next = perform_suggestion(unit, form, request) elif (translation.is_template() and not request.user.has_perm('trans.save_template')): # Need privilege to save messages.error( request, _('You don\'t have privileges to save templates!') ) elif not request.user.has_perm('trans.save_translation'): # Need privilege to save messages.error( request, _('You don\'t have privileges to save translations!') ) elif (unit.only_vote_suggestions() and not request.user.has_perm('trans.override_suggestion')): messages.error( request, _('Only suggestions are allowed in this translation!') ) elif not user_locked: # Custom commit message message = request.POST.get('commit_message') if message and message != unit.translation.commit_message: # Commit pending changes so that they don't get new message unit.translation.commit_pending(request, request.user) # Store new commit message unit.translation.commit_message = message unit.translation.save() go_next = perform_translation(unit, form, request) # Redirect to next entry if go_next: return HttpResponseRedirect(next_unit_url) else: return HttpResponseRedirect(this_unit_url)
def save_zen(request, project, subproject, lang): """ Save handler for zen mode. """ translation = get_translation(request, project, subproject, lang) form = TranslationForm(translation, None, request.POST) if not form.is_valid(): messages.error(_("Failed to save translation!")) else: unit = form.cleaned_data["unit"] perform_translation(unit, form, request) return render(request, "zen-response.html")
def save_zen(request, project, subproject, lang): ''' Save handler for zen mode. ''' translation = get_translation(request, project, subproject, lang) form = TranslationForm(translation, None, request.POST) if not form.is_valid(): messages.error(_('Failed to save translation!')) else: unit = form.cleaned_data['unit'] perform_translation(unit, form, request) return render( request, 'zen-response.html', )
def save_zen(request, project, component, lang): """Save handler for zen mode.""" _obj, _project, unit_set = parse_params(request, project, component, lang) checksum_form = ChecksumForm(unit_set, request.POST) if not checksum_form.is_valid(): show_form_errors(request, checksum_form) return HttpResponseBadRequest("Invalid checksum") unit = checksum_form.cleaned_data["unit"] translationsum = "" form = TranslationForm(request.user, unit, request.POST) if not form.is_valid(): show_form_errors(request, form) elif not request.user.has_perm("unit.edit", unit): messages.error(request, _("Insufficient privileges for saving translations.")) else: perform_translation(unit, form, request) translationsum = hash_to_checksum(unit.get_target_hash()) response = { "messages": [], "state": "success", "translationsum": translationsum, "unit_flags": get_state_css(unit) if unit is not None else [], } storage = get_messages(request) if storage: response["messages"] = [{ "tags": m.tags, "kind": get_message_kind(m.tags), "text": m.message } for m in storage] tags = {m.tags for m in storage} if "error" in tags: response["state"] = "danger" elif "warning" in tags: response["state"] = "warning" elif "info" in tags: response["state"] = "info" return JsonResponse(data=response)
def handle_translate(translation, request, user_locked, this_unit_url, next_unit_url): """Save translation or suggestion to database and backend.""" # Antispam protection antispam = AntispamForm(request.POST) if not antispam.is_valid(): # Silently redirect to next entry return HttpResponseRedirect(next_unit_url) # Check whether translation is not outdated translation.check_sync() form = TranslationForm( request.user.profile, translation, None, request.POST ) if not form.is_valid(): show_form_errors(request, form) return unit = form.cleaned_data['unit'] go_next = True if 'suggest' in request.POST: go_next = perform_suggestion(unit, form, request) elif not can_translate(request.user, unit.translation): messages.error( request, _('You don\'t have privileges to save translations!') ) elif not user_locked: # Custom commit message message = request.POST.get('commit_message') if message is not None and message != unit.translation.commit_message: # Commit pending changes so that they don't get new message unit.translation.commit_pending(request, request.user) # Store new commit message unit.translation.commit_message = message unit.translation.save() go_next = perform_translation(unit, form, request) # Redirect to next entry if go_next: return HttpResponseRedirect(next_unit_url) else: return HttpResponseRedirect(this_unit_url)
def save_zen(request, project, subproject, lang): ''' Save handler for zen mode. ''' translation = get_translation(request, project, subproject, lang) form = TranslationForm(translation, None, request.POST) if not form.is_valid(): messages.error(request, _('Failed to save translation!')) else: unit = form.cleaned_data['unit'] perform_translation(unit, form, request) return render( request, 'zen-response.html', )
def save_zen(request, project, component, lang): """Save handler for zen mode.""" def render_mesage(message): return render_to_string( 'message.html', {'tags': message.tags, 'message': message.message} ) translation = get_translation(request, project, component, lang) form = TranslationForm( request.user, translation, None, request.POST ) translationsum = '' if not form.is_valid(): show_form_errors(request, form) elif not request.user.has_perm('unit.edit', form.cleaned_data['unit']): messages.error( request, _('Insufficient privileges for saving translations.') ) else: unit = form.cleaned_data['unit'] perform_translation(unit, form, request) translationsum = hash_to_checksum(unit.get_target_hash()) response = { 'messages': '', 'state': 'success', 'translationsum': translationsum, } storage = get_messages(request) if storage: response['messages'] = '\n'.join([render_mesage(m) for m in storage]) tags = {m.tags for m in storage} if 'error' in tags: response['state'] = 'danger' elif 'warning' in tags: response['state'] = 'warning' elif 'info' in tags: response['state'] = 'info' return JsonResponse(data=response)
def save_zen(request, project, subproject, lang): """ Save handler for zen mode. """ translation = get_translation(request, project, subproject, lang) user_locked = translation.is_user_locked(request.user) form = TranslationForm(translation, None, request.POST) if not can_translate(request.user, translation): messages.error(request, _("You don't have privileges to save translations!")) elif not form.is_valid(): messages.error(request, _("Failed to save translation!")) elif not user_locked: unit = form.cleaned_data["unit"] perform_translation(unit, form, request) return render(request, "zen-response.html", {})
def handle_translate(translation, request, user_locked, this_unit_url, next_unit_url): """ Saves translation or suggestion to database and backend. """ # Antispam protection antispam = AntispamForm(request.POST) if not antispam.is_valid(): # Silently redirect to next entry return HttpResponseRedirect(next_unit_url) # Check whether translation is not outdated translation.check_sync() form = TranslationForm(translation, None, request.POST) if not form.is_valid(): return unit = form.cleaned_data["unit"] go_next = True if "suggest" in request.POST: go_next = perform_suggestion(unit, form, request) elif not request.user.has_perm("trans.save_translation"): # Need privilege to save messages.error(request, _("You don't have privileges to save translations!")) elif unit.only_vote_suggestions() and not request.user.has_perm("trans.save_translation"): messages.error(request, _("Only suggestions are allowed in this translation!")) elif not user_locked: # Custom commit message if "commit_message" in request.POST and request.POST["commit_message"] != unit.translation.commit_message: # Commit pending changes so that they don't get new message unit.translation.commit_pending(request, request.user) # Store new commit message unit.translation.commit_message = request.POST["commit_message"] unit.translation.save() go_next = perform_translation(unit, form, request) # Redirect to next entry if go_next: return HttpResponseRedirect(next_unit_url) else: return HttpResponseRedirect(this_unit_url)
def save_zen(request, project, subproject, lang): """Save handler for zen mode.""" translation = get_translation(request, project, subproject, lang) form = TranslationForm(request.user, translation, None, request.POST) if not form.is_valid(): messages.error(request, _('Failed to save translation!')) elif not can_translate(request.user, form.cleaned_data['unit']): messages.error(request, _('Insufficient privileges for saving translations.')) else: unit = form.cleaned_data['unit'] perform_translation(unit, form, request) return render( request, 'zen-response.html', {}, )
def handle_translate(translation, request, this_unit_url, next_unit_url): """Save translation or suggestion to database and backend.""" # Antispam protection antispam = AntispamForm(request.POST) if not antispam.is_valid(): # Silently redirect to next entry return HttpResponseRedirect(next_unit_url) form = TranslationForm( request.user, translation, None, request.POST ) if not form.is_valid(): show_form_errors(request, form) return None unit = form.cleaned_data['unit'] go_next = True if 'suggest' in request.POST: go_next = perform_suggestion(unit, form, request) elif not request.user.has_perm('unit.edit', unit): messages.error( request, _('Insufficient privileges for saving translations.') ) else: # Custom commit message message = request.POST.get('commit_message') if message is not None and message != unit.translation.commit_message: # Commit pending changes so that they don't get new message unit.translation.commit_pending('commit message', request) # Store new commit message unit.translation.commit_message = message unit.translation.save() go_next = perform_translation(unit, form, request) # Redirect to next entry if go_next: return HttpResponseRedirect(next_unit_url) return HttpResponseRedirect(this_unit_url)
def save_zen(request, project, component, lang): """Save handler for zen mode.""" translation = get_translation(request, project, component, lang) form = TranslationForm(request.user, translation, None, request.POST) unit = None translationsum = '' if not form.is_valid(): show_form_errors(request, form) elif not request.user.has_perm('unit.edit', form.cleaned_data['unit']): messages.error(request, _('Insufficient privileges for saving translations.')) else: unit = form.cleaned_data['unit'] perform_translation(unit, form, request) translationsum = hash_to_checksum(unit.get_target_hash()) response = { 'messages': [], 'state': 'success', 'translationsum': translationsum, 'unit_flags': get_state_css(unit) if unit is not None else [], } storage = get_messages(request) if storage: response['messages'] = [{ 'tags': m.tags, 'text': m.message } for m in storage] tags = {m.tags for m in storage} if 'error' in tags: response['state'] = 'danger' elif 'warning' in tags: response['state'] = 'warning' elif 'info' in tags: response['state'] = 'info' return JsonResponse(data=response)
def handle_translate(translation, request, this_unit_url, next_unit_url): """Save translation or suggestion to database and backend.""" # Antispam protection antispam = AntispamForm(request.POST) if not antispam.is_valid(): # Silently redirect to next entry return HttpResponseRedirect(next_unit_url) form = TranslationForm( request.user, translation, None, request.POST ) if not form.is_valid(): show_form_errors(request, form) return None unit = form.cleaned_data['unit'] go_next = True if 'suggest' in request.POST: go_next = perform_suggestion(unit, form, request) elif not request.user.has_perm('unit.edit', unit): messages.error( request, _('Insufficient privileges for saving translations.') ) else: # Custom commit message message = request.POST.get('commit_message') if message is not None and message != unit.translation.commit_message: # Commit pending changes so that they don't get new message unit.translation.commit_pending(request) # Store new commit message unit.translation.commit_message = message unit.translation.save() go_next = perform_translation(unit, form, request) # Redirect to next entry if go_next: return HttpResponseRedirect(next_unit_url) return HttpResponseRedirect(this_unit_url)
def handle_translate(request, unit, this_unit_url, next_unit_url): """Save translation or suggestion to database and backend.""" form = TranslationForm(request.user, unit, request.POST) if not form.is_valid(): show_form_errors(request, form) return None go_next = True if "suggest" in request.POST: go_next = perform_suggestion(unit, form, request) elif not request.user.has_perm("unit.edit", unit): messages.error(request, _("Insufficient privileges for saving translations.")) else: go_next = perform_translation(unit, form, request) # Redirect to next entry if go_next: return HttpResponseRedirect(next_unit_url) return HttpResponseRedirect(this_unit_url)
def save_zen(request, project, subproject, lang): """Save handler for zen mode.""" translation = get_translation(request, project, subproject, lang) user_locked = translation.is_user_locked(request.user) form = TranslationForm(request.user.profile, translation, None, request.POST) if not can_translate(request.user, translation): messages.error(request, _('You don\'t have privileges to save translations!')) elif not form.is_valid(): messages.error(request, _('Failed to save translation!')) elif not user_locked: unit = form.cleaned_data['unit'] perform_translation(unit, form, request) return render( request, 'zen-response.html', {}, )
def get_zen_unitdata(translation, request): ''' Loads unit data for zen mode. ''' # Search results search_result = search(translation, request) # Search offset try: offset = int(request.GET.get('offset', 0)) except ValueError: offset = 0 # Handle redirects if isinstance(search_result, HttpResponse): return search_result, None search_result['last_section'] = offset + 20 >= len(search_result['ids']) search_result['offset'] = offset units = translation.unit_set.filter( pk__in=search_result['ids'][offset:offset + 20] ) unitdata = [ { 'unit': unit, 'secondary': ( unit.get_secondary_units(request.user) if request.user.is_authenticated and request.user.profile.secondary_in_zen else None ), 'form': TranslationForm( translation, unit, tabindex=100 + (unit.position * 10), ), 'offset': offset + pos, } for pos, unit in enumerate(units) ] return search_result, unitdata
def translate(request, project, subproject, lang): ''' Generic entry point for translating, suggesting and searching. ''' translation = get_translation(request, project, subproject, lang) # Check locks user_locked = translation.is_user_locked(request) project_locked = translation.subproject.locked own_lock = translation.lock_user == request.user locked = project_locked or user_locked # Search results search_result = search(translation, request) # Handle redirects if isinstance(search_result, HttpResponse): return search_result # Get numer of results num_results = len(search_result['ids']) # Search offset try: offset = int(request.GET.get('offset', search_result.get('offset', 0))) except ValueError: offset = 0 # Check boundaries if offset < 0 or offset >= num_results: messages.info(request, _('You have reached end of translating.')) # Delete search del request.session['search_%s' % search_result['search_id']] # Redirect to translation return redirect(translation) # Some URLs we will most likely use base_unit_url = '%s?sid=%s&offset=' % ( translation.get_translate_url(), search_result['search_id'], ) this_unit_url = base_unit_url + str(offset) next_unit_url = base_unit_url + str(offset + 1) response = None # Any form submitted? if request.method == 'POST' and not project_locked: # Handle accepting/deleting suggestions if ('accept' not in request.POST and 'delete' not in request.POST and 'upvote' not in request.POST and 'downvote' not in request.POST): response = handle_translate( translation, request, user_locked, this_unit_url, next_unit_url ) elif not locked: response = handle_suggestions( translation, request, this_unit_url ) # Handle translation merging elif 'merge' in request.GET and not locked: response = handle_merge( translation, request, next_unit_url ) # Handle reverting elif 'revert' in request.GET and not locked: response = handle_revert( translation, request, this_unit_url ) # Pass possible redirect further if response is not None: return response # Grab actual unit try: unit = translation.unit_set.get(pk=search_result['ids'][offset]) except Unit.DoesNotExist: # Can happen when using SID for other translation messages.error(request, _('Invalid search string!')) return redirect(translation) # Show secondary languages for logged in users if request.user.is_authenticated(): secondary = unit.get_secondary_units(request.user) else: secondary = None # Spam protection antispam = AntispamForm() # Prepare form form = TranslationForm(translation, unit) return render( request, 'translate.html', { 'this_unit_url': this_unit_url, 'first_unit_url': base_unit_url + '0', 'last_unit_url': base_unit_url + str(num_results - 1), 'next_unit_url': next_unit_url, 'prev_unit_url': base_unit_url + str(offset - 1), 'object': translation, 'project': translation.subproject.project, 'unit': unit, 'others': Unit.objects.same(unit).exclude(target=unit.target), 'total': translation.unit_set.all().count(), 'search_id': search_result['search_id'], 'search_query': search_result['query'], 'offset': offset, 'filter_name': search_result['name'], 'filter_count': num_results, 'filter_pos': offset + 1, 'form': form, 'antispam': antispam, 'comment_form': CommentForm(), 'search_form': SearchForm(), 'update_lock': own_lock, 'secondary': secondary, 'locked': locked, 'user_locked': user_locked, 'project_locked': project_locked, 'glossary': Dictionary.objects.get_words(unit), } )
def translate(request, project, component, lang): """Generic entry point for translating, suggesting and searching.""" obj, project, unit_set = parse_params(request, project, component, lang) # Search results search_result = search(obj, unit_set, request) # Handle redirects if isinstance(search_result, HttpResponse): return search_result # Get numer of results num_results = len(search_result["ids"]) # Search offset offset = search_result["offset"] # Checksum unit access checksum_form = ChecksumForm(unit_set, request.GET or request.POST) if checksum_form.is_valid(): unit = checksum_form.cleaned_data["unit"] try: offset = search_result["ids"].index(unit.id) + 1 except ValueError: messages.warning(request, _("No string matched your search!")) return redirect(obj) else: # Check boundaries if not 0 < offset <= num_results: messages.info(request, _("The translation has come to an end.")) # Delete search del request.session[search_result["key"]] return redirect(obj) # Grab actual unit try: unit = unit_set.get(pk=search_result["ids"][offset - 1]) except Unit.DoesNotExist: # Can happen when using SID for other translation messages.error(request, _("Invalid search string!")) return redirect(obj) # Check locks locked = unit.translation.component.locked # Some URLs we will most likely use base_unit_url = "{}?{}&offset=".format(obj.get_translate_url(), search_result["url"]) this_unit_url = base_unit_url + str(offset) next_unit_url = base_unit_url + str(offset + 1) response = None # Any form submitted? if "skip" in request.POST: return redirect(next_unit_url) if request.method == "POST" and "merge" not in request.POST: if (not locked and "accept" not in request.POST and "accept_edit" not in request.POST and "delete" not in request.POST and "spam" not in request.POST and "upvote" not in request.POST and "downvote" not in request.POST): # Handle translation response = handle_translate(request, unit, this_unit_url, next_unit_url) elif not locked or "delete" in request.POST or "spam" in request.POST: # Handle accepting/deleting suggestions response = handle_suggestions(request, unit, this_unit_url, next_unit_url) # Handle translation merging elif "merge" in request.POST and not locked: response = handle_merge(unit, request, next_unit_url) # Handle reverting elif "revert" in request.GET and not locked: response = handle_revert(unit, request, this_unit_url) # Pass possible redirect further if response is not None: return response # Show secondary languages for signed in users if request.user.is_authenticated: secondary = unit.get_secondary_units(request.user) else: secondary = None # Spam protection antispam = AntispamForm() # Prepare form form = TranslationForm(request.user, unit) sort = get_sort_name(request) return render( request, "translate.html", { "this_unit_url": this_unit_url, "first_unit_url": base_unit_url + "1", "last_unit_url": base_unit_url + str(num_results), "next_unit_url": next_unit_url, "prev_unit_url": base_unit_url + str(offset - 1), "object": obj, "project": project, "unit": unit, "nearby": unit.nearby(request.user.profile.nearby_strings), "nearby_keys": unit.nearby_keys(request.user.profile.nearby_strings), "others": get_other_units(unit), "search_url": search_result["url"], "search_items": search_result["items"], "search_query": search_result["query"], "offset": offset, "sort_name": sort["name"], "sort_query": sort["query"], "filter_name": search_result["name"], "filter_count": num_results, "filter_pos": offset, "form": form, "antispam": antispam, "comment_form": CommentForm( project, initial={ "scope": "global" if unit.is_source else "translation" }, ), "context_form": ContextForm(instance=unit.source_unit, user=request.user), "search_form": search_result["form"].reset_offset(), "secondary": secondary, "locked": locked, "glossary": Term.objects.get_terms(unit), "addterm_form": TermForm(project), "last_changes": unit.change_set.prefetch().order()[:10], "screenshots": (unit.source_unit.screenshots.all() | unit.screenshots.all()).order, "last_changes_url": urlencode(unit.translation.get_reverse_url_kwargs()), "display_checks": list(get_display_checks(unit)), "machinery_services": json.dumps(list(MACHINE_TRANSLATION_SERVICES.keys())), }, )
def translate(request, project, subproject, lang): obj = get_object_or_404(Translation, language__code = lang, subproject__slug = subproject, subproject__project__slug = project, enabled = True) if obj.subproject.locked: messages.error(request, _('This translation is currently locked for updates!')) if request.user.is_authenticated(): profile = request.user.get_profile() else: profile = None secondary = None unit = None rqtype, direction, pos, search_query, search_exact, search_source, search_target, search_context, search_url = parse_search_url(request) # Any form submitted? if request.method == 'POST': form = TranslationForm(request.POST) if form.is_valid() and not obj.subproject.locked: # Check whether translation is not outdated obj.check_sync() try: try: unit = Unit.objects.get(checksum = form.cleaned_data['checksum'], translation = obj) except Unit.MultipleObjectsReturned: # Possible temporary inconsistency caused by ongoing update of repo, # let's pretend everyting is okay unit = Unit.objects.filter(checksum = form.cleaned_data['checksum'], translation = obj)[0] if 'suggest' in request.POST: # Handle suggesion saving user = request.user if isinstance(user, AnonymousUser): user = None if form.cleaned_data['target'] == len(form.cleaned_data['target']) * ['']: messages.error(request, _('Your suggestion is empty!')) # Stay on same entry return HttpResponseRedirect('%s?type=%s&pos=%d&dir=stay%s' % ( obj.get_translate_url(), rqtype, pos, search_url )) Suggestion.objects.create( target = join_plural(form.cleaned_data['target']), checksum = unit.checksum, language = unit.translation.language, project = unit.translation.subproject.project, user = user) # Update suggestion stats if profile is not None: profile.suggested += 1 profile.save() elif not request.user.is_authenticated(): # We accept translations only from authenticated messages.error(request, _('You need to log in to be able to save translations!')) elif not request.user.has_perm('trans.save_translation'): # Need privilege to save messages.error(request, _('You don\'t have privileges to save translations!')) else: # Remember old checks oldchecks = set(unit.active_checks().values_list('check', flat = True)) # Update unit and save it unit.target = join_plural(form.cleaned_data['target']) unit.fuzzy = form.cleaned_data['fuzzy'] unit.save_backend(request) # Update stats profile.translated += 1 profile.save() # Get new set of checks newchecks = set(unit.active_checks().values_list('check', flat = True)) # Did we introduce any new failures? if newchecks > oldchecks: # Show message to user messages.error(request, _('Some checks have failed on your translation!')) # Stay on same entry return HttpResponseRedirect('%s?type=%s&pos=%d&dir=stay%s' % ( obj.get_translate_url(), rqtype, pos, search_url )) # Redirect to next entry return HttpResponseRedirect('%s?type=%s&pos=%d%s' % ( obj.get_translate_url(), rqtype, pos, search_url )) except Unit.DoesNotExist: logger.error('message %s disappeared!', form.cleaned_data['checksum']) messages.error(request, _('Message you wanted to translate is no longer available!')) # Handle translation merging if 'merge' in request.GET: if not request.user.has_perm('trans.save_translation'): # Need privilege to save messages.error(request, _('You don\'t have privileges to save translations!')) else: try: mergeform = MergeForm(request.GET) if mergeform.is_valid(): try: unit = Unit.objects.get(checksum = mergeform.cleaned_data['checksum'], translation = obj) except Unit.MultipleObjectsReturned: # Possible temporary inconsistency caused by ongoing update of repo, # let's pretend everyting is okay unit = Unit.objects.filter(checksum = mergeform.cleaned_data['checksum'], translation = obj)[0] merged = Unit.objects.get(pk = mergeform.cleaned_data['merge']) if unit.checksum != merged.checksum: messages.error(request, _('Can not merge different messages!')) else: unit.target = merged.target unit.fuzzy = merged.fuzzy unit.save_backend(request) # Update stats profile.translated += 1 profile.save() # Redirect to next entry return HttpResponseRedirect('%s?type=%s&pos=%d%s' % ( obj.get_translate_url(), rqtype, pos, search_url )) except Unit.DoesNotExist: logger.error('message %s disappeared!', form.cleaned_data['checksum']) messages.error(request, _('Message you wanted to translate is no longer available!')) # Handle accepting/deleting suggestions if not obj.subproject.locked and ('accept' in request.GET or 'delete' in request.GET): # Check for authenticated users if not request.user.is_authenticated(): messages.error(request, _('You need to log in to be able to manage suggestions!')) return HttpResponseRedirect('%s?type=%s&pos=%d&dir=stay%s' % ( obj.get_translate_url(), rqtype, pos, search_url )) # Parse suggestion ID if 'accept' in request.GET: if not request.user.has_perm('trans.accept_suggestion'): messages.error(request, _('You do not have privilege to accept suggestions!')) return HttpResponseRedirect('%s?type=%s&pos=%d&dir=stay%s' % ( obj.get_translate_url(), rqtype, pos, search_url )) sugid = request.GET['accept'] else: if not request.user.has_perm('trans.delete_suggestion'): messages.error(request, _('You do not have privilege to delete suggestions!')) return HttpResponseRedirect('%s?type=%s&pos=%d&dir=stay%s' % ( obj.get_translate_url(), rqtype, pos, search_url )) sugid = request.GET['delete'] try: sugid = int(sugid) suggestion = Suggestion.objects.get(pk = sugid) except: suggestion = None if suggestion is not None: if 'accept' in request.GET: # Accept suggesiont suggestion.accept(request) # Delete suggestion in both cases (accepted ones are no longer needed) suggestion.delete() else: messages.error(request, _('Invalid suggestion!')) # Redirect to same entry for possible editing return HttpResponseRedirect('%s?type=%s&pos=%d&dir=stay%s' % ( obj.get_translate_url(), rqtype, pos, search_url )) reviewform = ReviewForm(request.GET) if reviewform.is_valid(): allunits = obj.unit_set.review(reviewform.cleaned_data['date'], request.user) # Review if direction == 'stay': units = allunits.filter(position = pos) elif direction == 'back': units = allunits.filter(position__lt = pos).order_by('-position') else: units = allunits.filter(position__gt = pos) elif search_query != '': # Apply search conditions if search_exact: query = Q() if search_source: query |= Q(source = search_query) if search_target: query |= Q(target = search_query) if search_context: query |= Q(context = search_query) allunits = obj.unit_set.filter(query) else: allunits = obj.unit_set.search(search_query, search_source, search_context, search_target) if direction == 'stay': units = obj.unit_set.filter(position = pos) elif direction == 'back': units = allunits.filter(position__lt = pos).order_by('-position') else: units = allunits.filter(position__gt = pos) else: allunits = obj.unit_set.filter_type(rqtype) # What unit set is about to show if direction == 'stay': units = obj.unit_set.filter(position = pos) elif direction == 'back': units = allunits.filter(position__lt = pos).order_by('-position') else: units = allunits.filter(position__gt = pos) # If we failed to get unit above or on no POST if unit is None: # Grab actual unit try: unit = units[0] except IndexError: messages.info(request, _('You have reached end of translating.')) return HttpResponseRedirect(obj.get_absolute_url()) # Show secondary languages for logged in users if profile: secondary = Unit.objects.filter( checksum = unit.checksum, translated = True, translation__subproject__project = unit.translation.subproject.project, translation__language__in = profile.secondary_languages.exclude(id = unit.translation.language.id) ) # distinct('target') works with Django 1.4 so let's emulate that # based on presumption we won't get too many results targets = {} res = [] for s in secondary: if s.target in targets: continue targets[s.target] = 1 res.append(s) secondary = res # Prepare form form = TranslationForm(initial = { 'checksum': unit.checksum, 'target': (unit.translation.language, unit.get_target_plurals()), 'fuzzy': unit.fuzzy, }) total = obj.unit_set.all().count() filter_count = allunits.count() return render_to_response('translate.html', RequestContext(request, { 'object': obj, 'unit': unit, 'changes': unit.change_set.all()[:10], 'total': total, 'type': rqtype, 'filter_name': get_filter_name(rqtype, search_query), 'filter_count': filter_count, 'filter_pos': filter_count + 1 - units.count(), 'form': form, 'target_language': obj.language.code, 'secondary': secondary, 'search_query': search_query, 'search_url': search_url, 'search_query': search_query, 'search_source': bool2str(search_source), 'search_exact': bool2str(search_exact), 'search_target': bool2str(search_target), 'search_context': bool2str(search_context), }))
def translate(request, project, component, lang): """Generic entry point for translating, suggesting and searching.""" translation = get_translation(request, project, component, lang) # Check locks locked = translation.component.locked # Search results search_result = search(translation, request) # Handle redirects if isinstance(search_result, HttpResponse): return search_result # Get numer of results num_results = len(search_result['ids']) # Search offset offset = search_result['offset'] # Checksum unit access if search_result['checksum']: try: unit = translation.unit_set.get(id_hash=search_result['checksum']) offset = search_result['ids'].index(unit.id) + 1 except (Unit.DoesNotExist, ValueError): messages.warning(request, _('No string matched your search!')) return redirect(translation) # Check boundaries if not 0 < offset <= num_results: messages.info(request, _('The translation has come to an end.')) # Delete search del request.session[search_result['key']] # Redirect to translation return redirect(translation) # Some URLs we will most likely use base_unit_url = '{0}?{1}&offset='.format( translation.get_translate_url(), search_result['url'] ) this_unit_url = base_unit_url + str(offset) next_unit_url = base_unit_url + str(offset + 1) response = None # Any form submitted? if 'skip' in request.POST: return redirect(next_unit_url) if request.method == 'POST': if (not locked and 'accept' not in request.POST and 'accept_edit' not in request.POST and 'delete' not in request.POST and 'spam' not in request.POST and 'upvote' not in request.POST and 'downvote' not in request.POST): # Handle translation response = handle_translate( request, translation, this_unit_url, next_unit_url ) elif not locked or 'delete' in request.POST or 'spam' in request.POST: # Handle accepting/deleting suggestions response = handle_suggestions( translation, request, this_unit_url, next_unit_url, ) # Handle translation merging elif 'merge' in request.GET and not locked: response = handle_merge( translation, request, next_unit_url ) # Handle reverting elif 'revert' in request.GET and not locked: response = handle_revert( translation, request, this_unit_url ) # Pass possible redirect further if response is not None: return response # Grab actual unit try: unit = translation.unit_set.get(pk=search_result['ids'][offset - 1]) except Unit.DoesNotExist: # Can happen when using SID for other translation messages.error(request, _('Invalid search string!')) return redirect(translation) # Show secondary languages for logged in users if request.user.is_authenticated: secondary = unit.get_secondary_units(request.user) else: secondary = None # Spam protection antispam = AntispamForm() # Prepare form form = TranslationForm(request.user, translation, unit) return render( request, 'translate.html', { 'this_unit_url': this_unit_url, 'first_unit_url': base_unit_url + '1', 'last_unit_url': base_unit_url + str(num_results), 'next_unit_url': next_unit_url, 'prev_unit_url': base_unit_url + str(offset - 1), 'object': translation, 'project': translation.component.project, 'unit': unit, 'others': get_other_units(unit), 'total': translation.unit_set.all().count(), 'search_url': search_result['url'], 'search_items': search_result['items'], 'search_query': search_result['query'], 'offset': offset, 'filter_name': search_result['name'], 'filter_count': num_results, 'filter_pos': offset, 'form': form, 'antispam': antispam, 'comment_form': CommentForm(), 'search_form': search_result['form'].reset_offset(), 'secondary': secondary, 'locked': locked, 'glossary': Dictionary.objects.get_words(unit), 'addword_form': InlineWordForm(), } )
def translate(request, project, component, lang): """Generic entry point for translating, suggesting and searching.""" translation = get_translation(request, project, component, lang) # Check locks locked = translation.component.locked # Search results search_result = search(translation, request) # Handle redirects if isinstance(search_result, HttpResponse): return search_result # Get numer of results num_results = len(search_result["ids"]) # Search offset offset = search_result["offset"] # Checksum unit access if search_result["checksum"]: try: unit = translation.unit_set.get(id_hash=search_result["checksum"]) offset = search_result["ids"].index(unit.id) + 1 except (Unit.DoesNotExist, ValueError): messages.warning(request, _("No string matched your search!")) return redirect(translation) # Check boundaries if not 0 < offset <= num_results: messages.info(request, _("The translation has come to an end.")) # Delete search del request.session[search_result["key"]] # Redirect to translation return redirect(translation) # Some URLs we will most likely use base_unit_url = "{0}?{1}&offset=".format(translation.get_translate_url(), search_result["url"]) this_unit_url = base_unit_url + str(offset) next_unit_url = base_unit_url + str(offset + 1) response = None # Any form submitted? if "skip" in request.POST: return redirect(next_unit_url) if request.method == "POST": if (not locked and "accept" not in request.POST and "accept_edit" not in request.POST and "delete" not in request.POST and "spam" not in request.POST and "upvote" not in request.POST and "downvote" not in request.POST): # Handle translation response = handle_translate(request, translation, this_unit_url, next_unit_url) elif not locked or "delete" in request.POST or "spam" in request.POST: # Handle accepting/deleting suggestions response = handle_suggestions(translation, request, this_unit_url, next_unit_url) # Handle translation merging elif "merge" in request.GET and not locked: response = handle_merge(translation, request, next_unit_url) # Handle reverting elif "revert" in request.GET and not locked: response = handle_revert(translation, request, this_unit_url) # Pass possible redirect further if response is not None: return response # Grab actual unit try: unit = translation.unit_set.get(pk=search_result["ids"][offset - 1]) except Unit.DoesNotExist: # Can happen when using SID for other translation messages.error(request, _("Invalid search string!")) return redirect(translation) # Show secondary languages for signed in users if request.user.is_authenticated: secondary = unit.get_secondary_units(request.user) else: secondary = None # Spam protection antispam = AntispamForm() # Prepare form form = TranslationForm(request.user, translation, unit) sort = get_sort_name(request) return render( request, "translate.html", { "this_unit_url": this_unit_url, "first_unit_url": base_unit_url + "1", "last_unit_url": base_unit_url + str(num_results), "next_unit_url": next_unit_url, "prev_unit_url": base_unit_url + str(offset - 1), "object": translation, "project": translation.component.project, "unit": unit, "others": get_other_units(unit), "search_url": search_result["url"], "search_items": search_result["items"], "search_query": search_result["query"], "offset": offset, "sort_name": sort["name"], "sort_query": sort["query"], "filter_name": search_result["name"], "filter_count": num_results, "filter_pos": offset, "form": form, "antispam": antispam, "comment_form": CommentForm( translation, initial={ "scope": "global" if unit.translation.is_source else "translation" }, ), "context_form": ContextForm(instance=unit.source_info, user=request.user), "search_form": search_result["form"].reset_offset(), "secondary": secondary, "locked": locked, "glossary": Dictionary.objects.get_words(unit), "addword_form": InlineWordForm(), "last_changes": unit.change_set.prefetch().order()[:10], "last_changes_url": urlencode(unit.translation.get_reverse_url_kwargs()), }, )