Nonexistent field
[wolnelektury.git] / src / catalogue / models / book.py
1 # This file is part of Wolne Lektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Wolne Lektury. See NOTICE for more information.
3 #
4 from collections import OrderedDict
5 import json
6 from datetime import date, timedelta
7 from random import randint
8 import os.path
9 import re
10 import requests
11 from slugify import slugify
12 from sortify import sortify
13 from urllib.request import urlretrieve
14 from django.apps import apps
15 from django.conf import settings
16 from django.db import connection, models, transaction
17 import django.dispatch
18 from django.contrib.contenttypes.fields import GenericRelation
19 from django.core.files.storage import storages
20 from django.urls import reverse
21 from django.utils.translation import gettext_lazy as _, get_language
22 from lxml import html
23 from librarian.cover import WLCover
24 from librarian.html import transform_abstrakt
25 from librarian.builders import builders
26 from newtagging import managers
27 from catalogue import constants
28 from catalogue import fields
29 from catalogue.models import Tag, Fragment, BookMedia
30 from catalogue.utils import create_zip, gallery_url, gallery_path, split_tags, get_random_hash
31 from catalogue.models.tag import prefetched_relations
32 from catalogue import app_settings
33 from wolnelektury.utils import makedirs, cached_render, clear_cached_renders
34
35
36 def get_storage():
37     return storages['book']
38
39
40 class Book(models.Model):
41     """Represents a book imported from WL-XML."""
42     title = models.CharField('tytuł', max_length=32767)
43     sort_key = models.CharField('klucz sortowania', max_length=120, db_index=True, db_collation='C', editable=False)
44     sort_key_author = models.CharField(
45         'klucz sortowania wg autora', max_length=120, db_index=True, db_collation='C', editable=False, default='')
46     slug = models.SlugField('slug', max_length=120, db_index=True, unique=True)
47     common_slug = models.SlugField('wspólny slug', max_length=120, db_index=True)
48     language = models.CharField('kod języka', max_length=3, db_index=True, default=app_settings.DEFAULT_LANGUAGE)
49     description = models.TextField('opis', blank=True)
50     license = models.CharField('licencja', max_length=255, blank=True, db_index=True)
51     abstract = models.TextField('abstrakt', blank=True)
52     toc = models.TextField('spis treści', blank=True)
53     created_at = models.DateTimeField('data utworzenia', auto_now_add=True, db_index=True)
54     changed_at = models.DateTimeField('data motyfikacji', auto_now=True, db_index=True)
55     parent_number = models.IntegerField('numer w ramach rodzica', default=0)
56     extra_info = models.TextField('dodatkowe informacje', default='{}')
57     gazeta_link = models.CharField(blank=True, max_length=240)
58     wiki_link = models.CharField(blank=True, max_length=240)
59     print_on_demand = models.BooleanField('druk na żądanie', default=False)
60     recommended = models.BooleanField('polecane', default=False)
61     audio_length = models.CharField('długość audio', blank=True, max_length=8)
62     preview = models.BooleanField('prapremiera', default=False)
63     preview_until = models.DateField('prapremiera do', blank=True, null=True)
64     preview_key = models.CharField(max_length=32, blank=True, null=True)
65     findable = models.BooleanField('wyszukiwalna', default=True, db_index=True)
66     can_sell = models.BooleanField('do sprzedaży', default=True)
67     can_sell_mp3 = models.BooleanField('do sprzedaży mp3', default=False)
68     isbn_mp3 = models.CharField('ISBN audiobooka', max_length=32, blank=True)
69
70     # files generated during publication
71     xml_file = fields.XmlField(storage=get_storage, with_etag=False)
72     html_file = fields.HtmlField(storage=get_storage)
73     html_nonotes_file = fields.HtmlNonotesField(storage=get_storage)
74     fb2_file = fields.Fb2Field(storage=get_storage)
75     txt_file = fields.TxtField(storage=get_storage)
76     epub_file = fields.EpubField(storage=get_storage)
77     mobi_file = fields.MobiField(storage=get_storage)
78     pdf_file = fields.PdfField(storage=get_storage)
79     cover = fields.CoverField('okładka', storage=get_storage)
80
81     ebook_formats = constants.EBOOK_FORMATS
82     formats = ebook_formats + ['html', 'xml', 'html_nonotes']
83
84     parent = models.ForeignKey('self', models.CASCADE, blank=True, null=True, related_name='children')
85     ancestor = models.ManyToManyField('self', blank=True, editable=False, related_name='descendant', symmetrical=False)
86
87     cached_author = models.CharField(blank=True, max_length=240, db_index=True)
88     has_audience = models.BooleanField(default=False)
89
90     objects = models.Manager()
91     tagged = managers.ModelTaggedItemManager(Tag)
92     tags = managers.TagDescriptor(Tag)
93     tag_relations = GenericRelation(Tag.intermediary_table_model, related_query_name='tagged_book')
94     translators = models.ManyToManyField(Tag, blank=True)
95     narrators = models.ManyToManyField(Tag, blank=True, related_name='narrated')
96     has_audio = models.BooleanField(default=False)
97     read_time = models.IntegerField(blank=True, null=True)
98     pages = models.IntegerField(blank=True, null=True)
99     
100     html_built = django.dispatch.Signal()
101     published = django.dispatch.Signal()
102
103     SORT_KEY_SEP = '$'
104
105     is_book = True
106
107     class AlreadyExists(Exception):
108         pass
109
110     class Meta:
111         ordering = ('sort_key_author', 'sort_key')
112         verbose_name = 'książka'
113         verbose_name_plural = 'książki'
114         app_label = 'catalogue'
115
116     def __str__(self):
117         return self.title
118
119     def get_extra_info_json(self):
120         return json.loads(self.extra_info or '{}')
121
122     def get_initial(self):
123         try:
124             return re.search(r'\w', self.title, re.U).group(0)
125         except AttributeError:
126             return ''
127
128     def authors(self):
129         return self.tags.filter(category='author')
130
131     def epochs(self):
132         return self.tags.filter(category='epoch')
133
134     def genres(self):
135         return self.tags.filter(category='genre')
136
137     def kinds(self):
138         return self.tags.filter(category='kind')
139
140     def tag_unicode(self, category):
141         relations = prefetched_relations(self, category)
142         if relations:
143             return ', '.join(rel.tag.name for rel in relations)
144         else:
145             return ', '.join(self.tags.filter(category=category).values_list('name', flat=True))
146
147     def tags_by_category(self):
148         return split_tags(self.tags.exclude(category__in=('set', 'theme')))
149
150     def author_unicode(self):
151         return self.cached_author
152
153     def kind_unicode(self):
154         return self.tag_unicode('kind')
155
156     def epoch_unicode(self):
157         return self.tag_unicode('epoch')
158
159     def genre_unicode(self):
160         return self.tag_unicode('genre')
161
162     def translator(self):
163         translators = self.get_extra_info_json().get('translators')
164         if not translators:
165             return None
166         if len(translators) > 3:
167             translators = translators[:2]
168             others = ' i inni'
169         else:
170             others = ''
171         return ', '.join('\xa0'.join(reversed(translator.split(', ', 1))) for translator in translators) + others
172
173     def cover_source(self):
174         return self.get_extra_info_json().get('cover_source', self.parent.cover_source() if self.parent else '')
175
176     @property
177     def isbn_pdf(self):
178         return self.get_extra_info_json().get('isbn_pdf')
179
180     @property
181     def isbn_epub(self):
182         return self.get_extra_info_json().get('isbn_epub')
183
184     @property
185     def isbn_mobi(self):
186         return self.get_extra_info_json().get('isbn_mobi')
187
188     @property
189     def redakcja(self):
190         return self.get_extra_info_json().get('about')
191     
192     def is_accessible_to(self, user):
193         if not self.preview:
194             return True
195         if not user.is_authenticated:
196             return False
197         Membership = apps.get_model('club', 'Membership')
198         if Membership.is_active_for(user):
199             return True
200         Funding = apps.get_model('funding', 'Funding')
201         if Funding.objects.filter(user=user, offer__book=self):
202             return True
203         return False
204
205     def save(self, force_insert=False, force_update=False, **kwargs):
206         from sortify import sortify
207
208         self.sort_key = sortify(self.title)[:120]
209         self.title = str(self.title)  # ???
210
211         try:
212             author = self.authors().first().sort_key
213         except AttributeError:
214             author = ''
215         self.sort_key_author = author
216
217         self.cached_author = self.tag_unicode('author')
218         self.has_audience = 'audience' in self.get_extra_info_json()
219
220         if self.preview and not self.preview_key:
221             self.preview_key = get_random_hash(self.slug)[:32]
222
223         ret = super(Book, self).save(
224             force_insert=force_insert, force_update=force_update, **kwargs)
225
226         return ret
227
228     def get_absolute_url(self):
229         return reverse('book_detail', args=[self.slug])
230
231     def gallery_path(self):
232         return gallery_path(self.slug)
233
234     def gallery_url(self):
235         return gallery_url(self.slug)
236
237     def get_first_text(self):
238         if self.html_file:
239             return self
240         child = self.children.all().order_by('parent_number').first()
241         if child is not None:
242             return child.get_first_text()
243
244     def get_last_text(self):
245         if self.html_file:
246             return self
247         child = self.children.all().order_by('parent_number').last()
248         if child is not None:
249             return child.get_last_text()
250
251     def get_prev_text(self):
252         if not self.parent:
253             return None
254         sibling = self.parent.children.filter(parent_number__lt=self.parent_number).order_by('-parent_number').first()
255         if sibling is not None:
256             return sibling.get_last_text()
257
258         if self.parent.html_file:
259             return self.parent
260
261         return self.parent.get_prev_text()
262
263     def get_next_text(self, inside=True):
264         if inside:
265             child = self.children.order_by('parent_number').first()
266             if child is not None:
267                 return child.get_first_text()
268
269         if not self.parent:
270             return None
271         sibling = self.parent.children.filter(parent_number__gt=self.parent_number).order_by('parent_number').first()
272         if sibling is not None:
273             return sibling.get_first_text()
274         return self.parent.get_next_text(inside=False)
275
276     def get_siblings(self):
277         if not self.parent:
278             return []
279         return self.parent.children.all().order_by('parent_number')
280
281     def get_children(self):
282         return self.children.all().order_by('parent_number')
283
284     @property
285     def name(self):
286         return self.title
287
288     def language_code(self):
289         return constants.LANGUAGES_3TO2.get(self.language, self.language)
290
291     def language_name(self):
292         return dict(settings.LANGUAGES).get(self.language_code(), "")
293
294     def is_foreign(self):
295         return self.language_code() != settings.LANGUAGE_CODE
296
297     def set_audio_length(self):
298         length = self.get_audio_length()
299         if length > 0:
300             self.audio_length = self.format_audio_length(length)
301             self.save()
302
303     @staticmethod
304     def format_audio_length(seconds):
305         """
306         >>> Book.format_audio_length(1)
307         '0:01'
308         >>> Book.format_audio_length(3661)
309         '1:01:01'
310         """
311         if seconds < 60*60:
312             minutes = seconds // 60
313             seconds = seconds % 60
314             return '%d:%02d' % (minutes, seconds)
315         else:
316             hours = seconds // 3600
317             minutes = seconds % 3600 // 60
318             seconds = seconds % 60
319             return '%d:%02d:%02d' % (hours, minutes, seconds)
320
321     def get_audio_length(self):
322         total = self.media.filter(type='mp3').aggregate(
323             models.Sum('duration'))['duration__sum']
324         return int(total or 0)
325
326     def get_time(self):
327         return round(self.xml_file.size / 1000 * 40)
328     
329     def has_media(self, type_):
330         if type_ in Book.formats:
331             return bool(getattr(self, "%s_file" % type_))
332         else:
333             return self.media.filter(type=type_).exists()
334
335     def get_media(self, type_):
336         if self.has_media(type_):
337             if type_ in Book.formats:
338                 return getattr(self, "%s_file" % type_)
339             else:
340                 return self.media.filter(type=type_)
341         else:
342             return None
343
344     def get_mp3(self):
345         return self.get_media("mp3")
346
347     def get_odt(self):
348         return self.get_media("odt")
349
350     def get_ogg(self):
351         return self.get_media("ogg")
352
353     def get_daisy(self):
354         return self.get_media("daisy")
355
356     def get_audio_epub(self):
357         return self.get_media("audio.epub")
358
359     def media_url(self, format_):
360         media = self.get_media(format_)
361         if media:
362             if self.preview:
363                 return reverse('embargo_link', kwargs={'key': self.preview_key, 'slug': self.slug, 'format_': format_})
364             else:
365                 return media.url
366         else:
367             return None
368
369     def html_url(self):
370         return self.media_url('html')
371
372     def html_nonotes_url(self):
373         return self.media_url('html_nonotes')
374
375     def pdf_url(self):
376         return self.media_url('pdf')
377
378     def epub_url(self):
379         return self.media_url('epub')
380
381     def mobi_url(self):
382         return self.media_url('mobi')
383
384     def txt_url(self):
385         return self.media_url('txt')
386
387     def fb2_url(self):
388         return self.media_url('fb2')
389
390     def xml_url(self):
391         return self.media_url('xml')
392
393     def has_description(self):
394         return len(self.description) > 0
395     has_description.short_description = 'opis'
396     has_description.boolean = True
397
398     def has_mp3_file(self):
399         return self.has_media("mp3")
400     has_mp3_file.short_description = 'MP3'
401     has_mp3_file.boolean = True
402
403     def has_ogg_file(self):
404         return self.has_media("ogg")
405     has_ogg_file.short_description = 'OGG'
406     has_ogg_file.boolean = True
407
408     def has_daisy_file(self):
409         return self.has_media("daisy")
410     has_daisy_file.short_description = 'DAISY'
411     has_daisy_file.boolean = True
412
413     def has_sync_file(self):
414         return settings.FEATURE_SYNCHRO and self.has_media("sync")
415
416     def build_sync_file(self):
417         from lxml import html
418         from django.core.files.base import ContentFile
419         with self.html_file.open('rb') as f:
420             h = html.fragment_fromstring(f.read().decode('utf-8'))
421
422         durations = [
423             m['mp3'].duration
424             for m in self.get_audiobooks()[0]
425         ]
426         if settings.MOCK_DURATIONS:
427             durations = settings.MOCK_DURATIONS
428
429         sync = []
430         ts = None
431         sid = 1
432         dirty = False
433         for elem in h.iter():
434             if elem.get('data-audio-ts'):
435                 part, ts = int(elem.get('data-audio-part')), float(elem.get('data-audio-ts'))
436                 ts = str(round(sum(durations[:part - 1]) + ts, 3))
437                 # check if inside verse
438                 p = elem.getparent()
439                 while p is not None:
440                     # Workaround for missing ids.
441                     if 'verse' in p.get('class', ''):
442                         if not p.get('id'):
443                             p.set('id', f'syn{sid}')
444                             dirty = True
445                             sid += 1
446                         sync.append((ts, p.get('id')))
447                         ts = None
448                         break
449                     p = p.getparent()
450             elif ts:
451                 cls = elem.get('class', '')
452                 # Workaround for missing ids.
453                 if 'paragraph' in cls or 'verse' in cls or elem.tag in ('h1', 'h2', 'h3', 'h4'):
454                     if not elem.get('id'):
455                         elem.set('id', f'syn{sid}')
456                         dirty = True
457                         sid += 1
458                     sync.append((ts, elem.get('id')))
459                     ts = None
460         if dirty:
461             htext = html.tostring(h, encoding='utf-8')
462             with open(self.html_file.path, 'wb') as f:
463                 f.write(htext)
464         try:
465             bm = self.media.get(type='sync')
466         except:
467             bm = BookMedia(book=self, type='sync')
468         sync = (
469             '27\n' + '\n'.join(
470                 f'{s[0]}\t{sync[i+1][0]}\t{s[1]}' for i, s in enumerate(sync[:-1])
471             )).encode('latin1')
472         bm.file.save(
473             None, ContentFile(sync)
474             )
475
476     def get_sync(self):
477         if not self.has_sync_file():
478             return []
479         with self.get_media('sync').first().file.open('r') as f:
480             sync = f.read().split('\n')
481         offset = float(sync[0])
482         items = []
483         for line in sync[1:]:
484             if not line:
485                 continue
486             start, end, elid = line.split()
487             items.append([elid, float(start) + offset])
488         return items
489
490     def sync_ts(self, ts):
491         elid = None
492         for cur_id, t in self.get_sync():
493             if ts >= t:
494                 elid = cur_id
495             else:
496                 break
497         return elid
498
499     def sync_elid(self, elid):
500         for cur_id, t in self.get_sync():
501             if cur_id == elid:
502                 return t
503
504     def has_audio_epub_file(self):
505         return self.has_media("audio.epub")
506
507     @property
508     def media_daisy(self):
509         return self.get_media('daisy')
510
511     @property
512     def media_audio_epub(self):
513         return self.get_media('audio.epub')
514
515     def get_audiobooks(self, with_children=False, processing=False):
516         ogg_files = {}
517         for m in self.media.filter(type='ogg').order_by().iterator():
518             ogg_files[m.name] = m
519
520         audiobooks = []
521         projects = set()
522         total_duration = 0
523         for mp3 in self.media.filter(type='mp3').iterator():
524             # ogg files are always from the same project
525             meta = mp3.get_extra_info_json()
526             project = meta.get('project')
527             if not project:
528                 # temporary fallback
529                 project = 'CzytamySłuchając'
530
531             projects.add((project, meta.get('funded_by', '')))
532             total_duration += mp3.duration or 0
533
534             media = {'mp3': mp3}
535
536             ogg = ogg_files.get(mp3.name)
537             if ogg:
538                 media['ogg'] = ogg
539             audiobooks.append(media)
540
541         if with_children:
542             for child in self.get_children():
543                 ch_audiobooks, ch_projects, ch_duration = child.get_audiobooks(
544                     with_children=True, processing=True)
545                 audiobooks.append({'part': child})
546                 audiobooks += ch_audiobooks
547                 projects.update(ch_projects)
548                 total_duration += ch_duration
549
550         if not processing:
551             projects = sorted(projects)
552             total_duration = '%d:%02d' % (
553                 total_duration // 60,
554                 total_duration % 60
555             )
556
557         return audiobooks, projects, total_duration
558
559     def get_audiobooks_with_children(self):
560         return self.get_audiobooks(with_children=True)
561     
562     def wldocument(self, parse_dublincore=True, inherit=True):
563         from catalogue.import_utils import ORMDocProvider
564         from librarian.parser import WLDocument
565
566         if inherit and self.parent:
567             meta_fallbacks = self.parent.cover_info()
568         else:
569             meta_fallbacks = None
570
571         return WLDocument.from_file(
572             self.xml_file.path,
573             provider=ORMDocProvider(self),
574             parse_dublincore=parse_dublincore,
575             meta_fallbacks=meta_fallbacks)
576
577     def wldocument2(self):
578         from catalogue.import_utils import ORMDocProvider
579         from librarian.document import WLDocument
580         doc = WLDocument(
581             self.xml_file.path,
582             provider=ORMDocProvider(self)
583         )
584         doc.meta.update(self.cover_info())
585         return doc
586
587
588     @staticmethod
589     def zip_format(format_):
590         def pretty_file_name(book):
591             return "%s/%s.%s" % (
592                 book.get_extra_info_json()['author'],
593                 book.slug,
594                 format_)
595
596         field_name = "%s_file" % format_
597         field = getattr(Book, field_name)
598         books = Book.objects.filter(parent=None).exclude(**{field_name: ""}).exclude(preview=True).exclude(findable=False)
599         paths = [(pretty_file_name(b), getattr(b, field_name).path) for b in books.iterator()]
600         return create_zip(paths, field.ZIP)
601
602     def search_index(self, index=None):
603         if not self.findable:
604             return
605         from search.index import Index
606         Index.index_book(self)
607
608     # will make problems in conjunction with paid previews
609     def download_pictures(self, remote_gallery_url):
610         # This is only needed for legacy relative image paths.
611         gallery_path = self.gallery_path()
612         # delete previous files, so we don't include old files in ebooks
613         if os.path.isdir(gallery_path):
614             for filename in os.listdir(gallery_path):
615                 file_path = os.path.join(gallery_path, filename)
616                 os.unlink(file_path)
617         ilustr_elements = list(self.wldocument().edoc.findall('.//ilustr'))
618         if ilustr_elements:
619             makedirs(gallery_path)
620             for ilustr in ilustr_elements:
621                 ilustr_src = ilustr.get('src')
622                 if '/' in ilustr_src:
623                     continue
624                 ilustr_path = os.path.join(gallery_path, ilustr_src)
625                 urlretrieve('%s/%s' % (remote_gallery_url, ilustr_src), ilustr_path)
626
627     def load_abstract(self):
628         abstract = self.wldocument(parse_dublincore=False).edoc.getroot().find('.//abstrakt')
629         if abstract is not None:
630             self.abstract = transform_abstrakt(abstract)
631         else:
632             self.abstract = ''
633
634     def load_toc(self):
635         self.toc = ''
636         if self.html_file:
637             parser = html.HTMLParser(encoding='utf-8')
638             tree = html.parse(self.html_file.path, parser=parser)
639             toc = tree.find('.//div[@id="toc"]/ol')
640             if toc is None or not len(toc):
641                 return
642             html_link = reverse('book_text', args=[self.slug])
643             for a in toc.findall('.//a'):
644                 a.attrib['href'] = html_link + a.attrib['href']
645             self.toc = html.tostring(toc, encoding='unicode')
646             # div#toc
647
648     @classmethod
649     def from_xml_file(cls, xml_file, **kwargs):
650         from django.core.files import File
651         from librarian import dcparser
652
653         # use librarian to parse meta-data
654         book_info = dcparser.parse(xml_file)
655
656         if not isinstance(xml_file, File):
657             xml_file = File(open(xml_file))
658
659         try:
660             return cls.from_text_and_meta(xml_file, book_info, **kwargs)
661         finally:
662             xml_file.close()
663
664     @classmethod
665     def from_text_and_meta(cls, raw_file, book_info, overwrite=False, dont_build=None, search_index=True,
666                            remote_gallery_url=None, days=0, findable=True, logo=None, logo_mono=None, logo_alt=None, can_sell=None, isbn_mp3=None):
667         from catalogue import tasks
668
669         if dont_build is None:
670             dont_build = set()
671         dont_build = set.union(set(dont_build), set(app_settings.DONT_BUILD))
672
673         # check for parts before we do anything
674         children = []
675         if hasattr(book_info, 'parts'):
676             for part_url in book_info.parts:
677                 try:
678                     children.append(Book.objects.get(slug=part_url.slug))
679                 except Book.DoesNotExist:
680                     raise Book.DoesNotExist('Książka "%s" nie istnieje.' % part_url.slug)
681
682         # Read book metadata
683         book_slug = book_info.url.slug
684         if re.search(r'[^a-z0-9-]', book_slug):
685             raise ValueError('Invalid characters in slug')
686         book, created = Book.objects.get_or_create(slug=book_slug)
687
688         if created:
689             book_shelves = []
690             old_cover = None
691             book.preview = bool(days)
692             if book.preview:
693                 book.preview_until = date.today() + timedelta(days)
694         else:
695             if not overwrite:
696                 raise Book.AlreadyExists('Książka %s już istnieje' % book_slug)
697             # Save shelves for this book
698             book_shelves = list(book.tags.filter(category='set'))
699             old_cover = book.cover_info()
700
701         # Save XML file
702         book.xml_file.save('%s.xml' % book.slug, raw_file, save=False)
703         if book.preview:
704             book.xml_file.set_readable(False)
705
706         book.findable = findable
707         book.language = book_info.language
708         book.title = book_info.title
709         book.license = book_info.license or ''
710         if book_info.variant_of:
711             book.common_slug = book_info.variant_of.slug
712         else:
713             book.common_slug = book.slug
714         extra = book_info.to_dict()
715         if logo:
716             extra['logo'] = logo
717         if logo_mono:
718             extra['logo_mono'] = logo_mono
719         if logo_alt:
720             extra['logo_alt'] = logo_alt
721         if can_sell is not None:
722             book.can_sell = can_sell
723         if isbn_mp3 is not None:
724             book.isbn_mp3 = isbn_mp3
725         book.extra_info = json.dumps(extra)
726         book.load_abstract()
727         book.load_toc()
728         book.save()
729
730         book.update_stats()
731         
732         meta_tags = Tag.tags_from_info(book_info)
733
734         just_tags = [t for (t, rel) in meta_tags if not rel]
735         book.tags = set(just_tags + book_shelves)
736         book.save()  # update sort_key_author
737
738         book.translators.set([t for (t, rel) in meta_tags if rel == 'translator'])
739
740         cover_changed = old_cover != book.cover_info()
741         obsolete_children = set(b for b in book.children.all()
742                                 if b not in children)
743         notify_cover_changed = []
744         for n, child_book in enumerate(children):
745             new_child = child_book.parent != book
746             child_book.parent = book
747             child_book.parent_number = n
748             child_book.save()
749             if new_child or cover_changed:
750                 notify_cover_changed.append(child_book)
751         # Disown unfaithful children and let them cope on their own.
752         for child in obsolete_children:
753             child.parent = None
754             child.parent_number = 0
755             child.save()
756             if old_cover:
757                 notify_cover_changed.append(child)
758
759         cls.repopulate_ancestors()
760         tasks.update_counters.delay()
761
762         if remote_gallery_url:
763             book.download_pictures(remote_gallery_url)
764
765         # No saves beyond this point.
766
767         # Build cover.
768         if 'cover' not in dont_build:
769             book.cover.build_delay()
770
771         # Build HTML and ebooks.
772         book.html_file.build_delay()
773         if not children:
774             for format_ in constants.EBOOK_FORMATS_WITHOUT_CHILDREN:
775                 if format_ not in dont_build:
776                     getattr(book, '%s_file' % format_).build_delay()
777         for format_ in constants.EBOOK_FORMATS_WITH_CHILDREN:
778             if format_ not in dont_build:
779                 getattr(book, '%s_file' % format_).build_delay()
780         if 'html_nonotes' not in dont_build:
781             book.html_nonotes_file.build_delay()
782
783         if not settings.NO_SEARCH_INDEX and search_index and findable:
784             tasks.index_book.delay(book.id)
785
786         for child in notify_cover_changed:
787             child.parent_cover_changed()
788
789         book.update_popularity()
790         if 'references' not in dont_build:
791             tasks.update_references.delay(book.id)
792
793         cls.published.send(sender=cls, instance=book)
794         return book
795
796     def update_stats(self):
797         stats = self.wldocument2().get_statistics()['total']
798         self.pages = round(
799             stats.get('verses_with_fn', 0) / 30 +
800             stats.get('chars_out_verse_with_fn', 0) / 1800)
801         self.read_time = round(self.get_time())
802         self.save(update_fields=['pages', 'read_time'])
803         if self.parent is not None:
804             self.parent.update_stats()
805
806     def update_references(self):
807         Entity = apps.get_model('references', 'Entity')
808         doc = self.wldocument2()
809         doc._compat_assign_section_ids()
810         doc._compat_assign_ordered_ids()
811         refs = {}
812         for ref_elem in doc.references():
813             uri = ref_elem.attrib.get('href', '')
814             if not uri:
815                 continue
816             if uri in refs:
817                 ref = refs[uri]
818             else:
819                 entity, entity_created = Entity.objects.get_or_create(uri=uri)
820                 if entity_created:
821                     try:
822                         entity.populate()
823                     except:
824                         pass
825                     else:
826                         entity.save()
827                 ref, ref_created = entity.reference_set.get_or_create(book=self)
828                 refs[uri] = ref
829                 if not ref_created:
830                     ref.occurence_set.all().delete()
831             sec = ref_elem.get_link()
832             m = re.match(r'sec(\d+)', sec)
833             assert m is not None
834             sec = int(m.group(1))
835             snippet = ref_elem.get_snippet()
836             b = builders['html-snippet']()
837             for s in snippet:
838                 s.html_build(b)
839             html = b.output().get_bytes().decode('utf-8')
840
841             ref.occurence_set.create(
842                 section=sec,
843                 html=html
844             )
845         self.reference_set.exclude(entity__uri__in=refs).delete()
846
847     @property
848     def references(self):
849         return self.reference_set.all().select_related('entity')
850
851     def update_has_audio(self):
852         self.has_audio = False
853         if self.media.filter(type='mp3').exists():
854             self.has_audio = True
855         if self.descendant.filter(has_audio=True).exists():
856             self.has_audio = True
857         self.save(update_fields=['has_audio'])
858         if self.parent is not None:
859             self.parent.update_has_audio()
860
861     def update_narrators(self):
862         narrator_names = set()
863         for bm in self.media.filter(type='mp3'):
864             artist = bm.artist
865             if artist:
866                 narrator_names.update(set(
867                     a.strip() for a in re.split(r',|\si\s', artist)
868                 ))
869         narrators = []
870
871         for name in narrator_names:
872             if not name: continue
873             slug = slugify(name)
874             try:
875                 t = Tag.objects.get(category='author', slug=slug)
876             except Tag.DoesNotExist:
877                 sort_key = sortify(
878                     ' '.join(name.rsplit(' ', 1)[::-1]).lower()
879                 )
880                 t = Tag.objects.create(
881                     category='author',
882                     name_pl=name,
883                     slug=slug,
884                     sort_key=sort_key,
885                 )
886             narrators.append(t)
887         self.narrators.set(narrators)
888
889     def update_can_sell_mp3(self):
890         ret = True
891         for child in self.get_children():
892             child.update_can_sell_mp3()
893             if not child.can_sell_mp3:
894                 ret = False
895         if self.has_mp3_file():
896             audio_items = requests.get(f'https://audio.wolnelektury.pl/archive/book/{self.slug}.json').json()['items']
897             if not all(x['project']['can_sell'] for x in audio_items):
898                 ret = False
899         self.can_sell_mp3 = ret
900         self.save(update_fields=['can_sell_mp3'])
901
902     @classmethod
903     @transaction.atomic
904     def repopulate_ancestors(cls):
905         """Fixes the ancestry cache."""
906         # TODO: table names
907         cursor = connection.cursor()
908         if connection.vendor == 'postgres':
909             cursor.execute("TRUNCATE catalogue_book_ancestor")
910             cursor.execute("""
911                 WITH RECURSIVE ancestry AS (
912                     SELECT book.id, book.parent_id
913                     FROM catalogue_book AS book
914                     WHERE book.parent_id IS NOT NULL
915                     UNION
916                     SELECT ancestor.id, book.parent_id
917                     FROM ancestry AS ancestor, catalogue_book AS book
918                     WHERE ancestor.parent_id = book.id
919                         AND book.parent_id IS NOT NULL
920                     )
921                 INSERT INTO catalogue_book_ancestor
922                     (from_book_id, to_book_id)
923                     SELECT id, parent_id
924                     FROM ancestry
925                     ORDER BY id;
926                 """)
927         else:
928             cursor.execute("DELETE FROM catalogue_book_ancestor")
929             for b in cls.objects.exclude(parent=None):
930                 parent = b.parent
931                 while parent is not None:
932                     b.ancestor.add(parent)
933                     parent = parent.parent
934
935     @property
936     def ancestors(self):
937         if self.parent:
938             for anc in self.parent.ancestors:
939                 yield anc
940             yield self.parent
941         else:
942             return []
943
944     def clear_cache(self):
945         clear_cached_renders(self.mini_box)
946         clear_cached_renders(self.mini_box_nolink)
947
948     def cover_info(self, inherit=True):
949         """Returns a dictionary to serve as fallback for BookInfo.
950
951         For now, the only thing inherited is the cover image.
952         """
953         need = False
954         info = {}
955         for field in ('cover_url', 'cover_by', 'cover_source'):
956             val = self.get_extra_info_json().get(field)
957             if val:
958                 info[field] = val
959             else:
960                 need = True
961         if inherit and need and self.parent is not None:
962             parent_info = self.parent.cover_info()
963             parent_info.update(info)
964             info = parent_info
965         return info
966
967     def related_themes(self):
968         return Tag.objects.usage_for_queryset(
969             Fragment.objects.filter(models.Q(book=self) | models.Q(book__ancestor=self)),
970             counts=True).filter(category='theme').order_by('-count')
971
972     def parent_cover_changed(self):
973         """Called when parent book's cover image is changed."""
974         if not self.cover_info(inherit=False):
975             if 'cover' not in app_settings.DONT_BUILD:
976                 self.cover.build_delay()
977             for format_ in constants.EBOOK_FORMATS_WITH_COVERS:
978                 if format_ not in app_settings.DONT_BUILD:
979                     getattr(self, '%s_file' % format_).build_delay()
980             for child in self.children.all():
981                 child.parent_cover_changed()
982
983     def other_versions(self):
984         """Find other versions (i.e. in other languages) of the book."""
985         return type(self).objects.filter(common_slug=self.common_slug, findable=True).exclude(pk=self.pk)
986
987     def parents(self):
988         books = []
989         parent = self.parent
990         while parent is not None:
991             books.insert(0, parent)
992             parent = parent.parent
993         return books
994
995     def pretty_title(self, html_links=False):
996         names = [(tag.name, tag.get_absolute_url()) for tag in self.authors().only('name', 'category', 'slug')]
997         books = self.parents() + [self]
998         names.extend([(b.title, b.get_absolute_url()) for b in books])
999
1000         if html_links:
1001             names = ['<a href="%s">%s</a>' % (tag[1], tag[0]) for tag in names]
1002         else:
1003             names = [tag[0] for tag in names]
1004         return ', '.join(names)
1005
1006     def publisher(self):
1007         publisher = self.get_extra_info_json()['publisher']
1008         if isinstance(publisher, str):
1009             return publisher
1010         elif isinstance(publisher, list):
1011             return ', '.join(publisher)
1012
1013     def get_recommended(self, limit=4):
1014         books_qs = type(self).objects.filter(findable=True)
1015         books_qs = books_qs.exclude(common_slug=self.common_slug).exclude(ancestor=self)
1016         books = type(self).tagged.related_to(self, books_qs)[:limit]
1017         return books
1018
1019     @classmethod
1020     def tagged_top_level(cls, tags):
1021         """ Returns top-level books tagged with `tags`.
1022
1023         It only returns those books which don't have ancestors which are
1024         also tagged with those tags.
1025
1026         """
1027         objects = cls.tagged.with_all(tags)
1028         return objects.filter(findable=True).exclude(ancestor__in=objects)
1029
1030     @classmethod
1031     def book_list(cls, book_filter=None):
1032         """Generates a hierarchical listing of all books.
1033
1034         Books are optionally filtered with a test function.
1035
1036         """
1037
1038         books_by_parent = {}
1039         books = cls.objects.filter(findable=True).order_by('parent_number', 'sort_key').only('title', 'parent', 'slug', 'extra_info')
1040         if book_filter:
1041             books = books.filter(book_filter).distinct()
1042
1043             book_ids = set(b['pk'] for b in books.values("pk").iterator())
1044             for book in books.iterator():
1045                 parent = book.parent_id
1046                 if parent not in book_ids:
1047                     parent = None
1048                 books_by_parent.setdefault(parent, []).append(book)
1049         else:
1050             for book in books.iterator():
1051                 books_by_parent.setdefault(book.parent_id, []).append(book)
1052
1053         orphans = []
1054         books_by_author = OrderedDict()
1055         for tag in Tag.objects.filter(category='author').iterator():
1056             books_by_author[tag] = []
1057
1058         for book in books_by_parent.get(None, ()):
1059             authors = list(book.authors().only('pk'))
1060             if authors:
1061                 for author in authors:
1062                     books_by_author[author].append(book)
1063             else:
1064                 orphans.append(book)
1065
1066         return books_by_author, orphans, books_by_parent
1067
1068     _audiences_pl = {
1069         "SP": (1, "szkoła podstawowa"),
1070         "SP1": (1, "szkoła podstawowa"),
1071         "SP2": (1, "szkoła podstawowa"),
1072         "SP3": (1, "szkoła podstawowa"),
1073         "P": (1, "szkoła podstawowa"),
1074         "G": (2, "gimnazjum"),
1075         "L": (3, "liceum"),
1076         "LP": (3, "liceum"),
1077     }
1078
1079     def audiences_pl(self):
1080         audiences = self.get_extra_info_json().get('audiences', [])
1081         audiences = sorted(set([self._audiences_pl.get(a, (99, a)) for a in audiences]))
1082         return [a[1] for a in audiences]
1083
1084     def stage_note(self):
1085         stage = self.get_extra_info_json().get('stage')
1086         if stage and stage < '0.4':
1087             return (_('Ten utwór wymaga uwspółcześnienia'),
1088                     reverse('infopage', args=['wymagajace-uwspolczesnienia']))
1089         else:
1090             return None, None
1091
1092     def choose_fragments(self, number):
1093         fragments = self.fragments.order_by()
1094         fragments_count = fragments.count()
1095         if not fragments_count and self.children.exists():
1096             fragments = Fragment.objects.filter(book__ancestor=self).order_by()
1097             fragments_count = fragments.count()
1098         if fragments_count:
1099             if fragments_count > number:
1100                 offset = randint(0, fragments_count - number)
1101             else:
1102                 offset = 0
1103             return fragments[offset : offset + number]
1104         elif self.parent:
1105             return self.parent.choose_fragments(number)
1106         else:
1107             return []
1108
1109     def choose_fragment(self):
1110         fragments = self.choose_fragments(1)
1111         if fragments:
1112             return fragments[0]
1113         else:
1114             return None
1115
1116     def fragment_data(self):
1117         fragment = self.choose_fragment()
1118         if fragment:
1119             return {
1120                 'title': fragment.book.pretty_title(),
1121                 'html': re.sub('</?blockquote[^>]*>', '', fragment.get_short_text()),
1122             }
1123         else:
1124             return None
1125
1126     def update_popularity(self):
1127         count = self.userlistitem_set.values('list__user').order_by('list__user').distinct().count()
1128         try:
1129             pop = self.popularity
1130             pop.count = count
1131             pop.save()
1132         except BookPopularity.DoesNotExist:
1133             BookPopularity.objects.create(book=self, count=count)
1134
1135     def ridero_link(self):
1136         return 'https://ridero.eu/%s/books/wl_%s/' % (get_language(), self.slug.replace('-', '_'))
1137
1138     def elevenreader_link(self):
1139         first_text = self.get_first_text()
1140         if first_text is None:
1141             return None
1142         return 'https://elevenreader.io/audiobooks/wolnelektury:' + first_text.slug
1143
1144     def content_warnings(self):
1145         warnings_def = {
1146             'wulgaryzmy': _('wulgaryzmy'),
1147         }
1148         warnings = self.get_extra_info_json().get('content_warnings', [])
1149         warnings = [
1150             warnings_def.get(w, w)
1151             for w in warnings
1152         ]
1153         warnings.sort()
1154         return warnings
1155
1156     def full_sort_key(self):
1157         return self.SORT_KEY_SEP.join((self.sort_key_author, self.sort_key, str(self.id)))
1158
1159     def cover_color(self):
1160         return WLCover.epoch_colors.get(self.get_extra_info_json().get('epoch'), '#000000')
1161
1162     @cached_render('catalogue/book_mini_box.html')
1163     def mini_box(self):
1164         return {
1165             'book': self
1166         }
1167
1168     @cached_render('catalogue/book_mini_box.html')
1169     def mini_box_nolink(self):
1170         return {
1171             'book': self,
1172             'no_link': True,
1173         }
1174
1175
1176 class BookPopularity(models.Model):
1177     book = models.OneToOneField(Book, models.CASCADE, related_name='popularity')
1178     count = models.IntegerField(default=0, db_index=True)