예제 #1
0
def download_media():
    id = request.values["id"]
    uid = uuid.UUID(id)

    try:  # Track -> direct download
        rv = Track[uid]
        return send_file(rv.path, mimetype=rv.mimetype, conditional=True)
    except ObjectNotFound:
        pass

    try:  # Folder -> stream zipped tracks, non recursive
        rv = Folder[uid]
    except ObjectNotFound:
        try:  # Album -> stream zipped tracks
            rv = Album[uid]
        except ObjectNotFound:
            raise NotFound("Track, Folder or Album")

    z = ZipFile(compression=ZIP_DEFLATED)
    for track in rv.tracks:
        z.write(track.path, os.path.basename(track.path))
    resp = Response(z, mimetype="application/zip")
    resp.headers["Content-Disposition"] = "attachment; filename={}.zip".format(
        rv.name)
    return resp
예제 #2
0
def stream_generator(descriptor_entry):
    rpipe, wpipe = os.pipe()
    pid = os.fork()
    if not pid:
        os.close(rpipe)
        zs = ZipFile(mode='w', compression=ZIP_DEFLATED)
        shrink_part = getattr(descriptor_entry.parent, 'relative', '')
        for fname in recursive_list(descriptor_entry):
            zip_path = (shrink(fname.relative, shrink_part)
                        if shrink_part != '.' else fname.relative)
            zs.write(fname.absolute, zip_path)
        for chunk in zs:
            try:
                _ = os.write(wpipe, chunk)
            except (BrokenPipeError, IOError):
                break
        os.close(wpipe)
        return
    os.close(wpipe)
    try:
        while True:
            r, _, _ = select.select([rpipe], [], [], 15)
            if not r:
                break
            chunk = os.read(rpipe, 4096)
            if not chunk:
                break
            yield chunk
    finally:
        # f**k the zombies!
        os.close(rpipe)
        os.wait()
예제 #3
0
    def generateChunks(path):
        stream = ZipFile(mode="w", compression=ZIP_DEFLATED)

        for item in path.glob('*'):
            if not item.exists() or item.is_dir():
                continue
            try:
                stream.write_iter((item.name.split('/')[-1]).lstrip("/"),
                                  generateFileChunks(item))
            except:
                continue

            for chunk in stream.next_file():
                yield chunk

        for chunk in stream:
            yield chunk
예제 #4
0
 def generate_file(self, out_file):
     """Zip all of the communications and files"""
     with ZipFile(mode='w', compression=ZIP_DEFLATED,
                  allowZip64=True) as zip_file:
         for i, comm in enumerate(self.foia.communications.all()):
             file_name = '{:03d}_{}_comm.txt'.format(i, comm.datetime)
             zip_file.writestr(file_name, comm.communication.encode('utf8'))
             for ffile in comm.files.all():
                 zip_file.write_iter(
                     ffile.name(),
                     # read in 5MB chunks at a time
                     read_in_chunks(ffile.ffile, size=5 * 1024 * 1024))
         for data in zip_file:
             out_file.write(data)
예제 #5
0
def download_media():
    id = request.values["id"]

    try:
        uid = get_entity_id(Track, id)
    except GenericError:
        uid = None
    try:
        fid = get_entity_id(Folder, id)
    except GenericError:
        fid = None

    if uid is None and fid is None:
        raise GenericError("Invalid ID")

    if uid is not None:
        try:
            rv = Track[uid]
            return send_file(rv.path, mimetype=rv.mimetype, conditional=True)
        except ObjectNotFound:
            try:  # Album -> stream zipped tracks
                rv = Album[uid]
            except ObjectNotFound:
                raise NotFound("Track or Album")
    else:
        try:  # Folder -> stream zipped tracks, non recursive
            rv = Folder[fid]
        except ObjectNotFound:
            raise NotFound("Folder")

    z = ZipFile(compression=ZIP_DEFLATED)
    for track in rv.tracks:
        z.write(track.path, os.path.basename(track.path))
    resp = Response(z, mimetype="application/zip")
    resp.headers["Content-Disposition"] = "attachment; filename={}.zip".format(
        rv.name)
    return resp
예제 #6
0
파일: media.py 프로젝트: spl0k/supysonic
def download_media():
    id = request.values['id']
    uid = uuid.UUID(id)

    try: # Track -> direct download
        rv = Track[uid]
        return send_file(rv.path, mimetype = rv.mimetype, conditional=True)
    except ObjectNotFound:
        pass

    try: # Folder -> stream zipped tracks, non recursive
        rv = Folder[uid]
    except ObjectNotFound:
        try: # Album -> stream zipped tracks
            rv = Album[uid]
        except ObjectNotFound:
            raise NotFound('Track, Folder or Album')

    z = ZipFile(compression = ZIP_DEFLATED)
    for track in rv.tracks:
        z.write(track.path, os.path.basename(track.path))
    resp = Response(z, mimetype = 'application/zip')
    resp.headers['Content-Disposition'] = 'attachment; filename={}.zip'.format(rv.name)
    return resp
예제 #7
0
파일: views.py 프로젝트: guydou/s3zipper
def zipball(request, token):
    zip_content = redis_client.get("zip:%s" % (token))
    if not(zip_content):
        return HttpResponseBadRequest()
    zip_content = json.loads(zip_content.decode('utf-8'))
    zip_filename = zip_content['zip_filename']
    z = ZipFile(mode='w', compression=ZIP_DEFLATED)
    for file_def in zip_content['files']:
        filepath = file_def.get("path", None)
        file_content = file_def.get("content", None)
        filename = file_def.get("filename", None)
        backend = file_def.get("backend", None)
        if filepath:
            storage = get_storage_class(backend)()
            f = storage.open(filepath, 'r')
            z.write_iter(filename, read_in_chunks(f))
        elif file_content:
            z.writestr(filename, file_content.encode("utf-8"))
    response = StreamingHttpResponse(z, content_type='application/zip')
    response['Content-Disposition'] = 'attachment; filename={}'.format(zip_filename)
    return response
예제 #8
0
def create_zip_stream(bucket, file_map):
    zf = ZipFile()
    for s3_key, file_path in file_map.items():
        write_file_to_zipfile(zf, f's3://{bucket}/{s3_key}', file_path)
    return zf