6 from datetime import datetime
7 from django.conf import settings
8 from django.db import models
9 from django.utils.timezone import now
10 from librarian.cover import make_cover
11 from librarian.builders import EpubBuilder, MobiBuilder
12 from .publishers.legimi import Legimi
13 from .publishers.woblink import Woblink
16 class Package(models.Model):
17 created_at = models.DateTimeField(auto_now_add=True)
18 placed_at = models.DateTimeField(null=True, blank=True)
19 finished_at = models.DateTimeField(null=True, blank=True)
20 definition_json = models.TextField(blank=True)
21 books = models.ManyToManyField('documents.Book')
22 status_json = models.TextField(blank=True)
23 logo = models.FileField(blank=True, upload_to='depot/logo')
24 file = models.FileField(blank=True, upload_to='depot/package/')
26 def save(self, *args, **kwargs):
28 self.set_status(self.get_status())
33 self.set_definition(self.get_definition())
37 super().save(*args, **kwargs)
40 return json.loads(self.status_json)
42 def set_status(self, status):
43 self.status_json = json.dumps(status, indent=4, ensure_ascii=False)
45 def get_definition(self):
46 return json.loads(self.definition_json)
48 def set_definition(self, definition):
49 self.definition_json = json.dumps(definition, indent=4, ensure_ascii=False)
52 f = tempfile.NamedTemporaryFile(prefix='depot-', suffix='.zip', mode='wb', delete=False)
53 book_count = self.books.all().count()
54 with zipfile.ZipFile(f, 'w') as z:
55 for i, book in enumerate(self.books.all()):
56 print(f'{i}/{book_count} {book.slug}')
57 self.build_for(book, z)
59 with open(f.name, 'rb') as ff:
60 self.file.save('package-{}.zip'.format(datetime.now().isoformat(timespec='seconds')), ff)
63 def build_for(self, book, z):
64 wldoc2 = book.wldocument(librarian2=True)
65 slug = wldoc2.meta.url.slug
66 for item in self.get_definition():
67 wldoc = book.wldocument()
68 wldoc2 = book.wldocument(librarian2=True)
69 base_url = 'file://' + book.gallery_path() + '/'
73 if item['type'] == 'cover':
76 kwargs['cover_logo'] = self.logo.path
77 for k in 'format', 'width', 'height', 'cover_class':
80 cover = make_cover(wldoc.book_info, **kwargs)
81 output = cover.output_file()
84 elif item['type'] == 'pdf':
86 if 'cover_class' in item:
87 cover_kwargs['cover_class'] = item['cover_class']
89 cover_kwargs['cover_logo'] = self.logo.path
90 cover = lambda *args, **kwargs: make_cover(*args, **kwargs, **cover_kwargs)
91 output = wldoc.as_pdf(cover=cover, base_url=base_url)
93 elif item['type'] == 'epub':
95 if 'cover_class' in item:
96 cover_kwargs['cover_class'] = item['cover_class']
98 cover_kwargs['cover_logo'] = self.logo.path
99 cover = lambda *args, **kwargs: make_cover(*args, **kwargs, **cover_kwargs)
101 output = EpubBuilder(
104 fundraising=item.get('fundraising', []),
107 elif item['type'] == 'mobi':
108 output = MobiBuilder(
111 fundraising=item.get('fundraising', []),
114 fname = f'{slug}/{slug}.'
116 fname += item['slug'] + '.'
125 class ShopBookPublish(models.Model):
126 book = models.ForeignKey('documents.Book', models.CASCADE)
127 user = models.ForeignKey(settings.AUTH_USER_MODEL, models.SET_NULL, null=True)
128 shop = models.ForeignKey('Shop', models.SET_NULL, null=True)
129 created_at = models.DateTimeField()
130 started_at = models.DateTimeField(null=True, blank=True)
131 finished_at = models.DateTimeField(null=True, blank=True)
132 status = models.PositiveSmallIntegerField(choices=[
138 error = models.TextField(blank=True)
141 def create_for(cls, book, user, shop):
142 book.assert_publishable()
143 changes = book.get_current_changes(publishable=True)
144 me = cls.objects.create(book=book, user=user, shop=shop, created_at=now())
145 for change in changes:
146 me.shopchunkpublish_set.create(change=change)
151 self.started_at = now()
152 self.save(update_fields=['status', 'started_at'])
156 self.shopchunkpublish_set.order_by('change__chunk__number')
159 self.shop.publish(self.book, changes=changes)
163 self.error = traceback.format_exc()
167 self.finished_at = now()
168 self.save(update_fields=['status', 'finished_at', 'error'])
171 class ShopChunkPublish(models.Model):
172 book_publish = models.ForeignKey(ShopBookPublish, models.CASCADE)
173 change = models.ForeignKey('documents.ChunkChange', models.CASCADE)
176 class Shop(models.Model):
177 name = models.CharField(max_length=255)
178 shop = models.CharField(max_length=32, choices=[
179 ('legimi', 'Legimi'),
180 ('woblink', 'Woblink'),
182 username = models.CharField(max_length=255)
183 password = models.CharField(max_length=255)
184 publisher_handle = models.CharField(max_length=255, blank=True)
185 description_add = models.TextField(blank=True)
191 return [t.text for t in self.mediainserttext_set.all()]
193 def get_price(self, words, pages):
194 price_obj = self.pricelevel_set.exclude(
198 ).order_by('-price').first()
199 if price_obj is None:
201 return price_obj.price
203 def get_publisher(self):
204 if self.shop == 'legimi':
206 elif self.shop == 'woblink':
208 return pub_class(self.username, self.password, self.publisher_handle)
210 def publish(self, book, changes):
211 self.get_publisher().send_book(
212 self, book, changes=changes,
215 def can_publish(self, book):
216 return self.get_publisher().can_publish(self, book)
218 def get_last(self, book):
219 return self.shopbookpublish_set.filter(book=book).order_by('-created_at').first()
222 class PriceLevel(models.Model):
223 shop = models.ForeignKey(Shop, models.CASCADE)
224 min_pages = models.IntegerField(null=True, blank=True)
225 min_words = models.IntegerField(null=True, blank=True)
226 price = models.IntegerField()
229 ordering = ('price',)
232 class MediaInsertText(models.Model):
233 shop = models.ForeignKey(Shop, models.CASCADE)
234 ordering = models.IntegerField()
235 text = models.TextField()
238 ordering = ('ordering',)