1 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
7 from django.apps import apps
8 from django.conf import settings
9 from django.core.files import File
10 from django.db import models
11 from django.db.models.fields.files import FieldFile
12 from django.utils.deconstruct import deconstructible
13 from catalogue.constants import LANGUAGES_3TO2
14 from catalogue.utils import absolute_url, remove_zip, truncate_html_words, gallery_path, gallery_url
15 from waiter.utils import clear_cache
17 ETAG_SCHEDULED_SUFFIX = '-scheduled'
18 EBOOK_BUILD_PRIORITY = 0
19 EBOOK_REBUILD_PRIORITY = 9
23 class UploadToPath(object):
24 def __init__(self, path):
27 def __call__(self, instance, filename):
28 return self.path % instance.slug
30 def __eq__(self, other):
31 return isinstance(other, type(self)) and other.path == self.path
34 class EbookFieldFile(FieldFile):
35 """Represents contents of an ebook file field."""
38 """Build the ebook immediately."""
39 etag = self.field.get_current_etag()
40 self.field.build(self)
41 self.update_etag(etag)
42 self.instance.clear_cache()
44 def build_delay(self, priority=EBOOK_BUILD_PRIORITY):
45 """Builds the ebook in a delayed task."""
46 from .tasks import build_field
49 "".join([self.field.get_current_etag(), ETAG_SCHEDULED_SUFFIX])
51 return build_field.apply_async(
52 [self.instance.pk, self.field.attname],
56 def set_readable(self, readable):
58 permissions = 0o644 if readable else 0o600
59 os.chmod(self.path, permissions)
61 def update_etag(self, etag):
62 setattr(self.instance, self.field.etag_field_name, etag)
64 self.instance.save(update_fields=[self.field.etag_field_name])
67 class EbookField(models.FileField):
68 """Represents an ebook file field, attachable to a model."""
69 attr_class = EbookFieldFile
72 librarian2_api = False
75 def __init__(self, verbose_name=None, with_etag=True, etag_field_name=None, **kwargs):
76 kwargs.setdefault('verbose_name', verbose_name)
77 self.with_etag = with_etag
78 self.etag_field_name = etag_field_name
79 kwargs.setdefault('max_length', 255)
80 kwargs.setdefault('blank', True)
81 kwargs.setdefault('default', '')
82 kwargs.setdefault('upload_to', self.get_upload_to(self.ext))
84 super().__init__(**kwargs)
86 def deconstruct(self):
87 name, path, args, kwargs = super().deconstruct()
88 if kwargs.get('max_length') == 255:
89 del kwargs['max_length']
90 if kwargs.get('blank') is True:
92 if kwargs.get('default') == '':
94 if self.get_upload_to(self.ext) == kwargs.get('upload_to'):
95 del kwargs['upload_to']
96 # with_etag creates a second field, which then deconstructs to manage
97 # its own migrations. So for migrations, etag_field_name is explicitly
98 # set to avoid double creation of the etag field.
100 kwargs['etag_field_name'] = self.etag_field_name
102 kwargs['with_etag'] = self.with_etag
104 return name, path, args, kwargs
107 def get_upload_to(cls, directory):
108 directory = getattr(cls, 'directory', cls.ext)
109 upload_template = f'book/{directory}/%s.{cls.ext}'
110 return UploadToPath(upload_template)
112 def contribute_to_class(self, cls, name):
113 super(EbookField, self).contribute_to_class(cls, name)
115 if self.with_etag and not self.etag_field_name:
116 self.etag_field_name = f'{name}_etag'
117 self.etag_field = models.CharField(max_length=255, editable=False, default='', db_index=True)
118 self.etag_field.contribute_to_class(cls, f'{name}_etag')
120 def has(model_instance):
121 return bool(getattr(model_instance, self.attname, None))
123 has.__name__ = str("has_%s" % self.attname)
124 has.short_description = self.name
127 setattr(cls, 'has_%s' % self.attname, has)
129 def get_current_etag(self):
130 MediaInsertSet = apps.get_model('annoy', 'MediaInsertSet')
131 librarian_version = pkg_resources.get_distribution("librarian").version
132 etag = librarian_version
133 mis = MediaInsertSet.get_for_format(self.ext)
135 etag += '_' + mis.etag
138 def find_stale(self, limit):
139 """Find some books where this format is stale."""
140 # If there is not ETag field, bail. That's true for xml file field.
141 if not self.with_etag:
144 etag = self.get_current_etag()
146 queryset = self.model.objects.all()
147 if not self.for_parents:
148 queryset = queryset.filter(children=None)
150 queryset = queryset.exclude(**{
151 f'{self.etag_field_name}__in': [
152 etag, f'{etag}{ETAG_SCHEDULED_SUFFIX}'
156 queryset = queryset.order_by('?')[:limit]
160 def find_all_stale(cls, model, limit):
161 """Schedules all stale ebooks of all formats to rebuild."""
163 for field in model._meta.fields:
164 if isinstance(field, cls):
165 for instance in field.find_stale(limit):
170 random.shuffle(found)
171 found = found[:limit]
175 def transform(wldoc):
176 """Transforms an librarian.WLDocument into an librarian.OutputFile.
178 raise NotImplemented()
180 def set_file_permissions(self, fieldfile):
181 if fieldfile.instance.preview:
182 fieldfile.set_readable(False)
184 def build(self, fieldfile):
185 book = fieldfile.instance
186 out = self.transform(
187 book.wldocument2() if self.librarian2_api else book.wldocument(),
189 with open(out.get_filename(), 'rb') as f:
190 fieldfile.save(None, File(f), save=False)
191 self.set_file_permissions(fieldfile)
192 if book.pk is not None:
193 book.save(update_fields=[self.attname])
198 class XmlField(EbookField):
201 def build(self, fieldfile):
205 class TxtField(EbookField):
210 def transform(wldoc):
211 return wldoc.as_text()
214 class Fb2Field(EbookField):
217 ZIP = 'wolnelektury_pl_fb2'
220 def transform(wldoc):
221 return wldoc.as_fb2()
224 class PdfField(EbookField):
226 ZIP = 'wolnelektury_pl_pdf'
229 def transform(wldoc):
231 morefloats=settings.LIBRARIAN_PDF_MOREFLOATS, cover=True,
232 base_url=absolute_url(gallery_url(wldoc.book_info.url.slug)), customizations=['notoc'])
234 def build(self, fieldfile):
235 super().build(fieldfile)
236 clear_cache(fieldfile.instance.slug)
239 class EpubField(EbookField):
241 librarian2_api = True
242 ZIP = 'wolnelektury_pl_epub'
245 def transform(wldoc):
246 from librarian.builders import EpubBuilder
247 MediaInsertSet = apps.get_model('annoy', 'MediaInsertSet')
249 base_url='file://' + os.path.abspath(gallery_path(wldoc.meta.url.slug)) + '/',
250 fundraising=MediaInsertSet.get_texts_for('epub')
254 class MobiField(EbookField):
256 librarian2_api = True
257 ZIP = 'wolnelektury_pl_mobi'
260 def transform(wldoc):
261 from librarian.builders import MobiBuilder
262 MediaInsertSet = apps.get_model('annoy', 'MediaInsertSet')
264 base_url='file://' + os.path.abspath(gallery_path(wldoc.meta.url.slug)) + '/',
265 fundraising=MediaInsertSet.get_texts_for('mobi')
269 class HtmlField(EbookField):
273 def build(self, fieldfile):
274 from django.core.files.base import ContentFile
275 from slugify import slugify
276 from sortify import sortify
277 from librarian import html
278 from catalogue.models import Fragment, Tag
280 book = fieldfile.instance
282 html_output = self.transform(book.wldocument(parse_dublincore=False))
284 # Delete old fragments, create from scratch if necessary.
285 book.fragments.all().delete()
288 meta_tags = list(book.tags.filter(
289 category__in=('author', 'epoch', 'genre', 'kind')))
292 lang = LANGUAGES_3TO2.get(lang, lang)
293 if lang not in [ln[0] for ln in settings.LANGUAGES]:
296 fieldfile.save(None, ContentFile(html_output.get_bytes()), save=False)
297 self.set_file_permissions(fieldfile)
298 type(book).objects.filter(pk=book.pk).update(**{
299 fieldfile.field.attname: fieldfile
303 closed_fragments, open_fragments = html.extract_fragments(fieldfile.path)
304 for fragment in closed_fragments.values():
306 theme_names = [s.strip() for s in fragment.themes.split(',')]
307 except AttributeError:
310 for theme_name in theme_names:
313 if lang == settings.LANGUAGE_CODE:
314 # Allow creating themes if book in default language.
315 tag, created = Tag.objects.get_or_create(
316 slug=slugify(theme_name),
320 tag.name = theme_name
321 setattr(tag, "name_%s" % lang, theme_name)
322 tag.sort_key = sortify(theme_name.lower())
326 elif lang is not None:
327 # Don't create unknown themes in non-default languages.
329 tag = Tag.objects.get(
331 **{"name_%s" % lang: theme_name}
333 except Tag.DoesNotExist:
340 text = fragment.to_string()
341 short_text = truncate_html_words(text, 15)
342 if text == short_text:
344 new_fragment = Fragment.objects.create(
348 short_text=short_text
352 new_fragment.tags = set(meta_tags + themes)
354 if not theme.for_books:
355 theme.for_books = True
357 book.html_built.send(sender=type(self), instance=book)
362 def transform(wldoc):
363 # ugly, but we can't use wldoc.book_info here
364 from librarian import DCNS
365 url_elem = wldoc.edoc.getroot().find('.//' + DCNS('identifier.url'))
370 slug = url_elem.text.rstrip('/').rsplit('/', 1)[1]
371 gal_url = gallery_url(slug=slug)
372 gal_path = gallery_path(slug=slug)
373 return wldoc.as_html(gallery_path=gal_path, gallery_url=gal_url, base_url=absolute_url(gal_url))
376 class CoverField(EbookField):
381 def transform(wldoc):
382 return wldoc.as_cover()
384 def set_file_permissions(self, fieldfile):
388 class CoverCleanField(CoverField):
389 directory = 'cover_clean'
392 def transform(wldoc):
393 from librarian.covers.marquise import MarquiseCover
394 return MarquiseCover(wldoc.book_info, width=360).output_file()
397 class CoverThumbField(CoverField):
398 directory = 'cover_thumb'
401 def transform(wldoc):
402 from librarian.cover import WLCover
403 return WLCover(wldoc.book_info, height=193).output_file()
406 class CoverApiThumbField(CoverField):
407 directory = 'cover_api_thumb'
410 def transform(wldoc):
411 from librarian.cover import WLNoBoxCover
412 return WLNoBoxCover(wldoc.book_info, height=500).output_file()
415 class SimpleCoverField(CoverField):
416 directory = 'cover_simple'
419 def transform(wldoc):
420 from librarian.cover import WLNoBoxCover
421 return WLNoBoxCover(wldoc.book_info, height=1000).output_file()
424 class CoverEbookpointField(CoverField):
425 directory = 'cover_ebookpoint'
428 def transform(wldoc):
429 from librarian.cover import EbookpointCover
430 return EbookpointCover(wldoc.book_info).output_file()