Example #1
0
def search(request):
    """
    Performs site-wide search on units.
    """
    search_form = SearchForm(request.GET)
    context = {
        'search_form': search_form,
    }

    if search_form.is_valid():
        units = Unit.objects.search(
            None,
            search_form.cleaned_data,
        ).select_related(
            'translation',
        )

        # Filter results by ACL
        acl_projects, filtered = Project.objects.get_acl_status(request.user)
        if filtered:
            units = units.filter(
                translation__subproject__project__in=acl_projects
            )

        limit = request.GET.get('limit', 50)
        page = request.GET.get('page', 1)

        paginator = Paginator(units, limit)

        try:
            units = paginator.page(page)
        except PageNotAnInteger:
            # If page is not an integer, deliver first page.
            units = paginator.page(1)
        except EmptyPage:
            # If page is out of range (e.g. 9999), deliver last page of
            # results.
            units = paginator.page(paginator.num_pages)

        context['page_obj'] = units
        context['title'] = _('Search for %s') % (
            search_form.cleaned_data['q']
        )
        context['query_string'] = search_form.urlencode()
        context['search_query'] = search_form.cleaned_data['q']
    else:
        messages.error(request, _('Invalid search query!'))

    return render(
        request,
        'search.html',
        context
    )
Example #2
0
def search(translation, request):
    """Perform search or returns cached search results."""
    # Possible new search
    form = SearchForm(request.GET)

    # Process form
    if not form.is_valid():
        show_form_errors(request, form)

    search_result = {
        'form': form,
        'offset': form.cleaned_data.get('offset', 0),
        'checksum': form.cleaned_data.get('checksum'),
    }
    search_url = form.urlencode()
    session_key = 'search_{0}_{1}'.format(translation.pk, search_url)

    if session_key in request.session and 'offset' in request.GET:
        search_result.update(request.session[session_key])
        return search_result

    allunits = translation.unit_set.search(
        form.cleaned_data,
        translation=translation,
    )

    search_query = form.get_search_query()
    name = form.get_name()

    # Grab unit IDs
    unit_ids = list(allunits.values_list('id', flat=True))

    # Check empty search results
    if not unit_ids:
        messages.warning(request, _('No string matched your search!'))
        return redirect(translation)

    # Remove old search results
    cleanup_session(request.session)

    store_result = {
        'query': search_query,
        'url': search_url,
        'key': session_key,
        'name': force_text(name),
        'ids': unit_ids,
        'ttl': int(time.time()) + 86400,
    }
    request.session[session_key] = store_result

    search_result.update(store_result)
    return search_result
Example #3
0
def download_translation_format(request, project, component, lang, fmt):
    obj = get_translation(request, project, component, lang)

    form = SearchForm(request.GET)
    if form.is_valid():
        units = obj.unit_set.search(
            form.cleaned_data,
            translation=obj,
        )
    else:
        units = obj.unit_set.all()

    return download_translation_file(obj, fmt, units)
Example #4
0
def parse_search_url(request):
    # Check where we are
    rqtype = request.REQUEST.get('type', 'all')
    direction = request.REQUEST.get('dir', 'forward')
    pos = request.REQUEST.get('pos', '-1')
    try:
        pos = int(pos)
    except:
        pos = -1

    # Pre-process search form
    if request.method == 'POST':
        s = SearchForm(request.POST)
    else:
        s = SearchForm(request.GET)
    if s.is_valid():
        search_query = s.cleaned_data['q']
        search_exact = s.cleaned_data['exact']
        search_source = s.cleaned_data['src']
        search_target = s.cleaned_data['tgt']
        search_context = s.cleaned_data['ctx']
        search_url = '&q=%s&src=%s&tgt=%s&ctx=%s&exact=%s' % (
            search_query,
            bool2str(search_source),
            bool2str(search_target),
            bool2str(search_context),
            bool2str(search_exact),
        )
    else:
        search_query = ''
        search_exact = False
        search_source = True
        search_target = True
        search_context = True
        search_url = ''

    if 'date' in request.REQUEST:
        search_url += '&date=%s' % request.REQUEST['date']

    return (
        rqtype,
        direction,
        pos,
        search_query,
        search_exact,
        search_source,
        search_target,
        search_context,
        search_url
        )
Example #5
0
def search(request):
    '''
    Performs sitewide search on units.
    '''
    search_form = SearchForm(request.GET)
    context = {
        'search_form': search_form,
    }

    if search_form.is_valid():
        units = Unit.objects.search(
            search_form.cleaned_data,
        ).select_related(
            'translation',
        )

        limit = request.GET.get('limit', 50)
        page = request.GET.get('page', 1)

        paginator = Paginator(units, limit)

        try:
            units = paginator.page(page)
        except PageNotAnInteger:
            # If page is not an integer, deliver first page.
            units = paginator.page(1)
        except EmptyPage:
            # If page is out of range (e.g. 9999), deliver last page of
            # results.
            units = paginator.page(paginator.num_pages)

        context['units'] = units
        context['title'] = _('Search for %s') % (
            search_form.cleaned_data['q']
        )
        context['query_string'] = search_form.urlencode()
        context['search_query'] = search_form.cleaned_data['q']
    else:
        messages.error(request, _('Invalid search query!'))

    return render(
        request,
        'search.html',
        context
    )
Example #6
0
def show_translation(request, project, component, lang):
    obj = get_translation(request, project, component, lang)
    obj.stats.ensure_all()
    last_changes = Change.objects.prefetch().filter(translation=obj)[:10]
    user = request.user

    # Get form
    form = get_upload_form(user, obj)

    # Search form for everybody
    search_form = SearchForm()

    # Review form for logged in users
    if user.is_anonymous:
        review_form = None
    else:
        review_form = ReviewForm(initial={'exclude_user': user.username})

    return render(
        request, 'translation.html', {
            'allow_index':
            True,
            'object':
            obj,
            'project':
            obj.component.project,
            'form':
            form,
            'download_form':
            DownloadForm(),
            'autoform':
            optional_form(
                AutoForm, user, 'translation.auto', obj, user=user, obj=obj),
            'search_form':
            search_form,
            'review_form':
            review_form,
            'replace_form':
            optional_form(ReplaceForm, user, 'unit.edit', obj),
            'mass_state_form':
            optional_form(BulkStateForm,
                          user,
                          'translation.auto',
                          obj,
                          user=user,
                          obj=obj),
            'new_unit_form':
            NewUnitForm(
                user,
                initial={
                    'value': Unit(translation=obj, id_hash=-1),
                },
            ),
            'whiteboard_form':
            optional_form(WhiteboardForm, user, 'component.edit', obj),
            'delete_form':
            optional_form(DeleteForm, user, 'translation.delete', obj,
                          obj=obj),
            'last_changes':
            last_changes,
            'last_changes_url':
            urlencode(obj.get_reverse_url_kwargs()),
            'show_only_component':
            True,
            'other_translations':
            prefetch_stats(Translation.objects.prefetch().filter(
                component__project=obj.component.project,
                language=obj.language,
            ).exclude(pk=obj.pk)),
            'exporters':
            list_exporters(),
        })
Example #7
0
def show_translation(request, project, subproject, lang):
    obj = get_translation(request, project, subproject, lang)
    last_changes = Change.objects.for_translation(obj)[:10]

    # Get form
    form = get_upload_form(request.user, obj)

    # Is user allowed to do automatic translation?
    if can_automatic_translation(request.user, obj.subproject.project):
        autoform = AutoForm(obj, request.user)
    else:
        autoform = None

    # Search form for everybody
    search_form = SearchForm()

    # Review form for logged in users
    if request.user.is_anonymous:
        review_form = None
    else:
        review_form = ReviewForm(
            initial={'exclude_user': request.user.username})

    replace_form = None
    if can_translate(request.user, translation=obj):
        replace_form = ReplaceForm()

    return render(
        request, 'translation.html', {
            'allow_index':
            True,
            'object':
            obj,
            'project':
            obj.subproject.project,
            'form':
            form,
            'autoform':
            autoform,
            'search_form':
            search_form,
            'review_form':
            review_form,
            'replace_form':
            replace_form,
            'new_unit_form':
            NewUnitForm(),
            'last_changes':
            last_changes,
            'last_changes_url':
            urlencode(obj.get_kwargs()),
            'show_only_component':
            True,
            'pending_fulltext':
            obj.unit_set.filter(id__in=IndexUpdate.objects.filter(
                to_delete=False).values('unitid')).exists(),
            'other_translations':
            Translation.objects.prefetch().filter(
                subproject__project=obj.subproject.project,
                language=obj.language,
            ).exclude(pk=obj.pk),
        })
Example #8
0
def show_project(request, project):
    obj = get_project(request, project)
    user = request.user

    dict_langs = Language.objects.filter(dictionary__project=obj).annotate(
        Count('dictionary'))

    last_changes = Change.objects.prefetch().filter(project=obj)[:10]

    language_stats = sort_unicode(obj.stats.get_language_stats(),
                                  lambda x: force_text(x.language.name))

    # Paginate components of project.
    all_components = obj.component_set.select_related().order_by(
        *Component.ordering)
    components = prefetch_stats(get_paginator(request, all_components))

    return render(
        request, 'project.html', {
            'allow_index':
            True,
            'object':
            obj,
            'project':
            obj,
            'dicts':
            dict_langs,
            'last_changes':
            last_changes,
            'last_changes_url':
            urlencode({'project': obj.slug}),
            'language_stats':
            language_stats,
            'language_count':
            Language.objects.filter(
                translation__component__project=obj).distinct().count(),
            'search_form':
            SearchForm(),
            'whiteboard_form':
            optional_form(WhiteboardForm, user, 'project.edit', obj),
            'delete_form':
            optional_form(DeleteForm, user, 'project.edit', obj, obj=obj),
            'rename_form':
            optional_form(ProjectRenameForm,
                          user,
                          'project.edit',
                          obj,
                          request=request,
                          instance=obj),
            'replace_form':
            optional_form(ReplaceForm, user, 'unit.edit', obj),
            'mass_state_form':
            optional_form(BulkStateForm,
                          user,
                          'translation.auto',
                          obj,
                          user=user,
                          obj=obj),
            'components':
            components,
            'licenses':
            ', '.join(
                sorted(set([x.license for x in all_components if x.license]))),
        })
Example #9
0
def show_translation(request, project, component, lang):
    obj = get_translation(request, project, component, lang)
    obj.stats.ensure_all()
    last_changes = Change.objects.prefetch().order().filter(
        translation=obj)[:10]
    user = request.user

    # Get form
    form = get_upload_form(user, obj)

    search_form = SearchForm(request.user)

    return render(
        request,
        'translation.html',
        {
            'allow_index':
            True,
            'object':
            obj,
            'project':
            obj.component.project,
            'form':
            form,
            'download_form':
            DownloadForm(auto_id="id_dl_%s"),
            'autoform':
            optional_form(
                AutoForm, user, 'translation.auto', obj, obj=obj.component),
            'search_form':
            search_form,
            'replace_form':
            optional_form(ReplaceForm, user, 'unit.edit', obj),
            'bulk_state_form':
            optional_form(
                BulkEditForm,
                user,
                'translation.auto',
                obj,
                user=user,
                obj=obj,
                project=obj.component.project,
                auto_id="id_bulk_%s",
            ),
            'new_unit_form':
            NewUnitForm(user,
                        initial={'value': Unit(translation=obj, id_hash=-1)}),
            'whiteboard_form':
            optional_form(WhiteboardForm, user, 'component.edit', obj),
            'delete_form':
            optional_form(DeleteForm, user, 'translation.delete', obj,
                          obj=obj),
            'last_changes':
            last_changes,
            'last_changes_url':
            urlencode(obj.get_reverse_url_kwargs()),
            'other_translations':
            prefetch_stats(Translation.objects.prefetch().filter(
                component__project=obj.component.project,
                language=obj.language).exclude(pk=obj.pk)),
            'exporters':
            list_exporters(obj),
        },
    )
Example #10
0
def dashboard_user(request):
    """Home page of Weblate for authenticated user."""
    user = request.user

    user_has_languages = user.is_authenticated and user.profile.languages.exists(
    )

    user_translations = get_user_translations(request, user,
                                              user_has_languages)

    suggestions = get_suggestions(request, user, user_has_languages,
                                  user_translations)

    usersubscriptions = None

    componentlists = fetch_componentlists(request.user, user_translations)

    active_tab_id = user.profile.dashboard_view
    active_tab_slug = Profile.DASHBOARD_SLUGS.get(active_tab_id)
    if (active_tab_id == Profile.DASHBOARD_COMPONENT_LIST
            and user.profile.dashboard_component_list):
        active_tab_slug = user.profile.dashboard_component_list.tab_slug()

    if user.is_authenticated:
        usersubscriptions = prefetch_stats(
            user_translations.filter_access(user).filter(
                component__project__in=user.watched_projects))
        usersubscriptions = get_paginator(request, usersubscriptions)

        if user.profile.hide_completed:
            usersubscriptions = get_untranslated(usersubscriptions)
            for componentlist in componentlists:
                componentlist.translations = get_untranslated(
                    prefetch_stats(componentlist.translations))
        usersubscriptions = translation_prefetch_tasks(usersubscriptions)

    return render(
        request,
        "dashboard/user.html",
        {
            "allow_index":
            True,
            "suggestions":
            suggestions,
            "search_form":
            SearchForm(request.user),
            "usersubscriptions":
            usersubscriptions,
            "componentlists":
            componentlists,
            "all_componentlists":
            prefetch_stats(
                ComponentList.objects.filter(
                    components__project_id__in=request.user.allowed_project_ids
                ).distinct().order()),
            "active_tab_slug":
            active_tab_slug,
            "reports_form":
            ReportsForm(),
        },
    )
Example #11
0
def show_project(request, project):
    obj = get_project(request, project)

    dict_langs = Language.objects.filter(dictionary__project=obj).annotate(
        Count('dictionary'))

    if request.method == 'POST' and can_edit_project(request.user, obj):
        settings_form = ProjectSettingsForm(request.POST, instance=obj)
        if settings_form.is_valid():
            settings_form.save()
            messages.success(request, _('Settings saved'))
            return redirect(obj)
        else:
            messages.error(
                request,
                _('Invalid settings, please check the form for errors!'))
    else:
        settings_form = ProjectSettingsForm(instance=obj)

    last_changes = Change.objects.for_project(obj)[:10]

    language_stats = sort_unicode(get_per_language_stats(obj),
                                  lambda tup: force_text(tup[0]))

    language_stats = [(tup[0], translation_percent(tup[1], tup[2]),
                       translation_percent(tup[3], tup[4]))
                      for tup in language_stats]

    if can_translate(request.user, project=obj):
        replace_form = ReplaceForm()
    else:
        replace_form = None

    return render(
        request, 'project.html', {
            'allow_index':
            True,
            'object':
            obj,
            'project':
            obj,
            'dicts':
            dict_langs,
            'last_changes':
            last_changes,
            'last_changes_url':
            urlencode({'project': obj.slug}),
            'settings_form':
            settings_form,
            'language_stats':
            language_stats,
            'unit_count':
            Unit.objects.filter(translation__subproject__project=obj).count(),
            'words_count':
            obj.get_total_words(),
            'language_count':
            Language.objects.filter(
                translation__subproject__project=obj).distinct().count(),
            'strings_count':
            obj.get_total(),
            'source_words_count':
            obj.get_source_words(),
            'search_form':
            SearchForm(),
            'replace_form':
            replace_form,
        })
Example #12
0
def show_project(request, project):
    obj = get_project(request, project)
    user = request.user

    last_changes = Change.objects.prefetch().order().filter(project=obj)[:10]

    language_stats = sort_unicode(obj.stats.get_language_stats(),
                                  lambda x: force_text(x.language))

    # Paginate components of project.
    all_components = obj.component_set.prefetch().order()
    components = prefetch_stats(get_paginator(request, all_components))

    return render(
        request,
        'project.html',
        {
            'allow_index':
            True,
            'object':
            obj,
            'project':
            obj,
            'last_changes':
            last_changes,
            'reports_form':
            ReportsForm(),
            'last_changes_url':
            urlencode({'project': obj.slug}),
            'language_stats':
            language_stats,
            'search_form':
            SearchForm(request.user),
            'whiteboard_form':
            optional_form(WhiteboardForm, user, 'project.edit', obj),
            'delete_form':
            optional_form(DeleteForm, user, 'project.edit', obj, obj=obj),
            'rename_form':
            optional_form(
                ProjectRenameForm,
                user,
                'project.edit',
                obj,
                request=request,
                instance=obj,
            ),
            'replace_form':
            optional_form(ReplaceForm, user, 'unit.edit', obj),
            'bulk_state_form':
            optional_form(
                BulkEditForm,
                user,
                'translation.auto',
                obj,
                user=user,
                obj=obj,
                project=obj,
                auto_id="id_bulk_%s",
            ),
            'components':
            components,
            'licenses':
            obj.component_set.exclude(license='').order_by('license'),
        },
    )
Example #13
0
def search(request, project=None, component=None, lang=None):
    """Perform site-wide search on units."""
    is_ratelimited = not check_rate_limit("search", request)
    search_form = SearchForm(user=request.user, data=request.GET)
    sort = get_sort_name(request)
    context = {"search_form": search_form}
    if component:
        obj = get_component(request, project, component)
        context["component"] = obj
        context["project"] = obj.project
        context["back_url"] = obj.get_absolute_url()
    elif project:
        obj = get_project(request, project)
        context["project"] = obj
        context["back_url"] = obj.get_absolute_url()
    else:
        obj = None
        context["back_url"] = None
    if lang:
        s_language = get_object_or_404(Language, code=lang)
        context["language"] = s_language
        if obj:
            if component:
                context["back_url"] = obj.translation_set.get(
                    language=s_language).get_absolute_url()
            else:
                context["back_url"] = reverse("project-language",
                                              kwargs={
                                                  "project": project,
                                                  "lang": lang
                                              })
        else:
            context["back_url"] = s_language.get_absolute_url()

    if not is_ratelimited and request.GET and search_form.is_valid():
        # This is ugly way to hide query builder when showing results
        search_form = SearchForm(user=request.user,
                                 data=request.GET,
                                 show_builder=False)
        search_form.is_valid()
        # Filter results by ACL
        if component:
            units = Unit.objects.filter(translation__component=obj)
        elif project:
            units = Unit.objects.filter(translation__component__project=obj)
        else:
            units = Unit.objects.filter_access(request.user)
        units = units.search(search_form.cleaned_data.get("q", "")).distinct()
        if lang:
            units = units.filter(translation__language=context["language"])

        units = get_paginator(request,
                              units.order_by_request(search_form.cleaned_data))
        # Rebuild context from scratch here to get new form
        context = {
            "search_form": search_form,
            "show_results": True,
            "page_obj": units,
            "title": _("Search for %s") % (search_form.cleaned_data["q"]),
            "query_string": search_form.urlencode(),
            "search_query": search_form.cleaned_data["q"],
            "search_items": search_form.items(),
            "filter_name": search_form.get_name(),
            "sort_name": sort["name"],
            "sort_query": sort["query"],
        }
    elif is_ratelimited:
        messages.error(request,
                       _("Too many search queries, please try again later."))
    elif request.GET:
        messages.error(request, _("Invalid search query!"))
        show_form_errors(request, search_form)

    return render(request, "search.html", context)
Example #14
0
def show_translation(request, project, component, lang):
    obj = get_translation(request, project, component, lang)
    obj.stats.ensure_all()
    last_changes = Change.objects.prefetch().order().filter(
        translation=obj)[:10]
    user = request.user

    # Get form
    form = get_upload_form(user, obj)

    search_form = SearchForm(request.user)

    # Translations to same language from other components in this project
    other_translations = prefetch_stats(
        list(Translation.objects.prefetch().filter(
            component__project=obj.component.project,
            language=obj.language).exclude(pk=obj.pk)))

    # Include ghost translations for other components, this
    # adds quick way to create transaltions in other components
    existing = {
        translation.component.slug
        for translation in other_translations
    }
    existing.add(obj.component.slug)
    for test_component in obj.component.project.component_set.filter_access(
            user).exclude(slug__in=existing):
        if test_component.can_add_new_language(user):
            other_translations.append(
                GhostTranslation(test_component, obj.language))

    return render(
        request,
        "translation.html",
        {
            "allow_index":
            True,
            "object":
            obj,
            "project":
            obj.component.project,
            "form":
            form,
            "download_form":
            DownloadForm(auto_id="id_dl_%s"),
            "autoform":
            optional_form(
                AutoForm, user, "translation.auto", obj, obj=obj.component),
            "search_form":
            search_form,
            "replace_form":
            optional_form(ReplaceForm, user, "unit.edit", obj),
            "bulk_state_form":
            optional_form(
                BulkEditForm,
                user,
                "translation.auto",
                obj,
                user=user,
                obj=obj,
                project=obj.component.project,
                auto_id="id_bulk_%s",
            ),
            "new_unit_form":
            NewUnitForm(user,
                        initial={"value": Unit(translation=obj, id_hash=-1)}),
            "announcement_form":
            optional_form(AnnouncementForm, user, "component.edit", obj),
            "delete_form":
            optional_form(TranslationDeleteForm,
                          user,
                          "translation.delete",
                          obj,
                          obj=obj),
            "last_changes":
            last_changes,
            "last_changes_url":
            urlencode(obj.get_reverse_url_kwargs()),
            "other_translations":
            other_translations,
            "exporters":
            EXPORTERS.list_exporters(obj),
        },
    )
Example #15
0
def show_translation(request, project, component, lang):
    obj = get_translation(request, project, component, lang)
    obj.stats.ensure_all()
    last_changes = Change.objects.for_translation(obj)[:10]

    # Get form
    form = get_upload_form(request.user, obj)

    # Is user allowed to do automatic translation?
    if not request.user.has_perm('translation.auto', obj):
        mass_state_form = MassStateForm(request.user, obj)
    else:
        mass_state_form = None

    # Is user allowed to do automatic translation?
    if not request.user.has_perm('translation.auto', obj):
        autoform = AutoForm(obj, request.user)
    else:
        autoform = None

    # Search form for everybody
    search_form = SearchForm()

    # Review form for logged in users
    if request.user.is_anonymous:
        review_form = None
    else:
        review_form = ReviewForm(
            initial={'exclude_user': request.user.username})

    if not request.user.has_perm('unit.edit', obj):
        replace_form = ReplaceForm()
    else:
        replace_form = None

    return render(
        request, 'translation.html', {
            'allow_index':
            True,
            'object':
            obj,
            'project':
            obj.component.project,
            'form':
            form,
            'autoform':
            autoform,
            'search_form':
            search_form,
            'review_form':
            review_form,
            'replace_form':
            replace_form,
            'mass_state_form':
            mass_state_form,
            'new_unit_form':
            NewUnitForm(
                request.user,
                initial={
                    'value': Unit(translation=obj, id_hash=-1),
                },
            ),
            'last_changes':
            last_changes,
            'last_changes_url':
            urlencode(obj.get_kwargs()),
            'show_only_component':
            True,
            'pending_fulltext':
            obj.unit_set.filter(id__in=IndexUpdate.objects.filter(
                to_delete=False).values('unitid')).exists(),
            'other_translations':
            prefetch_stats(Translation.objects.prefetch().filter(
                component__project=obj.component.project,
                language=obj.language,
            ).exclude(pk=obj.pk)),
        })
Example #16
0
def search(translation, request):
    """Perform search or returns cached search results."""
    # Possible new search
    search_form = SearchForm(request.GET)
    review_form = ReviewForm(request.GET)

    # Process form
    if 'date' in request.GET:
        if review_form.is_valid():
            form = review_form
        else:
            show_form_errors(request, review_form)
            # Use blank form
            form = SearchForm([])
            form.is_valid()
    elif search_form.is_valid():
        form = search_form
    else:
        show_form_errors(request, search_form)
        # Use blank form
        form = SearchForm([])
        form.is_valid()

    search_result = {
        'form': form,
        'offset': form.cleaned_data['offset'],
        'checksum': form.cleaned_data['checksum'],
    }
    search_url = form.urlencode()
    session_key = 'search_{0}_{1}'.format(translation.pk, search_url)

    if session_key in request.session and 'offset' in request.GET:
        search_result.update(request.session[session_key])
        return search_result

    if form.cleaned_data['type'] == 'review':
        allunits = translation.unit_set.review(form.cleaned_data['date'],
                                               request.user)
    else:
        allunits = translation.unit_set.search(
            translation,
            form.cleaned_data,
        )
        if form.cleaned_data['type'] == 'random':
            allunits = allunits[:25]

    search_query = form.get_search_query()
    name = form.get_name()

    # Grab unit IDs
    unit_ids = list(allunits.values_list('id', flat=True))

    # Check empty search results
    if len(unit_ids) == 0:
        messages.warning(request, _('No string matched your search!'))
        return redirect(translation)

    # Remove old search results
    cleanup_session(request.session)

    store_result = {
        'query': search_query,
        'url': search_url,
        'key': session_key,
        'name': force_text(name),
        'ids': unit_ids,
        'ttl': int(time.time()) + 86400,
    }
    request.session[session_key] = store_result

    search_result.update(store_result)
    return search_result
Example #17
0
def search(translation, request):
    """Perform search or returns cached search results."""
    # Possible new search
    search_form = SearchForm(request.GET)
    review_form = ReviewForm(request.GET)

    # Process form
    if 'date' in request.GET:
        if review_form.is_valid():
            form = review_form
        else:
            show_form_errors(request, review_form)
            # Use blank form
            form = SearchForm([])
            form.is_valid()
    elif search_form.is_valid():
        form = search_form
    else:
        show_form_errors(request, search_form)
        # Use blank form
        form = SearchForm([])
        form.is_valid()

    search_result = {
        'form': form,
        'offset': form.cleaned_data['offset'],
        'checksum': form.cleaned_data['checksum'],
    }
    search_url = form.urlencode()
    session_key = 'search_{0}_{1}'.format(translation.pk, search_url)

    if session_key in request.session:
        search_result.update(request.session[session_key])
        return search_result

    if form.cleaned_data['type'] == 'review':
        allunits = translation.unit_set.review(
            form.cleaned_data['date'],
            request.user
        )
    else:
        allunits = translation.unit_set.search(
            translation,
            form.cleaned_data,
        )
        if form.cleaned_data['type'] == 'random':
            allunits = allunits[:25]

    search_query = form.get_search_query()
    name = form.get_name()

    # Grab unit IDs
    unit_ids = list(allunits.values_list('id', flat=True))

    # Check empty search results
    if len(unit_ids) == 0:
        messages.warning(request, _('No string matched your search!'))
        return redirect(translation)

    # Remove old search results
    cleanup_session(request.session)

    store_result = {
        'query': search_query,
        'url': search_url,
        'key': session_key,
        'name': force_text(name),
        'ids': unit_ids,
        'ttl': int(time.time()) + 86400,
    }
    request.session[session_key] = store_result

    search_result.update(store_result)
    return search_result
Example #18
0
def show_project(request, lang, project):
    try:
        language_object = Language.objects.get(code=lang)
    except Language.DoesNotExist:
        language_object = Language.objects.fuzzy_get(lang)
        if isinstance(language_object, Language):
            return redirect(language_object)
        raise Http404("No Language matches the given query.")

    project_object = get_project(request, project)
    obj = ProjectLanguage(project_object, language_object)
    user = request.user

    last_changes = Change.objects.last_changes(user).filter(
        language=language_object, project=project_object)[:10]

    translations = list(obj.translation_set)

    # Add ghost translations
    if user.is_authenticated:
        existing = {translation.component.slug for translation in translations}
        for component in project_object.child_components:
            if component.slug in existing:
                continue
            if component.can_add_new_language(user, fast=True):
                translations.append(
                    GhostTranslation(component, language_object))

    return render(
        request,
        "language-project.html",
        {
            "allow_index":
            True,
            "language":
            language_object,
            "project":
            project_object,
            "object":
            obj,
            "last_changes":
            last_changes,
            "last_changes_url":
            urlencode({
                "lang": language_object.code,
                "project": project_object.slug
            }),
            "translations":
            translations,
            "title":
            f"{project_object} - {language_object}",
            "search_form":
            SearchForm(user, language=language_object),
            "licenses":
            project_object.component_set.exclude(
                license="").order_by("license"),
            "language_stats":
            project_object.stats.get_single_language_stats(language_object),
            "delete_form":
            optional_form(ProjectLanguageDeleteForm,
                          user,
                          "translation.delete",
                          obj,
                          obj=obj),
        },
    )
Example #19
0
def search(request, project=None, component=None, lang=None):
    """Perform site-wide search on units."""
    is_ratelimited = not check_rate_limit("search", request)
    search_form = SearchForm(request.user, request.GET)
    context = {"search_form": search_form}
    if component:
        obj = get_component(request, project, component)
        context["component"] = obj
        context["project"] = obj.project
        context["back_url"] = obj.get_absolute_url()
    elif project:
        obj = get_project(request, project)
        context["project"] = obj
        context["back_url"] = obj.get_absolute_url()
    else:
        obj = None
        context["back_url"] = None
    if lang:
        s_language = get_object_or_404(Language, code=lang)
        context["language"] = s_language
        if obj:
            if component:
                context["back_url"] = obj.translation_set.get(
                    language=s_language).get_absolute_url()
            else:
                context["back_url"] = reverse("project-language",
                                              kwargs={
                                                  "project": project,
                                                  "lang": lang
                                              })
        else:
            context["back_url"] = s_language.get_absolute_url()

    if not is_ratelimited and request.GET and search_form.is_valid():
        # Filter results by ACL
        if component:
            units = Unit.objects.filter(translation__component=obj)
        elif project:
            units = Unit.objects.filter(translation__component__project=obj)
        else:
            units = Unit.objects.filter(
                translation__component__project_id__in=request.user.
                allowed_project_ids)
        units = units.search(search_form.cleaned_data.get("q", "")).distinct()
        if lang:
            units = units.filter(translation__language=context["language"])

        units = get_paginator(request, units.order())

        context["show_results"] = True
        context["page_obj"] = units
        context["title"] = _("Search for %s") % (search_form.cleaned_data["q"])
        context["query_string"] = search_form.urlencode()
        context["search_query"] = search_form.cleaned_data["q"]
    elif is_ratelimited:
        messages.error(request,
                       _("Too many search queries, please try again later."))
    elif request.GET:
        messages.error(request, _("Invalid search query!"))
        show_form_errors(request, search_form)

    return render(request, "search.html", context)
Example #20
0
def dashboard_user(request):
    """Home page of Weblate showing list of projects, stats
    and user links if logged in.
    """

    user = request.user

    user_translations = get_user_translations(request, user)

    suggestions = get_suggestions(request, user, user_translations)

    usersubscriptions = None

    componentlists = list(
        ComponentList.objects.filter(show_dashboard=True,
                                     components__project__in=request.user.
                                     allowed_projects).distinct().order())
    for componentlist in componentlists:
        componentlist.translations = prefetch_stats(
            user_translations.filter(
                component__in=componentlist.components.all()))
    # Filter out component lists with translations
    # This will remove the ones where user doesn't have access to anything
    componentlists = [c for c in componentlists if c.translations]

    active_tab_id = user.profile.dashboard_view
    active_tab_slug = Profile.DASHBOARD_SLUGS.get(active_tab_id)
    if (active_tab_id == Profile.DASHBOARD_COMPONENT_LIST
            and user.profile.dashboard_component_list):
        active_tab_slug = user.profile.dashboard_component_list.tab_slug()

    if user.is_authenticated:
        # Ensure ACL filtering applies (user could have been removed
        # from the project meanwhile)
        watched_projects = user.allowed_projects.filter(profile=user.profile)

        usersubscriptions = user_translations.filter(
            component__project__in=watched_projects)

        if user.profile.hide_completed:
            usersubscriptions = get_untranslated(usersubscriptions)
            for componentlist in componentlists:
                componentlist.translations = get_untranslated(
                    componentlist.translations)
        usersubscriptions = prefetch_stats(usersubscriptions)

    return render(
        request, 'dashboard/user.html', {
            'allow_index':
            True,
            'suggestions':
            suggestions,
            'search_form':
            SearchForm(request.user),
            'usersubscriptions':
            get_paginator(request, usersubscriptions),
            'componentlists':
            componentlists,
            'all_componentlists':
            prefetch_stats(
                ComponentList.objects.filter(
                    components__project__in=request.user.allowed_projects).
                distinct().order()),
            'active_tab_slug':
            active_tab_slug,
            'reports_form':
            ReportsForm(),
        })
Example #21
0
def show_component(request, project, component):
    obj = get_component(request, project, component)
    user = request.user

    last_changes = Change.objects.prefetch().order().filter(component=obj)[:10]

    translations = prefetch_stats(list(obj.translation_set.prefetch()))

    # Show ghost translations for user languages
    if obj.can_add_new_language(request.user):
        existing = {translation.language.code for translation in translations}
        for language in user.profile.languages.all():
            if language.code in existing:
                continue
            translations.append(GhostTranslation(obj, language))

    return render(
        request,
        "component.html",
        {
            "allow_index":
            True,
            "object":
            obj,
            "project":
            obj.project,
            "translations":
            sort_objects(translations),
            "reports_form":
            ReportsForm(),
            "last_changes":
            last_changes,
            "last_changes_url":
            urlencode({
                "component": obj.slug,
                "project": obj.project.slug
            }),
            "replace_form":
            optional_form(ReplaceForm, user, "unit.edit", obj),
            "bulk_state_form":
            optional_form(
                BulkEditForm,
                user,
                "translation.auto",
                obj,
                user=user,
                obj=obj,
                project=obj.project,
                auto_id="id_bulk_%s",
            ),
            "announcement_form":
            optional_form(AnnouncementForm, user, "component.edit", obj),
            "delete_form":
            optional_form(
                ComponentDeleteForm, user, "component.edit", obj, obj=obj),
            "rename_form":
            optional_form(
                ComponentRenameForm,
                user,
                "component.edit",
                obj,
                request=request,
                instance=obj,
            ),
            "move_form":
            optional_form(
                ComponentMoveForm,
                user,
                "component.edit",
                obj,
                request=request,
                instance=obj,
            ),
            "search_form":
            SearchForm(request.user),
            "alerts":
            obj.all_alerts,
        },
    )
Example #22
0
def home(request):
    """
    Home page of Weblate showing list of projects, stats
    and user links if logged in.
    """

    if 'show_set_password' in request.session:
        messages.warning(
            request,
            _(
                'You have activated your account, now you should set '
                'the password to be able to login next time.'
            )
        )
        return redirect('password')

    wb_messages = WhiteboardMessage.objects.order_by(
        'message')

    projects = Project.objects.all_acl(request.user)
    if projects.count() == 1:
        projects = SubProject.objects.filter(
            project=projects[0]
        ).select_related()

    # Warn about not filled in username (usually caused by migration of
    # users from older system
    if not request.user.is_anonymous() and request.user.first_name == '':
        messages.warning(
            request,
            _('Please set your full name in your profile.')
        )

    # Load user translations if user is authenticated
    usertranslations = None
    if request.user.is_authenticated():
        usertranslations = Translation.objects.filter(
            language__in=request.user.profile.languages.all()
        ).order_by(
            'subproject__project__name', 'subproject__name'
        ).select_related()

    # Some stats
    top_translations = Profile.objects.order_by('-translated')[:10]
    top_suggestions = Profile.objects.order_by('-suggested')[:10]
    last_changes = Change.objects.last_changes(request.user)[:10]

    return render(
        request,
        'index.html',
        {
            'projects': projects,
            'top_translations': top_translations.select_related('user'),
            'top_suggestions': top_suggestions.select_related('user'),
            'last_changes': last_changes,
            'last_changes_rss': reverse('rss'),
            'last_changes_url': '',
            'usertranslations': usertranslations,
            'search_form': SearchForm(),
            'whiteboard_messages': wb_messages,
        }
    )
Example #23
0
def show_project(request, project):
    obj = get_project(request, project)
    user = request.user

    last_changes = Change.objects.prefetch().order().filter(project=obj)[:10]

    language_stats = sort_unicode(obj.stats.get_language_stats(),
                                  lambda x: force_str(x.language))

    # Paginate components of project.
    all_components = obj.component_set.prefetch().order()
    components = prefetch_stats(get_paginator(request, all_components))

    return render(
        request,
        "project.html",
        {
            "allow_index":
            True,
            "object":
            obj,
            "project":
            obj,
            "last_changes":
            last_changes,
            "reports_form":
            ReportsForm(),
            "last_changes_url":
            urlencode({"project": obj.slug}),
            "language_stats":
            language_stats,
            "search_form":
            SearchForm(request.user),
            "announcement_form":
            optional_form(AnnouncementForm, user, "project.edit", obj),
            "delete_form":
            optional_form(
                ProjectDeleteForm, user, "project.edit", obj, obj=obj),
            "rename_form":
            optional_form(
                ProjectRenameForm,
                user,
                "project.edit",
                obj,
                request=request,
                instance=obj,
            ),
            "replace_form":
            optional_form(ReplaceForm, user, "unit.edit", obj),
            "bulk_state_form":
            optional_form(
                BulkEditForm,
                user,
                "translation.auto",
                obj,
                user=user,
                obj=obj,
                project=obj,
                auto_id="id_bulk_%s",
            ),
            "components":
            components,
            "licenses":
            obj.component_set.exclude(license="").order_by("license"),
        },
    )
Example #24
0
def show_subproject(request, project, subproject):
    obj = get_subproject(request, project, subproject)

    last_changes = Change.objects.for_component(obj)[:10]

    if (request.method == 'POST'
            and can_edit_subproject(request.user, obj.project)):
        settings_form = SubprojectSettingsForm(request.POST, instance=obj)
        if settings_form.is_valid():
            settings_form.save()
            messages.success(request, _('Settings saved'))
            return redirect(obj)
        else:
            messages.error(
                request,
                _('Invalid settings, please check the form for errors!'))
    else:
        settings_form = SubprojectSettingsForm(instance=obj)

    try:
        sample = obj.translation_set.all()[0]
        source_words = sample.total_words
        total_strings = sample.total
    except IndexError:
        source_words = 0
        total_strings = 0

    if can_translate(request.user, project=obj.project):
        replace_form = ReplaceForm()
    else:
        replace_form = None

    return render(
        request, 'subproject.html', {
            'allow_index':
            True,
            'object':
            obj,
            'project':
            obj.project,
            'translations':
            sort_objects(obj.translation_set.enabled()),
            'show_language':
            1,
            'reports_form':
            ReportsForm(),
            'last_changes':
            last_changes,
            'last_changes_url':
            urlencode({
                'subproject': obj.slug,
                'project': obj.project.slug
            }),
            'settings_form':
            settings_form,
            'unit_count':
            Unit.objects.filter(translation__subproject=obj).count(),
            'words_count':
            obj.get_total_words(),
            'language_count':
            Language.objects.filter(
                translation__subproject=obj).distinct().count(),
            'strings_count':
            total_strings,
            'source_words_count':
            source_words,
            'replace_form':
            replace_form,
            'search_form':
            SearchForm(),
        })
Example #25
0
def search(request, project=None, component=None, lang=None):
    """Perform site-wide search on units."""
    is_ratelimited = not check_rate_limit('search', request)
    search_form = SearchForm(request.user, request.GET)
    context = {'search_form': search_form}
    if component:
        obj = get_component(request, project, component)
        context['component'] = obj
        context['project'] = obj.project
        context['back_url'] = obj.get_absolute_url()
    elif project:
        obj = get_project(request, project)
        context['project'] = obj
        context['back_url'] = obj.get_absolute_url()
    else:
        obj = None
        context['back_url'] = None
    if lang:
        s_language = get_object_or_404(Language, code=lang)
        context['language'] = s_language
        if obj:
            if component:
                context['back_url'] = obj.translation_set.get(
                    language=s_language).get_absolute_url()
            else:
                context['back_url'] = reverse('project-language',
                                              kwargs={
                                                  'project': project,
                                                  'lang': lang
                                              })
        else:
            context['back_url'] = s_language.get_absolute_url()

    if not is_ratelimited and request.GET and search_form.is_valid():
        # Filter results by ACL
        if component:
            units = Unit.objects.filter(translation__component=obj)
        elif project:
            units = Unit.objects.filter(translation__component__project=obj)
        else:
            allowed_projects = request.user.allowed_projects
            units = Unit.objects.filter(
                translation__component__project__in=allowed_projects)
        units = units.search(search_form.cleaned_data.get("q", ""))
        if lang:
            units = units.filter(translation__language=context['language'])

        units = get_paginator(request, units.order())

        context['show_results'] = True
        context['page_obj'] = units
        context['title'] = _('Search for %s') % (search_form.cleaned_data['q'])
        context['query_string'] = search_form.urlencode()
        context['search_query'] = search_form.cleaned_data['q']
    elif is_ratelimited:
        messages.error(request,
                       _('Too many search queries, please try again later.'))
    elif request.GET:
        messages.error(request, _('Invalid search query!'))
        show_form_errors(request, search_form)

    return render(request, 'search.html', context)
Example #26
0
def show_component(request, project, component):
    obj = get_component(request, project, component)
    user = request.user

    last_changes = Change.objects.prefetch().order().filter(component=obj)[:10]

    return render(
        request,
        'component.html',
        {
            'allow_index':
            True,
            'object':
            obj,
            'project':
            obj.project,
            'translations':
            sort_objects(prefetch_stats(obj.translation_set.prefetch())),
            'reports_form':
            ReportsForm(),
            'last_changes':
            last_changes,
            'last_changes_url':
            urlencode({
                'component': obj.slug,
                'project': obj.project.slug
            }),
            'language_count':
            Language.objects.filter(
                translation__component=obj).distinct().count(),
            'replace_form':
            optional_form(ReplaceForm, user, 'unit.edit', obj),
            'bulk_state_form':
            optional_form(
                BulkEditForm,
                user,
                'translation.auto',
                obj,
                user=user,
                obj=obj,
                project=obj.project,
                auto_id="id_bulk_%s",
            ),
            'whiteboard_form':
            optional_form(WhiteboardForm, user, 'component.edit', obj),
            'delete_form':
            optional_form(DeleteForm, user, 'component.edit', obj, obj=obj),
            'rename_form':
            optional_form(
                ComponentRenameForm,
                user,
                'component.edit',
                obj,
                request=request,
                instance=obj,
            ),
            'move_form':
            optional_form(
                ComponentMoveForm,
                user,
                'component.edit',
                obj,
                request=request,
                instance=obj,
            ),
            'search_form':
            SearchForm(request.user),
            'alerts':
            obj.all_alerts,
        },
    )
Example #27
0
def dashboard_user(request):
    """Home page of Weblate for authenticated user."""
    user = request.user

    user_has_languages = user.is_authenticated and user.profile.languages.exists()

    user_translations = get_user_translations(request, user, user_has_languages)

    suggestions = get_suggestions(request, user, user_has_languages, user_translations)

    usersubscriptions = None

    componentlists = list(
        ComponentList.objects.filter(
            show_dashboard=True,
            components__project_id__in=request.user.allowed_project_ids,
        )
        .distinct()
        .order()
    )
    for componentlist in componentlists:
        componentlist.translations = prefetch_stats(
            user_translations.filter(component__in=componentlist.components.all())
        )
    # Filter out component lists with translations
    # This will remove the ones where user doesn't have access to anything
    componentlists = [c for c in componentlists if c.translations]

    active_tab_id = user.profile.dashboard_view
    active_tab_slug = Profile.DASHBOARD_SLUGS.get(active_tab_id)
    if (
        active_tab_id == Profile.DASHBOARD_COMPONENT_LIST
        and user.profile.dashboard_component_list
    ):
        active_tab_slug = user.profile.dashboard_component_list.tab_slug()

    if user.is_authenticated:
        usersubscriptions = user_translations.filter(
            component__project__in=user.watched_projects
        )

        if user.profile.hide_completed:
            usersubscriptions = get_untranslated(usersubscriptions)
            for componentlist in componentlists:
                componentlist.translations = get_untranslated(
                    componentlist.translations
                )
        usersubscriptions = prefetch_stats(usersubscriptions)

    return render(
        request,
        "dashboard/user.html",
        {
            "allow_index": True,
            "suggestions": suggestions,
            "search_form": SearchForm(request.user),
            "usersubscriptions": get_paginator(request, usersubscriptions),
            "componentlists": componentlists,
            "all_componentlists": prefetch_stats(
                ComponentList.objects.filter(
                    components__project_id__in=request.user.allowed_project_ids
                )
                .distinct()
                .order()
            ),
            "active_tab_slug": active_tab_slug,
            "reports_form": ReportsForm(),
        },
    )
Example #28
0
def search(translation, request):
    '''
    Performs search or returns cached search results.
    '''

    # Already performed search
    if 'sid' in request.GET:
        # Grab from session storage
        search_id = 'search_%s' % request.GET['sid']

        # Check if we know the search
        if search_id not in request.session:
            messages.error(request, _('Invalid search string!'))
            return redirect(translation)

        search_result = copy.copy(request.session[search_id])
        if 'params' in search_result:
            search_result['form'] = SearchForm(search_result['params'])
        else:
            search_result['form'] = SearchForm()

        return search_result

    # Possible new search
    search_form = SearchForm(request.GET)
    review_form = ReviewForm(request.GET)

    search_query = None
    if 'date' in request.GET:
        if review_form.is_valid():
            # Review
            allunits = translation.unit_set.review(
                review_form.cleaned_data['date'],
                request.user
            )

            formatted_date = formats.date_format(
                review_form.cleaned_data['date'],
                'SHORT_DATE_FORMAT'
            )
            name = _('Review of translations since %s') % formatted_date
        else:
            show_form_errors(request, review_form)

            # Filtering by type
            allunits = translation.unit_set.all()
            name = _('All strings')
    elif search_form.is_valid():
        # Apply search conditions
        allunits = translation.unit_set.search(
            translation,
            search_form.cleaned_data,
        )

        search_query = search_form.cleaned_data['q']
        name = search_form.get_name()
    else:
        # Error reporting
        show_form_errors(request, search_form)

        # Filtering by type
        allunits = translation.unit_set.all()
        name = _('All strings')

    # Grab unit IDs
    unit_ids = list(allunits.values_list('id', flat=True))

    # Check empty search results
    if len(unit_ids) == 0:
        messages.warning(request, _('No string matched your search!'))
        return redirect(translation)

    # Checksum unit access
    offset = 0
    if 'checksum' in request.GET:
        try:
            unit = allunits.filter(checksum=request.GET['checksum'])[0]
            offset = unit_ids.index(unit.id)
        except (Unit.DoesNotExist, IndexError):
            messages.warning(request, _('No string matched your search!'))
            return redirect(translation)

    # Remove old search results
    cleanup_session(request.session)

    # Store in cache and return
    search_id = str(uuid.uuid1())
    search_result = {
        'params': request.GET,
        'query': search_query,
        'name': force_text(name),
        'ids': unit_ids,
        'search_id': search_id,
        'ttl': int(time.time()) + 86400,
        'offset': offset,
    }

    request.session['search_%s' % search_id] = search_result

    search_result = copy.copy(search_result)
    search_result['form'] = search_form
    return search_result
Example #29
0
def show_component(request, project, component):
    obj = get_component(request, project, component)
    user = request.user

    last_changes = Change.objects.prefetch().order().filter(component=obj)[:10]

    return render(
        request,
        "component.html",
        {
            "allow_index":
            True,
            "object":
            obj,
            "project":
            obj.project,
            "translations":
            sort_objects(prefetch_stats(obj.translation_set.prefetch())),
            "reports_form":
            ReportsForm(),
            "last_changes":
            last_changes,
            "last_changes_url":
            urlencode({
                "component": obj.slug,
                "project": obj.project.slug
            }),
            "language_count":
            Language.objects.filter(
                translation__component=obj).distinct().count(),
            "replace_form":
            optional_form(ReplaceForm, user, "unit.edit", obj),
            "bulk_state_form":
            optional_form(
                BulkEditForm,
                user,
                "translation.auto",
                obj,
                user=user,
                obj=obj,
                project=obj.project,
                auto_id="id_bulk_%s",
            ),
            "whiteboard_form":
            optional_form(WhiteboardForm, user, "component.edit", obj),
            "delete_form":
            optional_form(DeleteForm, user, "component.edit", obj, obj=obj),
            "rename_form":
            optional_form(
                ComponentRenameForm,
                user,
                "component.edit",
                obj,
                request=request,
                instance=obj,
            ),
            "move_form":
            optional_form(
                ComponentMoveForm,
                user,
                "component.edit",
                obj,
                request=request,
                instance=obj,
            ),
            "search_form":
            SearchForm(request.user),
            "alerts":
            obj.all_alerts,
        },
    )
Example #30
0
def show_translation(request, project, component, lang):
    obj = get_translation(request, project, component, lang)
    obj.stats.ensure_all()
    last_changes = Change.objects.prefetch().order().filter(
        translation=obj)[:10]
    user = request.user

    # Get form
    form = get_upload_form(user, obj)

    search_form = SearchForm(request.user)

    return render(
        request,
        "translation.html",
        {
            "allow_index":
            True,
            "object":
            obj,
            "project":
            obj.component.project,
            "form":
            form,
            "download_form":
            DownloadForm(auto_id="id_dl_%s"),
            "autoform":
            optional_form(
                AutoForm, user, "translation.auto", obj, obj=obj.component),
            "search_form":
            search_form,
            "replace_form":
            optional_form(ReplaceForm, user, "unit.edit", obj),
            "bulk_state_form":
            optional_form(
                BulkEditForm,
                user,
                "translation.auto",
                obj,
                user=user,
                obj=obj,
                project=obj.component.project,
                auto_id="id_bulk_%s",
            ),
            "new_unit_form":
            NewUnitForm(user,
                        initial={"value": Unit(translation=obj, id_hash=-1)}),
            "announcement_form":
            optional_form(AnnouncementForm, user, "component.edit", obj),
            "delete_form":
            optional_form(TranslationDeleteForm,
                          user,
                          "translation.delete",
                          obj,
                          obj=obj),
            "last_changes":
            last_changes,
            "last_changes_url":
            urlencode(obj.get_reverse_url_kwargs()),
            "other_translations":
            prefetch_stats(Translation.objects.prefetch().filter(
                component__project=obj.component.project,
                language=obj.language).exclude(pk=obj.pk)),
            "exporters":
            list_exporters(obj),
        },
    )
Example #31
0
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.user)
    project_locked = translation.subproject.locked
    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 'accept_edit' 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,
                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])
    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(request.GET),
            'search_form': search_result['form'],
            'update_lock': translation.lock_user == request.user,
            'secondary': secondary,
            'locked': locked,
            'user_locked': user_locked,
            'project_locked': project_locked,
            'glossary': Dictionary.objects.get_words(unit),
            'addword_form': InlineWordForm(),
        })
Example #32
0
def search(translation, request):
    """
    Performs search or returns cached search results.
    """

    # Already performed search
    if "sid" in request.GET:
        # Grab from session storage
        search_id = "search_%s" % request.GET["sid"]

        # Check if we know the search
        if search_id not in request.session:
            messages.error(request, _("Invalid search string!"))
            return redirect(translation)

        return request.session[search_id]

    # Possible new search
    rqtype = request.GET.get("type", "all")

    search_form = SearchForm(request.GET)
    review_form = ReviewForm(request.GET)

    search_query = None
    if review_form.is_valid():
        # Review
        allunits = translation.unit_set.review(review_form.cleaned_data["date"], request.user)

        formatted_date = formats.date_format(review_form.cleaned_data["date"], "SHORT_DATE_FORMAT")
        name = _("Review of translations since %s") % formatted_date
    elif search_form.is_valid():
        # Apply search conditions
        allunits = translation.unit_set.search(search_form.cleaned_data)

        search_query = search_form.cleaned_data["q"]
        name = get_search_name(search_form.cleaned_data["search"], search_query)
    else:
        # Error reporting
        if "date" in request.GET:
            show_form_errors(request, review_form)
        elif "q" in request.GET:
            show_form_errors(request, search_form)

        # Filtering by type
        allunits = translation.unit_set.filter_type(rqtype, translation, ignored="ignored" in request.GET)

        name = get_filter_name(rqtype)

    # Grab unit IDs
    unit_ids = list(allunits.values_list("id", flat=True))

    # Check empty search results
    if len(unit_ids) == 0:
        messages.warning(request, _("No string matched your search!"))
        return redirect(translation)

    # Checksum unit access
    offset = 0
    if "checksum" in request.GET:
        try:
            unit = allunits.filter(checksum=request.GET["checksum"])[0]
            offset = unit_ids.index(unit.id)
        except (Unit.DoesNotExist, IndexError):
            messages.warning(request, _("No string matched your search!"))
            return redirect(translation)

    # Remove old search results
    cleanup_session(request.session)

    # Store in cache and return
    search_id = str(uuid.uuid1())
    search_result = {
        "query": search_query,
        "name": unicode(name),
        "ids": unit_ids,
        "search_id": search_id,
        "ttl": int(time.time()) + 86400,
        "offset": offset,
    }

    request.session["search_%s" % search_id] = search_result

    return search_result
Example #33
0
def show_project(request, project):
    obj = get_project(request, project)
    obj.stats.ensure_basic()
    user = request.user

    last_changes = obj.change_set.prefetch().order()[:10]
    last_announcements = (obj.change_set.prefetch().order().filter(
        action=Change.ACTION_ANNOUNCEMENT)[:10])

    all_components = prefetch_stats(
        obj.child_components.filter_access(user).prefetch().order())
    all_components = get_paginator(request, all_components)
    for component in all_components:
        component.is_shared = None if component.project == obj else component.project

    language_stats = obj.stats.get_language_stats()
    # Show ghost translations for user languages
    component = None
    for component in all_components:
        if component.can_add_new_language(user, fast=True):
            break
    if component:
        add_ghost_translations(
            component,
            user,
            language_stats,
            GhostProjectLanguageStats,
            is_shared=component.is_shared,
        )

    language_stats = sort_unicode(
        language_stats,
        lambda x: "{}-{}".format(user.profile.get_translation_order(x), x.
                                 language),
    )

    components = prefetch_tasks(all_components)

    return render(
        request,
        "project.html",
        {
            "allow_index":
            True,
            "object":
            obj,
            "project":
            obj,
            "last_changes":
            last_changes,
            "last_announcements":
            last_announcements,
            "reports_form":
            ReportsForm(),
            "last_changes_url":
            urlencode({"project": obj.slug}),
            "language_stats": [stat.obj or stat for stat in language_stats],
            "search_form":
            SearchForm(request.user),
            "announcement_form":
            optional_form(AnnouncementForm, user, "project.edit", obj),
            "delete_form":
            optional_form(
                ProjectDeleteForm, user, "project.edit", obj, obj=obj),
            "rename_form":
            optional_form(
                ProjectRenameForm,
                user,
                "project.edit",
                obj,
                request=request,
                instance=obj,
            ),
            "replace_form":
            optional_form(ReplaceForm, user, "unit.edit", obj),
            "bulk_state_form":
            optional_form(
                BulkEditForm,
                user,
                "translation.auto",
                obj,
                user=user,
                obj=obj,
                project=obj,
                auto_id="id_bulk_%s",
            ),
            "components":
            components,
            "licenses":
            sorted(
                (component
                 for component in all_components if component.license),
                key=lambda component: component.license,
            ),
        },
    )
Example #34
0
def show_component(request, project, component):
    obj = get_component(request, project, component)
    obj.stats.ensure_basic()
    user = request.user

    last_changes = obj.change_set.prefetch().order()[:10]

    translations = prefetch_stats(list(obj.translation_set.prefetch()))

    # Show ghost translations for user languages
    add_ghost_translations(obj, user, translations, GhostTranslation)

    translations = sort_unicode(
        translations,
        lambda x: "{}-{}".format(user.profile.get_translation_order(x), x.
                                 language),
    )

    return render(
        request,
        "component.html",
        {
            "allow_index":
            True,
            "object":
            obj,
            "project":
            obj.project,
            "translations":
            translations,
            "reports_form":
            ReportsForm(),
            "last_changes":
            last_changes,
            "last_changes_url":
            urlencode({
                "component": obj.slug,
                "project": obj.project.slug
            }),
            "replace_form":
            optional_form(ReplaceForm, user, "unit.edit", obj),
            "bulk_state_form":
            optional_form(
                BulkEditForm,
                user,
                "translation.auto",
                obj,
                user=user,
                obj=obj,
                project=obj.project,
                auto_id="id_bulk_%s",
            ),
            "announcement_form":
            optional_form(AnnouncementForm, user, "component.edit", obj),
            "delete_form":
            optional_form(
                ComponentDeleteForm, user, "component.edit", obj, obj=obj),
            "rename_form":
            optional_form(
                ComponentRenameForm,
                user,
                "component.edit",
                obj,
                request=request,
                instance=obj,
            ),
            "move_form":
            optional_form(
                ComponentMoveForm,
                user,
                "component.edit",
                obj,
                request=request,
                instance=obj,
            ),
            "search_form":
            SearchForm(request.user),
            "alerts":
            obj.all_alerts,
        },
    )
Example #35
0
def show_translation(request, project, component, lang):
    obj = get_translation(request, project, component, lang)
    component = obj.component
    project = component.project
    obj.stats.ensure_all()
    last_changes = obj.change_set.prefetch().order()[:10]
    user = request.user

    # Get form
    form = get_upload_form(user, obj)

    search_form = SearchForm(request.user, language=obj.language)

    # Translations to same language from other components in this project
    other_translations = prefetch_stats(
        list(Translation.objects.prefetch().filter(
            component__project=project,
            language=obj.language).exclude(pk=obj.pk)))

    # Include ghost translations for other components, this
    # adds quick way to create translations in other components
    existing = {
        translation.component.slug
        for translation in other_translations
    }
    existing.add(component.slug)
    for test_component in project.child_components.filter_access(user).exclude(
            slug__in=existing):
        if test_component.can_add_new_language(user, fast=True):
            other_translations.append(
                GhostTranslation(test_component, obj.language))

    # Limit the number of other components displayed to 10, preferring untranslated ones
    other_translations = sorted(other_translations,
                                key=lambda t: t.stats.translated_percent)[:10]

    return render(
        request,
        "translation.html",
        {
            "allow_index":
            True,
            "object":
            obj,
            "project":
            project,
            "form":
            form,
            "download_form":
            DownloadForm(auto_id="id_dl_%s"),
            "autoform":
            optional_form(
                AutoForm, user, "translation.auto", obj, obj=component),
            "search_form":
            search_form,
            "replace_form":
            optional_form(ReplaceForm, user, "unit.edit", obj),
            "bulk_state_form":
            optional_form(
                BulkEditForm,
                user,
                "translation.auto",
                obj,
                user=user,
                obj=obj,
                project=project,
                auto_id="id_bulk_%s",
            ),
            "new_unit_form":
            get_new_unit_form(obj, user),
            "announcement_form":
            optional_form(AnnouncementForm, user, "component.edit", obj),
            "delete_form":
            optional_form(TranslationDeleteForm,
                          user,
                          "translation.delete",
                          obj,
                          obj=obj),
            "last_changes":
            last_changes,
            "last_changes_url":
            urlencode(obj.get_reverse_url_kwargs()),
            "other_translations":
            other_translations,
            "exporters":
            EXPORTERS.list_exporters(obj),
        },
    )
Example #36
0
def search(translation, request):
    '''
    Performs search or returns cached search results.
    '''

    # Already performed search
    if 'sid' in request.GET:
        # Grab from session storage
        search_id = 'search_%s' % request.GET['sid']

        # Check if we know the search
        if search_id not in request.session:
            messages.error(request, _('Invalid search string!'))
            return redirect(translation)

        return request.session[search_id]

    # Possible new search
    search_form = SearchForm(request.GET)
    review_form = ReviewForm(request.GET)

    search_query = None
    if review_form.is_valid():
        # Review
        allunits = translation.unit_set.review(
            review_form.cleaned_data['date'],
            request.user
        )

        formatted_date = formats.date_format(
            review_form.cleaned_data['date'],
            'SHORT_DATE_FORMAT'
        )
        name = _('Review of translations since %s') % formatted_date
    elif search_form.is_valid():
        # Apply search conditions
        allunits = translation.unit_set.search(
            translation,
            search_form.cleaned_data,
        )

        search_query = search_form.cleaned_data['q']
        name = search_form.get_name()
    else:
        # Error reporting
        if 'date' in request.GET:
            show_form_errors(request, review_form)
        elif 'q' in request.GET or 'type' in request.GET:
            show_form_errors(request, search_form)

        # Filtering by type
        allunits = translation.unit_set.all()
        name = _('All strings')

    # Grab unit IDs
    unit_ids = list(allunits.values_list('id', flat=True))

    # Check empty search results
    if len(unit_ids) == 0:
        messages.warning(request, _('No string matched your search!'))
        return redirect(translation)

    # Checksum unit access
    offset = 0
    if 'checksum' in request.GET:
        try:
            unit = allunits.filter(checksum=request.GET['checksum'])[0]
            offset = unit_ids.index(unit.id)
        except (Unit.DoesNotExist, IndexError):
            messages.warning(request, _('No string matched your search!'))
            return redirect(translation)

    # Remove old search results
    cleanup_session(request.session)

    if name is not None:
        name = unicode(name)

    # Store in cache and return
    search_id = str(uuid.uuid1())
    search_result = {
        'query': search_query,
        'name': name,
        'ids': unit_ids,
        'search_id': search_id,
        'ttl': int(time.time()) + 86400,
        'offset': offset,
    }

    request.session['search_%s' % search_id] = search_result

    return search_result
Example #37
0
def show_project(request, project):
    obj = get_project(request, project)
    obj.stats.ensure_basic()
    user = request.user

    last_changes = Change.objects.prefetch().order().filter(project=obj)[:10]
    last_announcements = (Change.objects.prefetch().order().filter(
        project=obj, action=Change.ACTION_ANNOUNCEMENT)[:10])

    language_stats = obj.stats.get_language_stats()
    # Show ghost translations for user languages
    component = None
    for component in obj.component_set.filter_access(user).all():
        if component.can_add_new_language(user):
            break
    if component:
        add_ghost_translations(component, user, language_stats,
                               GhostProjectLanguageStats)

    language_stats = sort_unicode(
        language_stats,
        lambda x: "{}-{}".format(user.profile.get_language_order(x.language), x
                                 .language),
    )

    # Paginate components of project.
    all_components = obj.component_set.filter_access(user).prefetch().order()
    components = prefetch_tasks(
        prefetch_stats(get_paginator(request, all_components)))

    return render(
        request,
        "project.html",
        {
            "allow_index":
            True,
            "object":
            obj,
            "project":
            obj,
            "last_changes":
            last_changes,
            "last_announcements":
            last_announcements,
            "reports_form":
            ReportsForm(),
            "last_changes_url":
            urlencode({"project": obj.slug}),
            "language_stats":
            language_stats,
            "search_form":
            SearchForm(request.user),
            "announcement_form":
            optional_form(AnnouncementForm, user, "project.edit", obj),
            "delete_form":
            optional_form(
                ProjectDeleteForm, user, "project.edit", obj, obj=obj),
            "rename_form":
            optional_form(
                ProjectRenameForm,
                user,
                "project.edit",
                obj,
                request=request,
                instance=obj,
            ),
            "replace_form":
            optional_form(ReplaceForm, user, "unit.edit", obj),
            "bulk_state_form":
            optional_form(
                BulkEditForm,
                user,
                "translation.auto",
                obj,
                user=user,
                obj=obj,
                project=obj,
                auto_id="id_bulk_%s",
            ),
            "components":
            components,
            "licenses":
            obj.component_set.exclude(license="").order_by("license"),
        },
    )