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
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/')
21 def save(self, *args, **kwargs):
23 self.set_status(self.get_status())
28 self.set_definition(self.get_definition())
32 super().save(*args, **kwargs)
35 return json.loads(self.status_json)
37 def set_status(self, status):
38 self.status_json = json.dumps(status, indent=4)
40 def get_definition(self):
41 return json.loads(self.definition_json)
43 def set_definition(self, definition):
44 self.definition_json = json.dumps(definition, indent=4)
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)
52 with open(f.name, 'rb') as ff:
53 self.file.save('package-{}.zip'.format(datetime.now().isoformat(timespec='seconds')), ff)
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() + '/'
66 if item['type'] == 'cover':
69 kwargs['cover_logo'] = self.logo.path
70 for k in 'format', 'width', 'height', 'cover_class':
73 cover = make_cover(wldoc.book_info, **kwargs)
74 output = cover.output_file()
77 elif item['type'] == 'pdf':
79 if 'cover_class' in item:
80 cover_kwargs['cover_class'] = item['cover_class']
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)
86 elif item['type'] == 'epub':
88 if 'cover_class' in item:
89 cover_kwargs['cover_class'] = item['cover_class']
91 cover_kwargs['cover_logo'] = self.logo.path
92 cover = lambda *args, **kwargs: make_cover(*args, **kwargs, **cover_kwargs)
100 elif item['type'] == 'mobi':
101 output = MobiBuilder(
106 fname = f'{slug}/{slug}.{ext}'