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.
4 from collections import OrderedDict
6 from datetime import date, timedelta
7 from random import randint
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
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
37 return storages['book']
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)
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)
81 ebook_formats = constants.EBOOK_FORMATS
82 formats = ebook_formats + ['html', 'xml', 'html_nonotes']
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)
87 cached_author = models.CharField(blank=True, max_length=240, db_index=True)
88 has_audience = models.BooleanField(default=False)
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)
100 html_built = django.dispatch.Signal()
101 published = django.dispatch.Signal()
107 class AlreadyExists(Exception):
111 ordering = ('sort_key_author', 'sort_key')
112 verbose_name = 'książka'
113 verbose_name_plural = 'książki'
114 app_label = 'catalogue'
119 def get_extra_info_json(self):
120 return json.loads(self.extra_info or '{}')
122 def get_initial(self):
124 return re.search(r'\w', self.title, re.U).group(0)
125 except AttributeError:
129 return self.tags.filter(category='author')
132 return self.tags.filter(category='epoch')
135 return self.tags.filter(category='genre')
138 return self.tags.filter(category='kind')
140 def tag_unicode(self, category):
141 relations = prefetched_relations(self, category)
143 return ', '.join(rel.tag.name for rel in relations)
145 return ', '.join(self.tags.filter(category=category).values_list('name', flat=True))
147 def tags_by_category(self):
148 return split_tags(self.tags.exclude(category__in=('set', 'theme')))
150 def author_unicode(self):
151 return self.cached_author
153 def kind_unicode(self):
154 return self.tag_unicode('kind')
156 def epoch_unicode(self):
157 return self.tag_unicode('epoch')
159 def genre_unicode(self):
160 return self.tag_unicode('genre')
162 def translator(self):
163 translators = self.get_extra_info_json().get('translators')
166 if len(translators) > 3:
167 translators = translators[:2]
171 return ', '.join('\xa0'.join(reversed(translator.split(', ', 1))) for translator in translators) + others
173 def cover_source(self):
174 return self.get_extra_info_json().get('cover_source', self.parent.cover_source() if self.parent else '')
178 return self.get_extra_info_json().get('isbn_pdf')
182 return self.get_extra_info_json().get('isbn_epub')
186 return self.get_extra_info_json().get('isbn_mobi')
190 return self.get_extra_info_json().get('about')
192 def is_accessible_to(self, user):
195 if not user.is_authenticated:
197 Membership = apps.get_model('club', 'Membership')
198 if Membership.is_active_for(user):
200 Funding = apps.get_model('funding', 'Funding')
201 if Funding.objects.filter(user=user, offer__book=self):
205 def save(self, force_insert=False, force_update=False, **kwargs):
206 from sortify import sortify
208 self.sort_key = sortify(self.title)[:120]
209 self.title = str(self.title) # ???
212 author = self.authors().first().sort_key
213 except AttributeError:
215 self.sort_key_author = author
217 self.cached_author = self.tag_unicode('author')
218 self.has_audience = 'audience' in self.get_extra_info_json()
220 if self.preview and not self.preview_key:
221 self.preview_key = get_random_hash(self.slug)[:32]
223 ret = super(Book, self).save(
224 force_insert=force_insert, force_update=force_update, **kwargs)
228 def get_absolute_url(self):
229 return reverse('book_detail', args=[self.slug])
231 def gallery_path(self):
232 return gallery_path(self.slug)
234 def gallery_url(self):
235 return gallery_url(self.slug)
237 def get_first_text(self):
240 child = self.children.all().order_by('parent_number').first()
241 if child is not None:
242 return child.get_first_text()
244 def get_last_text(self):
247 child = self.children.all().order_by('parent_number').last()
248 if child is not None:
249 return child.get_last_text()
251 def get_prev_text(self):
254 sibling = self.parent.children.filter(parent_number__lt=self.parent_number).order_by('-parent_number').first()
255 if sibling is not None:
256 return sibling.get_last_text()
258 if self.parent.html_file:
261 return self.parent.get_prev_text()
263 def get_next_text(self, inside=True):
265 child = self.children.order_by('parent_number').first()
266 if child is not None:
267 return child.get_first_text()
271 sibling = self.parent.children.filter(parent_number__gt=self.parent_number).order_by('parent_number').first()
272 if sibling is not None:
273 return sibling.get_first_text()
274 return self.parent.get_next_text(inside=False)
276 def get_siblings(self):
279 return self.parent.children.all().order_by('parent_number')
281 def get_children(self):
282 return self.children.all().order_by('parent_number')
288 def language_code(self):
289 return constants.LANGUAGES_3TO2.get(self.language, self.language)
291 def language_name(self):
292 return dict(settings.LANGUAGES).get(self.language_code(), "")
294 def is_foreign(self):
295 return self.language_code() != settings.LANGUAGE_CODE
297 def set_audio_length(self):
298 length = self.get_audio_length()
300 self.audio_length = self.format_audio_length(length)
304 def format_audio_length(seconds):
306 >>> Book.format_audio_length(1)
308 >>> Book.format_audio_length(3661)
312 minutes = seconds // 60
313 seconds = seconds % 60
314 return '%d:%02d' % (minutes, seconds)
316 hours = seconds // 3600
317 minutes = seconds % 3600 // 60
318 seconds = seconds % 60
319 return '%d:%02d:%02d' % (hours, minutes, seconds)
321 def get_audio_length(self):
322 total = self.media.filter(type='mp3').aggregate(
323 models.Sum('duration'))['duration__sum']
324 return int(total or 0)
327 return round(self.xml_file.size / 1000 * 40)
329 def has_media(self, type_):
330 if type_ in Book.formats:
331 return bool(getattr(self, "%s_file" % type_))
333 return self.media.filter(type=type_).exists()
335 def get_media(self, type_):
336 if self.has_media(type_):
337 if type_ in Book.formats:
338 return getattr(self, "%s_file" % type_)
340 return self.media.filter(type=type_)
345 return self.get_media("mp3")
348 return self.get_media("odt")
351 return self.get_media("ogg")
354 return self.get_media("daisy")
356 def get_audio_epub(self):
357 return self.get_media("audio.epub")
359 def media_url(self, format_):
360 media = self.get_media(format_)
363 return reverse('embargo_link', kwargs={'key': self.preview_key, 'slug': self.slug, 'format_': format_})
370 return self.media_url('html')
372 def html_nonotes_url(self):
373 return self.media_url('html_nonotes')
376 return self.media_url('pdf')
379 return self.media_url('epub')
382 return self.media_url('mobi')
385 return self.media_url('txt')
388 return self.media_url('fb2')
391 return self.media_url('xml')
393 def has_description(self):
394 return len(self.description) > 0
395 has_description.short_description = 'opis'
396 has_description.boolean = True
398 def has_mp3_file(self):
399 return self.has_media("mp3")
400 has_mp3_file.short_description = 'MP3'
401 has_mp3_file.boolean = True
403 def has_ogg_file(self):
404 return self.has_media("ogg")
405 has_ogg_file.short_description = 'OGG'
406 has_ogg_file.boolean = True
408 def has_daisy_file(self):
409 return self.has_media("daisy")
410 has_daisy_file.short_description = 'DAISY'
411 has_daisy_file.boolean = True
413 def has_sync_file(self):
414 return settings.FEATURE_SYNCHRO and self.has_media("sync")
416 def build_sync_file(self):
417 from lxml import html
418 from django.core.files.base import ContentFile
419 with self.html_file.open('rb') as f:
420 h = html.fragment_fromstring(f.read().decode('utf-8'))
424 for m in self.get_audiobooks()[0]
426 if settings.MOCK_DURATIONS:
427 durations = settings.MOCK_DURATIONS
433 for elem in h.iter():
434 if elem.get('data-audio-ts'):
435 part, ts = int(elem.get('data-audio-part')), float(elem.get('data-audio-ts'))
436 ts = str(round(sum(durations[:part - 1]) + ts, 3))
437 # check if inside verse
440 # Workaround for missing ids.
441 if 'verse' in p.get('class', ''):
443 p.set('id', f'syn{sid}')
446 sync.append((ts, p.get('id')))
451 cls = elem.get('class', '')
452 # Workaround for missing ids.
453 if 'paragraph' in cls or 'verse' in cls or elem.tag in ('h1', 'h2', 'h3', 'h4'):
454 if not elem.get('id'):
455 elem.set('id', f'syn{sid}')
458 sync.append((ts, elem.get('id')))
461 htext = html.tostring(h, encoding='utf-8')
462 with open(self.html_file.path, 'wb') as f:
465 bm = self.media.get(type='sync')
467 bm = BookMedia(book=self, type='sync')
470 f'{s[0]}\t{sync[i+1][0]}\t{s[1]}' for i, s in enumerate(sync[:-1])
473 None, ContentFile(sync)
477 if not self.has_sync_file():
479 with self.get_media('sync').first().file.open('r') as f:
480 sync = f.read().split('\n')
481 offset = float(sync[0])
483 for line in sync[1:]:
486 start, end, elid = line.split()
487 items.append([elid, float(start) + offset])
490 def sync_ts(self, ts):
492 for cur_id, t in self.get_sync():
499 def sync_elid(self, elid):
500 for cur_id, t in self.get_sync():
504 def has_audio_epub_file(self):
505 return self.has_media("audio.epub")
508 def media_daisy(self):
509 return self.get_media('daisy')
512 def media_audio_epub(self):
513 return self.get_media('audio.epub')
515 def get_audiobooks(self, with_children=False, processing=False):
517 for m in self.media.filter(type='ogg').order_by().iterator():
518 ogg_files[m.name] = m
523 for mp3 in self.media.filter(type='mp3').iterator():
524 # ogg files are always from the same project
525 meta = mp3.get_extra_info_json()
526 project = meta.get('project')
529 project = 'CzytamySłuchając'
531 projects.add((project, meta.get('funded_by', '')))
532 total_duration += mp3.duration or 0
536 ogg = ogg_files.get(mp3.name)
539 audiobooks.append(media)
542 for child in self.get_children():
543 ch_audiobooks, ch_projects, ch_duration = child.get_audiobooks(
544 with_children=True, processing=True)
545 audiobooks.append({'part': child})
546 audiobooks += ch_audiobooks
547 projects.update(ch_projects)
548 total_duration += ch_duration
551 projects = sorted(projects)
552 total_duration = '%d:%02d' % (
553 total_duration // 60,
557 return audiobooks, projects, total_duration
559 def get_audiobooks_with_children(self):
560 return self.get_audiobooks(with_children=True)
562 def wldocument(self, parse_dublincore=True, inherit=True):
563 from catalogue.import_utils import ORMDocProvider
564 from librarian.parser import WLDocument
566 if inherit and self.parent:
567 meta_fallbacks = self.parent.cover_info()
569 meta_fallbacks = None
571 return WLDocument.from_file(
573 provider=ORMDocProvider(self),
574 parse_dublincore=parse_dublincore,
575 meta_fallbacks=meta_fallbacks)
577 def wldocument2(self):
578 from catalogue.import_utils import ORMDocProvider
579 from librarian.document import WLDocument
582 provider=ORMDocProvider(self)
584 doc.meta.update(self.cover_info())
589 def zip_format(format_):
590 def pretty_file_name(book):
591 return "%s/%s.%s" % (
592 book.get_extra_info_json()['author'],
596 field_name = "%s_file" % format_
597 field = getattr(Book, field_name)
598 books = Book.objects.filter(parent=None).exclude(**{field_name: ""}).exclude(preview=True).exclude(findable=False)
599 paths = [(pretty_file_name(b), getattr(b, field_name).path) for b in books.iterator()]
600 return create_zip(paths, field.ZIP)
602 def search_index(self, index=None):
603 if not self.findable:
605 from search.index import Index
606 Index.index_book(self)
608 # will make problems in conjunction with paid previews
609 def download_pictures(self, remote_gallery_url):
610 # This is only needed for legacy relative image paths.
611 gallery_path = self.gallery_path()
612 # delete previous files, so we don't include old files in ebooks
613 if os.path.isdir(gallery_path):
614 for filename in os.listdir(gallery_path):
615 file_path = os.path.join(gallery_path, filename)
617 ilustr_elements = list(self.wldocument().edoc.findall('.//ilustr'))
619 makedirs(gallery_path)
620 for ilustr in ilustr_elements:
621 ilustr_src = ilustr.get('src')
622 if '/' in ilustr_src:
624 ilustr_path = os.path.join(gallery_path, ilustr_src)
625 urlretrieve('%s/%s' % (remote_gallery_url, ilustr_src), ilustr_path)
627 def load_abstract(self):
628 abstract = self.wldocument(parse_dublincore=False).edoc.getroot().find('.//abstrakt')
629 if abstract is not None:
630 self.abstract = transform_abstrakt(abstract)
637 parser = html.HTMLParser(encoding='utf-8')
638 tree = html.parse(self.html_file.path, parser=parser)
639 toc = tree.find('.//div[@id="toc"]/ol')
640 if toc is None or not len(toc):
642 html_link = reverse('book_text', args=[self.slug])
643 for a in toc.findall('.//a'):
644 a.attrib['href'] = html_link + a.attrib['href']
645 self.toc = html.tostring(toc, encoding='unicode')
649 def from_xml_file(cls, xml_file, **kwargs):
650 from django.core.files import File
651 from librarian import dcparser
653 # use librarian to parse meta-data
654 book_info = dcparser.parse(xml_file)
656 if not isinstance(xml_file, File):
657 xml_file = File(open(xml_file))
660 return cls.from_text_and_meta(xml_file, book_info, **kwargs)
665 def from_text_and_meta(cls, raw_file, book_info, overwrite=False, dont_build=None, search_index=True,
666 remote_gallery_url=None, days=0, findable=True, logo=None, logo_mono=None, logo_alt=None, can_sell=None, isbn_mp3=None):
667 from catalogue import tasks
669 if dont_build is None:
671 dont_build = set.union(set(dont_build), set(app_settings.DONT_BUILD))
673 # check for parts before we do anything
675 if hasattr(book_info, 'parts'):
676 for part_url in book_info.parts:
678 children.append(Book.objects.get(slug=part_url.slug))
679 except Book.DoesNotExist:
680 raise Book.DoesNotExist('Książka "%s" nie istnieje.' % part_url.slug)
683 book_slug = book_info.url.slug
684 if re.search(r'[^a-z0-9-]', book_slug):
685 raise ValueError('Invalid characters in slug')
686 book, created = Book.objects.get_or_create(slug=book_slug)
691 book.preview = bool(days)
693 book.preview_until = date.today() + timedelta(days)
696 raise Book.AlreadyExists('Książka %s już istnieje' % book_slug)
697 # Save shelves for this book
698 book_shelves = list(book.tags.filter(category='set'))
699 old_cover = book.cover_info()
702 book.xml_file.save('%s.xml' % book.slug, raw_file, save=False)
704 book.xml_file.set_readable(False)
706 book.findable = findable
707 book.language = book_info.language
708 book.title = book_info.title
709 book.license = book_info.license or ''
710 if book_info.variant_of:
711 book.common_slug = book_info.variant_of.slug
713 book.common_slug = book.slug
714 extra = book_info.to_dict()
718 extra['logo_mono'] = logo_mono
720 extra['logo_alt'] = logo_alt
721 if can_sell is not None:
722 book.can_sell = can_sell
723 if isbn_mp3 is not None:
724 book.isbn_mp3 = isbn_mp3
725 book.extra_info = json.dumps(extra)
732 meta_tags = Tag.tags_from_info(book_info)
734 just_tags = [t for (t, rel) in meta_tags if not rel]
735 book.tags = set(just_tags + book_shelves)
736 book.save() # update sort_key_author
738 book.translators.set([t for (t, rel) in meta_tags if rel == 'translator'])
740 cover_changed = old_cover != book.cover_info()
741 obsolete_children = set(b for b in book.children.all()
742 if b not in children)
743 notify_cover_changed = []
744 for n, child_book in enumerate(children):
745 new_child = child_book.parent != book
746 child_book.parent = book
747 child_book.parent_number = n
749 if new_child or cover_changed:
750 notify_cover_changed.append(child_book)
751 # Disown unfaithful children and let them cope on their own.
752 for child in obsolete_children:
754 child.parent_number = 0
757 notify_cover_changed.append(child)
759 cls.repopulate_ancestors()
760 tasks.update_counters.delay()
762 if remote_gallery_url:
763 book.download_pictures(remote_gallery_url)
765 # No saves beyond this point.
768 if 'cover' not in dont_build:
769 book.cover.build_delay()
771 # Build HTML and ebooks.
772 book.html_file.build_delay()
774 for format_ in constants.EBOOK_FORMATS_WITHOUT_CHILDREN:
775 if format_ not in dont_build:
776 getattr(book, '%s_file' % format_).build_delay()
777 for format_ in constants.EBOOK_FORMATS_WITH_CHILDREN:
778 if format_ not in dont_build:
779 getattr(book, '%s_file' % format_).build_delay()
780 if 'html_nonotes' not in dont_build:
781 book.html_nonotes_file.build_delay()
783 if not settings.NO_SEARCH_INDEX and search_index and findable:
784 tasks.index_book.delay(book.id)
786 for child in notify_cover_changed:
787 child.parent_cover_changed()
789 book.update_popularity()
790 if 'references' not in dont_build:
791 tasks.update_references.delay(book.id)
793 cls.published.send(sender=cls, instance=book)
796 def update_stats(self):
797 stats = self.wldocument2().get_statistics()['total']
799 stats.get('verses_with_fn', 0) / 30 +
800 stats.get('chars_out_verse_with_fn', 0) / 1800)
801 self.read_time = round(self.get_time())
802 self.save(update_fields=['pages', 'read_time'])
803 if self.parent is not None:
804 self.parent.update_stats()
806 def update_references(self):
807 Entity = apps.get_model('references', 'Entity')
808 doc = self.wldocument2()
809 doc._compat_assign_section_ids()
810 doc._compat_assign_ordered_ids()
812 for ref_elem in doc.references():
813 uri = ref_elem.attrib.get('href', '')
819 entity, entity_created = Entity.objects.get_or_create(uri=uri)
827 ref, ref_created = entity.reference_set.get_or_create(book=self)
830 ref.occurence_set.all().delete()
831 sec = ref_elem.get_link()
832 m = re.match(r'sec(\d+)', sec)
834 sec = int(m.group(1))
835 snippet = ref_elem.get_snippet()
836 b = builders['html-snippet']()
839 html = b.output().get_bytes().decode('utf-8')
841 ref.occurence_set.create(
845 self.reference_set.exclude(entity__uri__in=refs).delete()
848 def references(self):
849 return self.reference_set.all().select_related('entity')
851 def update_has_audio(self):
852 self.has_audio = False
853 if self.media.filter(type='mp3').exists():
854 self.has_audio = True
855 if self.descendant.filter(has_audio=True).exists():
856 self.has_audio = True
857 self.save(update_fields=['has_audio'])
858 if self.parent is not None:
859 self.parent.update_has_audio()
861 def update_narrators(self):
862 narrator_names = set()
863 for bm in self.media.filter(type='mp3'):
866 narrator_names.update(set(
867 a.strip() for a in re.split(r',|\si\s', artist)
871 for name in narrator_names:
872 if not name: continue
875 t = Tag.objects.get(category='author', slug=slug)
876 except Tag.DoesNotExist:
878 ' '.join(name.rsplit(' ', 1)[::-1]).lower()
880 t = Tag.objects.create(
887 self.narrators.set(narrators)
889 def update_can_sell_mp3(self):
891 for child in self.get_children():
892 child.update_can_sell_mp3()
893 if not child.can_sell_mp3:
895 if self.has_mp3_file():
896 audio_items = requests.get(f'https://audio.wolnelektury.pl/archive/book/{self.slug}.json').json()['items']
897 if not all(x['project']['can_sell'] for x in audio_items):
899 self.can_sell_mp3 = ret
900 self.save(update_fields=['can_sell_mp3'])
904 def repopulate_ancestors(cls):
905 """Fixes the ancestry cache."""
907 cursor = connection.cursor()
908 if connection.vendor == 'postgres':
909 cursor.execute("TRUNCATE catalogue_book_ancestor")
911 WITH RECURSIVE ancestry AS (
912 SELECT book.id, book.parent_id
913 FROM catalogue_book AS book
914 WHERE book.parent_id IS NOT NULL
916 SELECT ancestor.id, book.parent_id
917 FROM ancestry AS ancestor, catalogue_book AS book
918 WHERE ancestor.parent_id = book.id
919 AND book.parent_id IS NOT NULL
921 INSERT INTO catalogue_book_ancestor
922 (from_book_id, to_book_id)
928 cursor.execute("DELETE FROM catalogue_book_ancestor")
929 for b in cls.objects.exclude(parent=None):
931 while parent is not None:
932 b.ancestor.add(parent)
933 parent = parent.parent
938 for anc in self.parent.ancestors:
944 def clear_cache(self):
945 clear_cached_renders(self.mini_box)
946 clear_cached_renders(self.mini_box_nolink)
948 def cover_info(self, inherit=True):
949 """Returns a dictionary to serve as fallback for BookInfo.
951 For now, the only thing inherited is the cover image.
955 for field in ('cover_url', 'cover_by', 'cover_source'):
956 val = self.get_extra_info_json().get(field)
961 if inherit and need and self.parent is not None:
962 parent_info = self.parent.cover_info()
963 parent_info.update(info)
967 def related_themes(self):
968 return Tag.objects.usage_for_queryset(
969 Fragment.objects.filter(models.Q(book=self) | models.Q(book__ancestor=self)),
970 counts=True).filter(category='theme').order_by('-count')
972 def parent_cover_changed(self):
973 """Called when parent book's cover image is changed."""
974 if not self.cover_info(inherit=False):
975 if 'cover' not in app_settings.DONT_BUILD:
976 self.cover.build_delay()
977 for format_ in constants.EBOOK_FORMATS_WITH_COVERS:
978 if format_ not in app_settings.DONT_BUILD:
979 getattr(self, '%s_file' % format_).build_delay()
980 for child in self.children.all():
981 child.parent_cover_changed()
983 def other_versions(self):
984 """Find other versions (i.e. in other languages) of the book."""
985 return type(self).objects.filter(common_slug=self.common_slug, findable=True).exclude(pk=self.pk)
990 while parent is not None:
991 books.insert(0, parent)
992 parent = parent.parent
995 def pretty_title(self, html_links=False):
996 names = [(tag.name, tag.get_absolute_url()) for tag in self.authors().only('name', 'category', 'slug')]
997 books = self.parents() + [self]
998 names.extend([(b.title, b.get_absolute_url()) for b in books])
1001 names = ['<a href="%s">%s</a>' % (tag[1], tag[0]) for tag in names]
1003 names = [tag[0] for tag in names]
1004 return ', '.join(names)
1006 def publisher(self):
1007 publisher = self.get_extra_info_json()['publisher']
1008 if isinstance(publisher, str):
1010 elif isinstance(publisher, list):
1011 return ', '.join(publisher)
1013 def get_recommended(self, limit=4):
1014 books_qs = type(self).objects.filter(findable=True)
1015 books_qs = books_qs.exclude(common_slug=self.common_slug).exclude(ancestor=self)
1016 books = type(self).tagged.related_to(self, books_qs)[:limit]
1020 def tagged_top_level(cls, tags):
1021 """ Returns top-level books tagged with `tags`.
1023 It only returns those books which don't have ancestors which are
1024 also tagged with those tags.
1027 objects = cls.tagged.with_all(tags)
1028 return objects.filter(findable=True).exclude(ancestor__in=objects)
1031 def book_list(cls, book_filter=None):
1032 """Generates a hierarchical listing of all books.
1034 Books are optionally filtered with a test function.
1038 books_by_parent = {}
1039 books = cls.objects.filter(findable=True).order_by('parent_number', 'sort_key').only('title', 'parent', 'slug', 'extra_info')
1041 books = books.filter(book_filter).distinct()
1043 book_ids = set(b['pk'] for b in books.values("pk").iterator())
1044 for book in books.iterator():
1045 parent = book.parent_id
1046 if parent not in book_ids:
1048 books_by_parent.setdefault(parent, []).append(book)
1050 for book in books.iterator():
1051 books_by_parent.setdefault(book.parent_id, []).append(book)
1054 books_by_author = OrderedDict()
1055 for tag in Tag.objects.filter(category='author').iterator():
1056 books_by_author[tag] = []
1058 for book in books_by_parent.get(None, ()):
1059 authors = list(book.authors().only('pk'))
1061 for author in authors:
1062 books_by_author[author].append(book)
1064 orphans.append(book)
1066 return books_by_author, orphans, books_by_parent
1069 "SP": (1, "szkoła podstawowa"),
1070 "SP1": (1, "szkoła podstawowa"),
1071 "SP2": (1, "szkoła podstawowa"),
1072 "SP3": (1, "szkoła podstawowa"),
1073 "P": (1, "szkoła podstawowa"),
1074 "G": (2, "gimnazjum"),
1076 "LP": (3, "liceum"),
1079 def audiences_pl(self):
1080 audiences = self.get_extra_info_json().get('audiences', [])
1081 audiences = sorted(set([self._audiences_pl.get(a, (99, a)) for a in audiences]))
1082 return [a[1] for a in audiences]
1084 def stage_note(self):
1085 stage = self.get_extra_info_json().get('stage')
1086 if stage and stage < '0.4':
1087 return (_('Ten utwór wymaga uwspółcześnienia'),
1088 reverse('infopage', args=['wymagajace-uwspolczesnienia']))
1092 def choose_fragments(self, number):
1093 fragments = self.fragments.order_by()
1094 fragments_count = fragments.count()
1095 if not fragments_count and self.children.exists():
1096 fragments = Fragment.objects.filter(book__ancestor=self).order_by()
1097 fragments_count = fragments.count()
1099 if fragments_count > number:
1100 offset = randint(0, fragments_count - number)
1103 return fragments[offset : offset + number]
1105 return self.parent.choose_fragments(number)
1109 def choose_fragment(self):
1110 fragments = self.choose_fragments(1)
1116 def fragment_data(self):
1117 fragment = self.choose_fragment()
1120 'title': fragment.book.pretty_title(),
1121 'html': re.sub('</?blockquote[^>]*>', '', fragment.get_short_text()),
1126 def update_popularity(self):
1127 count = self.userlistitem_set.values('list__user').order_by('list__user').distinct().count()
1129 pop = self.popularity
1132 except BookPopularity.DoesNotExist:
1133 BookPopularity.objects.create(book=self, count=count)
1135 def ridero_link(self):
1136 return 'https://ridero.eu/%s/books/wl_%s/' % (get_language(), self.slug.replace('-', '_'))
1138 def elevenreader_link(self):
1139 first_text = self.get_first_text()
1140 if first_text is None:
1142 return 'https://elevenreader.io/audiobooks/wolnelektury:' + first_text.slug
1144 def content_warnings(self):
1146 'wulgaryzmy': _('wulgaryzmy'),
1148 warnings = self.get_extra_info_json().get('content_warnings', [])
1150 warnings_def.get(w, w)
1156 def full_sort_key(self):
1157 return self.SORT_KEY_SEP.join((self.sort_key_author, self.sort_key, str(self.id)))
1159 def cover_color(self):
1160 return WLCover.epoch_colors.get(self.get_extra_info_json().get('epoch'), '#000000')
1162 @cached_render('catalogue/book_mini_box.html')
1168 @cached_render('catalogue/book_mini_box.html')
1169 def mini_box_nolink(self):
1176 class BookPopularity(models.Model):
1177 book = models.OneToOneField(Book, models.CASCADE, related_name='popularity')
1178 count = models.IntegerField(default=0, db_index=True)