Some housekeeping
[redakcja.git] / src / catalogue / ebook_utils.py
1 # This file is part of FNP-Redakcja, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
3 #
4 from io import BytesIO
5 from catalogue.models import Book
6 from librarian import DocProvider
7 from django.http import HttpResponse
8
9
10 class RedakcjaDocProvider(DocProvider):
11     """Used for getting books' children."""
12
13     def __init__(self, publishable):
14         self.publishable = publishable
15
16     def by_slug(self, slug):
17         return BytesIO(Book.objects.get(dc_slug=slug
18                     ).materialize(publishable=self.publishable
19                     ).encode('utf-8'))
20
21
22 def serve_file(file_path, name, mime_type):
23     def read_chunks(f, size=8192):
24         chunk = f.read(size)
25         while chunk:
26             yield chunk
27             chunk = f.read(size)
28
29     response = HttpResponse(content_type=mime_type)
30     response['Content-Disposition'] = 'attachment; filename=%s' % name
31     with open(file_path, 'rb') as f:
32         for chunk in read_chunks(f):
33             response.write(chunk)
34     return response