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 import Task, shared_task
14 from celery.task import Task, task
15 from celery.utils.log import get_task_logger
16 from waiter.utils import clear_cache
18 task_logger = get_task_logger(__name__)
20 ETAG_SCHEDULED_SUFFIX = '-scheduled'
21 EBOOK_BUILD_PRIORITY = 0
22 EBOOK_REBUILD_PRIORITY = 9
25 class EbookFieldFile(FieldFile):
26 """Represents contents of an ebook file field."""
29 """Build the ebook immediately."""
30 return self.field.builder.build(self)
32 def build_delay(self, priority=EBOOK_BUILD_PRIORITY):
33 """Builds the ebook in a delayed task."""
35 "".join([self.field.get_current_etag(), ETAG_SCHEDULED_SUFFIX])
37 return self.field.builder.apply_async(
38 [self.instance, self.field.attname],
43 return self.instance.media_url(self.field.attname.split('_')[0])
45 def set_readable(self, readable):
47 permissions = 0o644 if readable else 0o600
48 os.chmod(self.path, permissions)
50 def update_etag(self, etag):
51 setattr(self.instance, self.field.etag_field_name, etag)
53 self.instance.save(update_fields=[self.field.etag_field_name])
56 class EbookField(models.FileField):
57 """Represents an ebook file field, attachable to a model."""
58 attr_class = EbookFieldFile
61 def __init__(self, format_name, *args, **kwargs):
62 super(EbookField, self).__init__(*args, **kwargs)
63 self.format_name = format_name
65 def deconstruct(self):
66 name, path, args, kwargs = super(EbookField, self).deconstruct()
67 args.insert(0, self.format_name)
68 return name, path, args, kwargs
72 """Finds a celery task suitable for the format of the field."""
73 return BuildEbook.for_format(self.format_name)
75 def contribute_to_class(self, cls, name):
76 super(EbookField, self).contribute_to_class(cls, name)
78 self.etag_field_name = f'{name}_etag'
80 def has(model_instance):
81 return bool(getattr(model_instance, self.attname, None))
83 has.__name__ = str("has_%s" % self.attname)
84 has.short_description = self.name
87 self.registry.append(self)
89 setattr(cls, 'has_%s' % self.attname, has)
91 def get_current_etag(self):
93 librarian_version = pkg_resources.get_distribution("librarian").version
94 return librarian_version
96 def schedule_stale(self, queryset=None):
97 """Schedule building this format for all the books where etag is stale."""
98 # If there is not ETag field, bail. That's true for xml file field.
99 if not hasattr(self.model, f'{self.attname}_etag'):
102 etag = self.get_current_etag()
104 queryset = self.model.objects.all()
106 if self.format_name in EBOOK_FORMATS_WITHOUT_CHILDREN + ['html']:
107 queryset = queryset.filter(children=None)
109 queryset = queryset.exclude(**{
110 f'{self.etag_field_name}__in': [
111 etag, f'{etag}{ETAG_SCHEDULED_SUFFIX}'
115 fieldfile = getattr(obj, self.attname)
116 priority = EBOOK_REBUILD_PRIORITY if fieldfile else EBOOK_BUILD_PRIORITY
117 fieldfile.build_delay(priority=priority)
120 def schedule_all_stale(cls):
121 """Schedules all stale ebooks of all formats to rebuild."""
122 for field in cls.registry:
123 field.schedule_stale()
127 class BuildEbook(Task):
128 librarian2_api = False
133 def register(cls, format_name):
134 """A decorator for registering subclasses for particular formats."""
135 def wrapper(builder):
136 cls.formats[format_name] = builder
141 def for_format(cls, format_name):
142 """Returns a celery task suitable for specified format."""
143 return cls.formats.get(format_name, BuildEbookTask)
146 def transform(wldoc, fieldfile):
147 """Transforms an librarian.WLDocument into an librarian.OutputFile.
149 By default, it just calls relevant wldoc.as_??? method.
152 return getattr(wldoc, "as_%s" % fieldfile.field.format_name)()
154 def run(self, obj, field_name):
155 """Just run `build` on FieldFile, can't pass it directly to Celery."""
156 fieldfile = getattr(obj, field_name)
158 # Get etag value before actually building the file.
159 etag = fieldfile.field.get_current_etag()
160 task_logger.info("%s -> %s@%s" % (obj.slug, field_name, etag))
161 ret = self.build(getattr(obj, field_name))
162 fieldfile.update_etag(etag)
166 def set_file_permissions(self, fieldfile):
167 if fieldfile.instance.preview:
168 fieldfile.set_readable(False)
170 def build(self, fieldfile):
171 book = fieldfile.instance
172 out = self.transform(
173 book.wldocument2() if self.librarian2_api else book.wldocument(),
175 fieldfile.save(None, File(open(out.get_filename(), 'rb')), save=False)
176 self.set_file_permissions(fieldfile)
177 if book.pk is not None:
178 book.save(update_fields=[fieldfile.field.attname])
179 if fieldfile.field.format_name in app_settings.FORMAT_ZIPS:
180 remove_zip(app_settings.FORMAT_ZIPS[fieldfile.field.format_name])
181 # Don't decorate BuildEbook, because we want to subclass it.
182 BuildEbookTask = task(BuildEbook, ignore_result=True)
185 @BuildEbook.register('txt')
186 @task(ignore_result=True)
187 class BuildTxt(BuildEbook):
189 def transform(wldoc, fieldfile):
190 return wldoc.as_text()
193 @BuildEbook.register('pdf')
194 @task(ignore_result=True)
195 class BuildPdf(BuildEbook):
197 def transform(wldoc, fieldfile):
199 morefloats=settings.LIBRARIAN_PDF_MOREFLOATS, cover=True,
200 base_url=absolute_url(gallery_url(wldoc.book_info.url.slug)), customizations=['notoc'])
202 def build(self, fieldfile):
203 BuildEbook.build(self, fieldfile)
204 clear_cache(fieldfile.instance.slug)
207 @BuildEbook.register('epub')
208 @task(ignore_result=True)
209 class BuildEpub(BuildEbook):
210 librarian2_api = True
213 def transform(wldoc, fieldfile):
214 from librarian.builders import EpubBuilder
216 base_url='file://' + os.path.abspath(gallery_path(wldoc.meta.url.slug)) + '/',
217 fundraising=settings.EPUB_FUNDRAISING
221 @BuildEbook.register('mobi')
222 @task(ignore_result=True)
223 class BuildMobi(BuildEbook):
224 librarian2_api = True
227 def transform(wldoc, fieldfile):
228 from librarian.builders import MobiBuilder
230 base_url='file://' + os.path.abspath(gallery_path(wldoc.meta.url.slug)) + '/',
231 fundraising=settings.EPUB_FUNDRAISING
235 @BuildEbook.register('html')
236 @task(ignore_result=True)
237 class BuildHtml(BuildEbook):
238 def build(self, fieldfile):
239 from django.core.files.base import ContentFile
240 from slugify import slugify
241 from sortify import sortify
242 from librarian import html
243 from catalogue.models import Fragment, Tag
245 book = fieldfile.instance
247 html_output = self.transform(book.wldocument(parse_dublincore=False), fieldfile)
249 # Delete old fragments, create from scratch if necessary.
250 book.fragments.all().delete()
253 meta_tags = list(book.tags.filter(
254 category__in=('author', 'epoch', 'genre', 'kind')))
257 lang = LANGUAGES_3TO2.get(lang, lang)
258 if lang not in [ln[0] for ln in settings.LANGUAGES]:
261 fieldfile.save(None, ContentFile(html_output.get_bytes()), save=False)
262 self.set_file_permissions(fieldfile)
263 type(book).objects.filter(pk=book.pk).update(**{
264 fieldfile.field.attname: fieldfile
268 closed_fragments, open_fragments = html.extract_fragments(fieldfile.path)
269 for fragment in closed_fragments.values():
271 theme_names = [s.strip() for s in fragment.themes.split(',')]
272 except AttributeError:
275 for theme_name in theme_names:
278 if lang == settings.LANGUAGE_CODE:
279 # Allow creating themes if book in default language.
280 tag, created = Tag.objects.get_or_create(
281 slug=slugify(theme_name),
285 tag.name = theme_name
286 setattr(tag, "name_%s" % lang, theme_name)
287 tag.sort_key = sortify(theme_name.lower())
291 elif lang is not None:
292 # Don't create unknown themes in non-default languages.
294 tag = Tag.objects.get(
296 **{"name_%s" % lang: theme_name}
298 except Tag.DoesNotExist:
305 text = fragment.to_string()
306 short_text = truncate_html_words(text, 15)
307 if text == short_text:
309 new_fragment = Fragment.objects.create(
313 short_text=short_text
317 new_fragment.tags = set(meta_tags + themes)
319 if not theme.for_books:
320 theme.for_books = True
322 book.html_built.send(sender=type(self), instance=book)
327 def transform(wldoc, fieldfile):
328 # ugly, but we can't use wldoc.book_info here
329 from librarian import DCNS
330 url_elem = wldoc.edoc.getroot().find('.//' + DCNS('identifier.url'))
335 slug = url_elem.text.rstrip('/').rsplit('/', 1)[1]
336 gal_url = gallery_url(slug=slug)
337 gal_path = gallery_path(slug=slug)
338 return wldoc.as_html(gallery_path=gal_path, gallery_url=gal_url, base_url=absolute_url(gal_url))
341 class BuildCover(BuildEbook):
342 def set_file_permissions(self, fieldfile):
346 @BuildEbook.register('cover_clean')
347 @task(ignore_result=True)
348 class BuildCoverClean(BuildCover):
350 def transform(cls, wldoc, fieldfile):
351 if wldoc.book_info.cover_box_position == 'none':
352 from librarian.cover import WLCover
353 return WLCover(wldoc.book_info, width=240).output_file()
354 from librarian.covers.marquise import MarquiseCover
355 return MarquiseCover(wldoc.book_info, width=240).output_file()
358 @BuildEbook.register('cover_thumb')
359 @task(ignore_result=True)
360 class BuildCoverThumb(BuildCover):
362 def transform(cls, wldoc, fieldfile):
363 from librarian.cover import WLCover
364 return WLCover(wldoc.book_info, height=193).output_file()
367 @BuildEbook.register('cover_api_thumb')
368 @task(ignore_result=True)
369 class BuildCoverApiThumb(BuildCover):
371 def transform(cls, wldoc, fieldfile):
372 from librarian.cover import WLNoBoxCover
373 return WLNoBoxCover(wldoc.book_info, height=500).output_file()
376 @BuildEbook.register('simple_cover')
377 @task(ignore_result=True)
378 class BuildSimpleCover(BuildCover):
380 def transform(cls, wldoc, fieldfile):
381 from librarian.cover import WLNoBoxCover
382 return WLNoBoxCover(wldoc.book_info, height=1000).output_file()
385 @BuildEbook.register('cover_ebookpoint')
386 @task(ignore_result=True)
387 class BuildCoverEbookpoint(BuildCover):
389 def transform(cls, wldoc, fieldfile):
390 from librarian.cover import EbookpointCover
391 return EbookpointCover(wldoc.book_info).output_file()
394 # not used, but needed for migrations
395 class OverwritingFieldFile(FieldFile):
397 Deletes the old file before saving the new one.
400 def save(self, name, content, *args, **kwargs):
401 leave = kwargs.pop('leave', None)
402 # delete if there's a file already and there's a new one coming
403 if not leave and self and (not hasattr(content, 'path') or content.path != self.path):
404 self.delete(save=False)
405 return super(OverwritingFieldFile, self).save(name, content, *args, **kwargs)
408 class OverwritingFileField(models.FileField):
409 attr_class = OverwritingFieldFile
412 class OverwriteStorage(FileSystemStorage):
414 def get_available_name(self, name, max_length=None):