def upload_create_resource_form(request, project, prefix='create_form'):
    """Form for creating a new resource."""
    resource = None
    display_form = False
    if request.method == 'POST' and request.POST.get('create_resource', None):
        cr_form = CreateResourceForm(request.POST,
                                     request.FILES,
                                     prefix=prefix)
        if cr_form.is_valid():
            name = cr_form.cleaned_data['name']
            slug = slugify(name)

            # Check if we already have a resource with this slug in the db.
            try:
                Resource.objects.get(slug=slug, project=project)
            except Resource.DoesNotExist:
                pass
            else:
                # if the resource exists, modify slug in order to force the
                # creation of a new resource.
                slug = slugify(name)
                identifier = Resource.objects.filter(
                    project=project, slug__icontains="%s_" % slug).count() + 1
                slug = "%s_%s" % (slug, identifier)
            method = cr_form.cleaned_data['i18n_method']
            content = content_from_uploaded_file(request.FILES)
            filename = filename_of_uploaded_file(request.FILES)
            rb = ResourceBackend()
            try:
                with transaction.commit_on_success():
                    rb.create(project,
                              slug,
                              name,
                              method,
                              project.source_language,
                              content,
                              user=request.user,
                              extra_data={'filename': filename})
            except ResourceBackendError, e:
                cr_form._errors['source_file'] = ErrorList([
                    e.message,
                ])
                display_form = True
            else:
                display_form = False
                resource = Resource.objects.get(slug=slug, project=project)
        else:
            display_form = True
def upload_create_resource_form(request, project, prefix='create_form'):
    """Form for creating a new resource."""
    resource = None
    display_form = False
    if request.method == 'POST' and request.POST.get('create_resource', None):
        cr_form = CreateResourceForm(
            request.POST, request.FILES, prefix=prefix
        )
        if cr_form.is_valid():
            name = cr_form.cleaned_data['name']
            slug = slugify(name)

            # Check if we already have a resource with this slug in the db.
            try:
                Resource.objects.get(slug=slug, project=project)
            except Resource.DoesNotExist:
                pass
            else:
                # if the resource exists, modify slug in order to force the
                # creation of a new resource.
                slug = slugify(name)
                identifier = Resource.objects.filter(
                    project=project, slug__icontains="%s_" % slug
                ).count() + 1
                slug = "%s_%s" % (slug, identifier)
            method = cr_form.cleaned_data['i18n_method']
            content = content_from_uploaded_file(request.FILES)
            filename = filename_of_uploaded_file(request.FILES)
            rb = ResourceBackend()
            try:
                rb.create(
                    project, slug, name, method, project.source_language,
                    content, user=request.user,
                    extra_data={'filename': filename}
                )
            except ResourceBackendError, e:
                transaction.rollback()
                cr_form._errors['source_file'] = ErrorList([e.message, ])
                display_form=True
            else:
                transaction.commit()
                display_form = False
                resource = Resource.objects.get(slug=slug, project=project)
        else:
            display_form=True
Exemplo n.º 3
0
def update_translation(request, project_slug, resource_slug, lang_code=None):
    """Ajax view that gets an uploaded translation as a file and saves it.

    If the language is not specified, the translation does not exist yet.
    Othewise, this is an update.

    Returns:
        Either an error message, or nothing for success.
    """
    resource = get_object_or_404(
        Resource.objects.select_related('project'),
        project__slug=project_slug, slug=resource_slug
    )
    if lang_code is None:
        lang_code = request.POST.get('language_code', None)
    target_language = get_object_or_404(Language, code=lang_code)
    project = resource.project
    # Get the team if exists to use it for permissions and links
    team = Team.objects.get_or_none(project, lang_code)

    check = ProjectPermission(request.user)
    if (not check.submit_translations(team or resource.project) or\
            not resource.accept_translations) and not\
            check.maintain(resource.project):
        return HttpResponse(
            simplejson.dumps({
                    'msg': _("You are not allowed to upload a translation."),
                    'status': 403,
            }),
            status=403, content_type='text/plain'
        )

    content = content_from_uploaded_file(request.FILES)
    try:
        _save_translation(resource, target_language, request.user, content)
    except FormatsBackendError, e:
        return HttpResponse(
            simplejson.dumps({
                    'msg': unicode(e),
                    'status': 400,
            }),
            status=400, content_type='text/plain'
        )
Exemplo n.º 4
0
def update_translation(request, project_slug, resource_slug, lang_code=None):
    """Ajax view that gets an uploaded translation as a file and saves it.

    If the language is not specified, the translation does not exist yet.
    Othewise, this is an update.

    Returns:
        Either an error message, or nothing for success.
    """
    resource = get_object_or_404(Resource.objects.select_related('project'),
                                 project__slug=project_slug,
                                 slug=resource_slug)
    if lang_code is None:
        lang_code = request.POST.get('language_code', None)
    target_language = get_object_or_404(Language, code=lang_code)
    project = resource.project
    # Get the team if exists to use it for permissions and links
    team = Team.objects.get_or_none(project, lang_code)

    check = ProjectPermission(request.user)
    if (not check.submit_translations(team or resource.project) or\
            not resource.accept_translations) and not\
            check.maintain(resource.project):
        return HttpResponse(simplejson.dumps({
            'msg':
            _("You are not allowed to upload a translation."),
            'status':
            403,
        }),
                            status=403,
                            content_type='text/plain')

    content = content_from_uploaded_file(request.FILES)
    try:
        _save_translation(resource, target_language, request.user, content)
    except FormatsBackendError, e:
        return HttpResponse(simplejson.dumps({
            'msg': unicode(e),
            'status': 400,
        }),
                            status=400,
                            content_type='text/plain')
Exemplo n.º 5
0
        Returns:
            The content of the string/file.
        """
        if 'application/json' in request.content_type:
            try:
                return data['content']
            except KeyError, e:
                msg = "No content provided"
                logger.warning(msg)
                raise NoContentError(msg)
        elif 'multipart/form-data' in request.content_type:
            if not request.FILES:
                msg = "No file has been uploaded."
                logger.warning(msg)
                raise NoContentError(msg)
            return content_from_uploaded_file(request.FILES)
        else:
            msg = "No content or file found"
            logger.warning(msg)
            raise NoContentError(msg)

    def _get_filename(self, request, data):
        """Get the filename of the uploaded file.

        Returns:
            The filename or None, if the request used json.
        """
        if 'application/json' in request.content_type:
            return None
        elif 'multipart/form-data' in request.content_type:
            if not request.FILES:
Exemplo n.º 6
0
def resource_edit(request, project_slug, resource_slug):
    """
    Edit the metadata of  a Translation Resource in a specific project.
    """
    resource = get_object_or_404(Resource, project__slug = project_slug,
                                  slug = resource_slug)
    try:
        urlinfo = URLInfo.objects.get(resource = resource)
    except URLInfo.DoesNotExist:
        urlinfo = None

    if request.method == 'POST':
        resource_form = ResourceForm(request.POST, request.FILES, instance=resource)
        if urlinfo:
            url_form = URLInfoForm(request.POST, instance=urlinfo,)
        else:
            url_form = URLInfoForm(request.POST,)
        if resource_form.is_valid() and url_form.is_valid():
            try:
                resource = resource_form.save(commit=False)
                if resource_form.cleaned_data['sourcefile'] is not None:
                    method = resource.i18n_method
                    content = content_from_uploaded_file(
                        {0: resource_form.cleaned_data['sourcefile'], }
                    )
                    filename = resource_form.cleaned_data['sourcefile'].name
                    save_source_file(
                        resource, request.user, content, method, filename
                    )

                urlinfo = url_form.save(commit=False)
                resource_new = resource_form.save()
                resource_new.save()
                urlinfo.resource = resource_new
                invalidate_object_templates(resource_new,
                    resource_new.source_language)
                if urlinfo.source_file_url:
                    try:
                        urlinfo.update_source_file(fake=True)
                    except Exception, e:
                        url_form._errors['source_file_url'] = _("The URL you provided"
                            " doesn't link to a valid file.")
                        return render_to_response('resources/resource_form.html', {
                            'resource_form': resource_form,
                            'url_form': url_form,
                            'resource': resource,
                        }, context_instance=RequestContext(request))
                    # If we got a URL, save the model instance
                    urlinfo.save()
                else:
                    if urlinfo.auto_update:
                        url_form._errors['source_file_url'] = _("You have checked"
                            " the auto update checkbox but you haven't provided a"
                            " valid url.")
                        return render_to_response('resources/resource_form.html', {
                            'resource_form': resource_form,
                            'url_form': url_form,
                            'resource': resource,
                        }, context_instance=RequestContext(request))
                    else:
                        if urlinfo.id:
                            urlinfo.delete()

                post_resource_save.send(sender=None, instance=resource_new,
                    created=False, user=request.user)

                return HttpResponseRedirect(reverse('resource_detail',
                    args=[resource.project.slug, resource.slug]))
            except FormatsBackendError, e:
                resource_form._errors['sourcefile'] = ErrorList([unicode(e), ])
Exemplo n.º 7
0
def resource_edit(request, project_slug, resource_slug):
    """
    Edit the metadata of  a Translation Resource in a specific project.
    """
    resource = get_object_or_404(Resource,
                                 project__slug=project_slug,
                                 slug=resource_slug)
    try:
        urlinfo = URLInfo.objects.get(resource=resource)
    except URLInfo.DoesNotExist:
        urlinfo = None

    if request.method == 'POST':
        resource_form = ResourceForm(request.POST,
                                     request.FILES,
                                     instance=resource)
        if urlinfo:
            url_form = URLInfoForm(
                request.POST,
                instance=urlinfo,
            )
        else:
            url_form = URLInfoForm(request.POST, )
        if resource_form.is_valid() and url_form.is_valid():
            try:
                resource = resource_form.save(commit=False)
                if resource_form.cleaned_data['sourcefile'] is not None:
                    method = resource.i18n_method
                    content = content_from_uploaded_file({
                        0:
                        resource_form.cleaned_data['sourcefile'],
                    })
                    filename = resource_form.cleaned_data['sourcefile'].name
                    save_source_file(resource, request.user, content, method,
                                     filename)

                urlinfo = url_form.save(commit=False)
                resource_new = resource_form.save()
                resource_new.save()
                urlinfo.resource = resource_new
                invalidate_object_templates(resource_new,
                                            resource_new.source_language)
                if urlinfo.source_file_url:
                    try:
                        urlinfo.update_source_file(fake=True)
                    except Exception, e:
                        url_form._errors['source_file_url'] = _(
                            "The URL you provided"
                            " doesn't link to a valid file.")
                        return render_to_response(
                            'resources/resource_form.html', {
                                'resource_form': resource_form,
                                'url_form': url_form,
                                'resource': resource,
                            },
                            context_instance=RequestContext(request))
                    # If we got a URL, save the model instance
                    urlinfo.save()
                else:
                    if urlinfo.auto_update:
                        url_form._errors['source_file_url'] = _(
                            "You have checked"
                            " the auto update checkbox but you haven't provided a"
                            " valid url.")
                        return render_to_response(
                            'resources/resource_form.html', {
                                'resource_form': resource_form,
                                'url_form': url_form,
                                'resource': resource,
                            },
                            context_instance=RequestContext(request))
                    else:
                        if urlinfo.id:
                            urlinfo.delete()

                send_notices_for_resource_edited.delay(resource_new,
                                                       request.user)

                return HttpResponseRedirect(
                    reverse('resource_detail',
                            args=[resource.project.slug, resource.slug]))
            except FormatsBackendError, e:
                resource_form._errors['sourcefile'] = ErrorList([
                    unicode(e),
                ])
Exemplo n.º 8
0
        Returns:
            The content of the string/file.
        """
        if 'application/json' in request.content_type:
            try:
                return data['content']
            except KeyError, e:
                msg = "No content provided"
                logger.warning(msg)
                raise NoContentError(msg)
        elif 'multipart/form-data' in request.content_type:
            if not request.FILES:
                msg = "No file has been uploaded."
                logger.warning(msg)
                raise NoContentError(msg)
            return content_from_uploaded_file(request.FILES)
        else:
            msg = "No content or file found"
            logger.warning(msg)
            raise NoContentError(msg)

    def _get_filename(self, request, data):
        """Get the filename of the uploaded file.

        Returns:
            The filename or None, if the request used json.
        """
        if 'application/json' in request.content_type:
            return None
        elif 'multipart/form-data' in request.content_type:
            if not request.FILES: