+def stream_zip(request, media_format=None, slug=None):
+ book = get_object_or_404(Book, slug=slug)
+ def iterate_audiobooks(book, names):
+ for bm in book.media.filter(type=media_format).order_by('index'):
+ yield (
+ bm.file.path,
+ names + (slugify(bm.part_name),) if bm.part_name else names
+ )
+ for child in book.get_children():
+ yield from iterate_audiobooks(child, names + (slugify(child.title),))
+
+ zs = ZipStream()
+
+ for i, (file_path, names) in enumerate(iterate_audiobooks(book, ())):
+ index = i + 1
+ part_name = '_'.join(names)
+ ext = file_path.rsplit('.', 1)[-1]
+ zip_name = f'{book.slug}_{index:03d}_{part_name}'[:240] + '.' + ext
+ zs.add_path(file_path, zip_name)
+
+ response = StreamingHttpResponse(zs, content_type='application/zip')
+ response['Content-Disposition'] = f'attachment; filename={slug}_{media_format}.zip'
+ return response
+
+