1 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
5 from django.conf import settings
6 from django.core.files import File
7 from django.core.files.storage import FileSystemStorage
8 from django.db import models
9 from django.db.models.fields.files import FieldFile
10 from catalogue import app_settings
11 from catalogue.constants import LANGUAGES_3TO2, EBOOK_FORMATS_WITH_CHILDREN, EBOOK_FORMATS_WITHOUT_CHILDREN
12 from catalogue.utils import absolute_url, remove_zip, truncate_html_words, gallery_path, gallery_url
13 from celery.task import Task, task
14 from celery.utils.log import get_task_logger
15 from waiter.utils import clear_cache
17 task_logger = get_task_logger(__name__)
19 ETAG_SCHEDULED_SUFFIX = '-scheduled'
20 EBOOK_BUILD_PRIORITY = 0
21 EBOOK_REBUILD_PRIORITY = 9
24 class EbookFieldFile(FieldFile):
25 """Represents contents of an ebook file field."""
28 """Build the ebook immediately."""
29 return self.field.builder.build(self)
31 def build_delay(self, priority=EBOOK_BUILD_PRIORITY):
32 """Builds the ebook in a delayed task."""
34 "".join([self.field.get_current_etag(), ETAG_SCHEDULED_SUFFIX])
36 return self.field.builder.apply_async(
37 [self.instance, self.field.attname],
42 return self.instance.media_url(self.field.attname.split('_')[0])
44 def set_readable(self, readable):
46 permissions = 0o644 if readable else 0o600
47 os.chmod(self.path, permissions)
49 def update_etag(self, etag):
50 setattr(self.instance, self.field.etag_field_name, etag)
52 self.instance.save(update_fields=[self.field.etag_field_name])
55 class EbookField(models.FileField):
56 """Represents an ebook file field, attachable to a model."""
57 attr_class = EbookFieldFile
60 def __init__(self, format_name, *args, **kwargs):
61 super(EbookField, self).__init__(*args, **kwargs)
62 self.format_name = format_name
64 def deconstruct(self):
65 name, path, args, kwargs = super(EbookField, self).deconstruct()
66 args.insert(0, self.format_name)
67 return name, path, args, kwargs
71 """Finds a celery task suitable for the format of the field."""
72 return BuildEbook.for_format(self.format_name)
74 def contribute_to_class(self, cls, name):
75 super(EbookField, self).contribute_to_class(cls, name)
77 self.etag_field_name = f'{name}_etag'
79 def has(model_instance):
80 return bool(getattr(model_instance, self.attname, None))
82 has.__name__ = str("has_%s" % self.attname)
83 has.short_description = self.name
86 self.registry.append(self)
88 setattr(cls, 'has_%s' % self.attname, has)
90 def get_current_etag(self):
92 librarian_version = pkg_resources.get_distribution("librarian").version
93 return librarian_version
95 def schedule_stale(self, queryset=None):
96 """Schedule building this format for all the books where etag is stale."""
97 # If there is not ETag field, bail. That's true for xml file field.
98 if not hasattr(self.model, f'{self.attname}_etag'):
101 etag = self.get_current_etag()
103 queryset = self.model.objects.all()
105 if self.format_name in EBOOK_FORMATS_WITHOUT_CHILDREN + ['html']:
106 queryset = queryset.filter(children=None)
108 queryset = queryset.exclude(**{
109 f'{self.etag_field_name}__in': [
110 etag, f'{etag}{ETAG_SCHEDULED_SUFFIX}'
114 fieldfile = getattr(obj, self.attname)
115 priority = EBOOK_REBUILD_PRIORITY if fieldfile else EBOOK_BUILD_PRIORITY
116 fieldfile.build_delay(priority=priority)
119 def schedule_all_stale(cls):
120 """Schedules all stale ebooks of all formats to rebuild."""
121 for field in cls.registry:
122 field.schedule_stale()
126 class BuildEbook(Task):
127 librarian2_api = False
132 def register(cls, format_name):
133 """A decorator for registering subclasses for particular formats."""
134 def wrapper(builder):
135 cls.formats[format_name] = builder
140 def for_format(cls, format_name):
141 """Returns a celery task suitable for specified format."""
142 return cls.formats.get(format_name, BuildEbookTask)
145 def transform(wldoc, fieldfile):
146 """Transforms an librarian.WLDocument into an librarian.OutputFile.
148 By default, it just calls relevant wldoc.as_??? method.
151 return getattr(wldoc, "as_%s" % fieldfile.field.format_name)()
153 def run(self, obj, field_name):
154 """Just run `build` on FieldFile, can't pass it directly to Celery."""
155 fieldfile = getattr(obj, field_name)
157 # Get etag value before actually building the file.
158 etag = fieldfile.field.get_current_etag()
159 task_logger.info("%s -> %s@%s" % (obj.slug, field_name, etag))
160 ret = self.build(getattr(obj, field_name))
161 fieldfile.update_etag(etag)
165 def set_file_permissions(self, fieldfile):
166 if fieldfile.instance.preview:
167 fieldfile.set_readable(False)
169 def build(self, fieldfile):
170 book = fieldfile.instance
171 out = self.transform(
172 book.wldocument2() if self.librarian2_api else book.wldocument(),
174 fieldfile.save(None, File(open(out.get_filename(), 'rb')), save=False)
175 self.set_file_permissions(fieldfile)
176 if book.pk is not None:
177 book.save(update_fields=[fieldfile.field.attname])
178 if fieldfile.field.format_name in app_settings.FORMAT_ZIPS:
179 remove_zip(app_settings.FORMAT_ZIPS[fieldfile.field.format_name])
180 # Don't decorate BuildEbook, because we want to subclass it.
181 BuildEbookTask = task(BuildEbook, ignore_result=True)
184 @BuildEbook.register('txt')
185 @task(ignore_result=True)
186 class BuildTxt(BuildEbook):
188 def transform(wldoc, fieldfile):
189 return wldoc.as_text()
192 @BuildEbook.register('pdf')
193 @task(ignore_result=True)
194 class BuildPdf(BuildEbook):
196 def transform(wldoc, fieldfile):
198 morefloats=settings.LIBRARIAN_PDF_MOREFLOATS, cover=True,
199 base_url=absolute_url(gallery_url(wldoc.book_info.url.slug)), customizations=['notoc'])
201 def build(self, fieldfile):
202 BuildEbook.build(self, fieldfile)
203 clear_cache(fieldfile.instance.slug)
206 @BuildEbook.register('epub')
207 @task(ignore_result=True)
208 class BuildEpub(BuildEbook):
209 librarian2_api = True
212 def transform(wldoc, fieldfile):
213 from librarian.builders import EpubBuilder
215 base_url='file://' + os.path.abspath(gallery_path(wldoc.meta.url.slug)) + '/',
216 fundraising=settings.EPUB_FUNDRAISING
220 @BuildEbook.register('mobi')
221 @task(ignore_result=True)
222 class BuildMobi(BuildEbook):
224 def transform(wldoc, fieldfile):
225 return wldoc.as_mobi(cover=True, base_url=absolute_url(gallery_url(wldoc.book_info.url.slug)))
228 @BuildEbook.register('html')
229 @task(ignore_result=True)
230 class BuildHtml(BuildEbook):
231 def build(self, fieldfile):
232 from django.core.files.base import ContentFile
233 from slugify import slugify
234 from sortify import sortify
235 from librarian import html
236 from catalogue.models import Fragment, Tag
238 book = fieldfile.instance
240 html_output = self.transform(book.wldocument(parse_dublincore=False), fieldfile)
242 # Delete old fragments, create from scratch if necessary.
243 book.fragments.all().delete()
246 meta_tags = list(book.tags.filter(
247 category__in=('author', 'epoch', 'genre', 'kind')))
250 lang = LANGUAGES_3TO2.get(lang, lang)
251 if lang not in [ln[0] for ln in settings.LANGUAGES]:
254 fieldfile.save(None, ContentFile(html_output.get_bytes()), save=False)
255 self.set_file_permissions(fieldfile)
256 type(book).objects.filter(pk=book.pk).update(**{
257 fieldfile.field.attname: fieldfile
261 closed_fragments, open_fragments = html.extract_fragments(fieldfile.path)
262 for fragment in closed_fragments.values():
264 theme_names = [s.strip() for s in fragment.themes.split(',')]
265 except AttributeError:
268 for theme_name in theme_names:
271 if lang == settings.LANGUAGE_CODE:
272 # Allow creating themes if book in default language.
273 tag, created = Tag.objects.get_or_create(
274 slug=slugify(theme_name),
278 tag.name = theme_name
279 setattr(tag, "name_%s" % lang, theme_name)
280 tag.sort_key = sortify(theme_name.lower())
284 elif lang is not None:
285 # Don't create unknown themes in non-default languages.
287 tag = Tag.objects.get(
289 **{"name_%s" % lang: theme_name}
291 except Tag.DoesNotExist:
298 text = fragment.to_string()
299 short_text = truncate_html_words(text, 15)
300 if text == short_text:
302 new_fragment = Fragment.objects.create(
306 short_text=short_text
310 new_fragment.tags = set(meta_tags + themes)
312 if not theme.for_books:
313 theme.for_books = True
315 book.html_built.send(sender=type(self), instance=book)
320 def transform(wldoc, fieldfile):
321 # ugly, but we can't use wldoc.book_info here
322 from librarian import DCNS
323 url_elem = wldoc.edoc.getroot().find('.//' + DCNS('identifier.url'))
328 slug = url_elem.text.rstrip('/').rsplit('/', 1)[1]
329 gal_url = gallery_url(slug=slug)
330 gal_path = gallery_path(slug=slug)
331 return wldoc.as_html(gallery_path=gal_path, gallery_url=gal_url, base_url=absolute_url(gal_url))
334 class BuildCover(BuildEbook):
335 def set_file_permissions(self, fieldfile):
339 @BuildEbook.register('cover_thumb')
340 @task(ignore_result=True)
341 class BuildCoverThumb(BuildCover):
343 def transform(cls, wldoc, fieldfile):
344 from librarian.cover import WLCover
345 return WLCover(wldoc.book_info, height=193).output_file()
348 @BuildEbook.register('cover_api_thumb')
349 @task(ignore_result=True)
350 class BuildCoverApiThumb(BuildCover):
352 def transform(cls, wldoc, fieldfile):
353 from librarian.cover import WLNoBoxCover
354 return WLNoBoxCover(wldoc.book_info, height=500).output_file()
357 @BuildEbook.register('simple_cover')
358 @task(ignore_result=True)
359 class BuildSimpleCover(BuildCover):
361 def transform(cls, wldoc, fieldfile):
362 from librarian.cover import WLNoBoxCover
363 return WLNoBoxCover(wldoc.book_info, height=1000).output_file()
366 @BuildEbook.register('cover_ebookpoint')
367 @task(ignore_result=True)
368 class BuildCoverEbookpoint(BuildCover):
370 def transform(cls, wldoc, fieldfile):
371 from librarian.cover import EbookpointCover
372 return EbookpointCover(wldoc.book_info).output_file()
375 # not used, but needed for migrations
376 class OverwritingFieldFile(FieldFile):
378 Deletes the old file before saving the new one.
381 def save(self, name, content, *args, **kwargs):
382 leave = kwargs.pop('leave', None)
383 # delete if there's a file already and there's a new one coming
384 if not leave and self and (not hasattr(content, 'path') or content.path != self.path):
385 self.delete(save=False)
386 return super(OverwritingFieldFile, self).save(name, content, *args, **kwargs)
389 class OverwritingFileField(models.FileField):
390 attr_class = OverwritingFieldFile
393 class OverwriteStorage(FileSystemStorage):
395 def get_available_name(self, name, max_length=None):