示例#1
0
文件: views.py 项目: Eyremba/ghiro
def new_image(request, case_id):
    """Upload a new image."""
    case = get_object_or_404(Case, pk=case_id)

    # Security check.
    if not request.user.is_superuser and not request.user in case.users.all():
        return render_to_response("error.html",
                                  {"error": "You are not authorized to add image to this."},
                                  context_instance=RequestContext(request))

    if case.state == "C":
        return render_to_response("error.html",
                                  {"error": "You cannot add an image to a closed case."},
                                  context_instance=RequestContext(request))

    if request.method == "POST":
        form = forms.UploadImageForm(request.POST, request.FILES)

        if form.is_valid():
            content_type = get_content_type_from_file(request.FILES["image"].temporary_file_path())

            task = Analysis.add_task(request.FILES["image"].temporary_file_path(), case=case,
                    user=request.user, content_type=content_type,
                    image_id=save_file(file_path=request.FILES["image"].temporary_file_path(),
                              content_type=content_type),
                    thumb_id=create_thumb(request.FILES["image"].temporary_file_path()),
                    file_name=request.FILES["image"].name)

            # Auditing.
            log_activity("I",
                         "Created new analysis %s" % task.file_name,
                         request)
            # Response designed for Plupload component.
            response = HttpResponse('{"jsonrpc": "2.0", "result": null, "id": "id"}', content_type="application/json")
            # Never cache AJAX response.
            response["Expires"] = "Mon, 1 Jan 2000 01:00:00 GMT"
            response["Cache-Control"] = "no-store, no-cache, must-revalidate, post-check=0, pre-check=0"
            response["Pragma"] = "no-cache"
            return response
        else:
            # Deal with a validation error. We are using Plupload which basically is an AJAX component
            # so we have to deal with custom validation errors passing in JSON.
            # Plupload needs a status code 200/OK to get additional data passed from the web server.
            response = HttpResponse(json.dumps({"jsonrpc" : "2.0",
                            "error" : {"code": 88,
                                       "message": " ".join([(" ".join([force_text(i) for i in v])) for k, v in form.errors.items()])},
                            "id" : "id"}),
                content_type="application/json")
            # Never cache AJAX response.
            response["Expires"] = "Mon, 1 Jan 2000 01:00:00 GMT"
            response["Cache-Control"] = "no-store, no-cache, must-revalidate, post-check=0, pre-check=0"
            response["Pragma"] = "no-cache"
            return response
    else:
        # Request is not a POST.
        form = forms.UploadImageForm()

    return render_to_response("analyses/images/new_image.html",
                              {"form": form, "case": case},
                              context_instance=RequestContext(request))
示例#2
0
def new_folder(request, case_id):
    """Load files from a local directory."""
    case = get_object_or_404(Case, pk=case_id)

    # Security check.
    if not(request.user.is_superuser or request.user in case.users.all()):
        return render_to_response("error.html",
                                  {"error": "You are not authorized to add image to this."},
                                  context_instance=RequestContext(request))

    if case.state == "C":
        return render_to_response("error.html",
                                  {"error": "You cannot add an image to a closed case."},
                                  context_instance=RequestContext(request))

    if request.method == "POST":
        form = forms.ImageFolderForm(request.POST)
        if form.is_valid():
            # Check.
            if not os.path.exists(request.POST.get("path")):
                return render_to_response("error.html",
                    {"error": "Folder does not exist."},
                    context_instance=RequestContext(request))
            elif not os.path.isdir(request.POST.get("path")):
                return render_to_response("error.html",
                    {"error": "Folder is not a directory."},
                    context_instance=RequestContext(request))
            # Add all files in directory.
            for file in os.listdir(request.POST.get("path")):
                content_type = get_content_type_from_file(os.path.join(request.POST.get("path"), file))
                # Check if content type is allowed.
                if not check_allowed_content(content_type):
                    # TODO: add some kind of feedback.
                    continue

                task = Analysis()
                task.owner = request.user
                task.case = case
                task.file_name = file
                task.image_id = save_file(file_path=os.path.join(request.POST.get("path"), file),
                                          content_type=content_type)
                task.thumb_id = create_thumb(os.path.join(request.POST.get("path"), file))
                task.save()

                # Auditing.
                log_activity("I",
                             "Created new analysis %s" % task.file_name,
                             request)
            return HttpResponseRedirect(reverse("analyses.views.show_case", args=(case.id, "list")))
    else:
        form = forms.ImageFolderForm()

    return render_to_response("analyses/images/new_folder.html",
                              {"form": form, "case": case},
                              context_instance=RequestContext(request))
示例#3
0
 def clean_image(self):
     image = self.cleaned_data.get("image", False)
     if image:
         # File check.
         if image._size > settings.MAX_FILE_UPLOAD:
             raise ValidationError("Image file too large")
         # Type check.
         file_type = get_content_type_from_file(image.temporary_file_path())
         if not check_allowed_content(file_type):
             raise ValidationError("Image type not supported.")
     else:
         raise ValidationError("Image field is mandatory.")
示例#4
0
 def clean_image(self):
     image = self.cleaned_data.get("image", False)
     if image:
         # File check.
         if image._size > settings.MAX_FILE_UPLOAD:
             raise ValidationError("Image file too large")
         # Type check.
         file_type = get_content_type_from_file(image.temporary_file_path())
         if not check_allowed_content(file_type):
             raise ValidationError("Image type not supported.")
     else:
         raise ValidationError("Image field is mandatory.")
示例#5
0
文件: models.py 项目: Scinawa/ghiro
    def add_task(file_path, file_name=None, case=None, user=None, content_type=None, image_id=None, thumb_id=None):
        """Adds a new task to database.
        @param file_path: file path
        @param file_name: file name
        @param case: case id
        @param user: user id
        @param content_type: file content type
        @param image_id: original image gridfs id
        @param thumb_id: thumbnail gridfs id
        """
        # TODO: re enable with py3 support.
        # assert isinstance(file_path, str)

        # File name.
        if not file_name:
            file_name = os.path.basename(file_path)

        # File type check.
        if not content_type:
            content_type = get_content_type_from_file(file_path)

        # If image is not already stored on gridfs.
        if not image_id:
            image_id = save_file(file_path=file_path, content_type=content_type)

        # If image thumbnail is available.
        if not thumb_id:
            thumb_id = create_thumb(file_path)

        # Check on allowed file type.
        if not check_allowed_content(content_type):
            raise GhiroValidationException("Skipping %s: file type not allowed." % file_name)
        else:
            # Add to analysis queue.
            return Analysis.objects.create(
                owner=user, case=case, file_name=file_name, image_id=image_id, thumb_id=thumb_id
            )
示例#6
0
def new_url(request, case_id):
    """Upload a new image via URL."""
    case = get_object_or_404(Case, pk=case_id)

    # Security check.
    if not request.user.is_superuser and not request.user in case.users.all():
        return render_to_response("error.html",
            {"error": "You are not authorized to add image to this."},
            context_instance=RequestContext(request))

    if case.state == "C":
        return render_to_response("error.html",
            {"error": "You cannot add an image to a closed case."},
            context_instance=RequestContext(request))

    if request.method == "POST":
        form = forms.UrlForm(request.POST)

        if form.is_valid():
            # Download file.
            try:
                url = urllib2.urlopen(request.POST.get("url"), timeout=5)
            except urllib2.URLError as e:
                if hasattr(e, "reason"):
                    return render_to_response("error.html",
                        {"error": "We failed to reach a server, reason: %s" % e.reason},
                        context_instance=RequestContext(request))
                elif hasattr(e, "code"):
                    return render_to_response("error.html",
                        {"error": "The remote server couldn't fulfill the request, HTTP error code %s" % e.code},
                        context_instance=RequestContext(request))

            # Store temp file.
            url_temp = NamedTemporaryFile(delete=True)
            url_temp.write(url.read())
            url_temp.flush()

            # Convert to File object.
            url_file = File(url_temp).name

            # Check content type.
            content_type = get_content_type_from_file(url_file)
            if not check_allowed_content(content_type):
                return render_to_response("error.html",
                    {"error": "File type not supported"},
                    context_instance=RequestContext(request))

            # Create analysis task.
            task = Analysis.add_task(os.path.basename(urlparse.urlparse(request.POST.get("url")).path),
                        case=case, user=request.user, content_type=content_type,
                        image_id=save_file(file_path=url_file, content_type=content_type),
                        thumb_id=create_thumb(url_file))
            # Auditing.
            log_activity("I",
                "Created new analysis %s from URL %s" % (task.file_name, request.POST.get("url")),
                request)
            return HttpResponseRedirect(reverse("analyses.views.show_case", args=(case.id, "list")))
    else:
        # Request is not a POST.
        form = forms.UrlForm()

    return render_to_response("analyses/images/new_url.html",
        {"form": form, "case": case},
        context_instance=RequestContext(request))
示例#7
0
        @param case: case id
        @param user: user id
        @param content_type: file content type
        @param image_id: original image gridfs id
        @param thumb_id: thumbnail gridfs id
        """
        # TODO: re enable with py3 support.
        # assert isinstance(file_path, str)

        # File name.
        if not file_name:
            file_name = os.path.basename(file_path)

        # File type check.
        if not content_type:
            content_type = get_content_type_from_file(file_path)

        # If image is not already stored on gridfs.
        if not image_id:
            image_id = save_file(file_path=file_path,
                                 content_type=content_type)

        # If image thumbnail is available.
        if not thumb_id:
            thumb_id = create_thumb(file_path)

        # Check on allowed file type.
        if not check_allowed_content(content_type):
            raise GhiroValidationException(
                "Skipping %s: file type not allowed." % file_name)
        else:
示例#8
0
        return render_to_response(
            "error.html",
            {"error": "You are not authorized to add image to this."},
            context_instance=RequestContext(request))

    if case.state == "C":
        return render_to_response(
            "error.html",
            {"error": "You cannot add an image to a closed case."},
            context_instance=RequestContext(request))

    if request.method == "POST":
        form = forms.UploadImageForm(request.POST, request.FILES)

        if form.is_valid():
            content_type = get_content_type_from_file(
                request.FILES["image"].temporary_file_path())

            task = Analysis.add_task(
                request.FILES["image"].temporary_file_path(),
                case=case,
                user=request.user,
                content_type=content_type,
                image_id=save_file(
                    file_path=request.FILES["image"].temporary_file_path(),
                    content_type=content_type),
                thumb_id=create_thumb(
                    request.FILES["image"].temporary_file_path()),
                file_name=request.FILES["image"].name)

            # Auditing.
            log_activity("I", "Created new analysis %s" % task.file_name,