Beispiel #1
0
def reload_entries(request, sheet_slug,
                   chronicle_slug=None, bridge=None,
                   form_class=TraitForm, **kwargs):
    if bridge is not None:
        try:
            group = bridge.get_group(chronicle_slug)
        except ObjectDoesNotExist:
            raise Http404
    else:
        group = None

    if group:
        sheet = get_object_or_404(group.content_objects(Sheet), slug=sheet_slug)
    else:
        sheet = get_object_or_404(Sheet, slug=sheet_slug)

    entries = sheet.experience_entries.all()

    # Check all of the various sheet editing permissions
    if not can_edit_sheet(request, sheet):
        return permission_denied(request)

    template_name = "characters/experience_entries.html"
    return render_to_response(template_name, {
        'sheet': sheet,
        'group': group,
        'experience_entries': entries,
        'is_ajax': request.is_ajax,
    }, context_instance=RequestContext(request))
Beispiel #2
0
def show_recent_expenditures(request, sheet_slug,
                             form_class=ExperienceEntryForm, **kwargs):
    group, bridge = group_and_bridge(request)

    if group:
        sheet = get_object_or_404(group.content_objects(Sheet), slug=sheet_slug)
    else:
        sheet = get_object_or_404(Sheet, slug=sheet_slug)

    # Check all of the various sheet editing permissions
    if not can_edit_sheet(request, sheet):
        return permission_denied(request)

    entry =  sheet.get_recent_expenditures_entry()
    form = form_class(None, instance=entry)

    ctx = group_context(group, bridge)
    ctx.update({
        'sheet': sheet,
        'form': form,
        'reason': entry.reason,
        'post_url': reverse('sheet_add_recent_expenditures', args=[sheet_slug])
    })
    return render_to_response(
        'characters/sheet_show_recent_purchases.html',
        RequestContext(request, ctx))
Beispiel #3
0
def reload_traits(request, sheet_slug, traitlistname_slug,
                  chronicle_slug=None, bridge=None,
                  form_class=TraitForm, **kwargs):
    traitlistname = get_object_or_404(TraitListName, slug=traitlistname_slug)
    if bridge is not None:
        try:
            group = bridge.get_group(chronicle_slug)
        except ObjectDoesNotExist:
            raise Http404
    else:
        group = None

    if group:
        sheet = get_object_or_404(group.content_objects(Sheet), slug=sheet_slug)
    else:
        sheet = get_object_or_404(Sheet, slug=sheet_slug)

    # Check all of the various sheet editing permissions
    if not can_edit_sheet(request, sheet):
        return permission_denied(request)

    template_name = "characters/_trait_category.html"
    return render_to_response(template_name, {
        'sheet': sheet,
        'group': group,
        'traitlistname': traitlistname,
        'prepend': '',
    }, context_instance=RequestContext(request))
Beispiel #4
0
def lock_and_get_translation_file(request, project_slug, resource_slug, lang_code):
    """
    Lock and download the translations file.

    View to lock a resource for the requested language and as a second step to
    download (export+download) the translations in a formatted file.
    """

    resource = get_object_or_404(Resource, project__slug = project_slug,
        slug = resource_slug)

    # Permissions handling
    # Project should always be available
    project = get_object_or_404(Project, slug=project_slug)
    team = Team.objects.get_or_none(project, lang_code)
    check = ProjectPermission(request.user)
    if not check.submit_translations(team or project) or not \
        resource.accept_translations:
        return permission_denied(request)

    language = get_object_or_404(Language, code=lang_code)
    lock = Lock.objects.get_valid(resource, language)
    can_lock = Lock.can_lock(resource, language, request.user)
    response = {}

    if not can_lock:
        #print_gray_text(You cannot assign this file to you)
        response['status'] = "FAILED"
        response['message'] = _("Sorry, you cannot lock this file!")
    else:
        # User can lock
        if not lock:
            try:
                # Lock the resource now
                Lock.objects.create_update(resource, language, request.user)
                response['status'] = 'OK'
                response['redirect'] = reverse('download_for_translation',
                    args=[resource.project.slug, resource.slug, lang_code])
            except:
                response['status'] = "FAILED"
                response['message'] = _("Failed to lock the resource!")
        else:
            if lock.owner == request.user:
                try:
                    # File already locked by me, so extend the lock period.
                    Lock.objects.create_update(resource, language, request.user)
                    response['status'] = 'OK'
                    response['redirect'] = reverse('download_for_translation',
                        args=[resource.project.slug, resource.slug, lang_code])
                except:
                    response['status'] = "FAILED"
                    response['message'] = _("Failed to extend lock period on "
                                            "the resource!")
            else:
                # File locked by someone else:
                response['status'] = "FAILED"
                response['message'] = _("You cannot lock it right now! (Locked "
                                        "by %s )" % (lock.owner,))

    return HttpResponse(simplejson.dumps(response), mimetype='application/json')
Beispiel #5
0
def edit_membership(request, group_slug=None, username=None, form_class=ChronicleMemberForm, **kwargs):
    template_name = kwargs.get("template_name", "chronicles/edit_membership.html")

    if request.is_ajax():
        template_name = kwargs.get("template_name_facebox", "chronicles/edit_membership_facebox.html")

    chronicle = get_object_or_404(Chronicle, slug=group_slug)
    if not can_edit_membership(request, chronicle):
        return permission_denied(request)

    user = get_object_or_404(User, username=username)
    if not chronicle.user_is_member(user):
        return "trying to edit a user that's not a member??? what now?"

    chronicle_membership = ChronicleMember.objects.filter(user=user, chronicle=chronicle)[0]
    chronicle_membership_form = form_class(request.POST or None, instance=chronicle_membership)
    if chronicle_membership_form.is_valid() and request.method == "POST":
        chronicle_membership = chronicle_membership_form.save()
        chronicle_membership.save()
        return HttpResponseRedirect(reverse("chronicle_members", args=[group_slug]))

    return render_to_response(
        template_name,
        {
            "chronicle_membership_form": chronicle_membership_form,
            "changing_username": user.username,
            "member": user,
            "chronicle": chronicle,
        },
        context_instance=RequestContext(request),
    )
Beispiel #6
0
def permission_denied(request,
                      template_name=None,
                      extra_context={},
                      *args,
                      **kwargs):
    """Wrapper to allow undeclared key arguments."""
    from authority.views import permission_denied
    return permission_denied(request, template_name, extra_context)
Beispiel #7
0
def exit(request, project_slug, lang_code, resource_slug=None, *args, **kwargs):
    """
    Exiting Lotte
    """
    if request.method != 'POST':
        return HttpResponse(status=405)

    # Permissions handling
    # Project should always be available
    project = get_object_or_404(Project, slug=project_slug)
    team = Team.objects.get_or_none(project, lang_code)
    check = ProjectPermission(request.user)
    if not check.submit_translations(team or project) and not\
        check.maintain(project):
        return permission_denied(request)

    language = Language.objects.by_code_or_alias(lang_code)

    resources = []
    if resource_slug:
        resources = Resource.objects.filter(slug=resource_slug, project=project)
        if not resources:
            raise Http404
    else:
        resources = Resource.objects.filter(project=project)


    data = simplejson.loads(request.raw_post_data)

    if data.get('updated'):
        modified = True
        # ActionLog & Notification
        for resource in resources:
            nt = 'project_resource_translated'
            context = {'project': project,
                       'resource': resource,
                       'language': language,
                       'sender': request.user}
            object_list = [project, resource, language]
            if team:
                object_list.append(team)
            action_logging(request.user, object_list, nt, context=context)
    else:
        modified = False

    lotte_done.send(None, request=request, resources=resources,
        language=language, modified=modified)

    redirect_url = reverse('team_detail', args=[project_slug, language.code])

    if request.is_ajax():
        json = simplejson.dumps(dict(redirect=redirect_url))
        return HttpResponse(json, mimetype='application/json')

    return HttpResponseRedirect(redirect_url)
Beispiel #8
0
def add_recent_expenditures(request, sheet_slug,
                            action_description="Recent Expenditures", object_description="Experience Entry",
                            chronicle_slug=None, bridge=None,
                            form_class=ExperienceEntryForm, **kwargs):
    if bridge is not None:
        try:
            group = bridge.get_group(chronicle_slug)
        except ObjectDoesNotExist:
            raise Http404
    else:
        group = None

    if group:
        sheet = get_object_or_404(group.content_objects(Sheet), slug=sheet_slug)
    else:
        sheet = get_object_or_404(Sheet, slug=sheet_slug)

    # Check all of the various sheet editing permissions
    if not can_edit_sheet(request, sheet):
        return permission_denied(request)

    template_name = kwargs.get("template_name", "characters/generic_edit.html")
    if request.is_ajax():
        template_name = kwargs.get(
            "template_name_facebox",
            "characters/generic_edit_facebox.html",
        )

    if request.method == "POST":
        print "Posting recent"
        form = form_class(request.POST)
        pprint(request.POST)
        form.is_valid()
        #pprint(form.cleaned_data)
        #pprint(form.errors)
        if form.is_valid():
            print "Valid?"
            sheet.add_experience_entry(form.save(commit=False))
            ChangedTrait.objects.filter(sheet=sheet).delete()
            return experience_entry_change_ajax_success(request, sheet, None, group)
        else:
            print "Invalid?"
    else:
        entry =  sheet.get_recent_expenditures_entry()
        form = form_class(None, instance=entry)

    return render_to_response(template_name, {
        'sheet': sheet,
        'form': form,
        'group': group,
        'action_description': action_description,
        'object_description': object_description,
        'form_template': 'characters/generic_edit_form.html',
        'post_url': reverse('sheet_add_recent_expenditures', args=[sheet_slug]),
    }, context_instance=RequestContext(request))
Beispiel #9
0
def reorder_traitlist(request, sheet_slug, traitlistname_slug,
                      chronicle_slug=None, bridge=None,
                      **kwargs):
    if bridge is not None:
        try:
            group = bridge.get_group(chronicle_slug)
        except ObjectDoesNotExist:
            raise Http404
    else:
        group = None

    if group:
        sheet = get_object_or_404(group.content_objects(Sheet), slug=sheet_slug)
    else:
        sheet = get_object_or_404(Sheet, slug=sheet_slug)

    # Check all of the various sheet editing permissions
    if not can_edit_sheet(request, sheet):
        return permission_denied(request)
    template_name = kwargs.get("template_name", "characters/traits/reorder_traitlist.html")

    if request.is_ajax():
        template_name = kwargs.get(
            "template_name_facebox",
            "characters/traits/reorder_traitlist_facebox.html",
        )

    tln = get_object_or_404(TraitListName, slug=traitlistname_slug)
    traits = []
    DisplayOrderFormSet = formset_factory(DisplayOrderForm, extra=0)
    if request.method == "POST":
        formset = DisplayOrderFormSet(request.POST)
        if formset.is_valid():
            pprint(formset.cleaned_data)
            for data in formset.cleaned_data:
                trait = sheet.traits.get(id=data['trait_id'])
                if data['order'] != trait.order:
                    trait.order = data['order']
                    trait.save()
            return trait_change_ajax_success(request, sheet, tln, group)
    else:
        traits = sheet.get_traits(tln.name)
        initial = []
        for trait in traits:
            initial.append({'order': trait.order, 'trait_id': trait.id, 'trait': unicode(trait)})
        formset = DisplayOrderFormSet(initial=initial)

    return render_to_response(template_name, {
        'sheet': sheet,
        'traitlistname': tln,
        'traits': traits,
        'formset': formset,
    }, context_instance=RequestContext(request))
Beispiel #10
0
def new_trait_from_menu(request, sheet_slug, traitlistname_slug, id_segment,
                        chronicle_slug=None, bridge=None,
                        form_class=TraitForm, **kwargs):
    traitlistname = get_object_or_404(TraitListName, slug=traitlistname_slug)
    if bridge is not None:
        try:
            group = bridge.get_group(chronicle_slug)
        except ObjectDoesNotExist:
            raise Http404
    else:
        group = None

    if group:
        sheet = get_object_or_404(group.content_objects(Sheet), slug=sheet_slug)
    else:
        sheet = get_object_or_404(Sheet, slug=sheet_slug)

    # Check all of the various sheet editing permissions
    if not can_edit_sheet(request, sheet):
        return permission_denied(request)

    template_name = kwargs.get("template_name", "characters/traits/new_trait.html")
    if request.is_ajax():
        template_name = kwargs.get(
            "template_name_facebox",
            "characters/traits/new_trait_facebox.html",
        )

    print traitlistname.name
    print "sheet in new_trait_from_menu", sheet
    send_segment = None
    if len(id_segment) > 0:
        print "id_segment", pformat(id_segment[1:])
        send_segment = id_segment[1:]
    else:
        try:
            try:
                if sheet.vampiresheet:
                    desired_menu = Menu.get_menu_for_traitlistname(traitlistname, VampireSheet)
            except ObjectDoesNotExist:
                desired_menu = Menu.get_menu_for_traitlistname(traitlistname)
        except Menu.DoesNotExist:
            return new_trait(request, sheet_slug, traitlistname_slug, chronicle_slug=chronicle_slug, bridge=bridge, **kwargs)
        print desired_menu.name
        send_segment = "%d" % desired_menu.id

    return show_menu(
        request,
        send_segment,
        sheet=sheet,
        traitlistname=traitlistname,
        group=group,
        template_name_facebox="characters/menus/show_menu.html")
Beispiel #11
0
def proofread(request, project_slug, lang_code, resource_slug=None, *args, **kwargs):
    """AJAX view that sets the reviewed flag on Translations to true or false.

    The request data is expected in JSON, with the following format:

    {
        'true': [1,2,3]
        'false': [4,5]
    }

    Note: The IDs are source entity IDs.
    """
    if request.method != 'POST':
        return HttpResponse(status=405)

    project = get_object_or_404(Project, slug=project_slug)
    resource = get_object_or_404(Resource, slug=resource_slug, project=project)

    try:
        language = Language.objects.by_code_or_alias(lang_code)
    except Language.DoesNotExist:
        raise Http404

    # Check if the user has the necessary permissions to review strings.
    check = ProjectPermission(request.user)
    if not check.proofread(project, language):
        return permission_denied(request)

    request_data = simplejson.loads(request.raw_post_data)

    if 'true' in request_data:
        source_entity_ids = request_data['true']
        translations = Translation.objects.filter(
            source_entity__id__in=source_entity_ids,
            language__code=lang_code,
        )
        translations.update(reviewed=True)
        ReviewHistory.add_many(translations, request.user, project.id, reviewed=True)

    if 'false' in request_data:
        source_entity_ids = request_data['false']
        translations = Translation.objects.filter(
            source_entity__id__in=source_entity_ids,
            language__code=lang_code,
        )
        translations.update(reviewed=False)
        ReviewHistory.add_many(translations, request.user, project.id, reviewed=False)

    invalidate_stats_cache(resource, language, user=request.user)

    return HttpResponse(status=200)
Beispiel #12
0
def exit(request, project_slug, lang_code, resource_slug=None, *args, **kwargs):
    """
    Exiting Lotte
    """

    # Permissions handling
    # Project should always be available
    project = get_object_or_404(Project, slug=project_slug)
    team = Team.objects.get_or_none(project, lang_code)
    check = ProjectPermission(request.user)
    if not check.submit_translations(team or project) and not\
        check.maintain(project):
        return permission_denied(request)

    language = Language.objects.by_code_or_alias(lang_code)

    resources = []
    if resource_slug:
        resources = Resource.objects.filter(slug=resource_slug, project=project)
        if not resources:
            raise Http404
        url = reverse('resource_detail', args=[project_slug, resource_slug])
    else:
        resources = Resource.objects.filter(project=project)
        url = reverse('project_detail', args=[project_slug])

    if request.POST.get('updated', None) == 'true':
        modified = True
        # ActionLog & Notification
        for resource in resources:
            nt = 'project_resource_translated'
            context = {'project': project,
                       'resource': resource,
                       'language': language}
            object_list = [project, resource, language]
            action_logging(request.user, object_list, nt, context=context)
            if settings.ENABLE_NOTICES:
                txnotification.send_observation_notices_for(project,
                        signal=nt, extra_context=context)
    else:
        modified = False

    lotte_done.send(None, request=request, resources=resources,
        language=language, modified=modified)

    if request.is_ajax():
        json = simplejson.dumps(dict(redirect=url))
        return HttpResponse(json, mimetype='application/json')

    return HttpResponseRedirect(url)
Beispiel #13
0
def experience_entry_action(request, sheet_slug, entry_id=None,
                            action_description="", object_description="Experience Entry",
                            post_url="", action=None,
                            chronicle_slug=None, bridge=None,
                            form_class=ExperienceEntryForm, **kwargs):
    if bridge is not None:
        try:
            group = bridge.get_group(chronicle_slug)
        except ObjectDoesNotExist:
            raise Http404
    else:
        group = None

    if group:
        sheet = get_object_or_404(group.content_objects(Sheet), slug=sheet_slug)
    else:
        sheet = get_object_or_404(Sheet, slug=sheet_slug)

    if entry_id is not None:
        entry = get_object_or_404(sheet.experience_entries.all(), id=entry_id)
    else:
        entry = None

    # Check all of the various sheet editing permissions
    if not can_edit_sheet(request, sheet):
        return permission_denied(request)

    template_name = kwargs.get("template_name", "characters/generic_edit.html")
    if request.is_ajax():
        template_name = kwargs.get(
            "template_name_facebox",
            "characters/generic_edit_facebox.html",
        )

    form = form_class(request.POST or None, instance=entry)
    if form.is_valid() and request.method == "POST":
        action(form, sheet)
        return experience_entry_change_ajax_success(request, sheet, entry, group)

    return render_to_response(template_name, {
        'sheet': sheet,
        'form': form,
        'group': group,
        'entry': entry,
        'action_description': action_description,
        'object_description': object_description,
        'form_template': 'characters/generic_edit_form.html',
        'post_url': post_url,
    }, context_instance=RequestContext(request))
Beispiel #14
0
def clone_language(request,
                   project_slug=None,
                   resource_slug=None,
                   source_lang_code=None,
                   target_lang_code=None):
    '''
    Get a resource, a src lang and a target lang and clone all translation
    strings for the src to the target.

    The user is redirected to the online editor for the target language.
    '''

    resource = get_object_or_404(Resource,
                                 slug=resource_slug,
                                 project__slug=project_slug)

    # Permissions handling
    # Project should always be available
    project = get_object_or_404(Project, slug=project_slug)
    team = Team.objects.get_or_none(project, target_lang_code)
    check = ProjectPermission(request.user)
    if not check.submit_translations(team or project) or not \
        resource.accept_translations:
        return permission_denied(request)

    source_lang = get_object_or_404(Language, code=source_lang_code)
    target_lang = get_object_or_404(Language, code=target_lang_code)

    # get the strings which will be cloned
    strings = Translation.objects.filter(resource=resource,
                                         language=source_lang)

    # If the language we want to create, has the same plural rules with the
    # source, we also copy the pluralized translations!
    if not source_lang.get_pluralrules() == target_lang.get_pluralrules():
        strings = strings.exclude(source_entity__pluralized=True)

    # clone them in new translation
    for s in strings:
        Translation.objects.get_or_create(language=target_lang,
                                          string=s.string,
                                          source_entity=s.source_entity,
                                          rule=s.rule,
                                          resource=s.resource)

    invalidate_stats_cache(resource, target_lang, user=request.user)
    return HttpResponseRedirect(
        reverse('translate_resource',
                args=[project_slug, resource_slug, target_lang_code]), )
def project_delete_permission_request(request, project_slug, permission_pk):
    """
    View for deleting a request of permission of a user.

    This view is an abstraction of a txpermissions.views method.
    """
    project, permission = _get_project_and_permission(project_slug,
                                                      permission_pk)

    # It's necessary to distinguish between maintainer and normal users that
    # did the request
    if request.user.id == permission.user.id:
        notice_type = 'project_submit_access_request_withdrawn'
        sendto = project.maintainers.all()
    else:
        notice_type = 'project_submit_access_request_denied'
        sendto = [permission.user]

    notice = {
        'type': notice_type,
        'object': project,
        'sendto': sendto,
        'extra_context': {
            'project': project,
            'user_request': permission.user,
            'user_action': request.user,
        },
    }

    check = ProjectPermission(request.user)
    if check.maintain(project) or \
        request.user.has_perm('authority.delete_permission') or \
        request.user.pk == permission.creator.pk:
        return delete_permission_or_request(
            request,
            permission,
            False,
            extra_context={'notice': notice},
        )

    check = ProjectPermission(request.user)
    if check.maintain(project) or \
            request.user.has_perm('authority.delete_permission') or \
            request.user.pk == permission.creator.pk:
        return delete_permission_or_request(request, permission, False)

    return permission_denied(request)
Beispiel #16
0
def tab_suggestions_snippet(request, entity_id, lang_code):
    """Return a template snippet with entity & translation details."""

    source_entity = get_object_or_404(SourceEntity, pk=entity_id)

    check = ProjectPermission(request.user)
    if not check.private(source_entity.resource.project):
        return permission_denied(request)

    current_translation = source_entity.get_translation(lang_code)

    return render_to_response("tab_suggestions_snippet.html", {
        'source_entity': source_entity,
        'lang_code': lang_code,
        'current_translation': current_translation
        },
    context_instance = RequestContext(request))
Beispiel #17
0
def tab_suggestions_snippet(request, entity_id, lang_code):
    """Return a template snippet with entity & translation details."""

    source_entity = get_object_or_404(SourceEntity, pk=entity_id)

    check = ProjectPermission(request.user)
    if not check.private(source_entity.resource.project):
        return permission_denied(request)

    current_translation = source_entity.get_translation(lang_code)

    return render_to_response("tab_suggestions_snippet.html", {
        'source_entity': source_entity,
        'lang_code': lang_code,
        'current_translation': current_translation
    },
                              context_instance=RequestContext(request))
Beispiel #18
0
def clone_language(request, project_slug=None, resource_slug=None,
            source_lang_code=None, target_lang_code=None):
    '''
    Get a resource, a src lang and a target lang and clone all translation
    strings for the src to the target.

    The user is redirected to the online editor for the target language.
    '''

    resource = get_object_or_404(Resource, slug=resource_slug,
                                 project__slug=project_slug)

    # Permissions handling
    # Project should always be available
    project = get_object_or_404(Project, slug=project_slug)
    team = Team.objects.get_or_none(project, target_lang_code)
    check = ProjectPermission(request.user)
    if not check.submit_translations(team or project) or not \
        resource.accept_translations:
        return permission_denied(request)

    source_lang = get_object_or_404(Language, code=source_lang_code)
    target_lang = get_object_or_404(Language, code=target_lang_code)

    # get the strings which will be cloned
    strings = Translation.objects.filter(
                resource = resource,
                language = source_lang)

    # If the language we want to create, has the same plural rules with the
    # source, we also copy the pluralized translations!
    if not source_lang.get_pluralrules() == target_lang.get_pluralrules():
        strings = strings.exclude(source_entity__pluralized = True)

    # clone them in new translation
    for s in strings:
        Translation.objects.get_or_create(
            language=target_lang, string=s.string,
            source_entity=s.source_entity, rule=s.rule,
            resource=s.resource
        )

    invalidate_stats_cache(resource, target_lang, user=request.user)
    return HttpResponseRedirect(reverse('translate_resource', args=[project_slug,
                                resource_slug, target_lang_code]),)
Beispiel #19
0
def list_sheet(request, sheet_slug, chronicle_slug=None, bridge=None):
    if bridge is not None:
        try:
            group = bridge.get_group(chronicle_slug)
        except ObjectDoesNotExist:
            raise Http404
    else:
        group = None

    sheet = get_object_or_404(Sheet, slug=sheet_slug)
    if not can_fullview_sheet(request, sheet):
        return permission_denied(request)

    return render_to_response(
        'characters/list_sheet.html',
        {'sheet':sheet,
         'group':group},
        context_instance=RequestContext(request))
Beispiel #20
0
def edit_traitlist(request, sheet_slug, traitlistname_slug,
                   chronicle_slug=None, bridge=None,
                   form_class=TraitListPropertyForm, **kwargs):
    if bridge is not None:
        try:
            group = bridge.get_group(chronicle_slug)
        except ObjectDoesNotExist:
            raise Http404
    else:
        group = None

    if group:
        sheet = get_object_or_404(group.content_objects(Sheet), slug=sheet_slug)
    else:
        sheet = get_object_or_404(Sheet, slug=sheet_slug)

    # Check all of the various sheet editing permissions
    if not can_edit_sheet(request, sheet):
        return permission_denied(request)
    template_name = kwargs.get("template_name", "characters/traits/edit_traitlist.html")

    if request.is_ajax():
        template_name = kwargs.get(
            "template_name_facebox",
            "characters/traits/edit_traitlist_facebox.html",
        )

    tln = get_object_or_404(TraitListName, slug=traitlistname_slug)
    tlp = sheet.get_traitlist_property(tln)
    form = form_class(request.POST or None, instance=tlp)
    if form.is_valid() and request.method == "POST":
        tlp = form.save()
        for trait in sheet.get_traitlist(tln.name):
            if trait.display_preference != tlp.display_preference:
                trait.display_preference = tlp.display_preference
                trait.save()
        print "tln", tln
        return trait_change_ajax_success(request, sheet, tln, group)

    return render_to_response(template_name, {
        'sheet': sheet,
        'traitlistname': tln,
        'form': form,
    }, context_instance=RequestContext(request))
Beispiel #21
0
def delete_experience_entry(request, sheet_slug, entry_id,
                            chronicle_slug=None, bridge=None,
                            **kwargs):
    if bridge is not None:
        try:
            group = bridge.get_group(chronicle_slug)
        except ObjectDoesNotExist:
            raise Http404
    else:
        group = None

    if group:
        sheet = get_object_or_404(group.content_objects(Sheet), slug=sheet_slug)
    else:
        sheet = get_object_or_404(Sheet, slug=sheet_slug)

    if entry_id is not None:
        entry = get_object_or_404(sheet.experience_entries.all(), id=entry_id)
    else:
        entry = None

    # Check all of the various sheet editing permissions
    if not can_edit_sheet(request, sheet):
        return permission_denied(request)

    template_name = kwargs.get("template_name", "characters/generic_delete.html")
    if request.is_ajax():
        template_name = kwargs.get(
            "template_name_facebox",
            "characters/generic_delete_facebox.html",
        )

    if request.method == "POST" and request.POST.has_key('__confirm__'):
        sheet.delete_experience_entry(entry)
        return experience_entry_change_ajax_success(request, sheet, None, group)

    return render_to_response(template_name, {
        'sheet': sheet,
        'group': group,
        'instance': entry,
        'object_description': 'Experience Entry',
        'form_template': 'characters/generic_delete_form.html',
        'post_url': reverse('sheet_delete_experience_entry', args=[sheet_slug, entry_id]),
    }, context_instance=RequestContext(request))
Beispiel #22
0
def tab_details_snippet(request, entity_id, lang_code):
    """Return a template snippet with entity & translation details."""

    source_entity = get_object_or_404(SourceEntity, pk=entity_id)

    check = ProjectPermission(request.user)
    if not check.private(source_entity.resource.project):
        return permission_denied(request)

    language = get_object_or_404(Language, code=lang_code)
    translation = source_entity.get_translation(language.code)

    return list_detail.object_detail(request,
        queryset=SourceEntity.objects.all(),
        object_id=entity_id,
        template_name="tab_details_snippet.html",
        template_object_name='source_entity',
        extra_context={"translation": translation,
            "project": source_entity.resource.project})
Beispiel #23
0
def edit_trait(request, sheet_slug, trait_id,
               chronicle_slug=None, bridge=None,
               form_class=TraitForm, **kwargs):
    if bridge is not None:
        try:
            group = bridge.get_group(chronicle_slug)
        except ObjectDoesNotExist:
            raise Http404
    else:
        group = None

    if group:
        sheet = get_object_or_404(group.content_objects(Sheet), slug=sheet_slug)
    else:
        sheet = get_object_or_404(Sheet, slug=sheet_slug)

    trait = get_object_or_404(sheet.traits.all(), id=trait_id)

    # Check all of the various sheet editing permissions
    if not can_edit_sheet(request, sheet):
        return permission_denied(request)

    template_name = kwargs.get("template_name", "characters/traits/edit_trait.html")
    if request.is_ajax():
        template_name = kwargs.get(
            "template_name_facebox",
            "characters/traits/edit_trait_facebox.html",
        )

    form = form_class(request.POST or None, instance=trait)
    form.is_valid()
    pprint(form.errors)
    print request.is_ajax()
    if form.is_valid() and request.method == "POST":
        form.save()
        return trait_change_ajax_success(request, sheet, trait.traitlistname, group)

    return render_to_response(template_name, {
        'sheet': sheet,
        'form': form,
        'trait': trait,
        'group': group,
    }, context_instance=RequestContext(request))
Beispiel #24
0
def download_sheet(request, sheet_slug,
                   chronicle_slug=None, bridge=None):
    if bridge is not None:
        try:
            group = bridge.get_group(chronicle_slug)
        except ObjectDoesNotExist:
            raise Http404
    else:
        group = None

    sheet = get_object_or_404(Sheet, slug=sheet_slug)
    if not can_fullview_sheet(request, sheet):
        return permission_denied(request)

    response = HttpResponse(mimetype="application/gex")
    response['Content-Disposition'] = 'filename=' + sheet_slug + '.gex'
    ve = VampireExporter(sheet)
    response.write(ve)
    return response
Beispiel #25
0
def project_delete_permission_request(request, project_slug, permission_pk):
    """
    View for deleting a request of permission of a user.

    This view is an abstraction of a txpermissions.views method.
    """
    project, permission=_get_project_and_permission(project_slug, permission_pk)

    # It's necessary to distinguish between maintainer and normal users that
    # did the request
    if request.user.id==permission.user.id:
        notice_type = 'project_submit_access_request_withdrawn'
        sendto = project.maintainers.all()
    else:
        notice_type = 'project_submit_access_request_denied'
        sendto = [permission.user]

    notice = {
            'type': notice_type,
            'object': project,
            'sendto': sendto,
            'extra_context': {'project': project,
                              'user_request': permission.user,
                              'user_action': request.user,
            },
        }

    check = ProjectPermission(request.user)
    if check.maintain(project) or \
        request.user.has_perm('authority.delete_permission') or \
        request.user.pk == permission.creator.pk:
        return delete_permission_or_request(request, permission, False,
                                            extra_context={ 'notice': notice },)


    check = ProjectPermission(request.user)
    if check.maintain(project) or \
            request.user.has_perm('authority.delete_permission') or \
            request.user.pk == permission.creator.pk:
        return delete_permission_or_request(request, permission, False)

    return permission_denied(request)
Beispiel #26
0
def suggestion_vote(request, entity_id, lang_code, suggestion_id, direction):
    """Vote up or down for a suggestion."""

    suggestion = get_object_or_404(Suggestion, pk=suggestion_id)

    # Permissions handling
    check = ProjectPermission(request.user)
    if not check.private(suggestion.source_entity.resource.project):
        return permission_denied(request)

    #FIXME: All basic POST checks could be done in a decorator.
    if not request.method == "POST":
        return HttpResponseBadRequest(_("POST method only allowed."))

    if direction == 'up':
        suggestion.vote_up(request.user)
    elif direction == 'down':
        suggestion.vote_down(request.user)

    return HttpResponse(status=200)
Beispiel #27
0
def suggestion_vote(request, entity_id, lang_code, suggestion_id, direction):
    
    """Vote up or down for a suggestion."""

    suggestion = get_object_or_404(Suggestion, pk=suggestion_id)

    # Permissions handling
    check = ProjectPermission(request.user)
    if not check.private(suggestion.source_entity.resource.project):
        return permission_denied(request)

    #FIXME: All basic POST checks could be done in a decorator.
    if not request.method == "POST":
        return HttpResponseBadRequest(_("POST method only allowed."))

    if direction == 'up':
        suggestion.vote_up(request.user)
    elif direction == 'down':
        suggestion.vote_down(request.user)

    return HttpResponse(status=200)
Beispiel #28
0
def tab_details_snippet(request, entity_id, lang_code):
    """Return a template snippet with entity & translation details."""

    source_entity = get_object_or_404(SourceEntity, pk=entity_id)

    check = ProjectPermission(request.user)
    if not check.private(source_entity.resource.project):
        return permission_denied(request)

    language = get_object_or_404(Language, code=lang_code)
    translation = source_entity.get_translation(language.code)

    return list_detail.object_detail(request,
                                     queryset=SourceEntity.objects.all(),
                                     object_id=entity_id,
                                     template_name="tab_details_snippet.html",
                                     template_object_name='source_entity',
                                     extra_context={
                                         "translation": translation,
                                         "project":
                                         source_entity.resource.project
                                     })
Beispiel #29
0
def suggestion_create(request, entity_id, lang_code):
    """Create a suggestion for an entity and a language."""

    source_entity = get_object_or_404(SourceEntity, pk=entity_id)

    # Permissions handling
    check = ProjectPermission(request.user)
    if not check.private(source_entity.resource.project):
        return permission_denied(request)

    #FIXME: All basic POST checks could be done in a decorator.
    if not request.method == "POST":
        return HttpResponseBadRequest(_("POST method only allowed."))
    suggestion_string = request.POST['suggestion_string']
    if not suggestion_string:
        return HttpResponseBadRequest(_("POST variable 'suggestion_string' missing."))

    language = Language.objects.by_code_or_alias(lang_code)
    source_entity.suggestions.create(language=language,
                                     string=request.POST['suggestion_string'],
                                     user=request.user)
    return HttpResponse(status=200)
Beispiel #30
0
 def decorated(request, *args, **kwargs):
     if request.user.is_authenticated():
         params = []
         for lookup_variable in lookup_variables:
             if isinstance(lookup_variable, basestring):
                 value = kwargs.get(lookup_variable, None)
                 if value is None:
                     continue
                 params.append(value)
             elif isinstance(lookup_variable, (tuple, list)):
                 model, lookup, varname = lookup_variable
                 value = kwargs.get(varname, None)
                 if value is None:
                     continue
                 if isinstance(model, basestring):
                     model_class = get_model(*model.split("."))
                 else:
                     model_class = model
                 if model_class is None:
                     raise ValueError(
                         "The given argument '%s' is not a valid model."
                         % model)
                 if (inspect.isclass(model_class)
                         and not issubclass(model_class, Model)):
                     raise ValueError(
                         'The argument %s needs to be a model.' % model)
                 obj = get_object_or_404(model_class, **{lookup: value})
                 params.append(obj)
         check = get_check(request.user, perm)
         granted = False
         if check is not None:
             granted = check(*params)
         if granted or request.user.has_perm(perm):
             return view_func(request, *args, **kwargs)
     if redirect_to_login:
         path = urlquote(request.get_full_path())
         tup = login_url, redirect_field_name, path
         return HttpResponseRedirect('%s?%s=%s' % tup)
     return permission_denied(request)
Beispiel #31
0
def delete_sheet(request, sheet_slug,
                 chronicle_slug=None, bridge=None,
                 **kwargs):
    if bridge is not None:
        try:
            group = bridge.get_group(chronicle_slug)
        except ObjectDoesNotExist:
            raise Http404
    else:
        group = None

    if group:
        sheet = get_object_or_404(group.content_objects(Sheet), slug=sheet_slug)
    else:
        sheet = get_object_or_404(Sheet, slug=sheet_slug)

    # Check all of the various sheet editing permissions
    if not can_delete_sheet(request, sheet):
        return permission_denied(request)

    template_name = kwargs.get("template_name", "characters/generic_delete.html")
    if request.is_ajax():
        template_name = kwargs.get(
            "template_name_facebox",
            "characters/generic_delete_facebox.html",
        )

    if request.method == "POST" and request.POST.has_key('__confirm__'):
        sheet.safe_delete()
        return HttpResponseRedirect(reverse('sheets_list'))

    return render_to_response(template_name, {
        'sheet': sheet,
        'group': group,
        'instance': sheet,
        'object_description': 'Sheet',
        'form_template': 'characters/generic_delete_form.html',
        'post_url': reverse('sheet_delete', args=[sheet_slug]),
    }, context_instance=RequestContext(request))
Beispiel #32
0
def delete_trait(request, sheet_slug, trait_id,
                 chronicle_slug=None, bridge=None,
                 **kwargs):
    if bridge is not None:
        try:
            group = bridge.get_group(chronicle_slug)
        except ObjectDoesNotExist:
            raise Http404
    else:
        group = None

    if group:
        sheet = get_object_or_404(group.content_objects(Sheet), slug=sheet_slug)
    else:
        sheet = get_object_or_404(Sheet, slug=sheet_slug)
    trait = get_object_or_404(sheet.traits.all(), id=trait_id)

    # Check all of the various sheet editing permissions
    if not can_edit_sheet(request, sheet):
        return permission_denied(request)

    template_name = kwargs.get("template_name", "characters/traits/delete_trait.html")
    if request.is_ajax():
        template_name = kwargs.get(
            "template_name_facebox",
            "characters/traits/delete_trait_facebox.html",
        )

    if request.method == "POST" and request.POST.has_key('__confirm__'):
        tln = trait.traitlistname
        trait.delete()
        return trait_change_ajax_success(request, sheet, tln, group)

    return render_to_response(template_name, {
        'sheet': sheet,
        'trait': trait,
        'group': group,
    }, context_instance=RequestContext(request))
Beispiel #33
0
 def decorated(request, *args, **kwargs):
     if request.user.is_authenticated():
         params = []
         for lookup_variable in lookup_variables:
             if isinstance(lookup_variable, string_types):
                 value = kwargs.get(lookup_variable, None)
                 if value is None:
                     continue
                 params.append(value)
             elif isinstance(lookup_variable, (tuple, list)):
                 model, lookup, varname = lookup_variable
                 value = kwargs.get(varname, None)
                 if value is None:
                     continue
                 if isinstance(model, string_types):
                     model_class = apps.get_model(*model.split("."))
                 else:
                     model_class = model
                 if model_class is None:
                     raise ValueError(
                         "The given argument '%s' is not a valid model." % model)
                 if (inspect.isclass(model_class) and
                         not issubclass(model_class, Model)):
                     raise ValueError(
                         'The argument %s needs to be a model.' % model)
                 obj = get_object_or_404(model_class, **{lookup: value})
                 params.append(obj)
         check = get_check(request.user, perm)
         granted = False
         if check is not None:
             granted = check(*params)
         if granted or request.user.has_perm(perm):
             return view_func(request, *args, **kwargs)
     if redirect_to_login:
         path = urlquote(request.get_full_path())
         tup = login_url, redirect_field_name, path
         return HttpResponseRedirect('%s?%s=%s' % tup)
     return permission_denied(request)
Beispiel #34
0
def suggestion_create(request, entity_id, lang_code):
    """Create a suggestion for an entity and a language."""

    source_entity = get_object_or_404(SourceEntity, pk=entity_id)

    # Permissions handling
    check = ProjectPermission(request.user)
    if not check.private(source_entity.resource.project):
        return permission_denied(request)

    #FIXME: All basic POST checks could be done in a decorator.
    if not request.method == "POST":
        return HttpResponseBadRequest(_("POST method only allowed."))
    suggestion_string = request.POST['suggestion_string']
    if not suggestion_string:
        return HttpResponseBadRequest(
            _("POST variable 'suggestion_string' missing."))

    language = Language.objects.by_code_or_alias(lang_code)
    source_entity.suggestions.create(language=language,
                                     string=request.POST['suggestion_string'],
                                     user=request.user)
    return HttpResponse(status=200)
Beispiel #35
0
def print_sheet(request, sheet_slug, chronicle_slug=None, bridge=None,
                form_class=PrintOptionsForm):
    if bridge is not None:
        try:
            group = bridge.get_group(chronicle_slug)
        except ObjectDoesNotExist:
            raise Http404
    else:
        group = None

    sheet = get_object_or_404(Sheet, slug=sheet_slug)
    if not can_fullview_sheet(request, sheet):
        return permission_denied(request)

    form = form_class(request.POST or None)
    pprint(form.errors)
    if form.is_valid() and request.method == "POST":
        try:
            return render_to_response(
                'characters/printing/vampire_{}.html'.format(form.cleaned_data['template']),
                {'sheet':sheet,
                 'group':group,
                 'printing':True,
                 'options':form.cleaned_data},
                context_instance=RequestContext(request))
        except TemplateDoesNotExist:
            if 'template' not in form.errors:
                form.errors['template'] = []
            form.errors['template'].append(u'Chosen printing template does not exist')

    return render_to_response(
        'characters/print_sheet_options.html',
        {'form':form,
         'sheet':sheet,
         'group':group,
         'printing':True},
        context_instance=RequestContext(request))
Beispiel #36
0
def edit_vampire_sheet_attributes(request, sheet_slug,
                                  form_class=VampireSheetAttributesForm, **kwargs):
    sheet = get_object_or_404(Sheet, slug=sheet_slug)
    if not can_edit_sheet(request, sheet):
        return permission_denied(request)

    template_name = kwargs.get("template_name", "characters/vampires/edit_vampire_sheet_attributes.html")

    if request.is_ajax():
        template_name = kwargs.get(
            "template_name_facebox",
            "characters/vampires/edit_vampire_sheet_attributes_facebox.html",
        )

    vampire_sheet = sheet.vampiresheet
    form = form_class(request.POST or None, instance=vampire_sheet)
    if form.is_valid() and request.method == "POST":
        form.save()
        return HttpResponseRedirect(reverse("sheet_list", args=[sheet_slug]))

    return render_to_response(template_name, {
        'sheet': vampire_sheet,
        'form': form,
    }, context_instance=RequestContext(request))
Beispiel #37
0
def permissions_sheet(request, sheet_slug,
                      chronicle_slug=None, bridge=None,
                      template_name="characters/permissions.html"):
    if bridge is not None:
        try:
            group = bridge.get_group(chronicle_slug)
        except ObjectDoesNotExist:
            raise Http404
    else:
        group = None

    if group:
        sheet = get_object_or_404(group.content_objects(Sheet), slug=sheet_slug)
    else:
        sheet = get_object_or_404(Sheet, slug=sheet_slug)

    # Check all of the various sheet editing permissions
    if not can_list_sheet(request, sheet):
        return permission_denied(request)

    permission_keys = ("list", "history", "delete", "edit")
    permissions = {}
    for key in permission_keys:
        #permissions[key] = [user for user in User.objects.all() if globals()['can_' + key + '_sheet'](request, sheet, user=user)]
        bl = []
        for user in User.objects.all():
            keep = globals()['can_' + key + '_sheet'](request, sheet, user=user, infodump=True)
            if keep[0]:
                bl.append((user, keep[1]))
        permissions[key] = bl

    return render_to_response(template_name, {
        'sheet': sheet,
        'permissions': permissions,
        'group': group,
    }, context_instance=RequestContext(request))
Beispiel #38
0
def proofread(request,
              project_slug,
              lang_code,
              resource_slug=None,
              *args,
              **kwargs):
    """AJAX view that sets the reviewed flag on Translations to true or false.

    The request data is expected in JSON, with the following format:

    {
        'true': [1,2,3]
        'false': [4,5]
    }

    Note: The IDs are source entity IDs.
    """
    if request.method != 'POST':
        return HttpResponse(status=405)

    project = get_object_or_404(Project, slug=project_slug)
    resource = get_object_or_404(Resource, slug=resource_slug, project=project)

    try:
        language = Language.objects.by_code_or_alias(lang_code)
    except Language.DoesNotExist:
        raise Http404

    # Check if the user has the necessary permissions to review strings.
    check = ProjectPermission(request.user)
    if not check.proofread(project, language):
        return permission_denied(request)

    request_data = simplejson.loads(request.raw_post_data)

    if 'true' in request_data:
        source_entity_ids = request_data['true']
        translations = Translation.objects.filter(
            source_entity__id__in=source_entity_ids,
            language__code=lang_code,
        )
        translations.update(reviewed=True)
        ReviewHistory.add_many(translations,
                               request.user,
                               project.id,
                               reviewed=True)

    if 'false' in request_data:
        source_entity_ids = request_data['false']
        translations = Translation.objects.filter(
            source_entity__id__in=source_entity_ids,
            language__code=lang_code,
        )
        translations.update(reviewed=False)
        ReviewHistory.add_many(translations,
                               request.user,
                               project.id,
                               reviewed=False)

    invalidate_stats_cache(resource, language, user=request.user)

    return HttpResponse(status=200)
Beispiel #39
0
def exit(request,
         project_slug,
         lang_code,
         resource_slug=None,
         *args,
         **kwargs):
    """
    Exiting Lotte
    """
    if request.method != 'POST':
        return HttpResponse(status=405)

    # Permissions handling
    # Project should always be available
    project = get_object_or_404(Project, slug=project_slug)
    team = Team.objects.get_or_none(project, lang_code)
    check = ProjectPermission(request.user)
    if not check.submit_translations(team or project) and not\
        check.maintain(project):
        return permission_denied(request)

    language = Language.objects.by_code_or_alias(lang_code)

    resources = []
    if resource_slug:
        resources = Resource.objects.filter(slug=resource_slug,
                                            project=project)
        if not resources:
            raise Http404
    else:
        resources = Resource.objects.filter(project=project)

    data = simplejson.loads(request.raw_post_data)

    if data.get('updated'):
        modified = True
        # ActionLog & Notification
        for resource in resources:
            nt = 'project_resource_translated'
            context = {
                'project': project,
                'resource': resource,
                'language': language,
                'sender': request.user
            }
            object_list = [project, resource, language]
            if team:
                object_list.append(team)
            action_logging(request.user, object_list, nt, context=context)
    else:
        modified = False

    lotte_done.send(None,
                    request=request,
                    resources=resources,
                    language=language,
                    modified=modified)

    redirect_url = reverse('team_detail', args=[project_slug, language.code])

    if request.is_ajax():
        json = simplejson.dumps(dict(redirect=redirect_url))
        return HttpResponse(json, mimetype='application/json')

    return HttpResponseRedirect(redirect_url)
Beispiel #40
0
def push_translation(request, project_slug, lang_code, *args, **kwargs):
    """
    Client pushes an id and a translation string.

    Id is considered to be of the source translation string and the string is
    in the target_lang.

    FIXME: Document in detail the form of the 'strings' POST variable.
    """

    logger.debug("POST data when saving translation: %s" % request.POST)
    # Permissions handling
    # Project should always be available
    project = get_object_or_404(Project, slug=project_slug)
    team = Team.objects.get_or_none(project, lang_code)
    check = ProjectPermission(request.user)
    if not check.submit_translations(team or project) and not\
        check.maintain(project):
        return permission_denied(request)

    if not request.POST:
        return HttpResponseBadRequest()

    data = simplejson.loads(request.raw_post_data)
    strings = data["strings"]

    try:
        target_language = Language.objects.by_code_or_alias(lang_code)
    except Language.DoesNotExist:
        raise Http404

    # This dictionary will hold the results of the save operation and will map
    # status code for each translation pushed, to indicate the result on each
    # translation push separately.
    push_response_dict = {}

    # Form the strings dictionary, get as Json object
    # The fields are the following:
    # id-> source_entity id
    # translations-> translation strings (includes all plurals)
    # context-> source_entity context
    # occurrence-> occurrence (not yet well supported)
    # Iterate through all the row data that have been sent.
    for row in strings:
        source_id = int(row['id'])
        try:
            source_string = Translation.objects.select_related(depth=1).get(
                id=source_id
            )
        except Translation.DoesNotExist:
            # TODO: Log or inform here
            push_response_dict[source_id] = { 'status':400,
                 'message':_("Source string cannot be identified in the DB")}
            # If the source_string cannot be identified in the DB then go to next
            # translation pair.
            continue

        if not source_string.resource.accept_translations:
            push_response_dict[source_id] = { 'status':400,
                 'message':_("The resource of this source string is not "
                    "accepting translations.") }

        # If the translated source string is pluralized check that all the
        # source language supported rules have been filled in, else return error
        # and donot save the translations.
        if source_string.source_entity.pluralized:
            error_flag = False
            for rule in target_language.get_pluralrules():
                if rule in row['translations'] and row['translations'][rule] != "":
                    continue
                else:
                    error_flag = True
            if error_flag:
                error_flag = False
                # Check also if all of them are "". If yes, delete all the plurals!
                for rule in target_language.get_pluralrules():
                    if rule in row['translations'] and row['translations'][rule] == "":
                        continue
                    else:
                        error_flag = True
            if error_flag:
                push_response_dict[source_id] = { 'status':400,
                    'message':(_("Cannot save unless plural translations are either "
                               "completely specified or entirely empty!"))}
                # Skip the save as we hit on an error.
                continue
        try:
            msgs = _save_translation(
                source_string, row['translations'],
                target_language, request.user
            )
            if not msgs:
                push_response_dict[source_id] = {'status': 200}
            else:
                push_response_dict[source_id] = {
                    'status': 200, 'message': msgs[-1]
                }
        except LotteBadRequestError, e:
            push_response_dict[source_id] = {
                'status': 400, 'message': e.message
            }
        except Exception, e:
            logger.error(
                "Unexpected exception raised: %s" % e.message, exc_info=True
            )
            push_response_dict[source_id] = {
                'status': 400, 'message': e.message
            }
Beispiel #41
0
def translate(request,
              project_slug,
              lang_code,
              resource_slug=None,
              *args,
              **kwargs):
    """
    Main lotte view.
    """

    # Permissions handling
    # Project should always be available
    project = get_object_or_404(Project, slug=project_slug)
    team = Team.objects.get_or_none(project, lang_code)
    check = ProjectPermission(request.user)
    if not check.submit_translations(team or project) and not\
        check.maintain(project):
        return permission_denied(request)

    resources = []
    if resource_slug:
        resource_list = [
            get_object_or_404(Resource, slug=resource_slug, project=project)
        ]
    else:
        resource_list = Resource.objects.filter(project=project)

        # Return a page explaining that the project has multiple source langs and
        # cannot be translated as a whole.
        if resource_list.values('source_language').distinct().count() > 1:
            messages.info(
                request,
                _("There are multiple source languages for this project. "
                  "You will only be able to translate resources for one "
                  "source language at a time."))
            return HttpResponseRedirect(
                reverse('project_detail', args=[project_slug]), )

    # Filter resources that are not accepting translations
    for resource in resource_list:
        if resource.accept_translations:
            resources.append(resource)

    # If no resource accepting translations, raise a 403
    if not resources:
        return permission_denied(request)

    target_language = Language.objects.by_code_or_alias_or_404(lang_code)

    # If it is an attempt to edit the source language, redirect the user to
    # resource_detail and show him a message explaining the reason.
    if target_language == get_source_language(resources):
        messages.error(
            request,
            _("Cannot edit the source language because this would "
              "result in translation mismatches! If you want to "
              "update the source strings consider using the transifex "
              "command-line client."))
        if resource_slug:
            return HttpResponseRedirect(
                reverse('resource_detail', args=[project_slug,
                                                 resource_slug]), )
        else:
            return HttpResponseRedirect(
                reverse('project_detail', args=[project_slug]), )

    total_strings = SourceEntity.objects.filter(resource__in=resources).count()

    translated_strings = Translation.objects.filter(
        resource__in=resources,
        language=target_language,
        source_entity__pluralized=False,
        rule=5).count()

    reviewed_strings = Translation.objects.filter(
        resource__in=resources,
        language=target_language,
        source_entity__pluralized=False,
        rule=5,
        reviewed=True).count()

    # Include counting of pluralized entities
    for pluralized_entity in SourceEntity.objects.filter(
            resource__in=resources, pluralized=True):
        plurals_translated = Translation.objects.filter(
            language=target_language, source_entity=pluralized_entity).count()
        if plurals_translated == len(target_language.get_pluralrules()):
            translated_strings += 1

    if len(resources) > 1:
        translation_resource = None
    else:
        translation_resource = resources[0]

    contributors = User.objects.filter(pk__in=Translation.objects.filter(
        resource__in=resources, language=target_language, rule=5).values_list(
            "user", flat=True))

    lotte_init.send(None,
                    request=request,
                    resources=resources,
                    language=target_language)

    if target_language in [team.language for team in project.available_teams]:
        team_language = True
    else:
        team_language = False

    GtModel = get_model('gtranslate', 'Gtranslate')
    try:
        auto_translate = GtModel.objects.get(project=project)
    except GtModel.DoesNotExist:
        auto_translate = None
    """
    if cache.get('lotte_%s' % request.session.session_key, None):
        cache.delete('lotte_%s' % request.session.session_key)
    """

    #Set rtl to True if target_language is an RTL language
    rtl = False
    if target_language.code in settings.RTL_LANGUAGE_CODES:
        rtl = True

    return render_to_response("translate.html", {
        'project': project,
        'resource': translation_resource,
        'target_language': target_language,
        'translated_strings': translated_strings,
        'reviewed_strings': reviewed_strings,
        'untranslated_strings': total_strings - translated_strings,
        'contributors': contributors,
        'resources': resources,
        'resource_slug': resource_slug,
        'languages': Language.objects.all(),
        'auto_translate': auto_translate,
        'spellcheck_supported_langs': SPELLCHECK_SUPPORTED_LANGS,
        'team_language': team_language,
        'RTL': rtl,
    },
                              context_instance=RequestContext(request))
Beispiel #42
0
def lock_and_get_translation_file(request, project_slug, resource_slug,
                                  lang_code):
    """
    Lock and download the translations file.

    View to lock a resource for the requested language and as a second step to
    download (export+download) the translations in a formatted file.
    """

    resource = get_object_or_404(Resource,
                                 project__slug=project_slug,
                                 slug=resource_slug)

    # Permissions handling
    # Project should always be available
    project = get_object_or_404(Project, slug=project_slug)
    team = Team.objects.get_or_none(project, lang_code)
    check = ProjectPermission(request.user)
    if not check.submit_translations(team or project) or not \
        resource.accept_translations:
        return permission_denied(request)

    language = get_object_or_404(Language, code=lang_code)
    lock = Lock.objects.get_valid(resource, language)
    can_lock = Lock.can_lock(resource, language, request.user)
    response = {}

    if not can_lock:
        #print_gray_text(You cannot assign this file to you)
        response['status'] = "FAILED"
        response['message'] = _("Sorry, you cannot lock this file!")
    else:
        # User can lock
        if not lock:
            try:
                # Lock the resource now
                Lock.objects.create_update(resource, language, request.user)
                response['status'] = 'OK'
                response['redirect'] = reverse(
                    'download_for_translation',
                    args=[resource.project.slug, resource.slug, lang_code])
            except:
                response['status'] = "FAILED"
                response['message'] = _("Failed to lock the resource!")
        else:
            if lock.owner == request.user:
                try:
                    # File already locked by me, so extend the lock period.
                    Lock.objects.create_update(resource, language,
                                               request.user)
                    response['status'] = 'OK'
                    response['redirect'] = reverse(
                        'download_for_translation',
                        args=[resource.project.slug, resource.slug, lang_code])
                except:
                    response['status'] = "FAILED"
                    response['message'] = _("Failed to extend lock period on "
                                            "the resource!")
            else:
                # File locked by someone else:
                response['status'] = "FAILED"
                response['message'] = _(
                    "You cannot lock it right now! (Locked "
                    "by %s )" % (lock.owner, ))

    return HttpResponse(simplejson.dumps(response),
                        mimetype='application/json')
Beispiel #43
0
def push_translation(request, project_slug, lang_code, *args, **kwargs):
    """
    Client pushes an id and a translation string.

    Id is considered to be of the source translation string and the string is
    in the target_lang.

    FIXME: Document in detail the form of the 'strings' POST variable.
    """

    logger.debug("POST data when saving translation: %s" % request.POST)
    # Permissions handling
    # Project should always be available
    project = get_object_or_404(Project, slug=project_slug)
    team = Team.objects.get_or_none(project, lang_code)
    check = ProjectPermission(request.user)
    if not check.submit_translations(team or project) and not\
        check.maintain(project):
        return permission_denied(request)

    if not request.POST:
        return HttpResponseBadRequest()

    data = simplejson.loads(request.raw_post_data)
    strings = data["strings"]

    try:
        target_language = Language.objects.by_code_or_alias(lang_code)
    except Language.DoesNotExist:
        raise Http404

    # This dictionary will hold the results of the save operation and will map
    # status code for each translation pushed, to indicate the result on each
    # translation push separately.
    push_response_dict = {}

    # Form the strings dictionary, get as Json object
    # The fields are the following:
    # id-> source_entity id
    # translations-> translation strings (includes all plurals)
    # context-> source_entity context
    # occurrence-> occurrence (not yet well supported)
    # Iterate through all the row data that have been sent.
    for row in strings:
        source_id = int(row['id'])
        try:
            source_string = Translation.objects.select_related(depth=1).get(
                id=source_id)
        except Translation.DoesNotExist:
            # TODO: Log or inform here
            push_response_dict[source_id] = {
                'status': 400,
                'message': _("Source string cannot be identified in the DB")
            }
            # If the source_string cannot be identified in the DB then go to next
            # translation pair.
            continue

        if not source_string.resource.accept_translations:
            push_response_dict[source_id] = {
                'status':
                400,
                'message':
                _("The resource of this source string is not "
                  "accepting translations.")
            }

        # If the translated source string is pluralized check that all the
        # source language supported rules have been filled in, else return error
        # and donot save the translations.
        if source_string.source_entity.pluralized:
            error_flag = False
            for rule in target_language.get_pluralrules():
                if rule in row[
                        'translations'] and row['translations'][rule] != "":
                    continue
                else:
                    error_flag = True
            if error_flag:
                error_flag = False
                # Check also if all of them are "". If yes, delete all the plurals!
                for rule in target_language.get_pluralrules():
                    if rule in row['translations'] and row['translations'][
                            rule] == "":
                        continue
                    else:
                        error_flag = True
            if error_flag:
                push_response_dict[source_id] = {
                    'status':
                    400,
                    'message':
                    (_("Cannot save unless plural translations are either "
                       "completely specified or entirely empty!"))
                }
                # Skip the save as we hit on an error.
                continue
        try:
            msgs = _save_translation(source_string, row['translations'],
                                     target_language, request.user)
            if not msgs:
                push_response_dict[source_id] = {'status': 200}
            else:
                push_response_dict[source_id] = {
                    'status': 200,
                    'message': msgs[-1]
                }
        except LotteBadRequestError, e:
            push_response_dict[source_id] = {
                'status': 400,
                'message': e.message
            }
        except Exception, e:
            logger.error("Unexpected exception raised: %s" % e.message,
                         exc_info=True)
            push_response_dict[source_id] = {
                'status': 400,
                'message': e.message
            }