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:
216 self.sort_key_author = author
218 self.cached_author = self.tag_unicode('author')
219 self.has_audience = 'audience' in self.get_extra_info_json()
221 if self.preview and not self.preview_key:
222 self.preview_key = get_random_hash(self.slug)[:32]
224 ret = super(Book, self).save(
225 force_insert=force_insert, force_update=force_update, **kwargs)
229 def get_absolute_url(self):
230 return reverse('book_detail', args=[self.slug])
232 def gallery_path(self):
233 return gallery_path(self.slug)
235 def gallery_url(self):
236 return gallery_url(self.slug)
238 def get_first_text(self):
241 child = self.children.all().order_by('parent_number').first()
242 if child is not None:
243 return child.get_first_text()
245 def get_last_text(self):
248 child = self.children.all().order_by('parent_number').last()
249 if child is not None:
250 return child.get_last_text()
252 def get_prev_text(self):
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()
259 if self.parent.html_file:
262 return self.parent.get_prev_text()
264 def get_next_text(self, inside=True):
266 child = self.children.order_by('parent_number').first()
267 if child is not None:
268 return child.get_first_text()
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)
277 def get_siblings(self):
280 return self.parent.children.all().order_by('parent_number')
282 def get_children(self):
283 return self.children.all().order_by('parent_number')
289 def language_code(self):
290 return constants.LANGUAGES_3TO2.get(self.language, self.language)
292 def language_name(self):
293 return dict(settings.LANGUAGES).get(self.language_code(), "")
295 def is_foreign(self):
296 return self.language_code() != settings.LANGUAGE_CODE
298 def set_audio_length(self):
299 length = self.get_audio_length()
301 self.audio_length = self.format_audio_length(length)
305 def format_audio_length(seconds):
307 >>> Book.format_audio_length(1)
309 >>> Book.format_audio_length(3661)
313 minutes = seconds // 60
314 seconds = seconds % 60
315 return '%d:%02d' % (minutes, seconds)
317 hours = seconds // 3600
318 minutes = seconds % 3600 // 60
319 seconds = seconds % 60
320 return '%d:%02d:%02d' % (hours, minutes, seconds)
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)
328 return round(self.xml_file.size / 1000 * 40)
330 def has_media(self, type_):
331 if type_ in Book.formats:
332 return bool(getattr(self, "%s_file" % type_))
334 return self.media.filter(type=type_).exists()
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_)
341 return self.media.filter(type=type_)
346 return self.get_media("mp3")
349 return self.get_media("odt")
352 return self.get_media("ogg")
355 return self.get_media("daisy")
357 def get_audio_epub(self):
358 return self.get_media("audio.epub")
360 def media_url(self, format_):
361 media = self.get_media(format_)
364 return reverse('embargo_link', kwargs={'key': self.preview_key, 'slug': self.slug, 'format_': format_})
371 return self.media_url('html')
373 def html_nonotes_url(self):
374 return self.media_url('html_nonotes')
377 return self.media_url('pdf')
380 return self.media_url('epub')
383 return self.media_url('mobi')
386 return self.media_url('txt')
389 return self.media_url('fb2')
392 return self.media_url('xml')
394 def has_description(self):
395 return len(self.description) > 0
396 has_description.short_description = 'opis'
397 has_description.boolean = True
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
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
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
414 def has_sync_file(self):
415 return settings.FEATURE_SYNCHRO and self.has_media("sync")
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'))
425 for m in self.get_audiobooks()[0]
427 if settings.MOCK_DURATIONS:
428 durations = settings.MOCK_DURATIONS
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
441 # Workaround for missing ids.
442 if 'verse' in p.get('class', ''):
444 p.set('id', f'syn{sid}')
447 sync.append((ts, p.get('id')))
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}')
459 sync.append((ts, elem.get('id')))
462 htext = html.tostring(h, encoding='utf-8')
463 with open(self.html_file.path, 'wb') as f:
466 bm = self.media.get(type='sync')
468 bm = BookMedia(book=self, type='sync')
471 f'{s[0]}\t{sync[i+1][0]}\t{s[1]}' for i, s in enumerate(sync[:-1])
474 None, ContentFile(sync)
478 if not self.has_sync_file():
480 with self.get_media('sync').first().file.open('r') as f:
481 sync = f.read().split('\n')
482 offset = float(sync[0])
484 for line in sync[1:]:
487 start, end, elid = line.split()
488 items.append([elid, float(start) + offset])
491 def sync_ts(self, ts):
493 for cur_id, t in self.get_sync():
500 def sync_elid(self, elid):
501 for cur_id, t in self.get_sync():
505 def has_audio_epub_file(self):
506 return self.has_media("audio.epub")
509 def media_daisy(self):
510 return self.get_media('daisy')
513 def media_audio_epub(self):
514 return self.get_media('audio.epub')
516 def get_audiobooks(self, with_children=False, processing=False):
518 for m in self.media.filter(type='ogg').order_by().iterator():
519 ogg_files[m.name] = m
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')
530 project = 'CzytamySłuchając'
532 projects.add((project, meta.get('funded_by', '')))
533 total_duration += mp3.duration or 0
537 ogg = ogg_files.get(mp3.name)
540 audiobooks.append(media)
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
552 projects = sorted(projects)
553 total_duration = '%d:%02d' % (
554 total_duration // 60,
558 return audiobooks, projects, total_duration
560 def get_audiobooks_with_children(self):
561 return self.get_audiobooks(with_children=True)
563 def wldocument(self, parse_dublincore=True, inherit=True):
564 from catalogue.import_utils import ORMDocProvider
565 from librarian.parser import WLDocument
567 if inherit and self.parent:
568 meta_fallbacks = self.parent.cover_info()
570 meta_fallbacks = None
572 return WLDocument.from_file(
574 provider=ORMDocProvider(self),
575 parse_dublincore=parse_dublincore,
576 meta_fallbacks=meta_fallbacks)
578 def wldocument2(self):
579 from catalogue.import_utils import ORMDocProvider
580 from librarian.document import WLDocument
583 provider=ORMDocProvider(self)
585 doc.meta.update(self.cover_info())
590 def zip_format(format_):
591 def pretty_file_name(book):
592 return "%s/%s.%s" % (
593 book.get_extra_info_json()['author'],
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)
603 def search_index(self, index=None):
604 if not self.findable:
606 from search.index import Index
607 Index.index_book(self)
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)
618 ilustr_elements = list(self.wldocument().edoc.findall('.//ilustr'))
620 makedirs(gallery_path)
621 for ilustr in ilustr_elements:
622 ilustr_src = ilustr.get('src')
623 if '/' in ilustr_src:
625 ilustr_path = os.path.join(gallery_path, ilustr_src)
626 urlretrieve('%s/%s' % (remote_gallery_url, ilustr_src), ilustr_path)
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)
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):
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')
650 def from_xml_file(cls, xml_file, **kwargs):
651 from django.core.files import File
652 from librarian import dcparser
654 # use librarian to parse meta-data
655 book_info = dcparser.parse(xml_file)
657 if not isinstance(xml_file, File):
658 xml_file = File(open(xml_file))
661 return cls.from_text_and_meta(xml_file, book_info, **kwargs)
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
670 if dont_build is None:
672 dont_build = set.union(set(dont_build), set(app_settings.DONT_BUILD))
674 # check for parts before we do anything
676 if hasattr(book_info, 'parts'):
677 for part_url in book_info.parts:
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)
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)
692 book.preview = bool(days)
694 book.preview_until = date.today() + timedelta(days)
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()
703 book.xml_file.save('%s.xml' % book.slug, raw_file, save=False)
705 book.xml_file.set_readable(False)
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
714 book.common_slug = book.slug
715 extra = book_info.to_dict()
719 extra['logo_mono'] = logo_mono
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)
733 meta_tags = Tag.tags_from_info(book_info)
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
739 book.translators.set([t for (t, rel) in meta_tags if rel == 'translator'])
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
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:
755 child.parent_number = 0
758 notify_cover_changed.append(child)
760 cls.repopulate_ancestors()
761 tasks.update_counters.delay()
763 if remote_gallery_url:
764 book.download_pictures(remote_gallery_url)
766 # No saves beyond this point.
769 if 'cover' not in dont_build:
770 book.cover.build_delay()
772 # Build HTML and ebooks.
773 book.html_file.build_delay()
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()
784 if not settings.NO_SEARCH_INDEX and search_index and findable:
785 tasks.index_book.delay(book.id)
787 for child in notify_cover_changed:
788 child.parent_cover_changed()
790 book.update_popularity()
791 if 'references' not in dont_build:
792 tasks.update_references.delay(book.id)
794 cls.published.send(sender=cls, instance=book)
797 def update_stats(self):
798 stats = self.wldocument2().get_statistics()['total']
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()
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()
813 for ref_elem in doc.references():
814 uri = ref_elem.attrib.get('href', '')
820 entity, entity_created = Entity.objects.get_or_create(uri=uri)
828 ref, ref_created = entity.reference_set.get_or_create(book=self)
831 ref.occurence_set.all().delete()
832 sec = ref_elem.get_link()
833 m = re.match(r'sec(\d+)', sec)
835 sec = int(m.group(1))
836 snippet = ref_elem.get_snippet()
837 b = builders['html-snippet']()
840 html = b.output().get_bytes().decode('utf-8')
842 ref.occurence_set.create(
846 self.reference_set.exclude(entity__uri__in=refs).delete()
849 def references(self):
850 return self.reference_set.all().select_related('entity')
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()
862 def update_narrators(self):
863 narrator_names = set()
864 for bm in self.media.filter(type='mp3'):
867 narrator_names.update(set(
868 a.strip() for a in re.split(r',|\si\s', artist)
872 for name in narrator_names:
873 if not name: continue
876 t = Tag.objects.get(category='author', slug=slug)
877 except Tag.DoesNotExist:
879 ' '.join(name.rsplit(' ', 1)[::-1]).lower()
881 t = Tag.objects.create(
888 self.narrators.set(narrators)
890 def update_can_sell_mp3(self):
892 for child in self.get_children():
893 child.update_can_sell_mp3()
894 if not child.can_sell_mp3:
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):
900 self.can_sell_mp3 = ret
901 self.save(update_fields=['can_sell_mp3'])
905 def repopulate_ancestors(cls):
906 """Fixes the ancestry cache."""
908 cursor = connection.cursor()
909 if connection.vendor == 'postgres':
910 cursor.execute("TRUNCATE catalogue_book_ancestor")
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
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
922 INSERT INTO catalogue_book_ancestor
923 (from_book_id, to_book_id)
929 cursor.execute("DELETE FROM catalogue_book_ancestor")
930 for b in cls.objects.exclude(parent=None):
932 while parent is not None:
933 b.ancestor.add(parent)
934 parent = parent.parent
939 for anc in self.parent.ancestors:
945 def clear_cache(self):
946 clear_cached_renders(self.mini_box)
947 clear_cached_renders(self.mini_box_nolink)
949 def cover_info(self, inherit=True):
950 """Returns a dictionary to serve as fallback for BookInfo.
952 For now, the only thing inherited is the cover image.
956 for field in ('cover_url', 'cover_by', 'cover_source'):
957 val = self.get_extra_info_json().get(field)
962 if inherit and need and self.parent is not None:
963 parent_info = self.parent.cover_info()
964 parent_info.update(info)
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')
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()
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)
991 while parent is not None:
992 books.insert(0, parent)
993 parent = parent.parent
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])
1002 names = ['<a href="%s">%s</a>' % (tag[1], tag[0]) for tag in names]
1004 names = [tag[0] for tag in names]
1005 return ', '.join(names)
1007 def publisher(self):
1008 publisher = self.get_extra_info_json()['publisher']
1009 if isinstance(publisher, str):
1011 elif isinstance(publisher, list):
1012 return ', '.join(publisher)
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]
1021 def tagged_top_level(cls, tags):
1022 """ Returns top-level books tagged with `tags`.
1024 It only returns those books which don't have ancestors which are
1025 also tagged with those tags.
1028 objects = cls.tagged.with_all(tags)
1029 return objects.filter(findable=True).exclude(ancestor__in=objects)
1032 def book_list(cls, book_filter=None):
1033 """Generates a hierarchical listing of all books.
1035 Books are optionally filtered with a test function.
1039 books_by_parent = {}
1040 books = cls.objects.filter(findable=True).order_by('parent_number', 'sort_key').only('title', 'parent', 'slug', 'extra_info')
1042 books = books.filter(book_filter).distinct()
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:
1049 books_by_parent.setdefault(parent, []).append(book)
1051 for book in books.iterator():
1052 books_by_parent.setdefault(book.parent_id, []).append(book)
1055 books_by_author = OrderedDict()
1056 for tag in Tag.objects.filter(category='author').iterator():
1057 books_by_author[tag] = []
1059 for book in books_by_parent.get(None, ()):
1060 authors = list(book.authors().only('pk'))
1062 for author in authors:
1063 books_by_author[author].append(book)
1065 orphans.append(book)
1067 return books_by_author, orphans, books_by_parent
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"),
1077 "LP": (3, "liceum"),
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]
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']))
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()
1100 if fragments_count > number:
1101 offset = randint(0, fragments_count - number)
1104 return fragments[offset : offset + number]
1106 return self.parent.choose_fragments(number)
1110 def choose_fragment(self):
1111 fragments = self.choose_fragments(1)
1117 def fragment_data(self):
1118 fragment = self.choose_fragment()
1121 'title': fragment.book.pretty_title(),
1122 'html': re.sub('</?blockquote[^>]*>', '', fragment.get_short_text()),
1127 def update_popularity(self):
1128 count = self.userlistitem_set.values('list__user').order_by('list__user').distinct().count()
1130 pop = self.popularity
1133 except BookPopularity.DoesNotExist:
1134 BookPopularity.objects.create(book=self, count=count)
1136 def ridero_link(self):
1137 return 'https://ridero.eu/%s/books/wl_%s/' % (get_language(), self.slug.replace('-', '_'))
1139 def elevenreader_link(self):
1140 first_text = self.get_first_text()
1141 if first_text is None:
1143 return 'https://elevenreader.io/audiobooks/wolnelektury:' + first_text.slug
1145 def content_warnings(self):
1147 'wulgaryzmy': _('wulgaryzmy'),
1149 warnings = self.get_extra_info_json().get('content_warnings', [])
1151 warnings_def.get(w, w)
1157 def full_sort_key(self):
1158 return self.SORT_KEY_SEP.join((self.sort_key_author, self.sort_key, str(self.id)))
1160 def cover_color(self):
1161 return WLCover.epoch_colors.get(self.get_extra_info_json().get('epoch'), '#000000')
1163 @cached_render('catalogue/book_mini_box.html')
1169 @cached_render('catalogue/book_mini_box.html')
1170 def mini_box_nolink(self):
1177 class BookPopularity(models.Model):
1178 book = models.OneToOneField(Book, models.CASCADE, related_name='popularity')
1179 count = models.IntegerField(default=0, db_index=True)