12bd9c2a68e5819379147f1823a5ccb2a94685fb
[redakcja.git] / src / depot / models.py
1 import json
2 import os
3 import tempfile
4 import zipfile
5 from datetime import datetime
6 from django.db import models
7 from librarian.cover import make_cover
8 from librarian.builders import EpubBuilder, MobiBuilder
9
10
11 class Package(models.Model):
12     created_at = models.DateTimeField(auto_now_add=True)
13     placed_at = models.DateTimeField(null=True, blank=True)
14     finished_at = models.DateTimeField(null=True, blank=True)
15     definition_json = models.TextField(blank=True)
16     books = models.ManyToManyField('documents.Book')
17     status_json = models.TextField(blank=True)
18     logo = models.FileField(blank=True, upload_to='depot/logo')
19     file = models.FileField(blank=True, upload_to='depot/package/')
20
21     def save(self, *args, **kwargs):
22         try:
23             self.set_status(self.get_status())
24         except:
25             pass
26         
27         try:
28             self.set_definition(self.get_definition())
29         except:
30             pass
31
32         super().save(*args, **kwargs)
33     
34     def get_status(self):
35         return json.loads(self.status_json)
36
37     def set_status(self, status):
38         self.status_json = json.dumps(status, indent=4)
39
40     def get_definition(self):
41         return json.loads(self.definition_json)
42
43     def set_definition(self, definition):
44         self.definition_json = json.dumps(definition, indent=4)
45
46     def build(self):
47         f = tempfile.NamedTemporaryFile(prefix='depot-', suffix='.zip', mode='wb', delete=False)
48         with zipfile.ZipFile(f, 'w') as z:
49             for book in self.books.all():
50                 self.build_for(book, z)
51         f.close()
52         with open(f.name, 'rb') as ff:
53             self.file.save('package-{}.zip'.format(datetime.now().isoformat(timespec='seconds')), ff)
54         os.unlink(f.name)
55
56     def build_for(self, book, z):
57         wldoc2 = book.wldocument(librarian2=True)
58         slug = wldoc2.meta.url.slug
59         for item in self.get_definition():
60             wldoc = book.wldocument()
61             wldoc2 = book.wldocument(librarian2=True)
62             base_url = 'file://' + book.gallery_path() + '/'
63
64             ext = item['type']
65
66             if item['type'] == 'cover':
67                 kwargs = {}
68                 if self.logo:
69                     kwargs['cover_logo'] = self.logo.path
70                 for k in 'format', 'width', 'height', 'cover_class':
71                     if k in item:
72                         kwargs[k] = item[k]
73                 cover = make_cover(wldoc.book_info, **kwargs)
74                 output = cover.output_file()
75                 ext = cover.ext()
76
77             elif item['type'] == 'pdf':
78                 cover_kwargs = {}
79                 if 'cover_class' in item:
80                     cover_kwargs['cover_class'] = item['cover_class']
81                 if self.logo:
82                     cover_kwargs['cover_logo'] = self.logo.path
83                 cover = lambda *args, **kwargs: make_cover(*args, **kwargs, **cover_kwargs)
84                 output = wldoc.as_pdf(cover=cover, base_url=base_url)
85
86             elif item['type'] == 'epub':
87                 cover_kwargs = {}
88                 if 'cover_class' in item:
89                     cover_kwargs['cover_class'] = item['cover_class']
90                 if self.logo:
91                     cover_kwargs['cover_logo'] = self.logo.path
92                 cover = lambda *args, **kwargs: make_cover(*args, **kwargs, **cover_kwargs)
93
94                 output = EpubBuilder(
95                     cover=cover,
96                     base_url=base_url,
97 #                    fundraising=[]
98                 ).build(wldoc2)
99
100             elif item['type'] == 'mobi':
101                 output = MobiBuilder(
102                     cover=cover,
103                     base_url=base_url,
104                 ).build(wldoc2)
105
106             fname = f'{slug}/{slug}.{ext}'
107
108             z.writestr(
109                 fname,
110                 output.get_bytes()
111             )