Example #1
0
 def table(self):
     if self.view.object_children:
         return {
             'id': self.view.view_name,
             'fields': self.table_fields,
             'headings': get_table_headings(self.table_fields),
             'rows': self.view.object_children}
Example #2
0
def overview(request, language):
    translation_projects = language.children \
                                   .order_by('project__fullname')
    user_tps = filter(lambda x: x.is_accessible_by(request.user),
                      translation_projects)
    items = (make_project_item(tp) for tp in user_tps)

    table_fields = ['name', 'progress', 'total', 'need-translation',
                    'suggestions', 'critical', 'last-updated', 'activity']
    table = {
        'id': 'language',
        'fields': table_fields,
        'headings': get_table_headings(table_fields),
        'items': items,
    }

    ctx = get_overview_context(request)
    ctx.update({
        'language': {
          'code': language.code,
          'name': tr_lang(language.fullname),
        },
        'table': table,
        'stats': jsonify(request.resource_obj.get_stats()),

        'browser_extends': 'languages/base.html',
    })

    response = render(request, 'browser/overview.html', ctx)
    response.set_cookie('pootle-language', language.code)

    return response
Example #3
0
def browse(request, project, dir_path, filename):
    """Languages browser for a given project."""
    item_func = (make_xlanguage_item if dir_path or filename
                                     else make_language_item)
    items = [item_func(item) for item in
             request.resource_obj.get_children_for_user(request.profile)]
    items.sort(lambda x, y: locale.strcoll(x['title'], y['title']))

    table_fields = ['name', 'progress', 'total', 'need-translation',
                    'suggestions', 'critical', 'last-updated', 'activity']
    table = {
        'id': 'project',
        'fields': table_fields,
        'headings': get_table_headings(table_fields),
        'items': items,
    }

    ctx = get_browser_context(request)
    ctx.update({
        'project': project,
        'table': table,
        'stats': jsonify(request.resource_obj.get_stats()),

        'browser_extends': 'projects/base.html',
    })

    return render(request, 'browser/index.html', ctx)
Example #4
0
def test_panel_tp_subdir_table(subdir0, rf, member):
    request = rf.get(subdir0.pootle_path)
    request.user = member
    view = TPBrowseView(kwargs=dict(language_code=subdir0.tp.language.code,
                                    project_code=subdir0.tp.project.code,
                                    dir_path=subdir0.tp_path[1:]))
    view.request = request
    view.object = view.get_object()
    lang_panels = panels.gather(TPBrowseView)
    assert lang_panels.keys() == ["children", "vfolders"]
    assert lang_panels["children"] == ChildrenPanel
    panel = ChildrenPanel(view)
    assert panel.panel_name == "children"
    assert (panel.cache_key == ("panel.%s.%s" %
                                (panel.panel_name, view.cache_key)))
    table = {
        'id': view.view_name,
        'fields': panel.table_fields,
        'headings': get_table_headings(panel.table_fields),
        'items': view.items,
        'disabled_items': view.disabled_items
    }
    assert panel.table == table
    assert panel.get_context_data() == dict(table=table)
    assert (panel.content == loader.render_to_string(panel.template_name,
                                                     panel.get_context_data()))
Example #5
0
def overview(request, project, dir_path, filename):
    """Languages overview for a given project."""
    item_func = (make_xlanguage_item
                 if dir_path or filename else make_language_item)
    items = [item_func(item) for item in request.resource_obj.children]
    items.sort(lambda x, y: locale.strcoll(x['title'], y['title']))

    table_fields = [
        'name', 'progress', 'total', 'need-translation', 'suggestions',
        'critical', 'last-updated', 'activity'
    ]
    table = {
        'id': 'project',
        'fields': table_fields,
        'headings': get_table_headings(table_fields),
        'items': items,
    }

    ctx = get_overview_context(request)
    ctx.update({
        'project': project,
        'table': table,
        'stats': jsonify(request.resource_obj.get_stats()),
        'browser_extends': 'projects/base.html',
    })

    return render(request, 'browser/overview.html', ctx)
Example #6
0
def browse(request, language):
    user_tps = language.get_children_for_user(request.user)
    items = (make_project_item(tp) for tp in user_tps)

    table_fields = [
        'name', 'progress', 'total', 'need-translation', 'suggestions',
        'critical', 'last-updated', 'activity'
    ]

    ctx = get_browser_context(request)
    ctx.update({
        'language': {
            'code': language.code,
            'name': tr_lang(language.fullname),
        },
        'table': {
            'id': 'language',
            'fields': table_fields,
            'headings': get_table_headings(table_fields),
            'items': items,
        },
        'stats':
        jsonify(request.resource_obj.get_stats_for_user(request.user)),
        'browser_extends':
        'languages/base.html',
    })

    response = render(request, 'browser/index.html', ctx)
    response.set_cookie('pootle-language', language.code)

    return response
Example #7
0
def test_panel_tp_subdir_table(subdir0, rf, member):
    request = rf.get(subdir0.pootle_path)
    request.user = member
    request.permissions = get_matching_permissions(
        request.user,
        subdir0)
    view = TPBrowseView(
        kwargs=dict(
            language_code=subdir0.tp.language.code,
            project_code=subdir0.tp.project.code,
            dir_path=subdir0.tp_path[1:]))
    view.request = request
    view.object = view.get_object()
    lang_panels = panels.gather(TPBrowseView)
    assert lang_panels.keys() == ["children", "vfolders"]
    assert lang_panels["children"] == ChildrenPanel
    panel = ChildrenPanel(view)
    assert panel.panel_name == "children"
    assert (
        panel.cache_key
        == ("panel.%s.%s"
            % (panel.panel_name, view.cache_key)))
    table = {
        'id': view.view_name,
        'fields': panel.table_fields,
        'headings': get_table_headings(panel.table_fields),
        'rows': view.object_children}
    assert panel.table == table
    assert panel.get_context_data() == dict(
        table=table, can_translate=view.can_translate)
    content = loader.render_to_string(
        panel.template_name, context=panel.get_context_data())
    assert (
        panel.content
        == panel.update_times(content))
Example #8
0
def test_panel_tp_table(tp0, rf, member):
    request = rf.get('/language0/project0/')
    request.user = member
    request.permissions = get_matching_permissions(request.user, tp0.directory)
    view = TPBrowseView(kwargs=dict(language_code=tp0.language.code,
                                    project_code=tp0.project.code))
    view.request = request
    view.object = view.get_object()
    lang_panels = panels.gather(TPBrowseView)
    assert lang_panels.keys() == ["children", "vfolders"]
    assert lang_panels["children"] == ChildrenPanel
    panel = ChildrenPanel(view)
    assert panel.panel_name == "children"
    assert (panel.cache_key == ("panel.%s.%s" %
                                (panel.panel_name, view.cache_key)))
    table = {
        'id': view.view_name,
        'fields': panel.table_fields,
        'headings': get_table_headings(panel.table_fields),
        'rows': view.object_children
    }
    assert panel.table == table
    assert panel.get_context_data() == dict(table=table,
                                            can_translate=view.can_translate)
    content = loader.render_to_string(panel.template_name,
                                      context=panel.get_context_data())
    assert (panel.content == panel.update_times(content))
Example #9
0
def browse(request, language):
    user_tps = language.get_children_for_user(request.user)
    items = (make_project_item(tp) for tp in user_tps)

    table_fields = ['name', 'progress', 'total', 'need-translation',
                    'suggestions', 'critical', 'last-updated', 'activity']

    ctx = get_browser_context(request)
    ctx.update({
        'language': {
          'code': language.code,
          'name': tr_lang(language.fullname),
        },
        'table': {
            'id': 'language',
            'fields': table_fields,
            'headings': get_table_headings(table_fields),
            'items': items,
        },
        'stats': jsonify(request.resource_obj.get_stats_for_user(request.user)),

        'browser_extends': 'languages/base.html',
    })

    response = render(request, 'browser/index.html', ctx)
    response.set_cookie('pootle-language', language.code)

    return response
Example #10
0
def projects_browse(request, project_set):
    """Page listing all projects"""
    items = [make_project_list_item(project)
             for project in project_set.children]
    items.sort(lambda x, y: locale.strcoll(x['title'], y['title']))

    table_fields = ['name', 'progress', 'total', 'need-translation',
                    'suggestions', 'critical', 'last-updated', 'activity']
    table = {
        'id': 'projects',
        'fields': table_fields,
        'headings': get_table_headings(table_fields),
        'items': items,
    }

    ctx = get_browser_context(request)
    ctx.update({
        'table': table,
        'stats': jsonify(request.resource_obj.get_stats()),

        'browser_extends': 'projects/all/base.html',
    })

    response = render(request, 'browser/index.html', ctx)
    response.set_cookie('pootle-language', 'projects')

    return response
Example #11
0
def test_panel_language_table(language0, rf, member):
    request = rf.get("/language0/")
    request.user = member
    request.permissions = get_matching_permissions(request.user, language0.directory)
    view = LanguageBrowseView(kwargs=dict(language_code=language0.code))
    view.request = request
    view.object = view.get_object()
    lang_panels = panels.gather(LanguageBrowseView)
    assert lang_panels.keys() == ["children"]
    assert lang_panels["children"] == ChildrenPanel
    panel = ChildrenPanel(view)
    assert panel.panel_name == "children"
    assert panel.cache_key == ("panel.%s.%s" % (panel.panel_name, view.cache_key))

    table = {
        "id": view.view_name,
        "fields": panel.table_fields,
        "headings": get_table_headings(panel.table_fields),
        "rows": view.object_children,
    }

    assert panel.table == table
    assert panel.get_context_data() == dict(table=table, can_translate=view.can_translate)
    content = loader.render_to_string(panel.template_name, context=panel.get_context_data())
    assert panel.content == panel.update_times(content)
Example #12
0
def overview(request, language):
    translation_projects = language.children \
                                   .order_by('project__fullname')
    user_tps = filter(lambda x: x.is_accessible_by(request.user),
                      translation_projects)
    items = (make_project_item(tp) for tp in user_tps)

    table_fields = [
        'name', 'progress', 'total', 'need-translation', 'suggestions',
        'critical', 'last-updated', 'activity'
    ]
    table = {
        'id': 'language',
        'fields': table_fields,
        'headings': get_table_headings(table_fields),
        'items': items,
    }

    ctx = get_overview_context(request)
    ctx.update({
        'language': {
            'code': language.code,
            'name': tr_lang(language.fullname),
        },
        'table': table,
        'stats': jsonify(request.resource_obj.get_stats()),
        'browser_extends': 'languages/base.html',
    })

    response = render(request, 'browser/overview.html', ctx)
    response.set_cookie('pootle-language', language.code)

    return response
Example #13
0
def projects_overview(request, project_set):
    """Page listing all projects"""
    items = [
        make_project_list_item(project) for project in project_set.children
    ]
    items.sort(lambda x, y: locale.strcoll(x['title'], y['title']))

    table_fields = [
        'name', 'progress', 'total', 'need-translation', 'suggestions',
        'critical', 'last-updated', 'activity'
    ]
    table = {
        'id': 'projects',
        'fields': table_fields,
        'headings': get_table_headings(table_fields),
        'items': items,
    }

    ctx = get_overview_context(request)
    ctx.update({
        'table': table,
        'stats': jsonify(request.resource_obj.get_stats()),
        'browser_extends': 'projects/all/base.html',
    })

    response = render(request, 'browser/overview.html', ctx)
    response.set_cookie('pootle-language', 'projects')

    return response
Example #14
0
def test_panel_projects_table(rf, member, project0):
    request = rf.get('/projects/')
    request.user = member
    request.permissions = get_matching_permissions(
        request.user,
        project0.directory.parent)
    view = ProjectsBrowseView()
    view.request = request
    view.object = view.get_object()
    lang_panels = panels.gather(ProjectsBrowseView)
    assert lang_panels.keys() == ["children"]
    assert lang_panels["children"] == ChildrenPanel
    panel = ChildrenPanel(view)
    assert panel.panel_name == "children"
    assert (
        panel.cache_key
        == ("panel.%s.%s"
            % (panel.panel_name, view.cache_key)))

    table = {
        'id': view.view_name,
        'fields': panel.table_fields,
        'headings': get_table_headings(panel.table_fields),
        'rows': view.object_children}

    assert panel.table == table
    assert panel.get_context_data() == dict(
        table=table, can_translate=view.can_translate)
    content = loader.render_to_string(
        panel.template_name, context=panel.get_context_data())
    assert (
        panel.content
        == panel.update_times(content))
Example #15
0
def test_panel_project_store_table(project0, store0, rf, member):
    request = rf.get('/projects/project0/store0')
    request.user = member
    view = ProjectBrowseView(kwargs=dict(
        project_code=project0.code, dir_path="", filename=store0.name))
    view.request = request
    view.object = view.get_object()
    lang_panels = panels.gather(ProjectBrowseView)
    assert lang_panels.keys() == ["children"]
    assert lang_panels["children"] == ChildrenPanel
    panel = ChildrenPanel(view)
    assert panel.panel_name == "children"
    assert (panel.cache_key == ("panel.%s.%s" %
                                (panel.panel_name, view.cache_key)))

    table = {
        'id': view.view_name,
        'fields': panel.table_fields,
        'headings': get_table_headings(panel.table_fields),
        'items': view.items,
        'disabled_items': view.disabled_items
    }

    assert panel.table == table
    assert panel.get_context_data() == dict(table=table)
    assert (panel.content == loader.render_to_string(panel.template_name,
                                                     panel.get_context_data()))
Example #16
0
def test_vfolder_data_view(tp0, request_users):
    user = request_users["user"]
    dir0 = tp0.directory
    vf_data = vfolders_data_view.get(dir0.__class__)(dir0, user=user)
    assert isinstance(vf_data, VFoldersDataView)
    assert vf_data.context is dir0
    assert isinstance(vf_data.vfolder_data_tool, DirectoryVFDataTool)
    assert vf_data.vfolder_data_tool.context is dir0
    assert (
        vf_data.all_stats
        == vf_data.vfolder_data_tool.get_stats(user=user))
    assert vf_data.stats["children"] == vf_data.all_stats
    # ordering?
    rows = [
        make_vfolder_dict(dir0, *vf)
        for vf
        in vf_data.all_stats.items()]
    for i, row in enumerate(vf_data.table_items):
        assert rows[i] == row
    assert "priority" in vf_data.table_fields
    expected_table_data = dict(
        children=dict(
            id='vfolders',
            fields=vf_data.table_fields,
            headings=get_table_headings(vf_data.table_fields),
            rows=vf_data.table_items))
    assert vf_data.table_data == expected_table_data
Example #17
0
def projects_overview(request, project_set):
    """Page listing all projects."""
    items = [
        make_project_list_item(project)
        for project in project_set.get_children()
    ]

    table_fields = [
        'name', 'progress', 'total', 'need-translation', 'suggestions',
        'critical', 'last-updated', 'activity'
    ]

    ctx = get_overview_context(request)
    ctx.update({
        'table': {
            'id': 'projects',
            'fields': table_fields,
            'headings': get_table_headings(table_fields),
            'items': items,
        },
        'browser_extends': 'projects/all/base.html',
    })

    response = render(request, 'browser/overview.html', ctx)
    response.set_cookie('pootle-language', 'projects')

    return response
Example #18
0
 def table(self):
     if self.view.object_children:
         return {
             'id': self.view.view_name,
             'fields': self.table_fields,
             'headings': get_table_headings(self.table_fields),
             'rows': self.view.object_children
         }
Example #19
0
def test_view_projects_browse(client, request_users):
    user = request_users["user"]
    client.login(
        username=user.username,
        password=request_users["password"])
    response = client.get(reverse("pootle-projects-browse"))
    assert response.cookies["pootle-language"].value == "projects"
    ctx = response.context
    request = response.wsgi_request
    user_projects = Project.accessible_by_user(request.user)
    user_projects = (
        Project.objects.for_user(request.user)
                       .filter(code__in=user_projects))
    obj = ProjectSet(user_projects)
    items = [
        make_project_list_item(project)
        for project in obj.children]
    items.sort(lambda x, y: locale.strcoll(x['title'], y['title']))
    table_fields = [
        'name', 'progress', 'total', 'need-translation',
        'suggestions', 'critical', 'last-updated', 'activity']
    table = {
        'id': 'projects',
        'fields': table_fields,
        'headings': get_table_headings(table_fields),
        'items': items}

    if request.user.is_superuser:
        url_action_continue = obj.get_translate_url(state='incomplete')
        url_action_fixcritical = obj.get_critical_url()
        url_action_review = obj.get_translate_url(state='suggestions')
        url_action_view_all = obj.get_translate_url(state='all')
    else:
        (url_action_continue,
         url_action_fixcritical,
         url_action_review,
         url_action_view_all) = [None] * 4

    User = get_user_model()
    top_scorers = User.top_scorers(limit=10)
    assertions = dict(
        page="browse",
        pootle_path="/projects/",
        resource_path="",
        resource_path_parts=[],
        object=obj,
        table=table,
        browser_extends="projects/all/base.html",
        stats=obj.data_tool.get_stats(user=request.user),
        checks=get_qualitycheck_list(obj),
        top_scorers=top_scorers,
        top_scorers_data=get_top_scorers_data(top_scorers, 10),
        translation_states=get_translation_states(obj),
        url_action_continue=url_action_continue,
        url_action_fixcritical=url_action_fixcritical,
        url_action_review=url_action_review,
        url_action_view_all=url_action_view_all)
    view_context_test(ctx, **assertions)
Example #20
0
def test_view_projects_browse(client, request_users):
    user = request_users["user"]
    client.login(username=user.username, password=request_users["password"])
    response = client.get(reverse("pootle-projects-browse"))
    assert response.cookies["pootle-language"].value == "projects"
    ctx = response.context
    request = response.wsgi_request
    user_projects = Project.accessible_by_user(request.user)
    user_projects = (Project.objects.for_user(
        request.user).filter(code__in=user_projects))
    obj = ProjectSet(user_projects)
    items = [make_project_list_item(project) for project in obj.children]
    items.sort(lambda x, y: locale.strcoll(x['title'], y['title']))
    stats = obj.data_tool.get_stats(user=request.user)
    for item in items:
        if item["code"] in stats["children"]:
            item["stats"] = stats["children"][item["code"]]
    table_fields = [
        'name', 'progress', 'total', 'need-translation', 'suggestions',
        'critical', 'last-updated', 'activity'
    ]
    table = {
        'id': 'projects',
        'fields': table_fields,
        'headings': get_table_headings(table_fields),
        'items': items
    }

    if request.user.is_superuser:
        url_action_continue = obj.get_translate_url(state='incomplete')
        url_action_fixcritical = obj.get_critical_url()
        url_action_review = obj.get_translate_url(state='suggestions')
        url_action_view_all = obj.get_translate_url(state='all')
    else:
        (url_action_continue, url_action_fixcritical, url_action_review,
         url_action_view_all) = [None] * 4
    checks = ChecksDisplay(obj).checks_by_category
    stats = StatsDisplay(obj, stats=stats).stats
    del stats["children"]
    User = get_user_model()
    top_scorers = User.top_scorers(limit=10)
    assertions = dict(page="browse",
                      pootle_path="/projects/",
                      resource_path="",
                      resource_path_parts=[],
                      object=obj,
                      table=table,
                      browser_extends="projects/all/base.html",
                      top_scorers=top_scorers,
                      top_scorers_data=get_top_scorers_data(top_scorers, 10),
                      translation_states=get_translation_states(obj),
                      url_action_continue=url_action_continue,
                      url_action_fixcritical=url_action_fixcritical,
                      url_action_review=url_action_review,
                      url_action_view_all=url_action_view_all,
                      checks=checks,
                      stats=stats)
    view_context_test(ctx, **assertions)
Example #21
0
def _test_browse_view(project, request, response, kwargs):
    cookie_data = json.loads(unquote(response.cookies[SIDEBAR_COOKIE_NAME].value))
    assert cookie_data["foo"] == "bar"
    assert "announcements_projects_%s" % project.code in cookie_data
    ctx = response.context
    kwargs["project_code"] = project.code
    resource_path = "%(dir_path)s%(filename)s" % kwargs
    project_path = "%s/%s" % (kwargs["project_code"], resource_path)
    if not (kwargs["dir_path"] or kwargs["filename"]):
        ob = project
    elif not kwargs["filename"]:
        ob = ProjectResource(
            Directory.objects.live().filter(pootle_path__regex="^/.*/%s$" % project_path),
            pootle_path="/projects/%s" % project_path,
        )
    else:
        ob = ProjectResource(
            Store.objects.live().filter(pootle_path__regex="^/.*/%s$" % project_path),
            pootle_path="/projects/%s" % project_path,
        )

    item_func = make_xlanguage_item if (kwargs["dir_path"] or kwargs["filename"]) else make_language_item
    items = [item_func(item) for item in ob.get_children_for_user(request.profile)]
    items.sort(lambda x, y: locale.strcoll(x["title"], y["title"]))

    table_fields = [
        "name",
        "progress",
        "total",
        "need-translation",
        "suggestions",
        "critical",
        "last-updated",
        "activity",
    ]
    table = {"id": "project", "fields": table_fields, "headings": get_table_headings(table_fields), "items": items}

    assertions = dict(
        page="browse",
        project=project,
        resource_obj=ob,
        browser_extends="projects/base.html",
        pootle_path="/projects/%s" % project_path,
        resource_path=resource_path,
        resource_path_parts=get_path_parts(resource_path),
        url_action_continue=ob.get_translate_url(state="incomplete"),
        url_action_fixcritical=ob.get_critical_url(),
        url_action_review=ob.get_translate_url(state="suggestions"),
        url_action_view_all=ob.get_translate_url(state="all"),
        translation_states=get_translation_states(ob),
        check_categories=get_qualitycheck_schema(ob),
        table=table,
        stats=jsonify(ob.get_stats()),
    )
    sidebar = get_sidebar_announcements_context(request, (project,))
    for k in ["has_sidebar", "is_sidebar_open", "announcements"]:
        assertions[k] = sidebar[0][k]
    view_context_test(ctx, **assertions)
Example #22
0
def _test_browse_view(project, request, response, kwargs):
    cookie_data = json.loads(
        unquote(response.cookies[SIDEBAR_COOKIE_NAME].value))
    assert cookie_data["foo"] == "bar"
    assert "announcements_projects_%s" % project.code in cookie_data
    ctx = response.context
    kwargs["project_code"] = project.code
    resource_path = ("%(dir_path)s%(filename)s" % kwargs)
    project_path = ("%s/%s" % (kwargs["project_code"], resource_path))
    if not (kwargs["dir_path"] or kwargs["filename"]):
        ob = project
    elif not kwargs["filename"]:
        ob = ProjectResource(Directory.objects.live().filter(
            pootle_path__regex="^/.*/%s$" % project_path),
                             pootle_path="/projects/%s" % project_path)
    else:
        ob = ProjectResource(Store.objects.live().filter(
            pootle_path__regex="^/.*/%s$" % project_path),
                             pootle_path="/projects/%s" % project_path)

    item_func = (make_xlanguage_item if
                 (kwargs["dir_path"]
                  or kwargs["filename"]) else make_language_item)
    items = [
        item_func(item) for item in ob.get_children_for_user(request.user)
    ]
    items.sort(lambda x, y: locale.strcoll(x['title'], y['title']))

    table_fields = [
        'name', 'progress', 'total', 'need-translation', 'suggestions',
        'critical', 'last-updated', 'activity'
    ]
    table = {
        'id': 'project',
        'fields': table_fields,
        'headings': get_table_headings(table_fields),
        'items': items
    }

    assertions = dict(
        page="browse",
        project=project,
        browser_extends="projects/base.html",
        pootle_path="/projects/%s" % project_path,
        resource_path=resource_path,
        resource_path_parts=get_path_parts(resource_path),
        url_action_continue=ob.get_translate_url(state='incomplete'),
        url_action_fixcritical=ob.get_critical_url(),
        url_action_review=ob.get_translate_url(state='suggestions'),
        url_action_view_all=ob.get_translate_url(state='all'),
        translation_states=get_translation_states(ob),
        check_categories=get_qualitycheck_schema(ob),
        table=table,
        stats=jsonify(ob.get_stats()))
    sidebar = get_sidebar_announcements_context(request, (project, ))
    for k in ["has_sidebar", "is_sidebar_open", "announcements"]:
        assertions[k] = sidebar[0][k]
    view_context_test(ctx, **assertions)
Example #23
0
 def table(self):
     if self.view.items:
         return {
             'id': self.view.view_name,
             'fields': self.table_fields,
             'headings': get_table_headings(self.table_fields),
             'items': self.view.items,
             'disabled_items': self.view.disabled_items
         }
Example #24
0
 def table(self):
     if self.table_id and self.table_fields and self.items:
         return {
             'id': self.table_id,
             'fields': self.table_fields,
             'headings': get_table_headings(self.table_fields),
             'items': self.items,
             'disabled_items': self.disabled_items,
         }
Example #25
0
 def table(self):
     if self.table_id and self.table_fields and self.items:
         return {
             'id': self.table_id,
             'fields': self.table_fields,
             'headings': get_table_headings(self.table_fields),
             'items': self.items,
             'disabled_items': self.disabled_items,
         }
Example #26
0
 def table_data(self):
     ctx = {}
     if len(self.all_stats) > 0:
         ctx.update({
             'vfolders': {
                 'id': 'vfolders',
                 'fields': self.table_fields,
                 'headings': get_table_headings(self.table_fields),
                 'items': self.table_items}})
     return ctx
Example #27
0
def test_view_projects_browse(client, request_users):
    user = request_users["user"]
    client.login(
        username=user.username,
        password=request_users["password"])
    response = client.get(reverse("pootle-projects-browse"))
    assert response.cookies["pootle-language"].value == "projects"
    ctx = response.context
    request = response.wsgi_request
    user_projects = Project.accessible_by_user(request.user)
    user_projects = (
        Project.objects.for_user(request.user)
                       .filter(code__in=user_projects))
    ob = ProjectSet(user_projects)
    items = [
        make_project_list_item(project)
        for project in ob.children]
    items.sort(lambda x, y: locale.strcoll(x['title'], y['title']))
    table_fields = [
        'name', 'progress', 'total', 'need-translation',
        'suggestions', 'critical', 'last-updated', 'activity']
    table = {
        'id': 'projects',
        'fields': table_fields,
        'headings': get_table_headings(table_fields),
        'items': items}

    if request.user.is_superuser:
        url_action_continue = ob.get_translate_url(state='incomplete')
        url_action_fixcritical = ob.get_critical_url()
        url_action_review = ob.get_translate_url(state='suggestions')
        url_action_view_all = ob.get_translate_url(state='all')
    else:
        (url_action_continue,
         url_action_fixcritical,
         url_action_review,
         url_action_view_all) = [None] * 4

    assertions = dict(
        page="browse",
        pootle_path="/projects/",
        resource_path="",
        resource_path_parts=[],
        object=ob,
        table=table,
        browser_extends="projects/all/base.html",
        stats=jsonify(ob.get_stats()),
        check_categories=get_qualitycheck_schema(ob),
        translation_states=get_translation_states(ob),
        url_action_continue=url_action_continue,
        url_action_fixcritical=url_action_fixcritical,
        url_action_review=url_action_review,
        url_action_view_all=url_action_view_all)
    view_context_test(ctx, **assertions)
Example #28
0
def _test_browse_view(language, request, response, kwargs):
    assert (response.cookies["pootle-language"].value == language.code)
    cookie_data = json.loads(
        unquote(response.cookies[SIDEBAR_COOKIE_NAME].value))
    assert cookie_data["foo"] == "bar"
    assert "announcements_%s" % language.code in cookie_data
    ctx = response.context
    table_fields = [
        'name', 'progress', 'total', 'need-translation', 'suggestions',
        'critical', 'last-updated', 'activity'
    ]
    user_tps = language.get_children_for_user(request.user)
    stats = language.data_tool.get_stats(user=request.user)
    items = [make_project_item(tp) for tp in user_tps]
    for item in items:
        if item["code"] in stats["children"]:
            item["stats"] = stats["children"][item["code"]]
    table = {
        'id': 'language',
        'fields': table_fields,
        'headings': get_table_headings(table_fields),
        'items': items
    }
    checks = ChecksDisplay(language).checks_by_category
    stats = StatsDisplay(language, stats=stats).stats
    del stats["children"]
    top_scorers = get_user_model().top_scorers(language=language.code,
                                               limit=10)
    assertions = dict(
        page="browse",
        object=language,
        language={
            'code': language.code,
            'name': language.name
        },
        browser_extends="languages/base.html",
        pootle_path="/%s/" % language.code,
        resource_path="",
        resource_path_parts=[],
        url_action_continue=language.get_translate_url(state='incomplete'),
        url_action_fixcritical=language.get_critical_url(),
        url_action_review=language.get_translate_url(state='suggestions'),
        url_action_view_all=language.get_translate_url(state='all'),
        # check_categories=get_qualitycheck_schema(language),
        table=table,
        translation_states=get_translation_states(language),
        top_scorers=top_scorers,
        top_scorers_data=get_top_scorers_data(top_scorers, 10),
        checks=checks,
        stats=stats)
    sidebar = get_sidebar_announcements_context(request, (language, ))
    for k in ["has_sidebar", "is_sidebar_open", "announcements"]:
        assertions[k] = sidebar[0][k]
    view_context_test(ctx, **assertions)
Example #29
0
def overview(request, language):
    can_edit = check_permission("administrate", request)

    translation_projects = language.get_children().order_by("project__fullname")
    user_tps = filter(lambda x: x.is_accessible_by(request.user), translation_projects)
    items = (make_project_item(tp) for tp in user_tps)

    table_fields = [
        "name",
        "progress",
        "total",
        "need-translation",
        "suggestions",
        "critical",
        "last-updated",
        "activity",
    ]
    table = {"id": "language", "fields": table_fields, "headings": get_table_headings(table_fields), "items": items}

    ctx = get_overview_context(request)
    ctx.update(
        {
            "language": {
                "code": language.code,
                "name": tr_lang(language.fullname),
                "description": language.description,
            },
            "feed_path": "%s/" % language.code,
            "can_edit": can_edit,
            "table": table,
            "browser_extends": "languages/base.html",
        }
    )

    if can_edit:
        from pootle_language.forms import DescriptionForm

        ctx.update(
            {
                "form": DescriptionForm(instance=language),
                "form_action": reverse("pootle-language-admin-settings", args=[language.code]),
            }
        )

    response = render_to_response("browser/overview.html", ctx, context_instance=RequestContext(request))
    response.set_cookie("pootle-language", language.code)

    return response
Example #30
0
def overview(request, project):
    """Page listing all languages added to project."""
    from locale import strcoll

    items = [make_language_item(translation_project) for translation_project in project.get_children().iterator()]
    items.sort(lambda x, y: strcoll(x["title"], y["title"]))

    table_fields = [
        "name",
        "progress",
        "total",
        "need-translation",
        "suggestions",
        "critical",
        "last-updated",
        "activity",
    ]

    ctx = get_overview_context(request)
    ctx.update(
        {
            "project": project,
            "can_edit": check_permission("administrate", request),
            "table": {
                "id": "project",
                "fields": table_fields,
                "headings": get_table_headings(table_fields),
                "items": items,
            },
            "browser_extends": "projects/base.html",
            "browser_body_id": "projectoverview",
        }
    )

    if ctx["can_edit"]:
        from pootle_project.forms import DescriptionForm

        tag_action_url = reverse("pootle-xhr-tag-tp-in-project", kwargs={"project_code": project.code})
        ctx.update(
            {
                "form": DescriptionForm(instance=project),
                "form_action": reverse("pootle-project-admin-settings", args=[project.code]),
                "add_tag_form": TranslationProjectTagForm(project=project),
                "add_tag_action_url": tag_action_url,
            }
        )

    return render(request, "browser/overview.html", ctx)
Example #31
0
 def vfolder_data(self):
     ctx = {}
     if 'virtualfolder' not in settings.INSTALLED_APPS:
         return {}
     if len(self.vfolders) > 0:
         table_fields = [
             'name', 'priority', 'progress', 'total',
             'need-translation', 'suggestions', 'critical',
             'last-updated', 'activity']
         ctx.update({
             'vfolders': {
                 'id': 'vfolders',
                 'fields': table_fields,
                 'headings': get_table_headings(table_fields),
                 'items': self.vfolders}})
     return ctx
Example #32
0
 def vfolder_data(self):
     ctx = {}
     if 'virtualfolder' not in settings.INSTALLED_APPS:
         return {}
     if len(self.vfolders) > 0:
         table_fields = [
             'name', 'priority', 'progress', 'total',
             'need-translation', 'suggestions', 'critical',
             'last-updated', 'activity']
         ctx.update({
             'vfolders': {
                 'id': 'vfolders',
                 'fields': table_fields,
                 'headings': get_table_headings(table_fields),
                 'items': self.vfolders}})
     return ctx
Example #33
0
def overview(request, language):
    can_edit = check_permission('administrate', request)

    translation_projects = language.get_children() \
                                   .order_by('project__fullname')
    user_tps = filter(lambda x: x.is_accessible_by(request.user),
                      translation_projects)
    items = (make_project_item(tp) for tp in user_tps)

    table_fields = [
        'name', 'progress', 'total', 'need-translation', 'suggestions',
        'critical', 'last-updated', 'activity'
    ]
    table = {
        'id': 'language',
        'fields': table_fields,
        'headings': get_table_headings(table_fields),
        'items': items,
    }

    ctx = get_overview_context(request)
    ctx.update({
        'language': {
            'code': language.code,
            'name': tr_lang(language.fullname),
            'description': language.description,
        },
        'feed_path': '%s/' % language.code,
        'can_edit': can_edit,
        'table': table,
        'browser_extends': 'languages/base.html',
        'browser_body_id': 'languageoverview',
    })

    if can_edit:
        from pootle_language.forms import DescriptionForm
        ctx.update({
            'form':
            DescriptionForm(instance=language),
            'form_action':
            reverse('pootle-language-admin-settings', args=[language.code]),
        })

    return render_to_response("browser/overview.html",
                              ctx,
                              context_instance=RequestContext(request))
Example #34
0
def _test_browse_view(language, request, response, kwargs):
    assert (
        response.cookies["pootle-language"].value == language.code)
    cookie_data = json.loads(
        unquote(response.cookies[SIDEBAR_COOKIE_NAME].value))
    assert cookie_data["foo"] == "bar"
    assert "announcements_%s" % language.code in cookie_data
    ctx = response.context
    table_fields = [
        'name', 'progress', 'total', 'need-translation',
        'suggestions', 'critical', 'last-updated', 'activity']
    user_tps = language.get_children_for_user(request.user)
    items = [make_project_item(tp) for tp in user_tps]
    table = {
        'id': 'language',
        'fields': table_fields,
        'headings': get_table_headings(table_fields),
        'items': items}
    top_scorers = get_user_model().top_scorers(language=language.code, limit=10)
    assertions = dict(
        page="browse",
        object=language,
        language={
            'code': language.code,
            'name': language.name},
        browser_extends="languages/base.html",
        pootle_path="/%s/" % language.code,
        resource_path="",
        resource_path_parts=[],
        url_action_continue=language.get_translate_url(state='incomplete'),
        url_action_fixcritical=language.get_critical_url(),
        url_action_review=language.get_translate_url(state='suggestions'),
        url_action_view_all=language.get_translate_url(state='all'),
        # check_categories=get_qualitycheck_schema(language),
        table=table,
        translation_states=get_translation_states(language),
        top_scorers=top_scorers,
        top_scorers_data=get_top_scorers_data(top_scorers, 10),
        stats=language.data_tool.get_stats(user=request.user)
    )
    sidebar = get_sidebar_announcements_context(
        request, (language, ))
    for k in ["has_sidebar", "is_sidebar_open", "announcements"]:
        assertions[k] = sidebar[0][k]
    view_context_test(ctx, **assertions)
Example #35
0
def overview(request, project):
    """Page listing all languages added to project."""
    from locale import strcoll

    items = [
        make_language_item(translation_project)
        for translation_project in project.get_children().iterator()
    ]
    items.sort(lambda x, y: strcoll(x['title'], y['title']))

    table_fields = [
        'name', 'progress', 'total', 'need-translation', 'suggestions',
        'critical', 'last-updated', 'activity'
    ]

    ctx = get_overview_context(request)
    ctx.update({
        'project': project,
        'can_edit': check_permission("administrate", request),
        'table': {
            'id': 'project',
            'fields': table_fields,
            'headings': get_table_headings(table_fields),
            'items': items,
        },
        'browser_extends': 'projects/base.html',
        'browser_body_id': 'projectoverview',
    })

    if ctx['can_edit']:
        from pootle_project.forms import DescriptionForm
        tag_action_url = reverse('pootle-xhr-tag-tp-in-project',
                                 kwargs={'project_code': project.code})
        ctx.update({
            'form':
            DescriptionForm(instance=project),
            'form_action':
            reverse('pootle-project-admin-settings', args=[project.code]),
            'add_tag_form':
            TranslationProjectTagForm(project=project),
            'add_tag_action_url':
            tag_action_url,
        })

    return render(request, 'browser/overview.html', ctx)
Example #36
0
def projects_index(request, root):
    """Page listing all projects."""
    user_accessible_projects = Project.accessible_by_user(request.user)
    user_projects = Project.objects.filter(code__in=user_accessible_projects)
    items = [make_project_list_item(project) for project in user_projects]

    table_fields = ['name']

    ctx = {
        'table': {
            'id': 'projects',
            'fields': table_fields,
            'headings': get_table_headings(table_fields),
            'items': items,
        },
    }

    return render(request, "projects/list.html", ctx)
Example #37
0
def projects_index(request, root):
    """Page listing all projects."""
    user_accessible_projects = Project.accessible_by_user(request.user)
    user_projects = Project.objects.filter(code__in=user_accessible_projects)
    items = [make_project_list_item(project) for project in user_projects]

    table_fields = ["name"]

    ctx = {
        "table": {
            "id": "projects",
            "fields": table_fields,
            "headings": get_table_headings(table_fields),
            "items": items,
        }
    }

    return render(request, "projects/list.html", ctx)
Example #38
0
def overview(request, language):
    can_edit = check_permission('administrate', request)

    translation_projects = language.get_children() \
                                   .order_by('project__fullname')
    user_tps = filter(lambda x: x.is_accessible_by(request.user),
                      translation_projects)
    items = (make_project_item(tp) for tp in user_tps)

    table_fields = ['name', 'progress', 'total', 'need-translation',
                    'suggestions', 'critical', 'last-updated', 'activity']
    table = {
        'id': 'language',
        'fields': table_fields,
        'headings': get_table_headings(table_fields),
        'items': items,
    }

    ctx = get_overview_context(request)
    ctx.update({
        'language': {
          'code': language.code,
          'name': tr_lang(language.fullname),
          'description': language.description,
        },
        'feed_path': '%s/' % language.code,
        'can_edit': can_edit,
        'table': table,

        'browser_extends': 'languages/base.html',
    })

    if can_edit:
        from pootle_language.forms import DescriptionForm
        ctx.update({
            'form': DescriptionForm(instance=language),
            'form_action': reverse('pootle-language-admin-settings',
                                   args=[language.code]),
        })

    response = render(request, "browser/overview.html", ctx)
    response.set_cookie('pootle-language', language.code)

    return response
Example #39
0
def browse(request, project, dir_path, filename):
    """Languages browser for a given project."""
    item_func = (make_xlanguage_item
                 if dir_path or filename else make_language_item)
    items = [
        item_func(item)
        for item in request.resource_obj.get_children_for_user(request.profile)
    ]
    items.sort(lambda x, y: locale.strcoll(x['title'], y['title']))

    table_fields = [
        'name', 'progress', 'total', 'need-translation', 'suggestions',
        'critical', 'last-updated', 'activity'
    ]
    table = {
        'id': 'project',
        'fields': table_fields,
        'headings': get_table_headings(table_fields),
        'items': items,
    }

    ctx, cookie_data = get_sidebar_announcements_context(
        request,
        (project, ),
    )

    ctx.update(get_browser_context(request))
    ctx.update({
        'project':
        project,
        'table':
        table,
        'stats':
        jsonify(request.resource_obj.get_stats_for_user(request.user)),
        'browser_extends':
        'projects/base.html',
    })

    response = render(request, 'browser/index.html', ctx)

    if cookie_data:
        response.set_cookie(SIDEBAR_COOKIE_NAME, cookie_data)

    return response
Example #40
0
def test_vfolder_data_view(tp0, request_users):
    user = request_users["user"]
    dir0 = tp0.directory
    vf_data = vfolders_data_view.get(dir0.__class__)(dir0, user=user)
    assert isinstance(vf_data, VFoldersDataView)
    assert vf_data.context is dir0
    assert isinstance(vf_data.vfolder_data_tool, DirectoryVFDataTool)
    assert vf_data.vfolder_data_tool.context is dir0
    assert (vf_data.all_stats == vf_data.vfolder_data_tool.get_stats(
        user=user))
    assert vf_data.stats["children"] == vf_data.all_stats
    # ordering?
    rows = [make_vfolder_dict(dir0, *vf) for vf in vf_data.all_stats.items()]
    for i, row in enumerate(vf_data.table_items):
        assert rows[i] == row
    expected_table_data = dict(
        children=dict(id='vfolders',
                      fields=vf_data.table_fields,
                      headings=get_table_headings(vf_data.table_fields),
                      items=vf_data.table_items))
    assert vf_data.table_data == expected_table_data
Example #41
0
def test_view_projects_browse(site_permissions, site_matrix_with_vfolders,
                              site_matrix_with_announcements,
                              client, nobody, default):
    response = client.get(reverse("pootle-projects-browse"))
    assert response.cookies["pootle-language"].value == "projects"
    ctx = response.context
    request = response.wsgi_request
    user_projects = Project.accessible_by_user(request.user)
    user_projects = (
        Project.objects.for_user(request.user)
                       .filter(code__in=user_projects))
    ob = ProjectSet(user_projects)
    items = [
        make_project_list_item(project)
        for project in ob.children]
    items.sort(lambda x, y: locale.strcoll(x['title'], y['title']))
    table_fields = [
        'name', 'progress', 'total', 'need-translation',
        'suggestions', 'critical', 'last-updated', 'activity']
    table = {
        'id': 'projects',
        'fields': table_fields,
        'headings': get_table_headings(table_fields),
        'items': items}
    assertions = dict(
        page="browse",
        pootle_path="/projects/",
        resource_path="",
        resource_path_parts=[],
        object=ob,
        table=table,
        browser_extends="projects/all/base.html",
        stats=jsonify(ob.get_stats()),
        check_categories=get_qualitycheck_schema(ob),
        translation_states=get_translation_states(ob),
        url_action_continue=ob.get_translate_url(state='incomplete'),
        url_action_fixcritical=ob.get_critical_url(),
        url_action_review=ob.get_translate_url(state='suggestions'),
        url_action_view_all=ob.get_translate_url(state='all'))
    view_context_test(ctx, **assertions)
Example #42
0
def test_view_projects_browse(
    site_permissions, site_matrix_with_vfolders, site_matrix_with_announcements, client, nobody, default
):
    response = client.get(reverse("pootle-projects-browse"))
    assert response.cookies["pootle-language"].value == "projects"
    ctx = response.context
    request = response.wsgi_request
    user_projects = Project.accessible_by_user(request.user)
    user_projects = Project.objects.for_user(request.user).filter(code__in=user_projects)
    ob = ProjectSet(user_projects)
    items = [make_project_list_item(project) for project in ob.children]
    items.sort(lambda x, y: locale.strcoll(x["title"], y["title"]))
    table_fields = [
        "name",
        "progress",
        "total",
        "need-translation",
        "suggestions",
        "critical",
        "last-updated",
        "activity",
    ]
    table = {"id": "projects", "fields": table_fields, "headings": get_table_headings(table_fields), "items": items}
    assertions = dict(
        page="browse",
        pootle_path="/projects/",
        resource_path="",
        resource_path_parts=[],
        resource_obj=ob,
        table=table,
        browser_extends="projects/all/base.html",
        stats=jsonify(ob.get_stats()),
        check_categories=get_qualitycheck_schema(ob),
        translation_states=get_translation_states(ob),
        url_action_continue=ob.get_translate_url(state="incomplete"),
        url_action_fixcritical=ob.get_critical_url(),
        url_action_review=ob.get_translate_url(state="suggestions"),
        url_action_view_all=ob.get_translate_url(state="all"),
    )
    view_context_test(ctx, **assertions)
Example #43
0
def overview(request, project, dir_path, filename):
    """Languages overview for a given project."""
    from locale import strcoll

    item_func = (make_xlanguage_item if dir_path or filename
                                     else make_language_item)
    items = [item_func(item) for item in request.resource_obj.get_children()]
    items.sort(lambda x, y: strcoll(x['title'], y['title']))

    table_fields = ['name', 'progress', 'total', 'need-translation',
                    'suggestions', 'critical', 'last-updated', 'activity']

    ctx = get_overview_context(request)
    ctx.update({
        'project': project,
        'can_edit': check_permission("administrate", request),
        'table': {
            'id': 'project',
            'fields': table_fields,
            'headings': get_table_headings(table_fields),
            'items': items,
        },

        'browser_extends': 'projects/base.html',
    })

    if ctx['can_edit']:
        from pootle_project.forms import DescriptionForm
        tag_action_url = reverse('pootle-xhr-tag-tp-in-project',
                                 kwargs={'project_code': project.code})
        ctx.update({
            'form': DescriptionForm(instance=project),
            'form_action': reverse('pootle-project-admin-settings',
                                   args=[project.code]),
            'add_tag_form': TranslationProjectTagForm(project=project),
            'add_tag_action_url': tag_action_url,
        })

    return render(request, 'browser/overview.html', ctx)
Example #44
0
def projects_overview(request, project_set):
    """Page listing all projects."""
    items = [make_project_list_item(project)
             for project in project_set.get_children()]

    table_fields = ['name', 'progress', 'total', 'need-translation',
                    'suggestions', 'critical', 'last-updated', 'activity']

    ctx = get_overview_context(request)
    ctx.update({
        'table': {
            'id': 'projects',
            'fields': table_fields,
            'headings': get_table_headings(table_fields),
            'items': items,
        },

        'browser_extends': 'projects/all/base.html',
    })

    response = render(request, 'browser/overview.html', ctx)
    response.set_cookie('pootle-language', 'projects')

    return response
Example #45
0
def overview(request, translation_project, dir_path, filename=None,
             goal=None, in_goal_overview=False):

    if filename:
        ctx = {
            'store_tags': request.store.tag_like_objects,
        }
        template_name = "translation_projects/store_overview.html"
    else:
        ctx = {
            'tp_tags': translation_project.tag_like_objects,
        }
        template_name = "browser/overview.html"

    if (check_permission('translate', request) or
        check_permission('suggest', request) or
        check_permission('overwrite', request)):

        ctx.update({
            'upload_form': _handle_upload_form(request, translation_project),
        })

    can_edit = check_permission('administrate', request)

    project = translation_project.project
    language = translation_project.language

    resource_obj = request.store or request.directory

    #TODO enable again some actions when drilling down a goal.
    if goal is None:
        actions = action_groups(request, resource_obj)
    else:
        actions = []

    action_output = ''
    running = request.GET.get(EXTDIR, '')

    #TODO enable the following again when drilling down a goal.
    if running and goal is None:
        if request.store:
            act = StoreAction
        else:
            act = TranslationProjectAction
        try:
            action = act.lookup(running)
        except KeyError:
            messages.error(request, _("Unable to find '%(action)s' in '%(extdir)s'") %
                                      {'action': act, 'extdir': running})
        else:
            if not getattr(action, 'nosync', False):
                (request.store or translation_project).sync()
            if action.is_active(request):
                vcs_dir = settings.VCS_DIRECTORY
                po_dir = settings.PODIRECTORY
                tp_dir = request.directory.get_real_path()
                store_fn = '*'
                if request.store:
                    tp_dir_slash = add_trailing_slash(tp_dir)
                    if request.store.file.name.startswith(tp_dir_slash):
                        # Note: store_f used below in reverse() call.
                        store_f = request.store.file.name[len(tp_dir_slash):]
                        store_fn = store_f.replace('/', os.sep)

                # Clear possibly stale output/error (even from other
                # resource_obj).
                action.set_output('')
                action.set_error('')
                try:
                    action.run(path=resource_obj, root=po_dir, tpdir=tp_dir,
                               project=project.code, language=language.code,
                               store=store_fn,
                               style=translation_project.file_style,
                               vc_root=vcs_dir)
                except StandardError:
                    err = (_("Error while running '%s' extension action") %
                           action.title)
                    logging.exception(err)
                    if (action.error):
                        messages.error(request, action.error)
                    else:
                        messages.error(request, err)
                else:
                    if (action.error):
                        messages.warning(request, action.error)

                action_output = action.output
                if getattr(action, 'get_download', None):
                    export_path = action.get_download(resource_obj)
                    if export_path:
                        import mimetypes
                        abs_path = absolute_real_path(export_path)
                        filename = os.path.basename(export_path)
                        mimetype, encoding = mimetypes.guess_type(filename)
                        mimetype = mimetype or 'application/octet-stream'
                        with open(abs_path, 'rb') as f:
                            response = HttpResponse(f.read(),
                                                    mimetype=mimetype)
                        response['Content-Disposition'] = (
                                'attachment; filename="%s"' % filename)
                        return response

                if not action_output:
                    if not request.store:
                        rev_args = [language.code, project.code, '']
                        overview_url = reverse('pootle-tp-overview',
                                               args=rev_args)
                    else:
                        slash = store_f.rfind('/')
                        store_d = ''
                        if slash > 0:
                            store_d = store_f[:slash]
                            store_f = store_f[slash + 1:]
                        elif slash == 0:
                            store_f = store_f[1:]
                        rev_args = [language.code, project.code, store_d,
                                    store_f]
                        overview_url = reverse('pootle-tp-overview',
                                               args=rev_args)
                    return HttpResponseRedirect(overview_url)

    if goal is None:
        description = translation_project.description
    else:
        description = goal.description

    # TODO: cleanup and refactor, retrieve from cache
    try:
        ann_virtual_path = 'announcements/' + project.code
        announcement = StaticPage.objects.live(request.user).get(
            virtual_path=ann_virtual_path,
        )
    except StaticPage.DoesNotExist:
        announcement = None

    display_announcement = True
    stored_mtime = None
    new_mtime = None
    cookie_data = {}

    if ANN_COOKIE_NAME in request.COOKIES:
        json_str = unquote(request.COOKIES[ANN_COOKIE_NAME])
        cookie_data = simplejson.loads(json_str)

        if 'isOpen' in cookie_data:
            display_announcement = cookie_data['isOpen']

        if project.code in cookie_data:
            stored_mtime = cookie_data[project.code]

    if announcement is not None:
        ann_mtime = dateformat.format(announcement.modified_on, 'U')
        if ann_mtime != stored_mtime:
            display_announcement = True
            new_mtime = ann_mtime

    ctx.update(get_overview_context(request))
    ctx.update({
        'resource_obj': request.store or request.directory,  # Dirty hack.
        'translation_project': translation_project,
        'description': description,
        'project': project,
        'language': language,
        'feed_path': request.directory.pootle_path[1:],
        'action_groups': actions,
        'action_output': action_output,
        'can_edit': can_edit,

        'browser_extends': 'translation_projects/base.html',
        'browser_body_id': 'tpoverview',

        'announcement': announcement,
        'announcement_displayed': display_announcement,
    })

    tp_pootle_path = translation_project.pootle_path

    if request.store is None:
        resource_obj_goals = Goal.get_goals_for_path(resource_obj.pootle_path)
        resource_obj_has_goals = len(resource_obj_goals) > 0

        if in_goal_overview and resource_obj_has_goals:
            # Then show the goals tab.
            table_fields = ['name', 'progress', 'priority', 'total',
                            'need-translation', 'suggestions']
            items = [make_goal_item(resource_obj_goal, resource_obj.pootle_path)
                     for resource_obj_goal in resource_obj_goals]
            ctx.update({
                'table': {
                    'id': 'tp-goals',
                    'fields': table_fields,
                    'headings': get_table_headings(table_fields),
                    'parent': get_parent(request.directory),
                    'items': items,
                },
                'resource_obj_has_goals': True,
            })
        elif goal in resource_obj_goals:
            # Then show the drill down view for the specified goal.
            table_fields = ['name', 'progress', 'total', 'need-translation',
                            'suggestions', 'critical', 'last-updated',
                            'activity']

            ctx.update({
                'table': {
                    'id': 'tp-goals',
                    'fields': table_fields,
                    'headings': get_table_headings(table_fields),
                    'parent': get_goal_parent(request.directory, goal),
                    'items': get_goal_children(request.directory, goal),
                },
                'goal': goal,
                'goal_url': goal.get_drill_down_url_for_path(tp_pootle_path),
                'resource_obj_has_goals': True,
            })
        else:
            # Then show the files tab.
            table_fields = ['name', 'progress', 'total', 'need-translation',
                            'suggestions', 'critical', 'last-updated',
                            'activity']
            ctx.update({
                'table': {
                    'id': 'tp-files',
                    'fields': table_fields,
                    'headings': get_table_headings(table_fields),
                    'parent': get_parent(request.directory),
                    'items': get_children(request.directory),
                },
                'resource_obj_has_goals': resource_obj_has_goals,
            })
    elif goal is not None:
        ctx.update({
            'goal': goal,
            'goal_url': goal.get_drill_down_url_for_path(tp_pootle_path),
        })

    if can_edit:
        if request.store is None:
            url_kwargs = {
                'language_code': language.code,
                'project_code': project.code,
            }
            add_tag_action_url = reverse('pootle-xhr-tag-tp',
                                         kwargs=url_kwargs)
        else:
            add_tag_action_url = reverse('pootle-xhr-tag-store',
                                         args=[resource_obj.pk])

        if goal is None:
            edit_form = DescriptionForm(instance=translation_project)
            edit_form_action = reverse('pootle-tp-admin-settings',
                                       args=[language.code, project.code])
        else:
            edit_form = GoalForm(instance=goal)
            edit_form_action = reverse('pootle-xhr-edit-goal',
                                       args=[goal.slug])

        ctx.update({
            'form': edit_form,
            'form_action': edit_form_action,
            'add_tag_form': TagForm(),
            'add_tag_action_url': add_tag_action_url,
        })

    response = render_to_response(template_name, ctx,
                                  context_instance=RequestContext(request))

    if new_mtime is not None:
        cookie_data[project.code] = new_mtime
        cookie_data = quote(simplejson.dumps(cookie_data))
        response.set_cookie(ANN_COOKIE_NAME, cookie_data)

    return response
Example #46
0
def _test_browse_view(tp, request, response, kwargs):
    cookie_data = json.loads(
        unquote(response.cookies[SIDEBAR_COOKIE_NAME].value))
    assert cookie_data["foo"] == "bar"
    assert "announcements_projects_%s" % tp.project.code in cookie_data
    assert "announcements_%s" % tp.language.code in cookie_data
    assert ("announcements_%s_%s" % (tp.language.code, tp.project.code)
            in cookie_data)
    ctx = response.context
    kwargs["project_code"] = tp.project.code
    kwargs["language_code"] = tp.language.code
    resource_path = "%(dir_path)s%(filename)s" % kwargs
    pootle_path = "%s%s" % (tp.pootle_path, resource_path)

    if not (kwargs["dir_path"] or kwargs.get("filename")):
        obj = tp.directory
    elif not kwargs.get("filename"):
        obj = Directory.objects.get(pootle_path=pootle_path)
    else:
        obj = Store.objects.get(pootle_path=pootle_path)
    if not kwargs.get("filename"):
        vf_view = vfolders_data_view.get(obj.__class__)(obj, request.user)
        stats = vf_view.stats
        vfolders = stats["vfolders"]
        stats.update(obj.data_tool.get_stats(user=request.user))
    else:
        stats = obj.data_tool.get_stats(user=request.user)
        vfolders = None

    filters = {}
    if vfolders:
        filters['sort'] = 'priority'
    dirs_with_vfolders = set(
        split_pootle_path(path)[2].split("/")[0] for path in tp.stores.filter(
            vfolders__isnull=False).values_list("pootle_path", flat=True))
    directories = [
        make_directory_item(
            child,
            **(dict(
                sort="priority") if child.name in dirs_with_vfolders else {}))
        for child in obj.get_children() if isinstance(child, Directory)
    ]
    stores = [
        make_store_item(child) for child in obj.get_children()
        if isinstance(child, Store)
    ]

    if not kwargs.get("filename"):
        table_fields = [
            'name', 'progress', 'total', 'need-translation', 'suggestions',
            'critical', 'last-updated', 'activity'
        ]
        table = {
            'id': 'tp',
            'fields': table_fields,
            'headings': get_table_headings(table_fields),
            'items': directories + stores
        }
    else:
        table = None

    User = get_user_model()
    top_scorers = User.top_scorers(language=tp.language.code,
                                   project=tp.project.code,
                                   limit=11)
    assertions = dict(
        page="browse",
        object=obj,
        translation_project=tp,
        language=tp.language,
        project=tp.project,
        has_admin_access=check_permission('administrate', request),
        is_store=(kwargs.get("filename") and True or False),
        browser_extends="translation_projects/base.html",
        pootle_path=pootle_path,
        resource_path=resource_path,
        resource_path_parts=get_path_parts(resource_path),
        translation_states=get_translation_states(obj),
        checks=get_qualitycheck_list(obj),
        top_scorers=top_scorers,
        top_scorers_data=get_top_scorers_data(top_scorers, 10),
        url_action_continue=obj.get_translate_url(state='incomplete',
                                                  **filters),
        url_action_fixcritical=obj.get_critical_url(**filters),
        url_action_review=obj.get_translate_url(state='suggestions',
                                                **filters),
        url_action_view_all=obj.get_translate_url(state='all'),
        stats=stats,
        parent=get_parent(obj))
    if table:
        assertions["table"] = table
    sidebar = get_sidebar_announcements_context(request,
                                                (tp.project, tp.language, tp))
    for k in ["has_sidebar", "is_sidebar_open", "announcements"]:
        assertions[k] = sidebar[0][k]
    view_context_test(ctx, **assertions)
    if vfolders:
        for vfolder in ctx["vfolders"]["items"]:
            assert (vfolder["is_grayed"]
                    and not ctx["has_admin_access"]) is False
        assert ctx["vfolders"]["items"] == vf_view.table_items

    assert (('display_download' in ctx
             and ctx['display_download']) == (request.user.is_authenticated()
                                              and check_permission(
                                                  'translate', request)))
Example #47
0
File: views.py Project: Yelp/pootle
def browse(request, translation_project, dir_path, filename=None):
    project = translation_project.project
    language = translation_project.language

    directory = request.directory
    store = request.store
    is_admin = check_permission('administrate', request)

    ctx, cookie_data = get_sidebar_announcements_context(
        request,
        (project, language, translation_project, ),
    )

    ctx.update(get_browser_context(request))

    # TODO improve plugin logic
    if "import_export" in settings.INSTALLED_APPS:
        if request.user.is_authenticated():
            if check_permission('translate', request):
                ctx.update(handle_upload_form(request, project))
            ctx.update({'display_download': True,
                        'has_sidebar': True})

    stats = request.resource_obj.get_stats()

    if store is None:
        table_fields = ['name', 'progress', 'total', 'need-translation',
                        'suggestions', 'critical', 'last-updated', 'activity']
        ctx.update({
            'table': {
                'id': 'tp',
                'fields': table_fields,
                'headings': get_table_headings(table_fields),
                'items': get_children(directory),
            }
        })

        if 'virtualfolder' in settings.INSTALLED_APPS:
            vfolders = get_vfolders(directory, all_vfolders=is_admin)
            if len(vfolders) > 0:
                table_fields = ['name', 'priority', 'progress', 'total',
                                'need-translation', 'suggestions', 'critical',
                                'last-updated', 'activity']
                ctx.update({
                    'vfolders': {
                        'id': 'vfolders',
                        'fields': table_fields,
                        'headings': get_table_headings(table_fields),
                        'items': vfolders,
                    },
                })

                # FIXME: set vfolders stats in the resource, don't inject them
                # here.
                stats['vfolders'] = {}

                for vfolder_treeitem in directory.vf_treeitems.iterator():
                    if request.user.is_superuser or vfolder_treeitem.is_visible:
                        stats['vfolders'][vfolder_treeitem.code] = \
                            vfolder_treeitem.get_stats(include_children=False)

    ctx.update({
        'parent': get_parent(directory if store is None else store),
        'translation_project': translation_project,
        'project': project,
        'language': language,
        'stats': jsonify(stats),
        'is_admin': is_admin,
        'is_store': store is not None,

        'browser_extends': 'translation_projects/base.html',
    })

    response = render(request, 'browser/index.html', ctx)

    if cookie_data:
        response.set_cookie(SIDEBAR_COOKIE_NAME, cookie_data)

    return response
Example #48
0
def overview(request, translation_project, dir_path, filename=None, goal=None):
    from django.utils import dateformat
    from staticpages.models import StaticPage
    from .actions import action_groups

    if filename:
        ctx = {
            'store_tags': request.store.tag_like_objects,
        }
        template_name = "translation_projects/store_overview.html"
    else:
        ctx = {
            'tp_tags': translation_project.tag_like_objects,
        }
        template_name = "browser/overview.html"

    if (check_permission('translate', request) or
        check_permission('suggest', request) or
        check_permission('overwrite', request)):

        ctx.update({
            'upload_form': _handle_upload_form(request, translation_project),
        })

    can_edit = check_permission('administrate', request)

    project = translation_project.project
    language = translation_project.language

    resource_obj = request.store or request.directory

    #TODO enable again some actions when drilling down a goal.
    if goal is None:
        actions = action_groups(request, resource_obj)
    else:
        actions = []

    action_output = ''

    # TODO: cleanup and refactor, retrieve from cache
    try:
        ann_virtual_path = 'announcements/' + project.code
        announcement = StaticPage.objects.live(request.user).get(
            virtual_path=ann_virtual_path,
        )
    except StaticPage.DoesNotExist:
        announcement = None

    display_announcement = True
    stored_mtime = None
    new_mtime = None
    cookie_data = {}

    if ANN_COOKIE_NAME in request.COOKIES:
        json_str = unquote(request.COOKIES[ANN_COOKIE_NAME])
        cookie_data = json.loads(json_str)

        if 'isOpen' in cookie_data:
            display_announcement = cookie_data['isOpen']

        if project.code in cookie_data:
            stored_mtime = cookie_data[project.code]

    if announcement is not None:
        ann_mtime = dateformat.format(announcement.modified_on, 'U')
        if ann_mtime != stored_mtime:
            display_announcement = True
            new_mtime = ann_mtime

    tp_goals = translation_project.all_goals

    ctx.update(get_overview_context(request))
    ctx.update({
        'resource_obj': request.store or request.directory,  # Dirty hack.
        'translation_project': translation_project,
        'description': translation_project.description,
        'project': project,
        'language': language,
        'tp_goals': tp_goals,
        'goal': goal,
        'feed_path': request.directory.pootle_path[1:],
        'action_groups': actions,
        'action_output': action_output,
        'can_edit': can_edit,

        'browser_extends': 'translation_projects/base.html',

        'announcement': announcement,
        'announcement_displayed': display_announcement,
    })

    tp_pootle_path = translation_project.pootle_path

    if request.store is None:
        table_fields = ['name', 'progress', 'total', 'need-translation',
                        'suggestions', 'critical', 'last-updated', 'activity']

        if goal is not None:
            # Then show the drill down view for the specified goal.
            continue_url = goal.get_translate_url_for_path(request.pootle_path,
                                                           state='incomplete')
            critical_url = goal.get_critical_url_for_path(request.pootle_path)
            review_url = goal.get_translate_url_for_path(request.pootle_path,
                                                         state='suggestions')
            all_url = goal.get_translate_url_for_path(request.pootle_path)

            ctx.update({
                'table': {
                    'id': 'tp-goals',
                    'fields': table_fields,
                    'headings': get_table_headings(table_fields),
                    'parent': get_goal_parent(request.directory, goal),
                    'items': get_goal_children(request.directory, goal),
                },
                'url_action_continue': continue_url,
                'url_action_fixcritical': critical_url,
                'url_action_review': review_url,
                'url_action_view_all': all_url,
            })
        else:
            # Then show the files tab.
            ctx.update({
                'table': {
                    'id': 'tp-files',
                    'fields': table_fields,
                    'headings': get_table_headings(table_fields),
                    'parent': get_parent(request.directory),
                    'items': get_children(request.directory),
                },
            })

    if can_edit:
        if request.store is None:
            add_tag_action_url = reverse('pootle-xhr-tag-tp',
                                         args=[language.code, project.code])
        else:
            add_tag_action_url = reverse('pootle-xhr-tag-store',
                                         args=[resource_obj.pk])

        ctx.update({
            'form': DescriptionForm(instance=translation_project),
            'form_action': reverse('pootle-tp-admin-settings',
                                   args=[language.code, project.code]),
            'add_tag_form': TagForm(),
            'add_tag_action_url': add_tag_action_url,
        })

        if goal is not None:
            ctx.update({
                'goal_form': GoalForm(instance=goal),
                'goal_form_action': reverse('pootle-xhr-edit-goal',
                                            args=[goal.slug]),
            })

    response = render(request, template_name, ctx)

    if new_mtime is not None:
        cookie_data[project.code] = new_mtime
        cookie_data = quote(json.dumps(cookie_data))
        response.set_cookie(ANN_COOKIE_NAME, cookie_data)

    return response
Example #49
0
def overview(request, translation_project, dir_path, filename=None):
    project = translation_project.project
    language = translation_project.language

    directory = request.directory
    store = request.store

    # TODO: cleanup and refactor, retrieve from cache
    try:
        ann_virtual_path = 'announcements/projects/' + project.code
        announcement = StaticPage.objects.live(request.user).get(
            virtual_path=ann_virtual_path, )
    except StaticPage.DoesNotExist:
        announcement = None

    has_announcement = announcement is not None
    has_sidebar = has_announcement
    is_sidebar_open = True
    stored_mtime = None
    new_mtime = None
    cookie_data = {}

    if SIDEBAR_COOKIE_NAME in request.COOKIES:
        json_str = unquote(request.COOKIES[SIDEBAR_COOKIE_NAME])
        cookie_data = json.loads(json_str)

        if 'isOpen' in cookie_data:
            is_sidebar_open = cookie_data['isOpen']

        if project.code in cookie_data:
            stored_mtime = cookie_data[project.code]

    if has_announcement:
        ann_mtime = dateformat.format(announcement.modified_on, 'U')
        if ann_mtime != stored_mtime:
            is_sidebar_open = True
            new_mtime = ann_mtime

    ctx = get_overview_context(request)

    # TODO improve plugin logic
    if "import_export" in settings.INSTALLED_APPS and request.user.is_authenticated(
    ):
        from import_export.views import handle_upload_form
        from pootle_app.models.permissions import check_permission

        ctx.update(handle_upload_form(request))

        has_download = (check_permission('translate', request)
                        or check_permission('suggest', request))
        ctx.update({
            'display_download': has_download,
        })
        has_sidebar = True

    if store is None:
        table_fields = [
            'name', 'progress', 'total', 'need-translation', 'suggestions',
            'critical', 'last-updated', 'activity'
        ]
        ctx.update({
            'table': {
                'id': 'tp',
                'fields': table_fields,
                'headings': get_table_headings(table_fields),
                'parent': get_parent(directory),
                'items': get_children(directory),
            }
        })

    ctx.update({
        'translation_project': translation_project,
        'project': project,
        'language': language,
        'stats': jsonify(request.resource_obj.get_stats()),
        'browser_extends': 'translation_projects/base.html',
        'announcement': announcement,
        'is_sidebar_open': is_sidebar_open,
        'has_sidebar': has_sidebar,
    })

    response = render(request, 'browser/overview.html', ctx)

    if new_mtime is not None:
        cookie_data[project.code] = new_mtime
        cookie_data = quote(json.dumps(cookie_data))
        response.set_cookie(SIDEBAR_COOKIE_NAME, cookie_data)

    return response
Example #50
0
def _test_browse_view(project, request, response, kwargs):
    cookie_data = json.loads(
        unquote(response.cookies[SIDEBAR_COOKIE_NAME].value))
    assert cookie_data["foo"] == "bar"
    assert "announcements_projects_%s" % project.code in cookie_data
    ctx = response.context
    kwargs["project_code"] = project.code
    resource_path = (
        "%(dir_path)s%(filename)s" % kwargs)
    project_path = (
        "%s/%s"
        % (kwargs["project_code"], resource_path))
    if not (kwargs["dir_path"] or kwargs["filename"]):
        obj = project
    elif not kwargs["filename"]:
        obj = ProjectResource(
            Directory.objects.live().filter(
                pootle_path__regex="^/.*/%s$" % project_path),
            pootle_path="/projects/%s" % project_path)
    else:
        obj = ProjectResource(
            Store.objects.live().filter(
                pootle_path__regex="^/.*/%s$" % project_path),
            pootle_path="/projects/%s" % project_path)

    item_func = (
        make_xlanguage_item
        if (kwargs["dir_path"]
            or kwargs["filename"])
        else make_language_item)
    items = [
        item_func(item)
        for item
        in obj.get_children_for_user(request.user)
    ]
    items.sort(lambda x, y: locale.strcoll(x['title'], y['title']))

    table_fields = ['name', 'progress', 'total', 'need-translation',
                    'suggestions', 'critical', 'last-updated', 'activity']
    table = {
        'id': 'project',
        'fields': table_fields,
        'headings': get_table_headings(table_fields),
        'items': items}

    if request.user.is_superuser or kwargs.get("language_code"):
        url_action_continue = obj.get_translate_url(state='incomplete')
        url_action_fixcritical = obj.get_critical_url()
        url_action_review = obj.get_translate_url(state='suggestions')
        url_action_view_all = obj.get_translate_url(state='all')
    else:
        (url_action_continue,
         url_action_fixcritical,
         url_action_review,
         url_action_view_all) = [None] * 4

    User = get_user_model()
    top_scorers = User.top_scorers(project=project.code, limit=10)
    assertions = dict(
        page="browse",
        project=project,
        browser_extends="projects/base.html",
        pootle_path="/projects/%s" % project_path,
        resource_path=resource_path,
        resource_path_parts=get_path_parts(resource_path),
        url_action_continue=url_action_continue,
        url_action_fixcritical=url_action_fixcritical,
        url_action_review=url_action_review,
        url_action_view_all=url_action_view_all,
        translation_states=get_translation_states(obj),
        checks=get_qualitycheck_list(obj),
        table=table,
        top_scorers=top_scorers,
        top_scorers_data=get_top_scorers_data(top_scorers, 10),
        stats=obj.data_tool.get_stats(user=request.user),
    )
    sidebar = get_sidebar_announcements_context(
        request, (project, ))
    for k in ["has_sidebar", "is_sidebar_open", "announcements"]:
        assertions[k] = sidebar[0][k]
    view_context_test(ctx, **assertions)
Example #51
0
def overview(request, translation_project, dir_path, filename=None):
    project = translation_project.project
    language = translation_project.language

    directory = request.directory
    store = request.store

    # TODO: cleanup and refactor, retrieve from cache
    try:
        ann_virtual_path = 'announcements/' + project.code
        announcement = StaticPage.objects.live(request.user).get(
            virtual_path=ann_virtual_path,
        )
    except StaticPage.DoesNotExist:
        announcement = None

    display_announcement = True
    stored_mtime = None
    new_mtime = None
    cookie_data = {}

    if ANN_COOKIE_NAME in request.COOKIES:
        json_str = unquote(request.COOKIES[ANN_COOKIE_NAME])
        cookie_data = json.loads(json_str)

        if 'isOpen' in cookie_data:
            display_announcement = cookie_data['isOpen']

        if project.code in cookie_data:
            stored_mtime = cookie_data[project.code]

    if announcement is not None:
        ann_mtime = dateformat.format(announcement.modified_on, 'U')
        if ann_mtime != stored_mtime:
            display_announcement = True
            new_mtime = ann_mtime

    ctx = get_overview_context(request)
    ctx.update({
        'translation_project': translation_project,
        'project': project,
        'language': language,
        'stats': jsonify(request.resource_obj.get_stats()),

        'browser_extends': 'translation_projects/base.html',

        'announcement': announcement,
        'announcement_displayed': display_announcement,
    })

    if store is None:
        table_fields = ['name', 'progress', 'total', 'need-translation',
                        'suggestions', 'critical', 'last-updated', 'activity']
        ctx.update({
            'table': {
                'id': 'tp',
                'fields': table_fields,
                'headings': get_table_headings(table_fields),
                'parent': get_parent(directory),
                'items': get_children(directory),
            }
        })

    response = render(request, 'browser/overview.html', ctx)

    if new_mtime is not None:
        cookie_data[project.code] = new_mtime
        cookie_data = quote(json.dumps(cookie_data))
        response.set_cookie(ANN_COOKIE_NAME, cookie_data)

    return response
Example #52
0
def overview(request, translation_project, dir_path, filename=None,
             goal=None, in_goal_overview=False):

    if filename:
        ctx = {
            'store_tags': request.store.tag_like_objects,
        }
        template_name = "translation_projects/store_overview.html"
    else:
        ctx = {
            'tp_tags': translation_project.tag_like_objects,
        }
        template_name = "browser/overview.html"

    if (check_permission('translate', request) or
        check_permission('suggest', request) or
        check_permission('overwrite', request)):

        ctx.update({
            'upload_form': _handle_upload_form(request, translation_project),
        })

    can_edit = check_permission('administrate', request)

    project = translation_project.project
    language = translation_project.language

    resource_obj = request.store or request.directory

    #TODO enable again some actions when drilling down a goal.
    if goal is None:
        actions = action_groups(request, resource_obj)
    else:
        actions = []

    action_output = ''
    running = request.GET.get(EXTDIR, '')

    #TODO enable the following again when drilling down a goal.
    if running and goal is None:
        if request.store:
            act = StoreAction
        else:
            act = TranslationProjectAction
        try:
            action = act.lookup(running)
        except KeyError:
            messages.error(request, _("Unable to find '%(action)s' in '%(extdir)s'") %
                                      {'action': act, 'extdir': running})
        else:
            if not getattr(action, 'nosync', False):
                (request.store or translation_project).sync()
            if action.is_active(request):
                vcs_dir = settings.VCS_DIRECTORY
                po_dir = settings.PODIRECTORY
                tp_dir = request.directory.get_real_path()
                store_fn = '*'
                if request.store:
                    tp_dir_slash = add_trailing_slash(tp_dir)
                    if request.store.file.name.startswith(tp_dir_slash):
                        # Note: store_f used below in reverse() call.
                        store_f = request.store.file.name[len(tp_dir_slash):]
                        store_fn = store_f.replace('/', os.sep)

                # Clear possibly stale output/error (even from other
                # resource_obj).
                action.set_output('')
                action.set_error('')
                try:
                    action.run(path=resource_obj, root=po_dir, tpdir=tp_dir,
                               project=project.code, language=language.code,
                               store=store_fn,
                               style=translation_project.file_style,
                               vc_root=vcs_dir)
                except StandardError:
                    err = (_("Error while running '%s' extension action") %
                           action.title)
                    logging.exception(err)
                    if (action.error):
                        messages.error(request, action.error)
                    else:
                        messages.error(request, err)
                else:
                    if (action.error):
                        messages.warning(request, action.error)

                action_output = action.output
                if getattr(action, 'get_download', None):
                    export_path = action.get_download(resource_obj)
                    if export_path:
                        import mimetypes
                        abs_path = absolute_real_path(export_path)
                        filename = os.path.basename(export_path)
                        mimetype, encoding = mimetypes.guess_type(filename)
                        mimetype = mimetype or 'application/octet-stream'
                        with open(abs_path, 'rb') as f:
                            response = HttpResponse(f.read(),
                                                    mimetype=mimetype)
                        response['Content-Disposition'] = (
                                'attachment; filename="%s"' % filename)
                        return response

                if not action_output:
                    if not request.store:
                        rev_args = [language.code, project.code, '']
                        overview_url = reverse('pootle-tp-overview',
                                               args=rev_args)
                    else:
                        slash = store_f.rfind('/')
                        store_d = ''
                        if slash > 0:
                            store_d = store_f[:slash]
                            store_f = store_f[slash + 1:]
                        elif slash == 0:
                            store_f = store_f[1:]
                        rev_args = [language.code, project.code, store_d,
                                    store_f]
                        overview_url = reverse('pootle-tp-overview',
                                               args=rev_args)
                    return HttpResponseRedirect(overview_url)

    if goal is None:
        description = translation_project.description
    else:
        description = goal.description

    # TODO: cleanup and refactor, retrieve from cache
    try:
        ann_virtual_path = 'announcements/' + project.code
        announcement = StaticPage.objects.live(request.user).get(
            virtual_path=ann_virtual_path,
        )
    except StaticPage.DoesNotExist:
        announcement = None

    display_announcement = True
    stored_mtime = None
    new_mtime = None
    cookie_data = {}

    if ANN_COOKIE_NAME in request.COOKIES:
        json_str = unquote(request.COOKIES[ANN_COOKIE_NAME])
        cookie_data = json.loads(json_str)

        if 'isOpen' in cookie_data:
            display_announcement = cookie_data['isOpen']

        if project.code in cookie_data:
            stored_mtime = cookie_data[project.code]

    if announcement is not None:
        ann_mtime = dateformat.format(announcement.modified_on, 'U')
        if ann_mtime != stored_mtime:
            display_announcement = True
            new_mtime = ann_mtime

    ctx.update(get_overview_context(request))
    ctx.update({
        'resource_obj': request.store or request.directory,  # Dirty hack.
        'translation_project': translation_project,
        'description': description,
        'project': project,
        'language': language,
        'feed_path': request.directory.pootle_path[1:],
        'action_groups': actions,
        'action_output': action_output,
        'can_edit': can_edit,

        'browser_extends': 'translation_projects/base.html',

        'announcement': announcement,
        'announcement_displayed': display_announcement,
    })

    tp_pootle_path = translation_project.pootle_path

    if request.store is None:
        resource_obj_goals = Goal.get_goals_for_path(resource_obj.pootle_path)
        resource_obj_has_goals = len(resource_obj_goals) > 0

        if in_goal_overview and resource_obj_has_goals:
            # Then show the goals tab.
            table_fields = ['name', 'progress', 'priority', 'total',
                            'need-translation', 'suggestions']
            items = [make_goal_item(resource_obj_goal, resource_obj.pootle_path)
                     for resource_obj_goal in resource_obj_goals]
            ctx.update({
                'table': {
                    'id': 'tp-goals',
                    'fields': table_fields,
                    'headings': get_table_headings(table_fields),
                    'parent': get_parent(request.directory),
                    'items': items,
                },
                'resource_obj_has_goals': True,
            })
        elif goal in resource_obj_goals:
            # Then show the drill down view for the specified goal.
            table_fields = ['name', 'progress', 'total', 'need-translation',
                            'suggestions', 'critical', 'last-updated',
                            'activity']

            ctx.update({
                'table': {
                    'id': 'tp-goals',
                    'fields': table_fields,
                    'headings': get_table_headings(table_fields),
                    'parent': get_goal_parent(request.directory, goal),
                    'items': get_goal_children(request.directory, goal),
                },
                'goal': goal,
                'goal_url': goal.get_drill_down_url_for_path(tp_pootle_path),
                'resource_obj_has_goals': True,
            })
        else:
            # Then show the files tab.
            table_fields = ['name', 'progress', 'total', 'need-translation',
                            'suggestions', 'critical', 'last-updated',
                            'activity']
            ctx.update({
                'table': {
                    'id': 'tp-files',
                    'fields': table_fields,
                    'headings': get_table_headings(table_fields),
                    'parent': get_parent(request.directory),
                    'items': get_children(request.directory),
                },
                'resource_obj_has_goals': resource_obj_has_goals,
            })
    elif goal is not None:
        ctx.update({
            'goal': goal,
            'goal_url': goal.get_drill_down_url_for_path(tp_pootle_path),
        })

    if can_edit:
        if request.store is None:
            url_kwargs = {
                'language_code': language.code,
                'project_code': project.code,
            }
            add_tag_action_url = reverse('pootle-xhr-tag-tp',
                                         kwargs=url_kwargs)
        else:
            add_tag_action_url = reverse('pootle-xhr-tag-store',
                                         args=[resource_obj.pk])

        if goal is None:
            edit_form = DescriptionForm(instance=translation_project)
            edit_form_action = reverse('pootle-tp-admin-settings',
                                       args=[language.code, project.code])
        else:
            edit_form = GoalForm(instance=goal)
            edit_form_action = reverse('pootle-xhr-edit-goal',
                                       args=[goal.slug])

        ctx.update({
            'form': edit_form,
            'form_action': edit_form_action,
            'add_tag_form': TagForm(),
            'add_tag_action_url': add_tag_action_url,
        })

    response = render_to_response(template_name, ctx,
                                  context_instance=RequestContext(request))

    if new_mtime is not None:
        cookie_data[project.code] = new_mtime
        cookie_data = quote(json.dumps(cookie_data))
        response.set_cookie(ANN_COOKIE_NAME, cookie_data)

    return response
Example #53
0
def overview(request, translation_project, dir_path, filename=None):
    project = translation_project.project
    language = translation_project.language

    directory = request.directory
    store = request.store

    # TODO: cleanup and refactor, retrieve from cache
    try:
        ann_virtual_path = 'announcements/projects/' + project.code
        announcement = StaticPage.objects.live(request.user).get(
            virtual_path=ann_virtual_path, )
    except StaticPage.DoesNotExist:
        announcement = None

    display_announcement = True
    stored_mtime = None
    new_mtime = None
    cookie_data = {}

    if ANN_COOKIE_NAME in request.COOKIES:
        json_str = unquote(request.COOKIES[ANN_COOKIE_NAME])
        cookie_data = json.loads(json_str)

        if 'isOpen' in cookie_data:
            display_announcement = cookie_data['isOpen']

        if project.code in cookie_data:
            stored_mtime = cookie_data[project.code]

    if announcement is not None:
        ann_mtime = dateformat.format(announcement.modified_on, 'U')
        if ann_mtime != stored_mtime:
            display_announcement = True
            new_mtime = ann_mtime

    ctx = get_overview_context(request)
    ctx.update({
        'translation_project': translation_project,
        'project': project,
        'language': language,
        'stats': jsonify(request.resource_obj.get_stats()),
        'browser_extends': 'translation_projects/base.html',
        'announcement': announcement,
        'announcement_displayed': display_announcement,
    })

    if store is None:
        table_fields = [
            'name', 'progress', 'total', 'need-translation', 'suggestions',
            'critical', 'last-updated', 'activity'
        ]
        ctx.update({
            'table': {
                'id': 'tp',
                'fields': table_fields,
                'headings': get_table_headings(table_fields),
                'parent': get_parent(directory),
                'items': get_children(directory),
            }
        })

    response = render(request, 'browser/overview.html', ctx)

    if new_mtime is not None:
        cookie_data[project.code] = new_mtime
        cookie_data = quote(json.dumps(cookie_data))
        response.set_cookie(ANN_COOKIE_NAME, cookie_data)

    return response
Example #54
0
def _test_browse_view(project, request, response, kwargs):
    cookie_data = json.loads(
        unquote(response.cookies[SIDEBAR_COOKIE_NAME].value))
    assert cookie_data["foo"] == "bar"
    assert "announcements_projects_%s" % project.code in cookie_data
    ctx = response.context
    kwargs["project_code"] = project.code
    resource_path = ("%(dir_path)s%(filename)s" % kwargs)
    project_path = ("%s/%s" % (kwargs["project_code"], resource_path))
    if not (kwargs["dir_path"] or kwargs["filename"]):
        obj = project
    elif not kwargs["filename"]:
        obj = ProjectResource(Directory.objects.live().filter(
            pootle_path__regex="^/.*/%s$" % project_path),
                              pootle_path="/projects/%s" % project_path)
    else:
        obj = ProjectResource(Store.objects.live().filter(
            pootle_path__regex="^/.*/%s$" % project_path),
                              pootle_path="/projects/%s" % project_path)

    item_func = (make_xlanguage_item if
                 (kwargs["dir_path"]
                  or kwargs["filename"]) else make_language_item)
    items = [
        item_func(item) for item in obj.get_children_for_user(request.user)
    ]
    items.sort(lambda x, y: locale.strcoll(x['title'], y['title']))
    stats = obj.data_tool.get_stats(user=request.user)
    for item in items:
        if item["code"] in stats["children"]:
            item["stats"] = stats["children"][item["code"]]
    table_fields = [
        'name', 'progress', 'total', 'need-translation', 'suggestions',
        'critical', 'last-updated', 'activity'
    ]
    table = {
        'id': 'project',
        'fields': table_fields,
        'headings': get_table_headings(table_fields),
        'items': items
    }

    if request.user.is_superuser or kwargs.get("language_code"):
        url_action_continue = obj.get_translate_url(state='incomplete')
        url_action_fixcritical = obj.get_critical_url()
        url_action_review = obj.get_translate_url(state='suggestions')
        url_action_view_all = obj.get_translate_url(state='all')
    else:
        (url_action_continue, url_action_fixcritical, url_action_review,
         url_action_view_all) = [None] * 4
    checks = ChecksDisplay(obj).checks_by_category
    stats = StatsDisplay(obj, stats=stats).stats
    del stats["children"]
    User = get_user_model()
    top_scorers = User.top_scorers(project=project.code, limit=10)
    assertions = dict(page="browse",
                      project=project,
                      browser_extends="projects/base.html",
                      pootle_path="/projects/%s" % project_path,
                      resource_path=resource_path,
                      resource_path_parts=get_path_parts(resource_path),
                      url_action_continue=url_action_continue,
                      url_action_fixcritical=url_action_fixcritical,
                      url_action_review=url_action_review,
                      url_action_view_all=url_action_view_all,
                      translation_states=get_translation_states(obj),
                      table=table,
                      top_scorers=top_scorers,
                      top_scorers_data=get_top_scorers_data(top_scorers, 10),
                      checks=checks,
                      stats=stats)
    sidebar = get_sidebar_announcements_context(request, (project, ))
    for k in ["has_sidebar", "is_sidebar_open", "announcements"]:
        assertions[k] = sidebar[0][k]
    view_context_test(ctx, **assertions)
Example #55
0
def _test_browse_view(tp, request, response, kwargs):
    cookie_data = json.loads(
        unquote(response.cookies[SIDEBAR_COOKIE_NAME].value))
    assert cookie_data["foo"] == "bar"
    assert "announcements_projects_%s" % tp.project.code in cookie_data
    assert "announcements_%s" % tp.language.code in cookie_data
    assert (
        "announcements_%s_%s"
        % (tp.language.code, tp.project.code)
        in cookie_data)
    ctx = response.context
    kwargs["project_code"] = tp.project.code
    kwargs["language_code"] = tp.language.code
    resource_path = "%(dir_path)s%(filename)s" % kwargs
    pootle_path = "%s%s" % (tp.pootle_path, resource_path)

    if not (kwargs["dir_path"] or kwargs.get("filename")):
        ob = tp.directory
    elif not kwargs.get("filename"):
        ob = Directory.objects.get(
            pootle_path=pootle_path)
    else:
        ob = Store.objects.get(
            pootle_path=pootle_path)
    if not kwargs.get("filename"):
        vftis = ob.vf_treeitems.select_related("vfolder")
        if not ctx["has_admin_access"]:
            vftis = vftis.filter(vfolder__is_public=True)
        vfolders = [
            make_vfolder_treeitem_dict(vfolder_treeitem)
            for vfolder_treeitem
            in vftis.order_by('-vfolder__priority')
            if (ctx["has_admin_access"]
                or vfolder_treeitem.is_visible)]
        stats = {"vfolders": {}}
        for vfolder_treeitem in vfolders or []:
            stats['vfolders'][
                vfolder_treeitem['code']] = vfolder_treeitem["stats"]
            del vfolder_treeitem["stats"]
        if stats["vfolders"]:
            stats.update(ob.get_stats())
        else:
            stats = ob.get_stats()
        stats = jsonify(stats)
    else:
        stats = jsonify(ob.get_stats())
        vfolders = None

    filters = {}
    if vfolders:
        filters['sort'] = 'priority'

    dirs_with_vfolders = vftis_for_child_dirs(ob).values_list(
        "directory__pk", flat=True)
    directories = [
        make_directory_item(
            child,
            **(dict(sort="priority")
               if child.pk in dirs_with_vfolders
               else {}))
        for child in ob.get_children()
        if isinstance(child, Directory)]
    stores = [
        make_store_item(child)
        for child in ob.get_children()
        if isinstance(child, Store)]

    if not kwargs.get("filename"):
        table_fields = [
            'name', 'progress', 'total', 'need-translation',
            'suggestions', 'critical', 'last-updated', 'activity']
        table = {
            'id': 'tp',
            'fields': table_fields,
            'headings': get_table_headings(table_fields),
            'items': directories + stores}
    else:
        table = None

    assertions = dict(
        page="browse",
        object=ob,
        translation_project=tp,
        language=tp.language,
        project=tp.project,
        has_admin_access=check_permission('administrate', request),
        is_store=(kwargs.get("filename") and True or False),
        browser_extends="translation_projects/base.html",
        pootle_path=pootle_path,
        resource_path=resource_path,
        resource_path_parts=get_path_parts(resource_path),
        translation_states=get_translation_states(ob),
        check_categories=get_qualitycheck_schema(ob),
        url_action_continue=ob.get_translate_url(
            state='incomplete', **filters),
        url_action_fixcritical=ob.get_critical_url(**filters),
        url_action_review=ob.get_translate_url(
            state='suggestions', **filters),
        url_action_view_all=ob.get_translate_url(state='all'),
        stats=stats,
        parent=get_parent(ob))
    if table:
        assertions["table"] = table
    sidebar = get_sidebar_announcements_context(
        request, (tp.project, tp.language, tp))
    for k in ["has_sidebar", "is_sidebar_open", "announcements"]:
        assertions[k] = sidebar[0][k]
    view_context_test(ctx, **assertions)
    if vfolders:
        for vfolder in ctx["vfolders"]["items"]:
            assert (vfolder["is_grayed"] and not ctx["has_admin_access"]) is False
        assert (
            ctx["vfolders"]["items"]
            == vfolders)

    assert (('display_download' in ctx and ctx['display_download']) ==
            (request.user.is_authenticated()
             and check_permission('translate', request)))
Example #56
0
def overview(request, translation_project, dir_path, filename=None, goal=None, in_goal_overview=False):

    if filename:
        ctx = {"store_tags": request.store.tag_like_objects}
        template_name = "translation_projects/store_overview.html"
    else:
        ctx = {"tp_tags": translation_project.tag_like_objects}
        template_name = "browser/overview.html"

    if (
        check_permission("translate", request)
        or check_permission("suggest", request)
        or check_permission("overwrite", request)
    ):

        ctx.update({"upload_form": _handle_upload_form(request, translation_project)})

    can_edit = check_permission("administrate", request)

    project = translation_project.project
    language = translation_project.language

    resource_obj = request.store or request.directory

    # TODO enable again some actions when drilling down a goal.
    if goal is None:
        actions = action_groups(request, resource_obj)
    else:
        actions = []

    action_output = ""
    running = request.GET.get(EXTDIR, "")

    # TODO enable the following again when drilling down a goal.
    if running and goal is None:
        if request.store:
            act = StoreAction
        else:
            act = TranslationProjectAction
        try:
            action = act.lookup(running)
        except KeyError:
            messages.error(
                request, _("Unable to find '%(action)s' in '%(extdir)s'") % {"action": act, "extdir": running}
            )
        else:
            if not getattr(action, "nosync", False):
                (request.store or translation_project).sync()
            if action.is_active(request):
                vcs_dir = settings.VCS_DIRECTORY
                po_dir = settings.PODIRECTORY
                tp_dir = request.directory.get_real_path()
                store_fn = "*"
                if request.store:
                    tp_dir_slash = add_trailing_slash(tp_dir)
                    if request.store.file.name.startswith(tp_dir_slash):
                        # Note: store_f used below in reverse() call.
                        store_f = request.store.file.name[len(tp_dir_slash) :]
                        store_fn = store_f.replace("/", os.sep)

                # Clear possibly stale output/error (even from other
                # resource_obj).
                action.set_output("")
                action.set_error("")
                try:
                    action.run(
                        path=resource_obj,
                        root=po_dir,
                        tpdir=tp_dir,
                        project=project.code,
                        language=language.code,
                        store=store_fn,
                        style=translation_project.file_style,
                        vc_root=vcs_dir,
                    )
                except StandardError:
                    err = _("Error while running '%s' extension action") % action.title
                    logging.exception(err)
                    if action.error:
                        messages.error(request, action.error)
                    else:
                        messages.error(request, err)
                else:
                    if action.error:
                        messages.warning(request, action.error)

                action_output = action.output
                if getattr(action, "get_download", None):
                    export_path = action.get_download(resource_obj)
                    if export_path:
                        import mimetypes

                        abs_path = absolute_real_path(export_path)
                        filename = os.path.basename(export_path)
                        mimetype, encoding = mimetypes.guess_type(filename)
                        mimetype = mimetype or "application/octet-stream"
                        with open(abs_path, "rb") as f:
                            response = HttpResponse(f.read(), mimetype=mimetype)
                        response["Content-Disposition"] = 'attachment; filename="%s"' % filename
                        return response

                if not action_output:
                    if not request.store:
                        rev_args = [language.code, project.code, ""]
                        overview_url = reverse("pootle-tp-overview", args=rev_args)
                    else:
                        slash = store_f.rfind("/")
                        store_d = ""
                        if slash > 0:
                            store_d = store_f[:slash]
                            store_f = store_f[slash + 1 :]
                        elif slash == 0:
                            store_f = store_f[1:]
                        rev_args = [language.code, project.code, store_d, store_f]
                        overview_url = reverse("pootle-tp-overview", args=rev_args)
                    return HttpResponseRedirect(overview_url)

    if goal is None:
        description = translation_project.description
    else:
        description = goal.description

    ctx.update(get_overview_context(request))
    ctx.update(
        {
            "resource_obj": request.store or request.directory,  # Dirty hack.
            "translation_project": translation_project,
            "description": description,
            "project": project,
            "language": language,
            "feed_path": request.directory.pootle_path[1:],
            "action_groups": actions,
            "action_output": action_output,
            "can_edit": can_edit,
            "browser_extends": "translation_projects/base.html",
            "browser_body_id": "tpoverview",
        }
    )

    tp_pootle_path = translation_project.pootle_path

    if request.store is None:
        resource_obj_goals = Goal.get_goals_for_path(resource_obj.pootle_path)
        resource_obj_has_goals = len(resource_obj_goals) > 0

        if in_goal_overview and resource_obj_has_goals:
            # Then show the goals tab.
            table_fields = ["name", "progress", "priority", "total", "need-translation", "suggestions"]
            items = [
                make_goal_item(resource_obj_goal, resource_obj.pootle_path) for resource_obj_goal in resource_obj_goals
            ]
            ctx.update(
                {
                    "table": {
                        "id": "tp-goals",
                        "fields": table_fields,
                        "headings": get_table_headings(table_fields),
                        "parent": get_parent(request.directory),
                        "items": items,
                    },
                    "resource_obj_has_goals": True,
                }
            )
        elif goal in resource_obj_goals:
            # Then show the drill down view for the specified goal.
            table_fields = ["name", "progress", "total", "need-translation", "suggestions", "critical", "activity"]

            ctx.update(
                {
                    "table": {
                        "id": "tp-goals",
                        "fields": table_fields,
                        "headings": get_table_headings(table_fields),
                        "parent": get_goal_parent(request.directory, goal),
                        "items": get_goal_children(request.directory, goal),
                    },
                    "goal": goal,
                    "goal_url": goal.get_drill_down_url_for_path(tp_pootle_path),
                    "resource_obj_has_goals": True,
                }
            )
        else:
            # Then show the files tab.
            table_fields = ["name", "progress", "total", "need-translation", "suggestions", "critical", "activity"]
            ctx.update(
                {
                    "table": {
                        "id": "tp-files",
                        "fields": table_fields,
                        "headings": get_table_headings(table_fields),
                        "parent": get_parent(request.directory),
                        "items": get_children(request.directory),
                    },
                    "resource_obj_has_goals": resource_obj_has_goals,
                }
            )
    elif goal is not None:
        ctx.update({"goal": goal, "goal_url": goal.get_drill_down_url_for_path(tp_pootle_path)})

    if can_edit:
        if request.store is None:
            url_kwargs = {"language_code": language.code, "project_code": project.code}
            add_tag_action_url = reverse("pootle-xhr-tag-tp", kwargs=url_kwargs)
        else:
            add_tag_action_url = reverse("pootle-xhr-tag-store", args=[resource_obj.pk])

        if goal is None:
            edit_form = DescriptionForm(instance=translation_project)
            edit_form_action = reverse("pootle-tp-admin-settings", args=[language.code, project.code])
        else:
            edit_form = GoalForm(instance=goal)
            edit_form_action = reverse("pootle-xhr-edit-goal", args=[goal.slug])

        ctx.update(
            {
                "form": edit_form,
                "form_action": edit_form_action,
                "add_tag_form": TagForm(),
                "add_tag_action_url": add_tag_action_url,
            }
        )

    return render_to_response(template_name, ctx, context_instance=RequestContext(request))
Example #57
0
def _test_browse_view(tp, request, response, kwargs):
    cookie_data = json.loads(
        unquote(response.cookies[SIDEBAR_COOKIE_NAME].value))
    assert cookie_data["foo"] == "bar"
    assert "announcements_projects_%s" % tp.project.code in cookie_data
    assert "announcements_%s" % tp.language.code in cookie_data
    assert ("announcements_%s_%s" % (tp.language.code, tp.project.code)
            in cookie_data)
    ctx = response.context
    kwargs["project_code"] = tp.project.code
    kwargs["language_code"] = tp.language.code
    resource_path = "%(dir_path)s%(filename)s" % kwargs
    pootle_path = "%s%s" % (tp.pootle_path, resource_path)

    if not (kwargs["dir_path"] or kwargs.get("filename")):
        ob = tp.directory
    elif not kwargs.get("filename"):
        ob = Directory.objects.get(pootle_path=pootle_path)
    else:
        ob = Store.objects.get(pootle_path=pootle_path)
    if not kwargs.get("filename"):
        vftis = ob.vf_treeitems.select_related("vfolder")
        if not ctx["is_admin"]:
            vftis = vftis.filter(vfolder__is_public=True)
        vfolders = [
            make_vfolder_treeitem_dict(vfolder_treeitem)
            for vfolder_treeitem in vftis.order_by('-vfolder__priority')
            if (ctx["is_admin"] or vfolder_treeitem.is_visible)
        ]
        stats = {"vfolders": {}}
        for vfolder_treeitem in vfolders or []:
            stats['vfolders'][
                vfolder_treeitem['code']] = vfolder_treeitem["stats"]
            del vfolder_treeitem["stats"]
        if stats["vfolders"]:
            stats.update(ob.get_stats())
        else:
            stats = ob.get_stats()
        stats = jsonify(stats)
    else:
        stats = jsonify(ob.get_stats())
        vfolders = None

    filters = {}
    if vfolders:
        filters['sort'] = 'priority'

    dirs_with_vfolders = vftis_for_child_dirs(ob).values_list("directory__pk",
                                                              flat=True)
    directories = [
        make_directory_item(
            child,
            **(dict(
                sort="priority") if child.pk in dirs_with_vfolders else {}))
        for child in ob.get_children() if isinstance(child, Directory)
    ]
    stores = [
        make_store_item(child) for child in ob.get_children()
        if isinstance(child, Store)
    ]

    if not kwargs.get("filename"):
        table_fields = [
            'name', 'progress', 'total', 'need-translation', 'suggestions',
            'critical', 'last-updated', 'activity'
        ]
        table = {
            'id': 'tp',
            'fields': table_fields,
            'headings': get_table_headings(table_fields),
            'items': directories + stores
        }
    else:
        table = None

    assertions = dict(
        page="browse",
        object=ob,
        translation_project=tp,
        language=tp.language,
        project=tp.project,
        is_admin=check_permission('administrate', request),
        is_store=(kwargs.get("filename") and True or False),
        browser_extends="translation_projects/base.html",
        pootle_path=pootle_path,
        resource_path=resource_path,
        resource_path_parts=get_path_parts(resource_path),
        translation_states=get_translation_states(ob),
        check_categories=get_qualitycheck_schema(ob),
        url_action_continue=ob.get_translate_url(state='incomplete',
                                                 **filters),
        url_action_fixcritical=ob.get_critical_url(**filters),
        url_action_review=ob.get_translate_url(state='suggestions', **filters),
        url_action_view_all=ob.get_translate_url(state='all'),
        stats=stats,
        parent=get_parent(ob))
    if table:
        assertions["table"] = table
    sidebar = get_sidebar_announcements_context(request,
                                                (tp.project, tp.language, tp))
    for k in ["has_sidebar", "is_sidebar_open", "announcements"]:
        assertions[k] = sidebar[0][k]
    view_context_test(ctx, **assertions)
    if vfolders:
        for vfolder in ctx["vfolders"]["items"]:
            assert (vfolder["is_grayed"] and not ctx["is_admin"]) is False
        assert (ctx["vfolders"]["items"] == vfolders)

    assert (('display_download' in ctx
             and ctx['display_download']) == (request.user.is_authenticated()
                                              and check_permission(
                                                  'translate', request)))
Example #58
0
def overview(request, translation_project, dir_path, filename=None):
    project = translation_project.project
    language = translation_project.language

    directory = request.directory
    store = request.store
    is_admin = check_permission('administrate', request)

    # TODO: cleanup and refactor, retrieve from cache
    try:
        ann_virtual_path = 'announcements/projects/' + project.code
        announcement = StaticPage.objects.live(request.user).get(
            virtual_path=ann_virtual_path,
        )
    except StaticPage.DoesNotExist:
        announcement = None

    has_announcement = announcement is not None
    has_sidebar = has_announcement
    is_sidebar_open = True
    stored_mtime = None
    new_mtime = None
    cookie_data = {}

    if SIDEBAR_COOKIE_NAME in request.COOKIES:
        json_str = unquote(request.COOKIES[SIDEBAR_COOKIE_NAME])
        cookie_data = json.loads(json_str)

        if 'isOpen' in cookie_data:
            is_sidebar_open = cookie_data['isOpen']

        if project.code in cookie_data:
            stored_mtime = cookie_data[project.code]

    if has_announcement:
        ann_mtime = dateformat.format(announcement.modified_on, 'U')
        if ann_mtime != stored_mtime:
            is_sidebar_open = True
            new_mtime = ann_mtime

    ctx = get_overview_context(request)

    # TODO improve plugin logic
    if "import_export" in settings.INSTALLED_APPS and request.user.is_authenticated():
        from import_export.views import handle_upload_form

        ctx.update(handle_upload_form(request))

        has_download = (check_permission('translate', request) or
                        check_permission('suggest', request))
        ctx.update({
            'display_download': has_download,
        })
        has_sidebar = True

    stats = request.resource_obj.get_stats()

    if store is None:
        table_fields = ['name', 'progress', 'total', 'need-translation',
                        'suggestions', 'critical', 'last-updated', 'activity']
        ctx.update({
            'table': {
                'id': 'tp',
                'fields': table_fields,
                'headings': get_table_headings(table_fields),
                'parent': get_parent(directory),
                'items': get_children(directory),
            }
        })

        vfolders = get_vfolders(directory)
        if len(vfolders) > 0:
            table_fields = ['name', 'priority', 'progress', 'total',
                            'need-translation', 'suggestions', 'critical',
                            'activity']
            ctx.update({
                'vfolders': {
                    'id': 'vfolders',
                    'fields': table_fields,
                    'headings': get_table_headings(table_fields),
                    'items': get_vfolders(directory, all_vfolders=is_admin),
                },
            })

            #FIXME: set vfolders stats in the resource, don't inject them here.
            stats['vfolders'] = VirtualFolder.get_stats_for(
                directory.pootle_path,
                all_vfolders=is_admin
            )

    ctx.update({
        'translation_project': translation_project,
        'project': project,
        'language': language,
        'stats': jsonify(stats),
        'is_admin': is_admin,

        'browser_extends': 'translation_projects/base.html',

        'announcement': announcement,
        'is_sidebar_open': is_sidebar_open,
        'has_sidebar': has_sidebar,
    })

    response = render(request, 'browser/overview.html', ctx)

    if new_mtime is not None:
        cookie_data[project.code] = new_mtime
        cookie_data = quote(json.dumps(cookie_data))
        response.set_cookie(SIDEBAR_COOKIE_NAME, cookie_data)

    return response
Example #59
0
def overview(request, translation_project, dir_path, filename=None, goal=None):
    from django.utils import dateformat
    from staticpages.models import StaticPage
    from .actions import action_groups

    if filename:
        ctx = {
            'store_tags': request.store.tag_like_objects,
        }
        template_name = "translation_projects/store_overview.html"
    else:
        ctx = {
            'tp_tags': translation_project.tag_like_objects,
        }
        template_name = "browser/overview.html"

    if (check_permission('translate', request)
            or check_permission('suggest', request)
            or check_permission('overwrite', request)):

        ctx.update({
            'upload_form':
            _handle_upload_form(request, translation_project),
        })

    can_edit = check_permission('administrate', request)

    project = translation_project.project
    language = translation_project.language

    resource_obj = request.store or request.directory

    #TODO enable again some actions when drilling down a goal.
    if goal is None:
        actions = action_groups(request, resource_obj)
    else:
        actions = []

    action_output = ''

    # TODO: cleanup and refactor, retrieve from cache
    try:
        ann_virtual_path = 'announcements/' + project.code
        announcement = StaticPage.objects.live(request.user).get(
            virtual_path=ann_virtual_path, )
    except StaticPage.DoesNotExist:
        announcement = None

    display_announcement = True
    stored_mtime = None
    new_mtime = None
    cookie_data = {}

    if ANN_COOKIE_NAME in request.COOKIES:
        json_str = unquote(request.COOKIES[ANN_COOKIE_NAME])
        cookie_data = json.loads(json_str)

        if 'isOpen' in cookie_data:
            display_announcement = cookie_data['isOpen']

        if project.code in cookie_data:
            stored_mtime = cookie_data[project.code]

    if announcement is not None:
        ann_mtime = dateformat.format(announcement.modified_on, 'U')
        if ann_mtime != stored_mtime:
            display_announcement = True
            new_mtime = ann_mtime

    tp_goals = translation_project.all_goals

    ctx.update(get_overview_context(request))
    ctx.update({
        'resource_obj': request.store or request.directory,  # Dirty hack.
        'translation_project': translation_project,
        'description': translation_project.description,
        'project': project,
        'language': language,
        'tp_goals': tp_goals,
        'goal': goal,
        'feed_path': request.directory.pootle_path[1:],
        'action_groups': actions,
        'action_output': action_output,
        'can_edit': can_edit,
        'browser_extends': 'translation_projects/base.html',
        'announcement': announcement,
        'announcement_displayed': display_announcement,
    })

    tp_pootle_path = translation_project.pootle_path

    if request.store is None:
        table_fields = [
            'name', 'progress', 'total', 'need-translation', 'suggestions',
            'critical', 'last-updated', 'activity'
        ]

        if goal is not None:
            # Then show the drill down view for the specified goal.
            continue_url = goal.get_translate_url_for_path(request.pootle_path,
                                                           state='incomplete')
            critical_url = goal.get_critical_url_for_path(request.pootle_path)
            review_url = goal.get_translate_url_for_path(request.pootle_path,
                                                         state='suggestions')
            all_url = goal.get_translate_url_for_path(request.pootle_path)

            ctx.update({
                'table': {
                    'id': 'tp-goals',
                    'fields': table_fields,
                    'headings': get_table_headings(table_fields),
                    'parent': get_goal_parent(request.directory, goal),
                    'items': get_goal_children(request.directory, goal),
                },
                'url_action_continue': continue_url,
                'url_action_fixcritical': critical_url,
                'url_action_review': review_url,
                'url_action_view_all': all_url,
            })
        else:
            # Then show the files tab.
            ctx.update({
                'table': {
                    'id': 'tp-files',
                    'fields': table_fields,
                    'headings': get_table_headings(table_fields),
                    'parent': get_parent(request.directory),
                    'items': get_children(request.directory),
                },
            })

    if can_edit:
        if request.store is None:
            add_tag_action_url = reverse('pootle-xhr-tag-tp',
                                         args=[language.code, project.code])
        else:
            add_tag_action_url = reverse('pootle-xhr-tag-store',
                                         args=[resource_obj.pk])

        ctx.update({
            'form':
            DescriptionForm(instance=translation_project),
            'form_action':
            reverse('pootle-tp-admin-settings',
                    args=[language.code, project.code]),
            'add_tag_form':
            TagForm(),
            'add_tag_action_url':
            add_tag_action_url,
        })

        if goal is not None:
            ctx.update({
                'goal_form':
                GoalForm(instance=goal),
                'goal_form_action':
                reverse('pootle-xhr-edit-goal', args=[goal.slug]),
            })

    response = render(request, template_name, ctx)

    if new_mtime is not None:
        cookie_data[project.code] = new_mtime
        cookie_data = quote(json.dumps(cookie_data))
        response.set_cookie(ANN_COOKIE_NAME, cookie_data)

    return response