1 # -*- coding: utf-8 -*-
2 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
3 # 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
12 from catalogue.utils import 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__)
20 class EbookFieldFile(FieldFile):
21 """Represents contents of an ebook file field."""
24 """Build the ebook immediately."""
25 return self.field.builder.build(self)
27 def build_delay(self):
28 """Builds the ebook in a delayed task."""
29 return self.field.builder.delay(self.instance, self.field.attname)
32 class EbookField(models.FileField):
33 """Represents an ebook file field, attachable to a model."""
34 attr_class = EbookFieldFile
36 def __init__(self, format_name, *args, **kwargs):
37 super(EbookField, self).__init__(*args, **kwargs)
38 self.format_name = format_name
40 def deconstruct(self):
41 name, path, args, kwargs = super(EbookField, self).deconstruct()
42 args.insert(0, self.format_name)
43 return name, path, args, kwargs
47 """Finds a celery task suitable for the format of the field."""
48 return BuildEbook.for_format(self.format_name)
50 def contribute_to_class(self, cls, name):
51 super(EbookField, self).contribute_to_class(cls, name)
53 def has(model_instance):
54 return bool(getattr(model_instance, self.attname, None))
56 has.__name__ = str("has_%s" % self.attname)
57 has.short_description = self.name
59 setattr(cls, 'has_%s' % self.attname, has)
62 class BuildEbook(Task):
66 def register(cls, format_name):
67 """A decorator for registering subclasses for particular formats."""
69 cls.formats[format_name] = builder
74 def for_format(cls, format_name):
75 """Returns a celery task suitable for specified format."""
76 return cls.formats.get(format_name, BuildEbookTask)
79 def transform(wldoc, fieldfile):
80 """Transforms an librarian.WLDocument into an librarian.OutputFile.
82 By default, it just calls relevant wldoc.as_??? method.
85 return getattr(wldoc, "as_%s" % fieldfile.field.format_name)()
87 def run(self, obj, field_name):
88 """Just run `build` on FieldFile, can't pass it directly to Celery."""
89 task_logger.info("%s -> %s" % (obj.slug, field_name))
90 ret = self.build(getattr(obj, field_name))
94 def build(self, fieldfile):
95 book = fieldfile.instance
96 out = self.transform(book.wldocument(), fieldfile)
97 fieldfile.save(None, File(open(out.get_filename())), save=False)
98 if book.pk is not None:
99 type(book).objects.filter(pk=book.pk).update(**{
100 fieldfile.field.attname: fieldfile
102 if fieldfile.field.format_name in app_settings.FORMAT_ZIPS:
103 remove_zip(app_settings.FORMAT_ZIPS[fieldfile.field.format_name])
104 # Don't decorate BuildEbook, because we want to subclass it.
105 BuildEbookTask = task(BuildEbook, ignore_result=True)
108 @BuildEbook.register('txt')
109 @task(ignore_result=True)
110 class BuildTxt(BuildEbook):
112 def transform(wldoc, fieldfile):
113 return wldoc.as_text()
116 @BuildEbook.register('pdf')
117 @task(ignore_result=True)
118 class BuildPdf(BuildEbook):
120 def transform(wldoc, fieldfile):
121 return wldoc.as_pdf(morefloats=settings.LIBRARIAN_PDF_MOREFLOATS, cover=True,
122 ilustr_path=gallery_path(wldoc.book_info.url.slug))
124 def build(self, fieldfile):
125 BuildEbook.build(self, fieldfile)
126 clear_cache(fieldfile.instance.slug)
129 @BuildEbook.register('epub')
130 @task(ignore_result=True)
131 class BuildEpub(BuildEbook):
133 def transform(wldoc, fieldfile):
134 return wldoc.as_epub(cover=True, ilustr_path=gallery_path(wldoc.book_info.url.slug))
137 @BuildEbook.register('mobi')
138 @task(ignore_result=True)
139 class BuildMobi(BuildEbook):
141 def transform(wldoc, fieldfile):
142 return wldoc.as_mobi(cover=True, ilustr_path=gallery_path(wldoc.book_info.url.slug))
145 @BuildEbook.register('html')
146 @task(ignore_result=True)
147 class BuildHtml(BuildEbook):
148 def build(self, fieldfile):
149 from django.core.files.base import ContentFile
150 from fnpdjango.utils.text.slughifi import slughifi
151 from sortify import sortify
152 from librarian import html
153 from catalogue.models import Fragment, Tag
155 book = fieldfile.instance
157 html_output = self.transform(book.wldocument(parse_dublincore=False), fieldfile)
159 # Delete old fragments, create from scratch if necessary.
160 book.fragments.all().delete()
163 meta_tags = list(book.tags.filter(
164 category__in=('author', 'epoch', 'genre', 'kind')))
167 lang = LANGUAGES_3TO2.get(lang, lang)
168 if lang not in [ln[0] for ln in settings.LANGUAGES]:
171 fieldfile.save(None, ContentFile(html_output.get_string()), save=False)
172 type(book).objects.filter(pk=book.pk).update(**{
173 fieldfile.field.attname: fieldfile
177 closed_fragments, open_fragments = html.extract_fragments(fieldfile.path)
178 for fragment in closed_fragments.values():
180 theme_names = [s.strip() for s in fragment.themes.split(',')]
181 except AttributeError:
184 for theme_name in theme_names:
187 if lang == settings.LANGUAGE_CODE:
188 # Allow creating themes if book in default language.
189 tag, created = Tag.objects.get_or_create(
190 slug=slughifi(theme_name),
193 tag.name = theme_name
194 setattr(tag, "name_%s" % lang, theme_name)
195 tag.sort_key = sortify(theme_name.lower())
199 elif lang is not None:
200 # Don't create unknown themes in non-default languages.
202 tag = Tag.objects.get(category='theme', **{"name_%s" % lang: theme_name})
203 except Tag.DoesNotExist:
210 text = fragment.to_string()
211 short_text = truncate_html_words(text, 15)
212 if text == short_text:
214 new_fragment = Fragment.objects.create(anchor=fragment.id, book=book, text=text, short_text=short_text)
217 new_fragment.tags = set(meta_tags + themes)
219 if not theme.for_books:
220 theme.for_books = True
222 book.html_built.send(sender=type(self), instance=book)
227 def transform(wldoc, fieldfile):
228 # ugly, but we can't use wldoc.book_info here
229 from librarian import DCNS
230 url_elem = wldoc.edoc.getroot().find('.//' + DCNS('identifier.url'))
234 gallery = gallery_url(slug=url_elem.text.rsplit('/', 1)[1])
235 return wldoc.as_html(options={'gallery': "'%s'" % gallery})
238 @BuildEbook.register('cover_thumb')
239 @task(ignore_result=True)
240 class BuildCoverThumb(BuildEbook):
242 def transform(cls, wldoc, fieldfile):
243 from librarian.cover import WLCover
244 return WLCover(wldoc.book_info, height=193).output_file()
247 # not used, but needed for migrations
248 class OverwritingFieldFile(FieldFile):
250 Deletes the old file before saving the new one.
253 def save(self, name, content, *args, **kwargs):
254 leave = kwargs.pop('leave', None)
255 # delete if there's a file already and there's a new one coming
256 if not leave and self and (not hasattr(content, 'path') or content.path != self.path):
257 self.delete(save=False)
258 return super(OverwritingFieldFile, self).save(name, content, *args, **kwargs)
261 class OverwritingFileField(models.FileField):
262 attr_class = OverwritingFieldFile
265 class OverwriteStorage(FileSystemStorage):
267 def get_available_name(self, name, max_length=None):