Ejemplo n.º 1
0
    def get(self, request, *args, **kwargs):
        temp_file = ContentFile(b(""), name=self.tarfile_name)
        with tarfile.TarFile(fileobj=temp_file, mode='w', debug=3) as tar_file:
            files = self.get_files()
            for file_ in files:
                file_name = file_.name
                try:
                    data = file_.read()
                except UnicodeDecodeError:
                    pass
                file_.seek(0, os.SEEK_SET)
                size = len(data)
                try:
                    if isinstance(data, bytes):
                        lol = BytesIO(data)
                    else:
                        lol = BytesIO(data.encode())
                except UnicodeDecodeError:
                    pass
                try:
                    info = tar_file.gettarinfo(fileobj=file_)
                except UnsupportedOperation:
                    info = tarfile.TarInfo(name=file_name)
                info.size = size
                tar_file.addfile(tarinfo=info, fileobj=lol)
        file_size = temp_file.tell()
        temp_file.seek(0)

        response = HttpResponse(temp_file, content_type='application/x-tar')
        response['Content-Disposition'] = 'attachment; filename=%s' % self.tarfile_name
        response['Content-Length'] = file_size
        return response
Ejemplo n.º 2
0
    def get(self, request, *args, **kwargs):
        temp_file = ContentFile(b(""), name=self.tarfile_name)
        with tarfile.TarFile(fileobj=temp_file, mode='w', debug=3) as tar_file:
            files = self.get_files()
            for file_ in files:
                file_name = file_.name
                try:
                    data = file_.read()
                except UnicodeDecodeError:
                    pass
                file_.seek(0, os.SEEK_SET)
                size = len(data)
                try:
                    if isinstance(data, bytes):
                        lol = BytesIO(data)
                    else:
                        lol = BytesIO(data.encode())
                except UnicodeDecodeError:
                    pass
                try:
                    info = tar_file.gettarinfo(fileobj=file_)
                except UnsupportedOperation:
                    info = tarfile.TarInfo(name=file_name)
                info.size = size
                tar_file.addfile(tarinfo=info, fileobj=lol)
        file_size = temp_file.tell()
        temp_file.seek(0)

        response = HttpResponse(temp_file, content_type='application/x-tar')
        response[
            'Content-Disposition'] = 'attachment; filename=%s' % self.tarfile_name
        response['Content-Length'] = file_size
        return response
Ejemplo n.º 3
0
def serve_tracks_as_zipfile(request, pk):
    """
    Create a Zip archive with all the Tracks in a Project.
    The Tracks will be organized in folders according to Songs and Groups.
    Based on https://github.com/thibault/django-zipview/
    """
    project = get_object_or_404(Project, pk=pk)
    timestamp = now().astimezone(TZ).strftime("%Y-%m-%d %H-%M-%S")
    name = "%s %s.zip" % (to_folder_name(project.title), timestamp)
    temp_file = ContentFile(b(""), name=name)

    with ZipFile(temp_file, mode="w", compression=ZIP_DEFLATED) as zip_file:
        for track in Track.objects.filter(group__song__project=project):
            path = "{}/{}/{}".format(to_folder_name(track.group.song.title),
                                     to_folder_name(track.group.title),
                                     track.file.name.split("/")[-1])
            zip_file.writestr(path, track.file.read())

    file_size = temp_file.tell()
    temp_file.seek(0)

    response = HttpResponse(temp_file, content_type="application/zip")
    response["Content-Disposition"] = "attachment; filename=\"%s\"" % name
    response["Content-Length"] = file_size
    return response
Ejemplo n.º 4
0
def downloadFolderAsTar(path):
    temp_file = ContentFile(b(""), name=os.path.basename(path) + '.tar')
    with tarfile.TarFile(fileobj=temp_file, mode='w', debug=3) as tar_file:
        tar_file.add(path, arcname=os.path.basename(path))
    file_size = temp_file.tell()
    temp_file.seek(0)

    response = HttpResponse(temp_file, content_type='application/x-tar')
    response[
        'Content-Disposition'] = 'attachment; filename=\"' + os.path.basename(
            path) + '.tar\"'
    response['Content-Length'] = file_size
    return response
Ejemplo n.º 5
0
    def get(self, request, *args, **kwargs):
        temp_file = ContentFile(b(""), name=self.zipfile_name)
        with zipfile.ZipFile(temp_file,
                             mode='w',
                             compression=zipfile.ZIP_DEFLATED) as zip_file:
            files = self.get_files()
            for file_ in files:
                path = file_.name
                zip_file.writestr(path, file_.read())

        file_size = temp_file.tell()
        temp_file.seek(0)

        response = HttpResponse(temp_file, content_type='application/zip')
        response[
            'Content-Disposition'] = 'attachment; filename=%s' % self.zipfile_name
        response['Content-Length'] = file_size
        return response
Ejemplo n.º 6
0
def resize_image(image: InMemoryUploadedFile,
                 max: int,
                 quality=85) -> InMemoryUploadedFile:
    """ Returns a resized image based on the given maximum size """
    img: Image = Image.open(image)
    if img.size[0] > img.size[1]:
        width_ratio = (max / float(img.size[0]))
        height = int((float(img.size[1]) * float(width_ratio)))
        img = img.resize((max, height), Image.ANTIALIAS)
    else:
        height_ratio = (max / float(img.size[1]))
        width = int((float(img.size[0]) * float(height_ratio)))
        img = img.resize((width, max), Image.ANTIALIAS)
    buffer = BytesIO()
    img.save(fp=buffer, format='PNG', quality=quality)
    resized_image = ContentFile(buffer.getvalue())
    return InMemoryUploadedFile(resized_image, 'ImageField',
                                "%s.png" % image.name, 'image/png',
                                resized_image.tell(), None)
Ejemplo n.º 7
0
def resize_image(image: InMemoryUploadedFile, max: int, quality=85) -> InMemoryUploadedFile:
	""" Returns a resized image based on the given maximum size """
	with Image.open(image) as img:
		width, height = img.size
		# no need to resize if width or height is already less than the max
		if width <= max or height <= max:
			return image
		if width > height:
			width_ratio = max / float(width)
			new_height = int((float(height) * float(width_ratio)))
			img = img.resize((max, new_height), Image.ANTIALIAS)
		else:
			height_ratio = max / float(height)
			new_width = int((float(width) * float(height_ratio)))
			img = img.resize((new_width, max), Image.ANTIALIAS)
		with BytesIO() as buffer:
			img.save(fp=buffer, format="PNG", quality=quality)
			resized_image = ContentFile(buffer.getvalue())
	file_name_without_ext = os.path.splitext(image.name)[0]
	return InMemoryUploadedFile(
		resized_image, "ImageField", "%s.png" % file_name_without_ext, "image/png", resized_image.tell(), None
	)
Ejemplo n.º 8
0
def get_file(request, add_attachment_headers):

    name = request.GET.get('name')
    if 'check1' in request.POST:
        # bf = 64 * 1024
        name = request.POST.get('name')
        # raise ValidationError(request.POST)

        try:
            #     raise ValidationError('Hello')
            #     _file = storage.open(name)
            #     _fin = io.BytesIO(_file)
            #     _fdec = io.BytesIO()
            #     pyAesCrypt.decryptStream(_fin,_fdec,password,bf,len(_fin.getvalue()))
            #     _file=_fcip.getvalue()
            # raise ValidationError(request.POST)
            _file = storage._openlnx(name)
    # _fill = base64.b64decode(_fil)
    # _fin = io.BytesIO(_fill)
    # _fdec = io.BytesIO()
    # pyAesCrypt.decryptStream(_fin,_fdec,password,bf,len(_fin.getvalue()))
    # _file=storage._getme(_fdec.getvalue())
    # raise ValidationError(_file.mimetype)

        except Exception:
            return HttpResponseBadRequest(('Invalid request'))
        response = HttpResponse(FileWrapper(_file),
                                content_type=_file.mimetype)
        response['Content-Length'] = _file.tell()
        if add_attachment_headers:
            response['Content-Disposition'] = \
                'attachment; filename=%(name)s' % {'name': _file.filename}

    else:
        # raise ValidationError(request.POST)

        try:
            password = request.session['key']
            schm = request.session['scm']
        except Exception:
            return redirect('model_files:book.scm')
        # storage.itii()
        # scm = request.session['scm']
    #     raise ValidationError('Hello')
    #     _file = storage.open(name)
    #     _fin = io.BytesIO(_file)
    #     _fdec = io.BytesIO()
    #     pyAesCrypt.decryptStream(_fin,_fdec,password,bf,len(_fin.getvalue()))
    #     _file=_fcip.getvalue()
        try:
            # _fil = storage.open(name,password)[1]
            if schm == "aes":
                _file = storage.open(name, password)
                # raise ValidationError(type(_fil))
                enc = Encryptor(password)
                # raise ValidationError(_gb.open('rb').read())
                plt = enc.decrypt(_file.open('rb').read())
                # raise ValidationError(plt)

                gb1 = ContentFile(plt)
                _file.close()
            elif schm == "des":
                _file = storage.open(name, password)
                # raise ValidationError(type(_fil))
                enc = des("DESCRYPT",
                          CBC,
                          password,
                          pad=None,
                          padmode=PAD_PKCS5)
                plt = enc.decrypt(_file.open('rb').read())
                gb1 = ContentFile(plt)
                _file.close()
            elif schm == 'bf':
                _file = storage.open(name, password)
                enc = blowfish.Cipher(password.encode())

                # iv1 = os.urandom(8)
                # raise ValidationError(iv1)
                iv1 = b"\xf9\x11\xeb\x8a\x871\x98\x89"
                plt = b"".join(enc.decrypt_cfb(_file.open('rb').read(), iv1))
                # raise ValidationError(plt)

                gb1 = ContentFile(plt)
                _file.close()
            # _file.close()
            # raise ValidationError(plt)

        # _file.close()
        # with _file.open('wb') as f:
        #     f.write(plt)
        # _file.open('wb').write(plt)
        # _file.close()
        # raise ValidationError(plt)
        # raise ValidationError(gb.open('rb').read())

    # _fill = base64.b64decode(_fil)
    # _fin = io.BytesIO(_fill)
    # _fdec = io.BytesIO()
    # pyAesCrypt.decryptStream(_fin,_fdec,password,bf,len(_fin.getvalue()))
    # _file=storage._getme(_fdec.getvalue())
    # raise ValidationError(_file.mimetype)

        except Exception:
            return HttpResponseBadRequest(('Invalid request'))

        response = HttpResponse(FileWrapper(gb1), content_type=_file.mimetype)
        # raise ValidationError(plt)

        response['Content-Length'] = gb1.tell()
        if add_attachment_headers:
            response['Content-Disposition'] = \
                'attachment; filename=%(name)s' % {'name': _file.filename}

    return response