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