Django 4.
[wolnelektury.git] / src / catalogue / fields.py
1 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
3 #
4 import os
5 from django.conf import settings
6 from django.core.files import File
7 from django.db import models
8 from django.db.models.fields.files import FieldFile
9 from django.utils.deconstruct import deconstructible
10 from django.utils.translation import gettext_lazy as _
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 waiter.utils import clear_cache
14
15 ETAG_SCHEDULED_SUFFIX = '-scheduled'
16 EBOOK_BUILD_PRIORITY = 0
17 EBOOK_REBUILD_PRIORITY = 9
18
19
20 @deconstructible
21 class UploadToPath(object):
22     def __init__(self, path):
23         self.path = path
24
25     def __call__(self, instance, filename):
26         return self.path % instance.slug
27
28     def __eq__(self, other):
29         return isinstance(other, type(self)) and other.path == self.path
30
31
32 class EbookFieldFile(FieldFile):
33     """Represents contents of an ebook file field."""
34
35     def build(self):
36         """Build the ebook immediately."""
37         etag = self.field.get_current_etag()
38         self.field.build(self)
39         self.update_etag(etag)
40         self.instance.clear_cache()
41
42     def build_delay(self, priority=EBOOK_BUILD_PRIORITY):
43         """Builds the ebook in a delayed task."""
44         from .tasks import build_field
45
46         self.update_etag(
47             "".join([self.field.get_current_etag(), ETAG_SCHEDULED_SUFFIX])
48         )
49         return build_field.apply_async(
50             [self.instance.pk, self.field.attname],
51             priority=priority
52         )
53
54     def set_readable(self, readable):
55         import os
56         permissions = 0o644 if readable else 0o600
57         os.chmod(self.path, permissions)
58
59     def update_etag(self, etag):
60         setattr(self.instance, self.field.etag_field_name, etag)
61         if self.instance.pk:
62             self.instance.save(update_fields=[self.field.etag_field_name])
63
64
65 class EbookField(models.FileField):
66     """Represents an ebook file field, attachable to a model."""
67     attr_class = EbookFieldFile
68     ext = None
69     librarian2_api = False
70     ZIP = None
71
72     def __init__(self, verbose_name=None, with_etag=True, etag_field_name=None, **kwargs):
73         kwargs.setdefault('verbose_name', verbose_name)
74         self.with_etag = with_etag
75         self.etag_field_name = etag_field_name
76         kwargs.setdefault('max_length', 255)
77         kwargs.setdefault('blank', True)
78         kwargs.setdefault('default', '')
79         kwargs.setdefault('upload_to', self.get_upload_to(self.ext))
80
81         super().__init__(**kwargs)
82
83     def deconstruct(self):
84         name, path, args, kwargs = super().deconstruct()
85         if kwargs.get('max_length') == 255:
86             del kwargs['max_length']
87         if kwargs.get('blank') is True:
88             del kwargs['blank']
89         if kwargs.get('default') == '':
90             del kwargs['default']
91         if self.get_upload_to(self.ext) == kwargs.get('upload_to'):
92             del kwargs['upload_to']
93         # with_etag creates a second field, which then deconstructs to manage
94         # its own migrations. So for migrations, etag_field_name is explicitly
95         # set to avoid double creation of the etag field.
96         if self.with_etag:
97             kwargs['etag_field_name'] = self.etag_field_name
98         else:
99             kwargs['with_etag'] = self.with_etag
100
101         return name, path, args, kwargs
102
103     @classmethod
104     def get_upload_to(cls, directory):
105         directory = getattr(cls, 'directory', cls.ext)
106         upload_template = f'book/{directory}/%s.{cls.ext}'
107         return UploadToPath(upload_template)
108
109     def contribute_to_class(self, cls, name):
110         super(EbookField, self).contribute_to_class(cls, name)
111
112         if self.with_etag and not self.etag_field_name:
113             self.etag_field_name = f'{name}_etag'
114             self.etag_field = models.CharField(max_length=255, editable=False, default='', db_index=True)
115             self.etag_field.contribute_to_class(cls, f'{name}_etag')
116
117         def has(model_instance):
118             return bool(getattr(model_instance, self.attname, None))
119         has.__doc__ = None
120         has.__name__ = str("has_%s" % self.attname)
121         has.short_description = self.name
122         has.boolean = True
123
124         setattr(cls, 'has_%s' % self.attname, has)
125
126     def get_current_etag(self):
127         import pkg_resources
128         librarian_version = pkg_resources.get_distribution("librarian").version
129         return librarian_version
130
131     def schedule_stale(self, queryset=None):
132         """Schedule building this format for all the books where etag is stale."""
133         # If there is not ETag field, bail. That's true for xml file field.
134         if not self.with_etag:
135             return
136
137         etag = self.get_current_etag()
138         if queryset is None:
139             queryset = self.model.objects.all()
140
141         if self.format_name in EBOOK_FORMATS_WITHOUT_CHILDREN + ['html']:
142             queryset = queryset.filter(children=None)
143
144         queryset = queryset.exclude(**{
145             f'{self.etag_field_name}__in': [
146                 etag, f'{etag}{ETAG_SCHEDULED_SUFFIX}'
147             ]
148         })
149         for obj in queryset:
150             fieldfile = getattr(obj, self.attname)
151             priority = EBOOK_REBUILD_PRIORITY if fieldfile else EBOOK_BUILD_PRIORITY
152             fieldfile.build_delay(priority=priority)
153
154     @classmethod
155     def schedule_all_stale(cls, model):
156         """Schedules all stale ebooks of all formats to rebuild."""
157         for field in model._meta.fields:
158             if isinstance(field, cls):
159                 field.schedule_stale()
160
161     @staticmethod
162     def transform(wldoc):
163         """Transforms an librarian.WLDocument into an librarian.OutputFile.
164         """
165         raise NotImplemented()
166
167     def set_file_permissions(self, fieldfile):
168         if fieldfile.instance.preview:
169             fieldfile.set_readable(False)
170
171     def build(self, fieldfile):
172         book = fieldfile.instance
173         out = self.transform(
174             book.wldocument2() if self.librarian2_api else book.wldocument(),
175         )
176         with open(out.get_filename(), 'rb') as f:
177             fieldfile.save(None, File(f), save=False)
178         self.set_file_permissions(fieldfile)
179         if book.pk is not None:
180             book.save(update_fields=[self.attname])
181         if self.ZIP:
182             remove_zip(self.ZIP)
183
184
185 class XmlField(EbookField):
186     ext = 'xml'
187
188     def build(self, fieldfile):
189         pass
190
191
192 class TxtField(EbookField):
193     ext = 'txt'
194
195     @staticmethod
196     def transform(wldoc):
197         return wldoc.as_text()
198
199
200 class Fb2Field(EbookField):
201     ext = 'fb2'
202     ZIP = 'wolnelektury_pl_fb2'
203
204     @staticmethod
205     def transform(wldoc):
206         return wldoc.as_fb2()
207
208
209 class PdfField(EbookField):
210     ext = 'pdf'
211     ZIP = 'wolnelektury_pl_pdf'
212
213     @staticmethod
214     def transform(wldoc):
215         return wldoc.as_pdf(
216             morefloats=settings.LIBRARIAN_PDF_MOREFLOATS, cover=True,
217             base_url=absolute_url(gallery_url(wldoc.book_info.url.slug)), customizations=['notoc'])
218
219     def build(self, fieldfile):
220         super().build(fieldfile)
221         clear_cache(fieldfile.instance.slug)
222
223
224 class EpubField(EbookField):
225     ext = 'epub'
226     librarian2_api = True
227     ZIP = 'wolnelektury_pl_epub'
228
229     @staticmethod
230     def transform(wldoc):
231         from librarian.builders import EpubBuilder
232         return EpubBuilder(
233                 base_url='file://' + os.path.abspath(gallery_path(wldoc.meta.url.slug)) + '/',
234                 fundraising=settings.EPUB_FUNDRAISING
235             ).build(wldoc)
236
237
238 class MobiField(EbookField):
239     ext = 'mobi'
240     librarian2_api = True
241     ZIP = 'wolnelektury_pl_mobi'
242
243     @staticmethod
244     def transform(wldoc):
245         from librarian.builders import MobiBuilder
246         return MobiBuilder(
247                 base_url='file://' + os.path.abspath(gallery_path(wldoc.meta.url.slug)) + '/',
248                 fundraising=settings.EPUB_FUNDRAISING
249             ).build(wldoc)
250
251
252 class HtmlField(EbookField):
253     ext = 'html'
254
255     def build(self, fieldfile):
256         from django.core.files.base import ContentFile
257         from slugify import slugify
258         from sortify import sortify
259         from librarian import html
260         from catalogue.models import Fragment, Tag
261
262         book = fieldfile.instance
263
264         html_output = self.transform(book.wldocument(parse_dublincore=False))
265
266         # Delete old fragments, create from scratch if necessary.
267         book.fragments.all().delete()
268
269         if html_output:
270             meta_tags = list(book.tags.filter(
271                 category__in=('author', 'epoch', 'genre', 'kind')))
272
273             lang = book.language
274             lang = LANGUAGES_3TO2.get(lang, lang)
275             if lang not in [ln[0] for ln in settings.LANGUAGES]:
276                 lang = None
277
278             fieldfile.save(None, ContentFile(html_output.get_bytes()), save=False)
279             self.set_file_permissions(fieldfile)
280             type(book).objects.filter(pk=book.pk).update(**{
281                 fieldfile.field.attname: fieldfile
282             })
283
284             # Extract fragments
285             closed_fragments, open_fragments = html.extract_fragments(fieldfile.path)
286             for fragment in closed_fragments.values():
287                 try:
288                     theme_names = [s.strip() for s in fragment.themes.split(',')]
289                 except AttributeError:
290                     continue
291                 themes = []
292                 for theme_name in theme_names:
293                     if not theme_name:
294                         continue
295                     if lang == settings.LANGUAGE_CODE:
296                         # Allow creating themes if book in default language.
297                         tag, created = Tag.objects.get_or_create(
298                             slug=slugify(theme_name),
299                             category='theme'
300                         )
301                         if created:
302                             tag.name = theme_name
303                             setattr(tag, "name_%s" % lang, theme_name)
304                             tag.sort_key = sortify(theme_name.lower())
305                             tag.for_books = True
306                             tag.save()
307                         themes.append(tag)
308                     elif lang is not None:
309                         # Don't create unknown themes in non-default languages.
310                         try:
311                             tag = Tag.objects.get(
312                                 category='theme',
313                                 **{"name_%s" % lang: theme_name}
314                             )
315                         except Tag.DoesNotExist:
316                             pass
317                         else:
318                             themes.append(tag)
319                 if not themes:
320                     continue
321
322                 text = fragment.to_string()
323                 short_text = truncate_html_words(text, 15)
324                 if text == short_text:
325                     short_text = ''
326                 new_fragment = Fragment.objects.create(
327                     anchor=fragment.id,
328                     book=book,
329                     text=text,
330                     short_text=short_text
331                 )
332
333                 new_fragment.save()
334                 new_fragment.tags = set(meta_tags + themes)
335                 for theme in themes:
336                     if not theme.for_books:
337                         theme.for_books = True
338                         theme.save()
339             book.html_built.send(sender=type(self), instance=book)
340             return True
341         return False
342
343     @staticmethod
344     def transform(wldoc):
345         # ugly, but we can't use wldoc.book_info here
346         from librarian import DCNS
347         url_elem = wldoc.edoc.getroot().find('.//' + DCNS('identifier.url'))
348         if url_elem is None:
349             gal_url = ''
350             gal_path = ''
351         else:
352             slug = url_elem.text.rstrip('/').rsplit('/', 1)[1]
353             gal_url = gallery_url(slug=slug)
354             gal_path = gallery_path(slug=slug)
355         return wldoc.as_html(gallery_path=gal_path, gallery_url=gal_url, base_url=absolute_url(gal_url))
356
357
358 class CoverField(EbookField):
359     ext = 'jpg'
360     directory = 'cover'
361
362     @staticmethod
363     def transform(wldoc):
364         return wldoc.as_cover()
365
366     def set_file_permissions(self, fieldfile):
367         pass
368
369
370 class CoverCleanField(CoverField):
371     directory = 'cover_clean'
372
373     @staticmethod
374     def transform(wldoc):
375         if wldoc.book_info.cover_box_position == 'none':
376             from librarian.cover import WLCover
377             return WLCover(wldoc.book_info, width=240).output_file()
378         from librarian.covers.marquise import MarquiseCover
379         return MarquiseCover(wldoc.book_info, width=240).output_file()
380
381
382 class CoverThumbField(CoverField):
383     directory = 'cover_thumb'
384
385     @staticmethod
386     def transform(wldoc):
387         from librarian.cover import WLCover
388         return WLCover(wldoc.book_info, height=193).output_file()
389
390
391 class CoverApiThumbField(CoverField):
392     directory = 'cover_api_thumb'
393
394     @staticmethod
395     def transform(wldoc):
396         from librarian.cover import WLNoBoxCover
397         return WLNoBoxCover(wldoc.book_info, height=500).output_file()
398
399
400 class SimpleCoverField(CoverField):
401     directory = 'cover_simple'
402
403     @staticmethod
404     def transform(wldoc):
405         from librarian.cover import WLNoBoxCover
406         return WLNoBoxCover(wldoc.book_info, height=1000).output_file()
407
408
409 class CoverEbookpointField(CoverField):
410     directory = 'cover_ebookpoint'
411
412     @staticmethod
413     def transform(wldoc):
414         from librarian.cover import EbookpointCover
415         return EbookpointCover(wldoc.book_info).output_file()