Exemplo n.º 1
0
def ajax_add_tag_to_store(request, store_pk):
    """Return an HTML snippet with the failed form or blank if valid."""

    if not check_permission('administrate', request):
        raise PermissionDenied(_("You do not have rights to add tags."))

    store = get_object_or_404(Store, pk=store_pk)

    add_tag_form = TagForm(request.POST)

    if add_tag_form.is_valid():
        new_tag_like_object = add_tag_form.save()
        return _add_tag(request, store, new_tag_like_object)
    else:
        # If the form is invalid, perhaps it is because the tag already exists,
        # so check if the tag exists.
        try:
            criteria = {
                'name': add_tag_form.data['name'],
                'slug': add_tag_form.data['slug'],
            }
            if len(store.tags.filter(**criteria)) == 1:
                # If the tag is already applied to the store then avoid
                # reloading the page.
                return HttpResponse(status=204)
            elif len(store.goals.filter(**criteria)) == 1:
                # If the goal is already applied to the store then avoid
                # reloading the page.
                return HttpResponse(status=204)
            else:
                # Else add the tag (or goal) to the store.
                if criteria['name'].startswith("goal:"):
                    tag_like_object = Goal.objects.get(**criteria)
                else:
                    tag_like_object = Tag.objects.get(**criteria)
                return _add_tag(request, store, tag_like_object)
        except Exception:
            # If the form is invalid and the tag doesn't exist yet then display
            # the form with the error messages.
            context = {
                'add_tag_form':
                add_tag_form,
                'add_tag_action_url':
                reverse('pootle-xhr-tag-store', args=[store.pk])
            }
            return render_to_response('core/xhr_add_tag_form.html', context,
                                      RequestContext(request))
Exemplo n.º 2
0
def ajax_add_tag_to_store(request, store_pk):
    """Return an HTML snippet with the failed form or blank if valid."""

    if not check_permission('administrate', request):
        raise PermissionDenied(_("You do not have rights to add tags."))

    store = get_object_or_404(Store, pk=store_pk)

    add_tag_form = TagForm(request.POST)

    if add_tag_form.is_valid():
        new_tag_like_object = add_tag_form.save()
        return _add_tag(request, store, new_tag_like_object)
    else:
        # If the form is invalid, perhaps it is because the tag already exists,
        # so check if the tag exists.
        try:
            criteria = {
                'name': add_tag_form.data['name'],
                'slug': add_tag_form.data['slug'],
            }
            if len(store.tags.filter(**criteria)) == 1:
                # If the tag is already applied to the store then avoid
                # reloading the page.
                return HttpResponse(status=204)
            elif len(store.goals.filter(**criteria)) == 1:
                # If the goal is already applied to the store then avoid
                # reloading the page.
                return HttpResponse(status=204)
            else:
                # Else add the tag (or goal) to the store.
                if criteria['name'].startswith("goal:"):
                    tag_like_object = Goal.objects.get(**criteria)
                else:
                    tag_like_object = Tag.objects.get(**criteria)
                return _add_tag(request, store, tag_like_object)
        except Exception:
            # If the form is invalid and the tag doesn't exist yet then display
            # the form with the error messages.
            context = {
                'add_tag_form': add_tag_form,
                'add_tag_action_url': reverse('pootle-xhr-tag-store',
                                              args=[store.pk])
            }
            return render_to_response('core/xhr_add_tag_form.html', context,
                                      RequestContext(request))
Exemplo n.º 3
0
def ajax_add_tag_to_tp(request, translation_project):
    """Return an HTML snippet with the failed form or blank if valid."""

    add_tag_form = TagForm(request.POST)

    if add_tag_form.is_valid():
        new_tag_like_object = add_tag_form.save()
        return _add_tag(request, translation_project, new_tag_like_object)
    else:
        # If the form is invalid, perhaps it is because the tag (or goal)
        # already exists, so check if the tag (or goal) exists.
        try:
            criteria = {
                'name': add_tag_form.data['name'],
                'slug': add_tag_form.data['slug'],
            }
            if len(translation_project.tags.filter(**criteria)) == 1:
                # If the tag is already applied to the translation project then
                # avoid reloading the page.
                return HttpResponse(status=204)
            elif len(translation_project.goals.filter(**criteria)) == 1:
                # If the goal is already applied to the translation project
                # then avoid reloading the page.
                return HttpResponse(status=204)
            else:
                # Else add the tag (or goal) to the translation project.
                if criteria['name'].startswith("goal:"):
                    tag_like_object = Goal.objects.get(**criteria)
                else:
                    tag_like_object = Tag.objects.get(**criteria)
                return _add_tag(request, translation_project, tag_like_object)
        except Exception:
            # If the form is invalid and the tag (or goal) doesn't exist yet
            # then display the form with the error messages.
            url_kwargs = {
                'language_code': translation_project.language.code,
                'project_code': translation_project.project.code,
            }
            context = {
                'add_tag_form':
                add_tag_form,
                'add_tag_action_url':
                reverse('pootle-xhr-tag-tp', kwargs=url_kwargs)
            }
            return render_to_response('core/xhr_add_tag_form.html', context,
                                      RequestContext(request))
Exemplo n.º 4
0
def ajax_add_tag_to_tp(request, translation_project):
    """Return an HTML snippet with the failed form or blank if valid."""

    add_tag_form = TagForm(request.POST)

    if add_tag_form.is_valid():
        new_tag_like_object = add_tag_form.save()
        return _add_tag(request, translation_project, new_tag_like_object)
    else:
        # If the form is invalid, perhaps it is because the tag (or goal)
        # already exists, so check if the tag (or goal) exists.
        try:
            criteria = {
                'name': add_tag_form.data['name'],
                'slug': add_tag_form.data['slug'],
            }
            if len(translation_project.tags.filter(**criteria)) == 1:
                # If the tag is already applied to the translation project then
                # avoid reloading the page.
                return HttpResponse(status=204)
            elif len(translation_project.goals.filter(**criteria)) == 1:
                # If the goal is already applied to the translation project
                # then avoid reloading the page.
                return HttpResponse(status=204)
            else:
                # Else add the tag (or goal) to the translation project.
                if criteria['name'].startswith("goal:"):
                    tag_like_object = Goal.objects.get(**criteria)
                else:
                    tag_like_object = Tag.objects.get(**criteria)
                return _add_tag(request, translation_project, tag_like_object)
        except Exception:
            # If the form is invalid and the tag (or goal) doesn't exist yet
            # then display the form with the error messages.
            url_kwargs = {
                'language_code': translation_project.language.code,
                'project_code': translation_project.project.code,
            }
            context = {
                'add_tag_form': add_tag_form,
                'add_tag_action_url': reverse('pootle-xhr-tag-tp',
                                              kwargs=url_kwargs)
            }
            return render_to_response('core/xhr_add_tag_form.html', context,
                                      RequestContext(request))
Exemplo n.º 5
0
def ajax_add_tag_to_tp(request, translation_project):
    """Return an HTML snippet with the failed form or blank if valid."""

    if not check_permission('administrate', request):
        raise PermissionDenied(_("You do not have rights to add tags."))

    if request.method != 'POST':
        return HttpResponseNotAllowed(['POST'])

    add_tag_form = TagForm(request.POST)

    if add_tag_form.is_valid():
        new_tag = add_tag_form.save()
        return _add_tag(request, translation_project, new_tag)
    else:
        # If the form is invalid, perhaps it is because the tag already exists,
        # so check if the tag exists.
        try:
            criteria = {
                'name': add_tag_form.data['name'],
                'slug': add_tag_form.data['slug'],
            }
            if len(translation_project.tags.filter(**criteria)) == 1:
                # If the tag is already applied to the translation project then
                # avoid reloading the page.
                return HttpResponse(status=204)
            else:
                # Else add the tag to the translation project.
                tag = Tag.objects.get(**criteria)
                return _add_tag(request, translation_project, tag)
        except Exception:
            # If the form is invalid and the tag doesn't exist yet then display
            # the form with the error messages.
            url_kwargs = {
                'language_code': translation_project.language.code,
                'project_code': translation_project.project.code,
            }
            context = {
                'add_tag_form': add_tag_form,
                'add_tag_action_url': reverse('tp.ajax_add_tag',
                                              kwargs=url_kwargs)
            }
            return render_to_response('common/xhr_add_tag_form.html', context,
                                      RequestContext(request))
Exemplo n.º 6
0
def ajax_add_tag_to_tp(request, translation_project):
    """Return an HTML snippet with the failed form or blank if valid."""

    if not check_permission('administrate', request):
        raise PermissionDenied(_("You do not have rights to add tags."))

    if request.method != 'POST':
        return HttpResponseNotAllowed(['POST'])

    add_tag_form = TagForm(request.POST)

    if add_tag_form.is_valid():
        new_tag = add_tag_form.save()
        return _add_tag(request, translation_project, new_tag)
    else:
        # If the form is invalid, perhaps it is because the tag already exists,
        # so check if the tag exists.
        try:
            criteria = {
                'name': add_tag_form.data['name'],
                'slug': add_tag_form.data['slug'],
            }
            if len(translation_project.tags.filter(**criteria)) == 1:
                # If the tag is already applied to the translation project then
                # avoid reloading the page.
                return HttpResponse(status=204)
            else:
                # Else add the tag to the translation project.
                tag = Tag.objects.get(**criteria)
                return _add_tag(request, translation_project, tag)
        except Exception:
            # If the form is invalid and the tag doesn't exist yet then display
            # the form with the error messages.
            url_kwargs = {
                'language_code': translation_project.language.code,
                'project_code': translation_project.project.code,
            }
            context = {
                'add_tag_form': add_tag_form,
                'add_tag_action_url': reverse('tp.ajax_add_tag',
                                              kwargs=url_kwargs)
            }
            return render_to_response('common/xhr_add_tag_form.html', context,
                                      RequestContext(request))
Exemplo n.º 7
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
Exemplo n.º 8
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
Exemplo n.º 9
0
def overview(request,
             translation_project,
             dir_path,
             filename=None,
             goal=None,
             in_goal_overview=False):
    current_path = translation_project.directory.pootle_path + dir_path

    if filename:
        current_path = current_path + filename
        store = get_object_or_404(Store, pootle_path=current_path)
        directory = store.parent
        ctx = {
            'store_tags': store.tag_like_objects,
        }
        template_name = "translation_projects/store_overview.html"
    else:
        store = None
        directory = get_object_or_404(Directory, pootle_path=current_path)
        ctx = {
            'tp_tags': translation_project.tag_like_objects,
        }
        template_name = "translation_projects/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, current_path, translation_project,
                                directory),
        })

    can_edit = check_permission('administrate', request)

    project = translation_project.project
    language = translation_project.language

    path_obj = store or directory

    #TODO enable again some actions when drilling down a goal.
    if goal is None:
        actions = action_groups(request, path_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 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):
                (store or translation_project).sync()
            if action.is_active(request):
                vcs_dir = settings.VCS_DIRECTORY
                po_dir = settings.PODIRECTORY
                tp_dir = directory.get_real_path()
                store_fn = '*'
                if store:
                    tp_dir_slash = add_trailing_slash(tp_dir)
                    if store.file.name.startswith(tp_dir_slash):
                        # Note: store_f used below in reverse() call.
                        store_f = store.file.name[len(tp_dir_slash):]
                        store_fn = store_f.replace('/', os.sep)

                # Clear possibly stale output/error (even from other path_obj).
                action.set_output('')
                action.set_error('')
                try:
                    action.run(path=path_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(path_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 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({
        'resource_obj': request.resource_obj,
        'translation_project': translation_project,
        'description': description,
        'project': project,
        'language': language,
        'path_obj': path_obj,
        'resource_path': request.resource_path,
        'topstats': gentopstats_translation_project(translation_project),
        'feed_path': directory.pootle_path[1:],
        'action_groups': actions,
        'action_output': action_output,
        'can_edit': can_edit,
    })

    tp_pootle_path = translation_project.pootle_path

    if store is None:
        path_obj_goals = Goal.get_goals_for_path(path_obj.pootle_path)
        path_obj_has_goals = len(path_obj_goals) > 0

        if in_goal_overview and path_obj_has_goals:
            # Then show the goals tab.
            table_fields = [
                'name', 'progress', 'priority', 'total', 'need-translation',
                'suggestions'
            ]
            items = [
                make_goal_item(path_obj_goal, path_obj.pootle_path)
                for path_obj_goal in path_obj_goals
            ]
            ctx.update({
                'table': {
                    'id': 'tp-goals',
                    'proportional': False,
                    'fields': table_fields,
                    'headings': get_table_headings(table_fields),
                    'parent': get_parent(directory),
                    'items': items,
                },
                'path_obj_has_goals': True,
            })
        elif goal in path_obj_goals:
            # Then show the drill down view for the specified goal.
            table_fields = [
                'name', 'progress', 'total', 'need-translation', 'suggestions'
            ]

            ctx.update({
                'table': {
                    'id': 'tp-goals',
                    'proportional': True,
                    'fields': table_fields,
                    'headings': get_table_headings(table_fields),
                    'parent': get_goal_parent(directory, goal),
                    'items': get_goal_children(directory, goal),
                },
                'goal':
                goal,
                'goal_url':
                goal.get_drill_down_url_for_path(tp_pootle_path),
                'path_obj_has_goals':
                True,
            })
        else:
            # Then show the files tab.
            table_fields = [
                'name', 'progress', 'total', 'need-translation', 'suggestions'
            ]
            ctx.update({
                'table': {
                    'id': 'tp-files',
                    'proportional': True,
                    'fields': table_fields,
                    'headings': get_table_headings(table_fields),
                    'parent': get_parent(directory),
                    'items': get_children(directory),
                },
                'path_obj_has_goals': path_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 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=[path_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))
Exemplo n.º 10
0
def overview(request, translation_project, dir_path, filename=None):
    current_path = translation_project.directory.pootle_path + dir_path

    if filename:
        current_path = current_path + filename
        store = get_object_or_404(Store, pootle_path=current_path)
        directory = store.parent
        template_vars = {
            'store_tags': store.tags.all().order_by('name'),
        }
        template = "translation_project/store_overview.html"
    else:
        store = None
        directory = get_object_or_404(Directory, pootle_path=current_path)
        template_vars = {
            'tp_tags': translation_project.tags.all().order_by('name'),
        }
        template = "translation_project/overview.html"

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

        template_vars.update({
            'upload_form':
            _handle_upload_form(request, current_path, translation_project,
                                directory),
        })

    can_edit = check_permission('administrate', request)

    project = translation_project.project
    language = translation_project.language

    path_obj = store or directory

    latest_action = ''
    # If current directory is the TP root directory.
    if not directory.path:
        latest_action = translation_project.get_latest_submission()
    elif store is None:  # If this is not a file.
        latest_action = Submission.get_latest_for_dir(path_obj)

    path_stats = get_raw_stats(path_obj, include_suggestions=True)
    path_summary = get_path_summary(path_obj, path_stats, latest_action)
    actions = action_groups(request, path_obj, path_stats=path_stats)
    action_output = ''
    running = request.GET.get(EXTDIR, '')
    if running:
        if store:
            act = StoreAction
        else:
            act = TranslationProjectAction
        try:
            action = act.lookup(running)
        except KeyError:
            messages.error(request, _("Unable to find %s %s") % (act, running))
        else:
            if not getattr(action, 'nosync', False):
                (store or translation_project).sync()
            if action.is_active(request):
                vcs_dir = settings.VCS_DIRECTORY
                po_dir = settings.PODIRECTORY
                tp_dir = directory.get_real_path()
                store_fn = '*'
                if store:
                    tp_dir_slash = add_trailing_slash(tp_dir)
                    if store.file.name.startswith(tp_dir_slash):
                        # Note: store_f used below in reverse() call.
                        store_f = store.file.name[len(tp_dir_slash):]
                        store_fn = store_f.replace('/', os.sep)

                # Clear possibly stale output/error (even from other path_obj).
                action.set_output('')
                action.set_error('')
                try:
                    action.run(path=path_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 = (_("Exception 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(path_obj)
                    if export_path:
                        response = HttpResponse('/export/' + export_path)
                        response['Content-Disposition'] = (
                            'attachment; filename="%s"' %
                            os.path.basename(export_path))
                        return response

                if not action_output:
                    if not store:
                        rev_args = [language.code, project.code, '']
                        overview_url = reverse('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('tp.overview', args=rev_args)
                    return HttpResponseRedirect(overview_url)

    template_vars.update({
        'translation_project':
        translation_project,
        'project':
        project,
        'language':
        language,
        'path_obj':
        path_obj,
        'resource_path':
        request.resource_path,
        'path_summary':
        path_summary,
        'stats':
        path_stats,
        'topstats':
        gentopstats_translation_project(translation_project),
        'feed_path':
        directory.pootle_path[1:],
        'action_groups':
        actions,
        'action_output':
        action_output,
        'can_edit':
        can_edit,
    })

    if store is None:
        table_fields = [
            'name', 'progress', 'total', 'need-translation', 'suggestions'
        ]
        template_vars.update({
            'table': {
                'id': 'tp',
                'proportional': True,
                'fields': table_fields,
                'headings': get_table_headings(table_fields),
                'items': get_children(translation_project, directory),
            }
        })

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

        template_vars.update({
            'form':
            DescriptionForm(instance=translation_project),
            'add_tag_form':
            TagForm(),
            'add_tag_action_url':
            add_tag_action_url,
        })

    return render_to_response(template,
                              template_vars,
                              context_instance=RequestContext(request))