1 # -*- coding: utf-8 -*-
2 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
3 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
5 from collections import namedtuple
7 from django.db import models
8 from django.db.models import permalink, Q
10 from django.core.cache import get_cache
11 from django.core.files.storage import DefaultStorage
12 from django.utils.translation import ugettext_lazy as _
13 from django.contrib.auth.models import User
14 from django.template.loader import render_to_string
15 from django.utils.datastructures import SortedDict
16 from django.utils.safestring import mark_safe
17 from django.utils.translation import get_language
18 from django.core.urlresolvers import reverse
19 from django.db.models.signals import post_save, m2m_changed, pre_delete, post_delete
22 from django.conf import settings
24 from newtagging.models import TagBase, tags_updated
25 from newtagging import managers
26 from catalogue.fields import JSONField, OverwritingFileField
27 from catalogue.utils import create_zip, split_tags, truncate_html_words
28 from catalogue.tasks import touch_tag, index_book
29 from shutil import copy
33 from waiter.settings import WAITER_ROOT
37 # Those are hard-coded here so that makemessages sees them.
39 ('author', _('author')),
40 ('epoch', _('epoch')),
42 ('genre', _('genre')),
43 ('theme', _('theme')),
49 permanent_cache = get_cache('permanent')
52 class TagSubcategoryManager(models.Manager):
53 def __init__(self, subcategory):
54 super(TagSubcategoryManager, self).__init__()
55 self.subcategory = subcategory
57 def get_query_set(self):
58 return super(TagSubcategoryManager, self).get_query_set().filter(category=self.subcategory)
62 name = models.CharField(_('name'), max_length=50, db_index=True)
63 slug = models.SlugField(_('slug'), max_length=120, db_index=True)
64 sort_key = models.CharField(_('sort key'), max_length=120, db_index=True)
65 category = models.CharField(_('category'), max_length=50, blank=False, null=False,
66 db_index=True, choices=TAG_CATEGORIES)
67 description = models.TextField(_('description'), blank=True)
69 user = models.ForeignKey(User, blank=True, null=True)
70 book_count = models.IntegerField(_('book count'), blank=True, null=True)
71 gazeta_link = models.CharField(blank=True, max_length=240)
72 wiki_link = models.CharField(blank=True, max_length=240)
74 created_at = models.DateTimeField(_('creation date'), auto_now_add=True, db_index=True)
75 changed_at = models.DateTimeField(_('creation date'), auto_now=True, db_index=True)
77 class UrlDeprecationWarning(DeprecationWarning):
88 categories_dict = dict((item[::-1] for item in categories_rev.iteritems()))
91 ordering = ('sort_key',)
92 verbose_name = _('tag')
93 verbose_name_plural = _('tags')
94 unique_together = (("slug", "category"),)
96 def __unicode__(self):
100 return "Tag(slug=%r)" % self.slug
103 def get_absolute_url(self):
104 return ('catalogue.views.tagged_object_list', [self.url_chunk])
106 def has_description(self):
107 return len(self.description) > 0
108 has_description.short_description = _('description')
109 has_description.boolean = True
112 """Returns global book count for book tags, fragment count for themes."""
114 if self.category == 'book':
116 objects = Book.objects.none()
117 elif self.category == 'theme':
118 objects = Fragment.tagged.with_all((self,))
120 objects = Book.tagged.with_all((self,)).order_by()
121 if self.category != 'set':
122 # eliminate descendants
123 l_tags = Tag.objects.filter(slug__in=[book.book_tag_slug() for book in objects])
124 descendants_keys = [book.pk for book in Book.tagged.with_any(l_tags)]
126 objects = objects.exclude(pk__in=descendants_keys)
127 return objects.count()
130 def get_tag_list(tags):
131 if isinstance(tags, basestring):
136 tags_splitted = tags.split('/')
137 for name in tags_splitted:
139 real_tags.append(Tag.objects.get(slug=name, category=category))
141 elif name in Tag.categories_rev:
142 category = Tag.categories_rev[name]
145 real_tags.append(Tag.objects.exclude(category='book').get(slug=name))
147 except Tag.MultipleObjectsReturned, e:
148 ambiguous_slugs.append(name)
151 # something strange left off
152 raise Tag.DoesNotExist()
154 # some tags should be qualified
155 e = Tag.MultipleObjectsReturned()
157 e.ambiguous_slugs = ambiguous_slugs
160 e = Tag.UrlDeprecationWarning()
165 return TagBase.get_tag_list(tags)
169 return '/'.join((Tag.categories_dict[self.category], self.slug))
172 def tags_from_info(info):
173 from slughifi import slughifi
174 from sortify import sortify
176 categories = (('kinds', 'kind'), ('genres', 'genre'), ('authors', 'author'), ('epochs', 'epoch'))
177 for field_name, category in categories:
179 tag_names = getattr(info, field_name)
182 tag_names = [getattr(info, category)]
184 # For instance, Pictures do not have 'genre' field.
186 for tag_name in tag_names:
187 tag_sort_key = tag_name
188 if category == 'author':
189 tag_sort_key = tag_name.last_name
190 tag_name = tag_name.readable()
191 tag, created = Tag.objects.get_or_create(slug=slughifi(tag_name), category=category)
194 tag.sort_key = sortify(tag_sort_key.lower())
196 meta_tags.append(tag)
201 def get_dynamic_path(media, filename, ext=None, maxlen=100):
202 from slughifi import slughifi
204 # how to put related book's slug here?
207 ext = media.formats[media.type].ext
208 if media is None or not media.name:
209 name = slughifi(filename.split(".")[0])
211 name = slughifi(media.name)
212 return 'book/%s/%s.%s' % (ext, name[:maxlen-len('book/%s/.%s' % (ext, ext))-4], ext)
215 # TODO: why is this hard-coded ?
216 def book_upload_path(ext=None, maxlen=100):
217 return lambda *args: get_dynamic_path(*args, ext=ext, maxlen=maxlen)
220 def customizations_hash(customizations):
221 customizations.sort()
222 return hash(tuple(customizations))
225 def get_customized_pdf_path(book, customizations):
227 Returns a MEDIA_ROOT relative path for a customized pdf. The name will contain a hash of customization options.
229 h = customizations_hash(customizations)
230 pdf_name = '%s/%s-custom-%s' % (book.slug, book.slug, h)
231 pdf_file = pdf_name + '.pdf'
236 def get_existing_customized_pdf(book):
238 Returns a list of paths to generated customized pdf of a book
240 pdf_glob = path.join(WAITER_ROOT, book.slug, '*')
241 return glob(pdf_glob)
244 class BookMedia(models.Model):
245 FileFormat = namedtuple("FileFormat", "name ext")
246 formats = SortedDict([
247 ('mp3', FileFormat(name='MP3', ext='mp3')),
248 ('ogg', FileFormat(name='Ogg Vorbis', ext='ogg')),
249 ('daisy', FileFormat(name='DAISY', ext='daisy.zip')),
251 format_choices = [(k, _('%s file') % t.name)
252 for k, t in formats.items()]
254 type = models.CharField(_('type'), choices=format_choices, max_length="100")
255 name = models.CharField(_('name'), max_length="100")
256 file = OverwritingFileField(_('file'), upload_to=book_upload_path())
257 uploaded_at = models.DateTimeField(_('creation date'), auto_now_add=True, editable=False)
258 extra_info = JSONField(_('extra information'), default='{}', editable=False)
259 book = models.ForeignKey('Book', related_name='media')
260 source_sha1 = models.CharField(null=True, blank=True, max_length=40, editable=False)
262 def __unicode__(self):
263 return "%s (%s)" % (self.name, self.file.name.split("/")[-1])
266 ordering = ('type', 'name')
267 verbose_name = _('book media')
268 verbose_name_plural = _('book media')
270 def save(self, *args, **kwargs):
271 from slughifi import slughifi
272 from catalogue.utils import ExistingFile, remove_zip
275 old = BookMedia.objects.get(pk=self.pk)
276 except BookMedia.DoesNotExist, e:
279 # if name changed, change the file name, too
280 if slughifi(self.name) != slughifi(old.name):
281 self.file.save(None, ExistingFile(self.file.path), save=False, leave=True)
283 super(BookMedia, self).save(*args, **kwargs)
285 # remove the zip package for book with modified media
287 remove_zip("%s_%s" % (old.book.slug, old.type))
288 remove_zip("%s_%s" % (self.book.slug, self.type))
290 extra_info = self.get_extra_info_value()
291 extra_info.update(self.read_meta())
292 self.set_extra_info_value(extra_info)
293 self.source_sha1 = self.read_source_sha1(self.file.path, self.type)
294 return super(BookMedia, self).save(*args, **kwargs)
298 Reads some metadata from the audiobook.
301 from mutagen import id3
303 artist_name = director_name = project = funded_by = ''
304 if self.type == 'mp3':
306 audio = id3.ID3(self.file.path)
307 artist_name = ', '.join(', '.join(tag.text) for tag in audio.getall('TPE1'))
308 director_name = ', '.join(', '.join(tag.text) for tag in audio.getall('TPE3'))
309 project = ", ".join([t.data for t in audio.getall('PRIV')
310 if t.owner=='wolnelektury.pl?project'])
311 funded_by = ", ".join([t.data for t in audio.getall('PRIV')
312 if t.owner=='wolnelektury.pl?funded_by'])
315 elif self.type == 'ogg':
317 audio = mutagen.File(self.file.path)
318 artist_name = ', '.join(audio.get('artist', []))
319 director_name = ', '.join(audio.get('conductor', []))
320 project = ", ".join(audio.get('project', []))
321 funded_by = ", ".join(audio.get('funded_by', []))
326 return {'artist_name': artist_name, 'director_name': director_name,
327 'project': project, 'funded_by': funded_by}
330 def read_source_sha1(filepath, filetype):
332 Reads source file SHA1 from audiobok metadata.
335 from mutagen import id3
337 if filetype == 'mp3':
339 audio = id3.ID3(filepath)
340 return [t.data for t in audio.getall('PRIV')
341 if t.owner=='wolnelektury.pl?flac_sha1'][0]
344 elif filetype == 'ogg':
346 audio = mutagen.File(filepath)
347 return audio.get('flac_sha1', [None])[0]
354 class Book(models.Model):
355 title = models.CharField(_('title'), max_length=120)
356 sort_key = models.CharField(_('sort key'), max_length=120, db_index=True, editable=False)
357 slug = models.SlugField(_('slug'), max_length=120, db_index=True,
359 common_slug = models.SlugField(_('slug'), max_length=120, db_index=True)
360 language = models.CharField(_('language code'), max_length=3, db_index=True,
361 default=settings.CATALOGUE_DEFAULT_LANGUAGE)
362 description = models.TextField(_('description'), blank=True)
363 created_at = models.DateTimeField(_('creation date'), auto_now_add=True, db_index=True)
364 changed_at = models.DateTimeField(_('creation date'), auto_now=True, db_index=True)
365 parent_number = models.IntegerField(_('parent number'), default=0)
366 extra_info = JSONField(_('extra information'), default='{}')
367 gazeta_link = models.CharField(blank=True, max_length=240)
368 wiki_link = models.CharField(blank=True, max_length=240)
369 # files generated during publication
371 cover = models.FileField(_('cover'), upload_to=book_upload_path('png'),
372 null=True, blank=True)
373 ebook_formats = ['pdf', 'epub', 'mobi', 'txt']
374 formats = ebook_formats + ['html', 'xml']
376 parent = models.ForeignKey('self', blank=True, null=True, related_name='children')
378 _related_info = jsonfield.JSONField(blank=True, null=True, editable=False)
380 objects = models.Manager()
381 tagged = managers.ModelTaggedItemManager(Tag)
382 tags = managers.TagDescriptor(Tag)
384 html_built = django.dispatch.Signal()
385 published = django.dispatch.Signal()
387 class AlreadyExists(Exception):
391 ordering = ('sort_key',)
392 verbose_name = _('book')
393 verbose_name_plural = _('books')
395 def __unicode__(self):
398 def save(self, force_insert=False, force_update=False, reset_short_html=True, **kwargs):
399 from sortify import sortify
401 self.sort_key = sortify(self.title)
403 ret = super(Book, self).save(force_insert, force_update)
406 self.reset_short_html()
411 def get_absolute_url(self):
412 return ('catalogue.views.book_detail', [self.slug])
418 def book_tag_slug(self):
419 return ('l-' + self.slug)[:120]
422 slug = self.book_tag_slug()
423 book_tag, created = Tag.objects.get_or_create(slug=slug, category='book')
425 book_tag.name = self.title[:50]
426 book_tag.sort_key = self.title.lower()
430 def has_media(self, type):
431 if type in Book.formats:
432 return bool(getattr(self, "%s_file" % type))
434 return self.media.filter(type=type).exists()
436 def get_media(self, type):
437 if self.has_media(type):
438 if type in Book.formats:
439 return getattr(self, "%s_file" % type)
441 return self.media.filter(type=type)
446 return self.get_media("mp3")
448 return self.get_media("odt")
450 return self.get_media("ogg")
452 return self.get_media("daisy")
454 def reset_short_html(self):
458 type(self).objects.filter(pk=self.pk).update(_related_info=None)
459 # Fragment.short_html relies on book's tags, so reset it here too
460 for fragm in self.fragments.all():
461 fragm.reset_short_html()
463 def has_description(self):
464 return len(self.description) > 0
465 has_description.short_description = _('description')
466 has_description.boolean = True
469 def has_mp3_file(self):
470 return bool(self.has_media("mp3"))
471 has_mp3_file.short_description = 'MP3'
472 has_mp3_file.boolean = True
474 def has_ogg_file(self):
475 return bool(self.has_media("ogg"))
476 has_ogg_file.short_description = 'OGG'
477 has_ogg_file.boolean = True
479 def has_daisy_file(self):
480 return bool(self.has_media("daisy"))
481 has_daisy_file.short_description = 'DAISY'
482 has_daisy_file.boolean = True
484 def wldocument(self, parse_dublincore=True):
485 from catalogue.import_utils import ORMDocProvider
486 from librarian.parser import WLDocument
488 return WLDocument.from_file(self.xml_file.path,
489 provider=ORMDocProvider(self),
490 parse_dublincore=parse_dublincore)
492 def build_cover(self, book_info=None):
493 """(Re)builds the cover image."""
494 from StringIO import StringIO
495 from django.core.files.base import ContentFile
496 from librarian.cover import WLCover
498 if book_info is None:
499 book_info = self.wldocument().book_info
501 cover = WLCover(book_info).image()
503 cover.save(imgstr, 'png')
504 self.cover.save(None, ContentFile(imgstr.getvalue()))
506 def build_pdf(self, customizations=None, file_name=None):
507 """ (Re)builds the pdf file.
508 customizations - customizations which are passed to LaTeX class file.
509 file_name - save the pdf file under a different name and DO NOT save it in db.
511 from os import unlink
512 from django.core.files import File
513 from catalogue.utils import remove_zip
515 pdf = self.wldocument().as_pdf(customizations=customizations,
516 morefloats=settings.LIBRARIAN_PDF_MOREFLOATS)
518 if file_name is None:
519 # we'd like to be sure not to overwrite changes happening while
520 # (timely) pdf generation is taking place (async celery scenario)
521 current_self = Book.objects.get(id=self.id)
522 current_self.pdf_file.save('%s.pdf' % self.slug,
523 File(open(pdf.get_filename())))
524 self.pdf_file = current_self.pdf_file
526 # remove cached downloadables
527 remove_zip(settings.ALL_PDF_ZIP)
529 for customized_pdf in get_existing_customized_pdf(self):
530 unlink(customized_pdf)
532 print "saving %s" % file_name
533 print "to: %s" % DefaultStorage().path(file_name)
534 DefaultStorage().save(file_name, File(open(pdf.get_filename())))
536 def build_mobi(self):
537 """ (Re)builds the MOBI file.
540 from django.core.files import File
541 from catalogue.utils import remove_zip
543 mobi = self.wldocument().as_mobi()
545 self.mobi_file.save('%s.mobi' % self.slug, File(open(mobi.get_filename())))
547 # remove zip with all mobi files
548 remove_zip(settings.ALL_MOBI_ZIP)
550 def build_epub(self):
551 """(Re)builds the epub file."""
552 from django.core.files import File
553 from catalogue.utils import remove_zip
555 epub = self.wldocument().as_epub()
557 self.epub_file.save('%s.epub' % self.slug,
558 File(open(epub.get_filename())))
560 # remove zip package with all epub files
561 remove_zip(settings.ALL_EPUB_ZIP)
564 from django.core.files.base import ContentFile
566 text = self.wldocument().as_text()
567 self.txt_file.save('%s.txt' % self.slug, ContentFile(text.get_string()))
570 def build_html(self):
571 from django.core.files.base import ContentFile
572 from slughifi import slughifi
573 from librarian import html
575 meta_tags = list(self.tags.filter(
576 category__in=('author', 'epoch', 'genre', 'kind')))
577 book_tag = self.book_tag()
579 html_output = self.wldocument(parse_dublincore=False).as_html()
581 self.html_file.save('%s.html' % self.slug,
582 ContentFile(html_output.get_string()))
584 # get ancestor l-tags for adding to new fragments
588 ancestor_tags.append(p.book_tag())
591 # Delete old fragments and create them from scratch
592 self.fragments.all().delete()
594 closed_fragments, open_fragments = html.extract_fragments(self.html_file.path)
595 for fragment in closed_fragments.values():
597 theme_names = [s.strip() for s in fragment.themes.split(',')]
598 except AttributeError:
601 for theme_name in theme_names:
604 tag, created = Tag.objects.get_or_create(slug=slughifi(theme_name), category='theme')
606 tag.name = theme_name
607 tag.sort_key = theme_name.lower()
613 text = fragment.to_string()
614 short_text = truncate_html_words(text, 15)
615 if text == short_text:
617 new_fragment = Fragment.objects.create(anchor=fragment.id, book=self,
618 text=text, short_text=short_text)
621 new_fragment.tags = set(meta_tags + themes + [book_tag] + ancestor_tags)
623 self.html_built.send(sender=self)
628 def zip_format(format_):
629 def pretty_file_name(book):
630 return "%s/%s.%s" % (
631 b.get_extra_info_value()['author'],
635 field_name = "%s_file" % format_
636 books = Book.objects.filter(parent=None).exclude(**{field_name: ""})
637 paths = [(pretty_file_name(b), getattr(b, field_name).path)
639 result = create_zip.delay(paths,
640 getattr(settings, "ALL_%s_ZIP" % format_.upper()))
643 def zip_audiobooks(self, format_):
644 bm = BookMedia.objects.filter(book=self, type=format_)
645 paths = map(lambda bm: (None, bm.file.path), bm)
646 result = create_zip.delay(paths, "%s_%s" % (self.slug, format_))
649 def search_index(self, book_info=None, reuse_index=False, index_tags=True):
651 idx = search.ReusableIndex()
657 idx.index_book(self, book_info)
664 def from_xml_file(cls, xml_file, **kwargs):
665 from django.core.files import File
666 from librarian import dcparser
668 # use librarian to parse meta-data
669 book_info = dcparser.parse(xml_file)
671 if not isinstance(xml_file, File):
672 xml_file = File(open(xml_file))
675 return cls.from_text_and_meta(xml_file, book_info, **kwargs)
680 def from_text_and_meta(cls, raw_file, book_info, overwrite=False,
681 build_epub=True, build_txt=True, build_pdf=True, build_mobi=True,
682 search_index=True, search_index_tags=True, search_index_reuse=False):
684 from sortify import sortify
686 # check for parts before we do anything
688 if hasattr(book_info, 'parts'):
689 for part_url in book_info.parts:
691 children.append(Book.objects.get(slug=part_url.slug))
692 except Book.DoesNotExist, e:
693 raise Book.DoesNotExist(_('Book "%s" does not exist.') %
698 book_slug = book_info.url.slug
699 if re.search(r'[^a-z0-9-]', book_slug):
700 raise ValueError('Invalid characters in slug')
701 book, created = Book.objects.get_or_create(slug=book_slug)
707 raise Book.AlreadyExists(_('Book %s already exists') % (
709 # Save shelves for this book
710 book_shelves = list(book.tags.filter(category='set'))
712 book.language = book_info.language
713 book.title = book_info.title
714 if book_info.variant_of:
715 book.common_slug = book_info.variant_of.slug
717 book.common_slug = book.slug
718 book.set_extra_info_value(book_info.to_dict())
721 meta_tags = Tag.tags_from_info(book_info)
723 book.tags = set(meta_tags + book_shelves)
725 book_tag = book.book_tag()
727 for n, child_book in enumerate(children):
728 child_book.parent = book
729 child_book.parent_number = n
732 # Save XML and HTML files
733 book.xml_file.save('%s.xml' % book.slug, raw_file, save=False)
735 # delete old fragments when overwriting
736 book.fragments.all().delete()
738 if book.build_html():
739 if not settings.NO_BUILD_TXT and build_txt:
742 book.build_cover(book_info)
744 if not settings.NO_BUILD_EPUB and build_epub:
747 if not settings.NO_BUILD_PDF and build_pdf:
750 if not settings.NO_BUILD_MOBI and build_mobi:
753 if not settings.NO_SEARCH_INDEX and search_index:
754 book.search_index(index_tags=search_index_tags, reuse_index=search_index_reuse)
755 #index_book.delay(book.id, book_info)
757 book_descendants = list(book.children.all())
758 descendants_tags = set()
759 # add l-tag to descendants and their fragments
760 while len(book_descendants) > 0:
761 child_book = book_descendants.pop(0)
762 descendants_tags.update(child_book.tags)
763 child_book.tags = list(child_book.tags) + [book_tag]
765 for fragment in child_book.fragments.all():
766 fragment.tags = set(list(fragment.tags) + [book_tag])
767 book_descendants += list(child_book.children.all())
769 for tag in descendants_tags:
775 book.reset_tag_counter()
776 book.reset_theme_counter()
778 cls.published.send(sender=book)
781 def related_info(self):
782 """Keeps info about related objects (tags, media) in cache field."""
783 if self._related_info is not None:
784 return self._related_info
786 rel = {'tags': {}, 'media': {}}
788 tags = self.tags.filter(category__in=(
789 'author', 'kind', 'genre', 'epoch'))
790 tags = split_tags(tags)
791 for category in tags:
792 rel['tags'][category] = [
793 (t.name, t.slug) for t in tags[category]]
795 for media_format in BookMedia.formats:
796 rel['media'][media_format] = self.has_media(media_format)
801 parents.append((book.parent.title, book.parent.slug))
803 parents = parents[::-1]
805 rel['parents'] = parents
808 type(self).objects.filter(pk=self.pk).update(_related_info=rel)
811 def reset_tag_counter(self):
815 cache_key = "Book.tag_counter/%d" % self.id
816 permanent_cache.delete(cache_key)
818 self.parent.reset_tag_counter()
821 def tag_counter(self):
823 cache_key = "Book.tag_counter/%d" % self.id
824 tags = permanent_cache.get(cache_key)
830 for child in self.children.all().order_by():
831 for tag_pk, value in child.tag_counter.iteritems():
832 tags[tag_pk] = tags.get(tag_pk, 0) + value
833 for tag in self.tags.exclude(category__in=('book', 'theme', 'set')).order_by():
837 permanent_cache.set(cache_key, tags)
840 def reset_theme_counter(self):
844 cache_key = "Book.theme_counter/%d" % self.id
845 permanent_cache.delete(cache_key)
847 self.parent.reset_theme_counter()
850 def theme_counter(self):
852 cache_key = "Book.theme_counter/%d" % self.id
853 tags = permanent_cache.get(cache_key)
859 for fragment in Fragment.tagged.with_any([self.book_tag()]).order_by():
860 for tag in fragment.tags.filter(category='theme').order_by():
861 tags[tag.pk] = tags.get(tag.pk, 0) + 1
864 permanent_cache.set(cache_key, tags)
867 def pretty_title(self, html_links=False):
869 names = list(book.tags.filter(category='author'))
875 names.extend(reversed(books))
878 names = ['<a href="%s">%s</a>' % (tag.get_absolute_url(), tag.name) for tag in names]
880 names = [tag.name for tag in names]
882 return ', '.join(names)
885 def tagged_top_level(cls, tags):
886 """ Returns top-level books tagged with `tags'.
888 It only returns those books which don't have ancestors which are
889 also tagged with those tags.
892 # get relevant books and their tags
893 objects = cls.tagged.with_all(tags)
894 # eliminate descendants
895 l_tags = Tag.objects.filter(category='book', slug__in=[book.book_tag_slug() for book in objects])
896 descendants_keys = [book.pk for book in cls.tagged.with_any(l_tags)]
898 objects = objects.exclude(pk__in=descendants_keys)
903 def book_list(cls, filter=None):
904 """Generates a hierarchical listing of all books.
906 Books are optionally filtered with a test function.
911 books = cls.objects.all().order_by('parent_number', 'sort_key').only(
912 'title', 'parent', 'slug')
914 books = books.filter(filter).distinct()
915 book_ids = set((book.pk for book in books))
917 parent = book.parent_id
918 if parent not in book_ids:
920 books_by_parent.setdefault(parent, []).append(book)
923 books_by_parent.setdefault(book.parent_id, []).append(book)
926 books_by_author = SortedDict()
927 for tag in Tag.objects.filter(category='author'):
928 books_by_author[tag] = []
930 for book in books_by_parent.get(None,()):
931 authors = list(book.tags.filter(category='author'))
933 for author in authors:
934 books_by_author[author].append(book)
938 return books_by_author, orphans, books_by_parent
941 "SP1": (1, u"szkoła podstawowa"),
942 "SP2": (1, u"szkoła podstawowa"),
943 "P": (1, u"szkoła podstawowa"),
944 "G": (2, u"gimnazjum"),
946 "LP": (3, u"liceum"),
948 def audiences_pl(self):
949 audiences = self.get_extra_info_value().get('audiences', [])
950 audiences = sorted(set([self._audiences_pl[a] for a in audiences]))
951 return [a[1] for a in audiences]
953 def choose_fragment(self):
954 tag = self.book_tag()
955 fragments = Fragment.tagged.with_any([tag])
956 if fragments.exists():
957 return fragments.order_by('?')[0]
959 return self.parent.choose_fragment()
964 def _has_factory(ftype):
965 has = lambda self: bool(getattr(self, "%s_file" % ftype))
966 has.short_description = t.upper()
968 has.__name__ = "has_%s_file" % ftype
972 # add the file fields
973 for t in Book.formats:
974 field_name = "%s_file" % t
975 models.FileField(_("%s file" % t.upper()),
976 upload_to=book_upload_path(t),
977 blank=True).contribute_to_class(Book, field_name)
979 setattr(Book, "has_%s_file" % t, _has_factory(t))
982 class Fragment(models.Model):
983 text = models.TextField()
984 short_text = models.TextField(editable=False)
985 anchor = models.CharField(max_length=120)
986 book = models.ForeignKey(Book, related_name='fragments')
988 objects = models.Manager()
989 tagged = managers.ModelTaggedItemManager(Tag)
990 tags = managers.TagDescriptor(Tag)
993 ordering = ('book', 'anchor',)
994 verbose_name = _('fragment')
995 verbose_name_plural = _('fragments')
997 def get_absolute_url(self):
998 return '%s#m%s' % (reverse('book_text', args=[self.book.slug]), self.anchor)
1000 def reset_short_html(self):
1004 cache_key = "Fragment.short_html/%d/%s"
1005 for lang, langname in settings.LANGUAGES:
1006 permanent_cache.delete(cache_key % (self.id, lang))
1008 def get_short_text(self):
1009 """Returns short version of the fragment."""
1010 return self.short_text if self.short_text else self.text
1012 def short_html(self):
1014 cache_key = "Fragment.short_html/%d/%s" % (self.id, get_language())
1015 short_html = permanent_cache.get(cache_key)
1019 if short_html is not None:
1020 return mark_safe(short_html)
1022 short_html = unicode(render_to_string('catalogue/fragment_short.html',
1023 {'fragment': self}))
1025 permanent_cache.set(cache_key, short_html)
1026 return mark_safe(short_html)
1029 class Collection(models.Model):
1030 """A collection of books, which might be defined before publishing them."""
1031 title = models.CharField(_('title'), max_length=120, db_index=True)
1032 slug = models.SlugField(_('slug'), max_length=120, primary_key=True)
1033 description = models.TextField(_('description'), null=True, blank=True)
1035 models.SlugField(_('slug'), max_length=120, unique=True, db_index=True)
1036 book_slugs = models.TextField(_('book slugs'))
1039 ordering = ('title',)
1040 verbose_name = _('collection')
1041 verbose_name_plural = _('collections')
1043 def __unicode__(self):
1054 def _tags_updated_handler(sender, affected_tags, **kwargs):
1055 # reset tag global counter
1056 # we want Tag.changed_at updated for API to know the tag was touched
1057 for tag in affected_tags:
1060 # if book tags changed, reset book tag counter
1061 if isinstance(sender, Book) and \
1062 Tag.objects.filter(pk__in=(tag.pk for tag in affected_tags)).\
1063 exclude(category__in=('book', 'theme', 'set')).count():
1064 sender.reset_tag_counter()
1065 # if fragment theme changed, reset book theme counter
1066 elif isinstance(sender, Fragment) and \
1067 Tag.objects.filter(pk__in=(tag.pk for tag in affected_tags)).\
1068 filter(category='theme').count():
1069 sender.book.reset_theme_counter()
1070 tags_updated.connect(_tags_updated_handler)
1073 def _pre_delete_handler(sender, instance, **kwargs):
1074 """ refresh Book on BookMedia delete """
1075 if sender == BookMedia:
1076 instance.book.save()
1077 pre_delete.connect(_pre_delete_handler)
1080 def _post_save_handler(sender, instance, **kwargs):
1081 """ refresh all the short_html stuff on BookMedia update """
1082 if sender == BookMedia:
1083 instance.book.save()
1084 post_save.connect(_post_save_handler)
1087 @django.dispatch.receiver(post_delete, sender=Book)
1088 def _remove_book_from_index_handler(sender, instance, **kwargs):
1089 """ remove the book from search index, when it is deleted."""
1090 idx = search.Index()
1091 idx.open(timeout=10000) # 10 seconds timeout.
1093 idx.remove_book(instance)