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