Fixes
[redakcja.git] / src / documents / 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 .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         print(slug)
18         return BytesIO(Book.objects.get(catalogue_book_id=slug
19                     ).materialize(publishable=self.publishable
20                     ).encode('utf-8'))
21
22
23 def serve_file(file_path, name, mime_type):
24     def read_chunks(f, size=8192):
25         chunk = f.read(size)
26         while chunk:
27             yield chunk
28             chunk = f.read(size)
29
30     response = HttpResponse(content_type=mime_type)
31     response['Content-Disposition'] = 'attachment; filename=%s' % name
32     with open(file_path, 'rb') as f:
33         for chunk in read_chunks(f):
34             response.write(chunk)
35     return response