Exemplo n.º 1
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()
    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),
            'bulk_state_form': optional_form(
                BulkStateForm, user, 'translation.auto', obj,
                user=user, obj=obj
            ),
            'components': components,
            'licenses': ', '.join(
                sorted({x.license for x in all_components if x.license})
            ),
        }
    )
Exemplo n.º 2
0
def get_untranslated(base, limit=None):
    """Filter untranslated."""
    result = []
    for item in prefetch_stats(base):
        if item.stats.translated != item.stats.all:
            result.append(item)
            if limit and len(result) >= limit:
                return result
    return result
Exemplo n.º 3
0
def get_untranslated(base, limit=None):
    """Filter untranslated."""
    result = []
    for item in prefetch_stats(base):
        if item.stats.translated != item.stats.all:
            result.append(item)
            if limit and len(result) >= limit:
                return result
    return result
Exemplo n.º 4
0
def list_projects(request):
    """List all projects"""

    return render(
        request, 'projects.html', {
            'allow_index': True,
            'projects': prefetch_stats(request.user.allowed_projects),
            'title': _('Projects'),
        })
Exemplo n.º 5
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(),
            '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(BulkStateForm,
                          user,
                          'translation.auto',
                          obj,
                          user=user,
                          obj=obj),
            'components':
            components,
            'licenses':
            ', '.join(sorted(obj.get_licenses())),
        })
Exemplo n.º 6
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()
    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(),
            'delete_form': optional_form(
                DeleteForm, user, 'project.edit', obj, obj=obj
            ),
            'rename_form': optional_form(
                ProjectRenameForm, user, 'project.edit', obj,
                request=request, instance=obj
            ),
# ProjectRenameForm, ComponentRenameForm, ComponentMoveForm,
            'replace_form': optional_form(ReplaceForm, user, 'unit.edit', obj),
            'mass_state_form': optional_form(
                MassStateForm, user, 'translation.auto', obj,
                user=user, obj=obj
            ),
            'components': components,
            'licenses': ', '.join(
                sorted(set([x.license for x in all_components if x.license]))
            ),
        }
    )
Exemplo n.º 7
0
 def items(self):
     return prefetch_stats(
         Translation.objects.prefetch_related(
             "component",
             "component__project",
             "language",
         )
         .filter(component__project__access_control__lt=Project.ACCESS_PRIVATE)
         .order_by("id")
     )
Exemplo n.º 8
0
def dashboard_anonymous(request):
    """Home page of Weblate showing list of projects for anonymous user."""
    all_projects = prefetch_stats(request.user.allowed_projects)
    top_projects = sorted(all_projects, key=lambda prj: -prj.stats.monthly_changes)

    return render(
        request,
        "dashboard/anonymous.html",
        {"top_projects": top_projects[:20], "all_projects": len(all_projects)},
    )
Exemplo n.º 9
0
def user_page(request, user):
    """User details page."""
    user = get_object_or_404(User, username=user)
    allowed_project_ids = request.user.allowed_project_ids

    # Filter all user activity
    all_changes = Change.objects.last_changes(request.user).filter(user=user)

    # Last user activity
    last_changes = all_changes[:10]

    # Filter where project is active
    user_projects_ids = set(
        all_changes.values_list("translation__component__project", flat=True))
    user_projects = Project.objects.filter(id__in=user_projects_ids
                                           & allowed_project_ids)

    return render(
        request,
        "accounts/user.html",
        {
            "page_profile":
            user.profile,
            "page_user":
            user,
            "last_changes":
            last_changes,
            "last_changes_url":
            urlencode({"user": user.username}),
            "user_projects":
            prefetch_project_flags(prefetch_stats(user_projects)),
            "owned_projects":
            prefetch_project_flags(
                prefetch_stats(
                    user.owned_projects.filter(id__in=allowed_project_ids))),
            "watched_projects":
            prefetch_project_flags(
                prefetch_stats(
                    user.watched_projects.filter(id__in=allowed_project_ids))),
            "user_languages":
            user.profile.languages.all()[:7],
        },
    )
Exemplo n.º 10
0
def show_languages(request):
    return render(
        request, 'languages.html', {
            'allow_index':
            True,
            'languages':
            prefetch_stats(sort_objects(Language.objects.have_translation())),
            'title':
            _('Languages'),
        })
Exemplo n.º 11
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(),
            '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(
                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()),
            'other_translations': prefetch_stats(
                Translation.objects.prefetch().filter(
                    component__project=obj.component.project,
                    language=obj.language,
                ).exclude(
                    pk=obj.pk
                )
            ),
            'exporters': list_exporters(obj),
        }
    )
Exemplo n.º 12
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(
                BulkStateForm, user, 'translation.auto', obj, user=user, obj=obj
            ),
            '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,
        },
    )
Exemplo n.º 13
0
def show_project(request, project):
    obj = get_project(request, project)

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

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

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

    if can_translate(request.user, project=obj):
        replace_form = ReplaceForm()
        mass_state_form = MassStateForm(request.user, obj)
    else:
        replace_form = None
        mass_state_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}),
            'language_stats':
            language_stats,
            'unit_count':
            Unit.objects.filter(translation__subproject__project=obj).count(),
            'words_count':
            obj.stats.all_words,
            'language_count':
            Language.objects.filter(
                translation__subproject__project=obj).distinct().count(),
            'strings_count':
            obj.stats.source_strings,
            'source_words_count':
            obj.stats.source_words,
            'search_form':
            SearchForm(),
            'replace_form':
            replace_form,
            'mass_state_form':
            mass_state_form,
            'components':
            prefetch_stats(obj.subproject_set.select_related()),
        })
Exemplo n.º 14
0
def list_projects(request):
    """List all projects."""
    return render(
        request,
        "projects.html",
        {
            "allow_index": True,
            "projects": prefetch_stats(request.user.allowed_projects),
            "title": _("Projects"),
        },
    )
Exemplo n.º 15
0
def get_suggestions(request, user, user_has_languages, base, filtered=False):
    """Return suggested translations for user."""
    if not filtered:
        non_alerts = base.annotate(
            alert_count=Count("component__alert__pk")).filter(alert_count=0)
        result = get_suggestions(request, user, user_has_languages, non_alerts,
                                 True)
        if result:
            return result
    if user_has_languages:
        # Remove user subscriptions
        result = get_untranslated(
            prefetch_stats(
                base.exclude(
                    component__project__in=user.profile.watched.all())),
            10,
        )
        if result:
            return result
    return get_untranslated(prefetch_stats(base), 10)
Exemplo n.º 16
0
def dashboard_anonymous(request):
    """Home page of Weblate showing list of projects for anonymous user."""

    all_projects = prefetch_stats(request.user.allowed_projects)
    top_projects = sorted(all_projects,
                          key=lambda prj: -prj.stats.recent_changes)

    return render(request, 'dashboard/anonymous.html', {
        'top_projects': top_projects[:20],
        'all_projects': len(all_projects),
    })
Exemplo n.º 17
0
def list_projects(request):
    """List all projects"""

    return render(
        request,
        'projects.html',
        {
            'allow_index': True,
            'projects': prefetch_stats(request.user.allowed_projects),
            'title': _('Projects'),
        }
    )
Exemplo n.º 18
0
def show_languages(request):
    if request.user.has_perm('language.edit'):
        languages = Language.objects.all()
    else:
        languages = Language.objects.have_translation()
    return render(
        request, 'languages.html', {
            'allow_index': True,
            'languages': prefetch_stats(sort_objects(languages)),
            'title': _('Languages'),
            'global_stats': GlobalStats(),
        })
Exemplo n.º 19
0
def show_project(request, project):
    obj = get_project(request, project)

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

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

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

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

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

    # Paginate components of project.
    components = get_paginator(request, obj.component_set.select_related())

    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(),
            'replace_form':
            replace_form,
            'mass_state_form':
            mass_state_form,
            'components':
            prefetch_stats(components),
        })
Exemplo n.º 20
0
    def get_context_data(self, **kwargs):
        """Create context for rendering page."""
        context = super().get_context_data(**kwargs)
        user = self.object
        request = self.request

        allowed_project_ids = request.user.allowed_project_ids

        # Filter all user activity
        all_changes = Change.objects.last_changes(
            request.user).filter(user=user)

        # Last user activity
        last_changes = all_changes[:10]

        # Filter where project is active
        user_translation_ids = set(
            all_changes.values_list("translation", flat=True))
        user_translations = (Translation.objects.prefetch().filter(
            id__in=user_translation_ids,
            component__project_id__in=allowed_project_ids,
        ).order())

        context["page_profile"] = user.profile
        context["last_changes"] = last_changes.preload()
        context["last_changes_url"] = urlencode({"user": user.username})
        context["page_user_translations"] = prefetch_stats(user_translations)
        context["page_owned_projects"] = prefetch_project_flags(
            prefetch_stats(
                user.owned_projects.filter(
                    id__in=allowed_project_ids).order()))
        context["page_watched_projects"] = prefetch_project_flags(
            prefetch_stats(
                user.watched_projects.filter(
                    id__in=allowed_project_ids).order()))
        context["user_languages"] = user.profile.all_languages[:7]
        context["group_form"] = self.group_form or GroupAddForm()
        context["page_user_groups"] = user.groups.prefetch_related(
            "defining_project").order()
        return context
Exemplo n.º 21
0
def show_subproject(request, project, subproject):
    obj = get_subproject(request, project, subproject)

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

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

    return render(
        request, 'subproject.html', {
            'allow_index':
            True,
            'object':
            obj,
            'project':
            obj.project,
            'translations':
            sort_objects(prefetch_stats(obj.translation_set.all())),
            'show_language':
            1,
            'reports_form':
            ReportsForm(),
            'last_changes':
            last_changes,
            'last_changes_url':
            urlencode({
                'subproject': obj.slug,
                'project': obj.project.slug
            }),
            'unit_count':
            Unit.objects.filter(translation__subproject=obj).count(),
            'words_count':
            obj.stats.all_words,
            'language_count':
            Language.objects.filter(
                translation__subproject=obj).distinct().count(),
            'strings_count':
            obj.stats.source_strings,
            'source_words_count':
            obj.stats.source_words,
            'replace_form':
            replace_form,
            'mass_state_form':
            mass_state_form,
            'search_form':
            SearchForm(),
        })
Exemplo n.º 22
0
def show_languages(request):
    return render(
        request,
        'languages.html',
        {
            'allow_index': True,
            'languages': prefetch_stats(
                sort_objects(
                    Language.objects.have_translation()
                )
            ),
            'title': _('Languages'),
        }
    )
Exemplo n.º 23
0
def dashboard_anonymous(request):
    """Home page of Weblate showing list of projects for anonymous user."""
    top_project_ids = cache.get("dashboard-anonymous-projects")
    if top_project_ids is None:
        top_projects = sorted(
            prefetch_stats(request.user.allowed_projects),
            key=lambda prj: -prj.stats.monthly_changes,
        )[:20]
        top_project_ids = {p.id for p in top_projects}
        cache.set("dashboard-anonymous-projects", top_project_ids, 3600)
    top_projects = request.user.allowed_projects.filter(id__in=top_project_ids)

    return render(
        request,
        "dashboard/anonymous.html",
        {
            "top_projects":
            prefetch_stats(prefetch_project_flags(top_projects)),
            "all_projects":
            Metric.objects.get_current(
                None, Metric.SCOPE_GLOBAL, 0, name="projects")["projects"],
        },
    )
Exemplo n.º 24
0
def show_languages(request):
    if request.user.has_perm("language.edit"):
        languages = Language.objects.all()
    else:
        languages = Language.objects.have_translation()
    return render(
        request,
        "languages.html",
        {
            "allow_index": True,
            "languages": prefetch_stats(sort_objects(languages)),
            "title": _("Languages"),
            "global_stats": GlobalStats(),
        },
    )
Exemplo n.º 25
0
def show_component(request, project, component):
    obj = get_component(request, project, component)

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

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

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

    return render(
        request, 'component.html', {
            'allow_index':
            True,
            'object':
            obj,
            'project':
            obj.project,
            'translations':
            sort_objects(prefetch_stats(obj.translation_set.all())),
            'show_language':
            1,
            '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':
            replace_form,
            'mass_state_form':
            mass_state_form,
            'search_form':
            SearchForm(),
        })
Exemplo n.º 26
0
def show_component(request, project, component):
    obj = get_component(request, project, component)
    user = request.user

    last_changes = Change.objects.prefetch().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.all())
            ),
            'show_language': 1,
            '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(
                BulkStateForm, user, 'translation.auto', obj,
                user=user, obj=obj
            ),
            '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(),
        }
    )
Exemplo n.º 27
0
def show_project(request, project):
    obj = get_project(request, project)

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

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

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

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

    if not request.user.has_perm('unit.edit', 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}
            ),
            'language_stats': language_stats,
            'language_count': Language.objects.filter(
                translation__component__project=obj
            ).distinct().count(),
            'search_form': SearchForm(),
            'replace_form': replace_form,
            'mass_state_form': mass_state_form,
            'components': prefetch_stats(obj.component_set.select_related()),
        }
    )
Exemplo n.º 28
0
def dashboard_anonymous(request):
    """Home page of Weblate showing list of projects for anonymous user."""

    all_projects = prefetch_stats(request.user.allowed_projects)
    top_projects = sorted(
        all_projects,
        key=lambda prj: -prj.stats.recent_changes
    )

    return render(
        request,
        'dashboard/anonymous.html',
        {
            'top_projects': top_projects[:20],
            'all_projects': len(all_projects),
        }
    )
Exemplo n.º 29
0
def show_language(request, lang):
    try:
        obj = Language.objects.get(code=lang)
    except Language.DoesNotExist:
        obj = Language.objects.fuzzy_get(lang)
        if isinstance(obj, Language):
            return redirect(obj)
        raise Http404("No Language matches the given query.")

    if request.method == "POST" and request.user.has_perm("language.edit"):
        if obj.translation_set.exists():
            messages.error(
                request,
                _("Remove all translations using this language first."))
        else:
            obj.delete()
            messages.success(request, _("Language %s removed.") % obj)
            return redirect("languages")

    last_changes = Change.objects.last_changes(
        request.user).filter(language=obj)[:10]
    projects = request.user.allowed_projects
    dicts = projects.filter(glossary__term__language=obj).distinct()
    projects = prefetch_project_flags(
        prefetch_stats(
            projects.filter(component__translation__language=obj).distinct()))

    stats = []
    for project in projects:
        project.language_stats = project.stats.get_single_language_stats(obj)
        stats.append(project.language_stats)
    ProjectLanguageStats.prefetch_many(stats)

    return render(
        request,
        "language.html",
        {
            "allow_index": True,
            "object": obj,
            "last_changes": last_changes,
            "last_changes_url": urlencode({"lang": obj.code}),
            "dicts": dicts,
            "projects": projects,
        },
    )
Exemplo n.º 30
0
def show_component(request, project, component):
    obj = get_component(request, project, component)

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

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

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

    return render(
        request,
        'component.html',
        {
            'allow_index': True,
            'object': obj,
            'project': obj.project,
            'translations': sort_objects(
                prefetch_stats(obj.translation_set.all())
            ),
            'show_language': 1,
            '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': replace_form,
            'mass_state_form': mass_state_form,
            'search_form': SearchForm(),
        }
    )
Exemplo n.º 31
0
    def collect_project(self, project: Project):
        languages = prefetch_stats(
            [ProjectLanguage(project, language) for language in project.languages]
        )
        for project_language in languages:
            self.collect_project_language(project_language)
        data = {
            "components": project.component_set.count(),
            "translations": Translation.objects.filter(
                component__project=project
            ).count(),
            "memory": project.memory_set.count(),
            "screenshots": Screenshot.objects.filter(
                translation__component__project=project
            ).count(),
            "changes": project.change_set.filter(
                timestamp__date=datetime.date.today() - datetime.timedelta(days=1)
            ).count(),
            "contributors": project.change_set.filter(
                timestamp__date__gte=datetime.date.today() - datetime.timedelta(days=30)
            )
            .values("user")
            .distinct()
            .count(),
        }
        keys = [
            f"machinery-accounting:internal:{project.id}",
            f"machinery-accounting:external:{project.id}",
        ]
        for key, value in cache.get_many(keys).items():
            if ":internal:" in key:
                data["machinery:internal"] = value
            else:
                data["machinery:external"] = value
        cache.delete_many(keys)

        self.create_metrics(
            data, project.stats, SOURCE_KEYS, Metric.SCOPE_PROJECT, project.pk
        )
        return data
Exemplo n.º 32
0
def stats(request):
    """View with Various stats about Weblate."""

    context = {}

    context['title'] = _('Weblate statistics')

    totals = Profile.objects.aggregate(
        Sum('translated'), Sum('suggested'), Count('id')
    )
    total_strings = []
    total_words = []
    for project in prefetch_stats(Project.objects.all()):
        total_strings.append(project.stats.source_strings)
        total_words.append(project.stats.source_words)

    context['total_translations'] = totals['translated__sum']
    context['total_suggestions'] = totals['suggested__sum']
    context['total_users'] = totals['id__count']
    context['total_strings'] = sum(total_strings)
    context['total_units'] = Unit.objects.count()
    context['total_words'] = sum(total_words)
    context['total_languages'] = Language.objects.filter(
        translation__pk__gt=0
    ).distinct().count()
    context['total_checks'] = Check.objects.count()
    context['ignored_checks'] = Check.objects.filter(ignore=True).count()

    top_translations = Profile.objects.order_by('-translated')[:10]
    top_suggestions = Profile.objects.order_by('-suggested')[:10]

    context['top_translations'] = top_translations.select_related('user')
    context['top_suggestions'] = top_suggestions.select_related('user')

    return render(
        request,
        'stats.html',
        context
    )
Exemplo n.º 33
0
 def notify_summary(self, frequency):
     users = {}
     notifications = defaultdict(list)
     for translation in prefetch_stats(Translation.objects.prefetch()):
         if not self.should_notify(translation):
             continue
         context = {
             'project': translation.component.project,
             'component': translation.component,
             'translation': translation,
         }
         for user in self.get_users(frequency, **context):
             users[user.pk] = user
             notifications[user.pk].append(context)
     for userid, changes in notifications.items():
         user = users[userid]
         self.send_digest(
             user.profile.language,
             user.email,
             changes,
             subscription=user.current_subscription,
         )
Exemplo n.º 34
0
def fetch_componentlists(user, user_translations):
    componentlists = list(
        ComponentList.objects.filter(
            show_dashboard=True, components__project_id__in=user.allowed_project_ids,
        )
        .distinct()
        .order()
    )
    for componentlist in componentlists:
        components = componentlist.components.filter_access(user)
        # Force fetching the query now
        list(components)

        translations = prefetch_stats(
            list(user_translations.filter(component__in=components))
        )

        # Show ghost translations for user languages
        existing = {
            (translation.component.slug, translation.language.code)
            for translation in translations
        }
        languages = user.profile.languages.all()
        for component in components:
            for language in languages:
                if (
                    component.slug,
                    language.code,
                ) in existing or not component.can_add_new_language(user):
                    continue
                translations.append(GhostTranslation(component, language))

        componentlist.translations = translations

    # Filter out component lists with translations
    # This will remove the ones where user doesn't have access to anything
    return [c for c in componentlists if c.translations]
Exemplo n.º 35
0
def dashboard_anonymous(request):
    """Home page of Weblate showing list of projects for anonymous user."""
    top_project_ids = cache.get("dashboard-anonymous-projects")
    if top_project_ids is None:
        top_projects = sorted(
            prefetch_stats(request.user.allowed_projects),
            key=lambda prj: -prj.stats.monthly_changes,
        )[:20]
        cache.set("dashboard-anonymous-projects", {p.id for p in top_projects}, 3600)
    else:
        # The allowed_projects is already fetched, so filter it in Python
        # instead of doing additional query
        top_projects = [
            p for p in request.user.allowed_projects if p.id in top_project_ids
        ]

    return render(
        request,
        "dashboard/anonymous.html",
        {
            "top_projects": top_projects,
            "all_projects": len(request.user.allowed_projects),
        },
    )
Exemplo n.º 36
0
def show_component(request, project, component):
    obj = get_component(request, project, component)
    user = request.user

    last_changes = Change.objects.prefetch().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.all())
            ),
            'show_language': 1,
            '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),
            'mass_state_form': optional_form(
                MassStateForm, user, 'translation.auto', obj,
                user=user, obj=obj
            ),
            'delete_form': optional_form(
                DeleteForm, user, 'component.edit', obj, obj=obj
            ),
            'search_form': SearchForm(),
        }
    )
Exemplo n.º 37
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')

    # This is used on Hosted Weblate to handle removed translation projects.
    # The redirect itself is done in the http server.
    if 'removed' in request.GET:
        messages.warning(
            request,
            _(
                'The project you were looking for has been removed, '
                'however you are welcome to contribute to other ones.'
            )
        )

    user = request.user

    user_translations = get_user_translations(request, user)

    suggestions = get_suggestions(request, user, user_translations)

    # Warn about not filled in username (usually caused by migration of
    # users from older system
    if user.is_authenticated and user.full_name == '':
        messages.warning(
            request,
            mark_safe('<a href="{0}">{1}</a>'.format(
                reverse('profile') + '#account',
                escape(_('Please set your full name in your profile.'))
            ))
        )

    usersubscriptions = None

    componentlists = list(ComponentList.objects.filter(show_dashboard=True))
    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:
        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)
        subscribed_projects = user.allowed_projects.filter(
            profile=user.profile
        )

        usersubscriptions = user_translations.filter(
            component__project__in=subscribed_projects
        )

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

    return render(
        request,
        'index.html',
        {
            'allow_index': True,
            'suggestions': suggestions,
            'search_form': SiteSearchForm(),
            'usersubscriptions': usersubscriptions,
            'userlanguages': prefetch_stats(user_translations),
            'componentlists': componentlists,
            'all_componentlists': prefetch_stats(ComponentList.objects.all()),
            'active_tab_slug': active_tab_slug,
        }
    )
Exemplo n.º 38
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))
    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)
        subscribed_projects = user.allowed_projects.filter(
            profile=user.profile
        )

        usersubscriptions = user_translations.filter(
            component__project__in=subscribed_projects
        )

        if user.profile.hide_completed:
            usersubscriptions = get_untranslated(usersubscriptions)
            user_translations = get_untranslated(user_translations)
            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': SiteSearchForm(),
            'usersubscriptions': get_paginator(request, usersubscriptions),
            'userlanguages': prefetch_stats(
                get_paginator(request, user_translations)
            ),
            'componentlists': componentlists,
            'all_componentlists': prefetch_stats(ComponentList.objects.all()),
            'active_tab_slug': active_tab_slug,
        }
    )
Exemplo n.º 39
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 translations 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))

    # 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":
            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),
        },
    )
Exemplo n.º 40
0
def show_component(request, project, component):
    obj = get_component(request, project, component)
    obj.stats.ensure_basic()
    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
    add_ghost_translations(obj, user, translations, GhostTranslation)

    translations = sort_unicode(
        translations,
        lambda x: "{}-{}".format(user.profile.get_language_order(x.language), 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,
        },
    )
Exemplo n.º 41
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 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 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
                )
            ),
        }
    )
Exemplo n.º 42
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),
            'bulk_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(obj),
        }
    )