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):
223 librarian2_api = True
226 def transform(wldoc, fieldfile):
227 from librarian.builders import MobiBuilder
229 base_url='file://' + os.path.abspath(gallery_path(wldoc.meta.url.slug)) + '/',
230 fundraising=settings.EPUB_FUNDRAISING
234 @BuildEbook.register('html')
235 @task(ignore_result=True)
236 class BuildHtml(BuildEbook):
237 def build(self, fieldfile):
238 from django.core.files.base import ContentFile
239 from slugify import slugify
240 from sortify import sortify
241 from librarian import html
242 from catalogue.models import Fragment, Tag
244 book = fieldfile.instance
246 html_output = self.transform(book.wldocument(parse_dublincore=False), fieldfile)
248 # Delete old fragments, create from scratch if necessary.
249 book.fragments.all().delete()
252 meta_tags = list(book.tags.filter(
253 category__in=('author', 'epoch', 'genre', 'kind')))
256 lang = LANGUAGES_3TO2.get(lang, lang)
257 if lang not in [ln[0] for ln in settings.LANGUAGES]:
260 fieldfile.save(None, ContentFile(html_output.get_bytes()), save=False)
261 self.set_file_permissions(fieldfile)
262 type(book).objects.filter(pk=book.pk).update(**{
263 fieldfile.field.attname: fieldfile
267 closed_fragments, open_fragments = html.extract_fragments(fieldfile.path)
268 for fragment in closed_fragments.values():
270 theme_names = [s.strip() for s in fragment.themes.split(',')]
271 except AttributeError:
274 for theme_name in theme_names:
277 if lang == settings.LANGUAGE_CODE:
278 # Allow creating themes if book in default language.
279 tag, created = Tag.objects.get_or_create(
280 slug=slugify(theme_name),
284 tag.name = theme_name
285 setattr(tag, "name_%s" % lang, theme_name)
286 tag.sort_key = sortify(theme_name.lower())
290 elif lang is not None:
291 # Don't create unknown themes in non-default languages.
293 tag = Tag.objects.get(
295 **{"name_%s" % lang: theme_name}
297 except Tag.DoesNotExist:
304 text = fragment.to_string()
305 short_text = truncate_html_words(text, 15)
306 if text == short_text:
308 new_fragment = Fragment.objects.create(
312 short_text=short_text
316 new_fragment.tags = set(meta_tags + themes)
318 if not theme.for_books:
319 theme.for_books = True
321 book.html_built.send(sender=type(self), instance=book)
326 def transform(wldoc, fieldfile):
327 # ugly, but we can't use wldoc.book_info here
328 from librarian import DCNS
329 url_elem = wldoc.edoc.getroot().find('.//' + DCNS('identifier.url'))
334 slug = url_elem.text.rstrip('/').rsplit('/', 1)[1]
335 gal_url = gallery_url(slug=slug)
336 gal_path = gallery_path(slug=slug)
337 return wldoc.as_html(gallery_path=gal_path, gallery_url=gal_url, base_url=absolute_url(gal_url))
340 class BuildCover(BuildEbook):
341 def set_file_permissions(self, fieldfile):
345 @BuildEbook.register('cover_thumb')
346 @task(ignore_result=True)
347 class BuildCoverThumb(BuildCover):
349 def transform(cls, wldoc, fieldfile):
350 from librarian.cover import WLCover
351 return WLCover(wldoc.book_info, height=193).output_file()
354 @BuildEbook.register('cover_api_thumb')
355 @task(ignore_result=True)
356 class BuildCoverApiThumb(BuildCover):
358 def transform(cls, wldoc, fieldfile):
359 from librarian.cover import WLNoBoxCover
360 return WLNoBoxCover(wldoc.book_info, height=500).output_file()
363 @BuildEbook.register('simple_cover')
364 @task(ignore_result=True)
365 class BuildSimpleCover(BuildCover):
367 def transform(cls, wldoc, fieldfile):
368 from librarian.cover import WLNoBoxCover
369 return WLNoBoxCover(wldoc.book_info, height=1000).output_file()
372 @BuildEbook.register('cover_ebookpoint')
373 @task(ignore_result=True)
374 class BuildCoverEbookpoint(BuildCover):
376 def transform(cls, wldoc, fieldfile):
377 from librarian.cover import EbookpointCover
378 return EbookpointCover(wldoc.book_info).output_file()
381 # not used, but needed for migrations
382 class OverwritingFieldFile(FieldFile):
384 Deletes the old file before saving the new one.
387 def save(self, name, content, *args, **kwargs):
388 leave = kwargs.pop('leave', None)
389 # delete if there's a file already and there's a new one coming
390 if not leave and self and (not hasattr(content, 'path') or content.path != self.path):
391 self.delete(save=False)
392 return super(OverwritingFieldFile, self).save(name, content, *args, **kwargs)
395 class OverwritingFileField(models.FileField):
396 attr_class = OverwritingFieldFile
399 class OverwriteStorage(FileSystemStorage):
401 def get_available_name(self, name, max_length=None):