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 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
21 from django.conf import settings
23 from newtagging.models import TagBase, tags_updated
24 from newtagging import managers
25 from catalogue.fields import JSONField, OverwritingFileField
26 from catalogue.utils import create_zip
27 from catalogue.tasks import touch_tag
28 from shutil import copy
35 ('author', _('author')),
36 ('epoch', _('epoch')),
38 ('genre', _('genre')),
39 ('theme', _('theme')),
44 # not quite, but Django wants you to set a timeout
45 CACHE_FOREVER = 2419200 # 28 days
48 class TagSubcategoryManager(models.Manager):
49 def __init__(self, subcategory):
50 super(TagSubcategoryManager, self).__init__()
51 self.subcategory = subcategory
53 def get_query_set(self):
54 return super(TagSubcategoryManager, self).get_query_set().filter(category=self.subcategory)
58 name = models.CharField(_('name'), max_length=50, db_index=True)
59 slug = models.SlugField(_('slug'), max_length=120, db_index=True)
60 sort_key = models.CharField(_('sort key'), max_length=120, db_index=True)
61 category = models.CharField(_('category'), max_length=50, blank=False, null=False,
62 db_index=True, choices=TAG_CATEGORIES)
63 description = models.TextField(_('description'), blank=True)
65 user = models.ForeignKey(User, blank=True, null=True)
66 book_count = models.IntegerField(_('book count'), blank=True, null=True)
67 gazeta_link = models.CharField(blank=True, max_length=240)
68 wiki_link = models.CharField(blank=True, max_length=240)
70 created_at = models.DateTimeField(_('creation date'), auto_now_add=True, db_index=True)
71 changed_at = models.DateTimeField(_('creation date'), auto_now=True, db_index=True)
73 class UrlDeprecationWarning(DeprecationWarning):
84 categories_dict = dict((item[::-1] for item in categories_rev.iteritems()))
87 ordering = ('sort_key',)
88 verbose_name = _('tag')
89 verbose_name_plural = _('tags')
90 unique_together = (("slug", "category"),)
92 def __unicode__(self):
96 return "Tag(slug=%r)" % self.slug
99 def get_absolute_url(self):
100 return ('catalogue.views.tagged_object_list', [self.url_chunk])
102 def has_description(self):
103 return len(self.description) > 0
104 has_description.short_description = _('description')
105 has_description.boolean = True
108 """Returns global book count for book tags, fragment count for themes."""
110 if self.category == 'book':
112 objects = Book.objects.none()
113 elif self.category == 'theme':
114 objects = Fragment.tagged.with_all((self,))
116 objects = Book.tagged.with_all((self,)).order_by()
117 if self.category != 'set':
118 # eliminate descendants
119 l_tags = Tag.objects.filter(slug__in=[book.book_tag_slug() for book in objects])
120 descendants_keys = [book.pk for book in Book.tagged.with_any(l_tags)]
122 objects = objects.exclude(pk__in=descendants_keys)
123 return objects.count()
126 def get_tag_list(tags):
127 if isinstance(tags, basestring):
132 tags_splitted = tags.split('/')
133 for name in tags_splitted:
135 real_tags.append(Tag.objects.get(slug=name, category=category))
137 elif name in Tag.categories_rev:
138 category = Tag.categories_rev[name]
141 real_tags.append(Tag.objects.exclude(category='book').get(slug=name))
143 except Tag.MultipleObjectsReturned, e:
144 ambiguous_slugs.append(name)
147 # something strange left off
148 raise Tag.DoesNotExist()
150 # some tags should be qualified
151 e = Tag.MultipleObjectsReturned()
153 e.ambiguous_slugs = ambiguous_slugs
156 e = Tag.UrlDeprecationWarning()
161 return TagBase.get_tag_list(tags)
165 return '/'.join((Tag.categories_dict[self.category], self.slug))
168 def tags_from_info(info):
169 from slughifi import slughifi
170 from sortify import sortify
172 categories = (('kinds', 'kind'), ('genres', 'genre'), ('authors', 'author'), ('epochs', 'epoch'))
173 for field_name, category in categories:
175 tag_names = getattr(info, field_name)
178 tag_names = [getattr(info, category)]
180 # For instance, Pictures do not have 'genre' field.
182 for tag_name in tag_names:
183 tag_sort_key = tag_name
184 if category == 'author':
185 tag_sort_key = tag_name.last_name
186 tag_name = tag_name.readable()
187 tag, created = Tag.objects.get_or_create(slug=slughifi(tag_name), category=category)
190 tag.sort_key = sortify(tag_sort_key.lower())
192 meta_tags.append(tag)
197 def get_dynamic_path(media, filename, ext=None, maxlen=100):
198 from slughifi import slughifi
200 # how to put related book's slug here?
203 ext = media.formats[media.type].ext
204 if media is None or not media.name:
205 name = slughifi(filename.split(".")[0])
207 name = slughifi(media.name)
208 return 'book/%s/%s.%s' % (ext, name[:maxlen-len('book/%s/.%s' % (ext, ext))-4], ext)
211 # TODO: why is this hard-coded ?
212 def book_upload_path(ext=None, maxlen=100):
213 return lambda *args: get_dynamic_path(*args, ext=ext, maxlen=maxlen)
216 def get_customized_pdf_path(book, customizations):
218 Returns a MEDIA_ROOT relative path for a customized pdf. The name will contain a hash of customization options.
220 customizations.sort()
221 h = hash(tuple(customizations))
223 pdf_name = '%s-custom-%s' % (book.fileid(), h)
224 pdf_file = get_dynamic_path(None, pdf_name, ext='pdf')
229 def get_existing_customized_pdf(book):
231 Returns a list of paths to generated customized pdf of a book
233 pdf_glob = '%s-custom-' % (book.fileid(),)
234 pdf_glob = get_dynamic_path(None, pdf_glob, ext='pdf')
235 pdf_glob = re.sub(r"[.]([a-z0-9]+)$", "*.\\1", pdf_glob)
236 return glob(path.join(settings.MEDIA_ROOT, pdf_glob))
239 class BookMedia(models.Model):
240 FileFormat = namedtuple("FileFormat", "name ext")
241 formats = SortedDict([
242 ('mp3', FileFormat(name='MP3', ext='mp3')),
243 ('ogg', FileFormat(name='Ogg Vorbis', ext='ogg')),
244 ('daisy', FileFormat(name='DAISY', ext='daisy.zip')),
246 format_choices = [(k, _('%s file') % t.name)
247 for k, t in formats.items()]
249 type = models.CharField(_('type'), choices=format_choices, max_length="100")
250 name = models.CharField(_('name'), max_length="100")
251 file = OverwritingFileField(_('file'), upload_to=book_upload_path())
252 uploaded_at = models.DateTimeField(_('creation date'), auto_now_add=True, editable=False)
253 extra_info = JSONField(_('extra information'), default='{}', editable=False)
254 book = models.ForeignKey('Book', related_name='media')
255 source_sha1 = models.CharField(null=True, blank=True, max_length=40, editable=False)
257 def __unicode__(self):
258 return "%s (%s)" % (self.name, self.file.name.split("/")[-1])
261 ordering = ('type', 'name')
262 verbose_name = _('book media')
263 verbose_name_plural = _('book media')
265 def save(self, *args, **kwargs):
266 from slughifi import slughifi
267 from catalogue.utils import ExistingFile, remove_zip
270 old = BookMedia.objects.get(pk=self.pk)
271 except BookMedia.DoesNotExist, e:
274 # if name changed, change the file name, too
275 if slughifi(self.name) != slughifi(old.name):
276 self.file.save(None, ExistingFile(self.file.path), save=False, leave=True)
278 super(BookMedia, self).save(*args, **kwargs)
280 # remove the zip package for book with modified media
281 remove_zip(self.book.fileid())
283 extra_info = self.get_extra_info_value()
284 extra_info.update(self.read_meta())
285 self.set_extra_info_value(extra_info)
286 self.source_sha1 = self.read_source_sha1(self.file.path, self.type)
287 return super(BookMedia, self).save(*args, **kwargs)
291 Reads some metadata from the audiobook.
294 from mutagen import id3
296 artist_name = director_name = project = funded_by = ''
297 if self.type == 'mp3':
299 audio = id3.ID3(self.file.path)
300 artist_name = ', '.join(', '.join(tag.text) for tag in audio.getall('TPE1'))
301 director_name = ', '.join(', '.join(tag.text) for tag in audio.getall('TPE3'))
302 project = ", ".join([t.data for t in audio.getall('PRIV')
303 if t.owner=='wolnelektury.pl?project'])
304 funded_by = ", ".join([t.data for t in audio.getall('PRIV')
305 if t.owner=='wolnelektury.pl?funded_by'])
308 elif self.type == 'ogg':
310 audio = mutagen.File(self.file.path)
311 artist_name = ', '.join(audio.get('artist', []))
312 director_name = ', '.join(audio.get('conductor', []))
313 project = ", ".join(audio.get('project', []))
314 funded_by = ", ".join(audio.get('funded_by', []))
319 return {'artist_name': artist_name, 'director_name': director_name,
320 'project': project, 'funded_by': funded_by}
323 def read_source_sha1(filepath, filetype):
325 Reads source file SHA1 from audiobok metadata.
328 from mutagen import id3
330 if filetype == 'mp3':
332 audio = id3.ID3(filepath)
333 return [t.data for t in audio.getall('PRIV')
334 if t.owner=='wolnelektury.pl?flac_sha1'][0]
337 elif filetype == 'ogg':
339 audio = mutagen.File(filepath)
340 return audio.get('flac_sha1', [None])[0]
347 class Book(models.Model):
348 title = models.CharField(_('title'), max_length=120)
349 sort_key = models.CharField(_('sort key'), max_length=120, db_index=True, editable=False)
350 slug = models.SlugField(_('slug'), max_length=120, db_index=True)
351 language = models.CharField(_('language code'), max_length=3, db_index=True,
352 default=settings.CATALOGUE_DEFAULT_LANGUAGE)
353 description = models.TextField(_('description'), blank=True)
354 created_at = models.DateTimeField(_('creation date'), auto_now_add=True, db_index=True)
355 changed_at = models.DateTimeField(_('creation date'), auto_now=True, db_index=True)
356 parent_number = models.IntegerField(_('parent number'), default=0)
357 extra_info = JSONField(_('extra information'), default='{}')
358 gazeta_link = models.CharField(blank=True, max_length=240)
359 wiki_link = models.CharField(blank=True, max_length=240)
360 # files generated during publication
362 cover = models.FileField(_('cover'), upload_to=book_upload_path('png'),
363 null=True, blank=True)
364 ebook_formats = ['pdf', 'epub', 'mobi', 'txt']
365 formats = ebook_formats + ['html', 'xml']
367 parent = models.ForeignKey('self', blank=True, null=True, related_name='children')
368 objects = models.Manager()
369 tagged = managers.ModelTaggedItemManager(Tag)
370 tags = managers.TagDescriptor(Tag)
372 html_built = django.dispatch.Signal()
373 published = django.dispatch.Signal()
375 URLID_RE = r'[a-z0-9-]+(?:/[a-z]{3})?'
376 FILEID_RE = r'[a-z0-9-]+(?:_[a-z]{3})?'
378 class AlreadyExists(Exception):
382 unique_together = [['slug', 'language']]
383 ordering = ('sort_key',)
384 verbose_name = _('book')
385 verbose_name_plural = _('books')
387 def __unicode__(self):
390 def urlid(self, sep='/'):
392 if self.language != settings.CATALOGUE_DEFAULT_LANGUAGE:
393 stem += sep + self.language
397 return self.urlid('_')
400 def split_urlid(urlid, sep='/', default_lang=settings.CATALOGUE_DEFAULT_LANGUAGE):
401 """Splits a URL book id into slug and language code.
403 Returns a dictionary usable i.e. for object lookup, or None.
405 >>> Book.split_urlid("a-slug/pol", default_lang="eng")
406 {'slug': 'a-slug', 'language': 'pol'}
407 >>> Book.split_urlid("a-slug", default_lang="eng")
408 {'slug': 'a-slug', 'language': 'eng'}
409 >>> Book.split_urlid("a-slug_pol", "_", default_lang="eng")
410 {'slug': 'a-slug', 'language': 'pol'}
411 >>> Book.split_urlid("a-slug/eng", default_lang="eng")
414 parts = urlid.rsplit(sep, 1)
416 if parts[1] == default_lang:
418 return {'slug': parts[0], 'language': parts[1]}
420 return {'slug': urlid, 'language': default_lang}
423 def split_fileid(cls, fileid):
424 return cls.split_urlid(fileid, '_')
426 def save(self, force_insert=False, force_update=False, reset_short_html=True, **kwargs):
427 from sortify import sortify
429 self.sort_key = sortify(self.title)
431 ret = super(Book, self).save(force_insert, force_update)
434 self.reset_short_html()
439 def get_absolute_url(self):
440 return ('catalogue.views.book_detail', [self.urlid()])
446 def book_tag_slug(self):
447 stem = 'l-' + self.slug
448 if self.language != settings.CATALOGUE_DEFAULT_LANGUAGE:
449 return stem[:116] + ' ' + self.language
454 slug = self.book_tag_slug()
455 book_tag, created = Tag.objects.get_or_create(slug=slug, category='book')
457 book_tag.name = self.title[:50]
458 book_tag.sort_key = self.title.lower()
462 def has_media(self, type):
463 if type in Book.formats:
464 return bool(getattr(self, "%s_file" % type))
466 return self.media.filter(type=type).exists()
468 def get_media(self, type):
469 if self.has_media(type):
470 if type in Book.formats:
471 return getattr(self, "%s_file" % type)
473 return self.media.filter(type=type)
478 return self.get_media("mp3")
480 return self.get_media("odt")
482 return self.get_media("ogg")
484 return self.get_media("daisy")
486 def reset_short_html(self):
490 cache_key = "Book.short_html/%d/%s"
491 for lang, langname in settings.LANGUAGES:
492 cache.delete(cache_key % (self.id, lang))
493 # Fragment.short_html relies on book's tags, so reset it here too
494 for fragm in self.fragments.all():
495 fragm.reset_short_html()
497 def short_html(self):
499 cache_key = "Book.short_html/%d/%s" % (self.id, get_language())
500 short_html = cache.get(cache_key)
504 if short_html is not None:
505 return mark_safe(short_html)
507 tags = self.tags.filter(~Q(category__in=('set', 'theme', 'book')))
508 tags = [mark_safe(u'<a href="%s">%s</a>' % (tag.get_absolute_url(), tag.name)) for tag in tags]
511 # files generated during publication
512 if self.has_media("html"):
513 formats.append(u'<a href="%s">%s</a>' % (reverse('book_text', args=[self.fileid()]), _('Read online')))
514 for ebook_format in self.ebook_formats:
515 if self.has_media(ebook_format):
516 formats.append(u'<a href="%s">%s</a>' % (
517 self.get_media(ebook_format).url,
521 for m in self.media.order_by('type'):
522 formats.append(u'<a href="%s">%s</a>' % (m.file.url, m.type.upper()))
524 formats = [mark_safe(format) for format in formats]
526 short_html = unicode(render_to_string('catalogue/book_short.html',
527 {'book': self, 'tags': tags, 'formats': formats}))
530 cache.set(cache_key, short_html, CACHE_FOREVER)
531 return mark_safe(short_html)
535 cache_key = "Book.mini_boxs/%d" % (self.id, )
536 short_html = cache.get(cache_key)
540 if short_html is None:
541 authors = self.tags.filter(category='author')
543 short_html = unicode(render_to_string('catalogue/book_mini_box.html',
544 {'book': self, 'authors': authors, 'STATIC_URL': settings.STATIC_URL}))
547 cache.set(cache_key, short_html, CACHE_FOREVER)
548 return mark_safe(short_html)
550 def has_description(self):
551 return len(self.description) > 0
552 has_description.short_description = _('description')
553 has_description.boolean = True
556 def has_mp3_file(self):
557 return bool(self.has_media("mp3"))
558 has_mp3_file.short_description = 'MP3'
559 has_mp3_file.boolean = True
561 def has_ogg_file(self):
562 return bool(self.has_media("ogg"))
563 has_ogg_file.short_description = 'OGG'
564 has_ogg_file.boolean = True
566 def has_daisy_file(self):
567 return bool(self.has_media("daisy"))
568 has_daisy_file.short_description = 'DAISY'
569 has_daisy_file.boolean = True
571 def wldocument(self, parse_dublincore=True):
572 from catalogue.utils import ORMDocProvider
573 from librarian.parser import WLDocument
575 return WLDocument.from_file(self.xml_file.path,
576 provider=ORMDocProvider(self),
577 parse_dublincore=parse_dublincore)
579 def build_cover(self, book_info=None):
580 """(Re)builds the cover image."""
581 from StringIO import StringIO
582 from django.core.files.base import ContentFile
583 from librarian.cover import WLCover
585 if book_info is None:
586 book_info = self.wldocument().book_info
588 cover = WLCover(book_info).image()
590 cover.save(imgstr, 'png')
591 self.cover.save(None, ContentFile(imgstr.getvalue()))
593 def build_pdf(self, customizations=None, file_name=None):
594 """ (Re)builds the pdf file.
595 customizations - customizations which are passed to LaTeX class file.
596 file_name - save the pdf file under a different name and DO NOT save it in db.
598 from os import unlink
599 from django.core.files import File
600 from catalogue.utils import remove_zip
602 pdf = self.wldocument().as_pdf(customizations=customizations)
604 if file_name is None:
605 # we'd like to be sure not to overwrite changes happening while
606 # (timely) pdf generation is taking place (async celery scenario)
607 current_self = Book.objects.get(id=self.id)
608 current_self.pdf_file.save('%s.pdf' % self.fileid(),
609 File(open(pdf.get_filename())))
610 self.pdf_file = current_self.pdf_file
612 # remove cached downloadables
613 remove_zip(settings.ALL_PDF_ZIP)
615 for customized_pdf in get_existing_customized_pdf(self):
616 unlink(customized_pdf)
618 print "saving %s" % file_name
619 print "to: %s" % DefaultStorage().path(file_name)
620 DefaultStorage().save(file_name, File(open(pdf.get_filename())))
622 def build_mobi(self):
623 """ (Re)builds the MOBI file.
626 from django.core.files import File
627 from catalogue.utils import remove_zip
629 mobi = self.wldocument().as_mobi()
631 self.mobi_file.save('%s.mobi' % self.fileid(), File(open(mobi.get_filename())))
633 # remove zip with all mobi files
634 remove_zip(settings.ALL_MOBI_ZIP)
636 def build_epub(self):
637 """(Re)builds the epub file."""
638 from django.core.files import File
639 from catalogue.utils import remove_zip
641 epub = self.wldocument().as_epub()
643 self.epub_file.save('%s.epub' % self.fileid(),
644 File(open(epub.get_filename())))
646 # remove zip package with all epub files
647 remove_zip(settings.ALL_EPUB_ZIP)
650 from django.core.files.base import ContentFile
652 text = self.wldocument().as_text()
653 self.txt_file.save('%s.txt' % self.fileid(), ContentFile(text.get_string()))
656 def build_html(self):
657 from markupstring import MarkupString
658 from django.core.files.base import ContentFile
659 from slughifi import slughifi
660 from librarian import html
662 meta_tags = list(self.tags.filter(
663 category__in=('author', 'epoch', 'genre', 'kind')))
664 book_tag = self.book_tag()
666 html_output = self.wldocument(parse_dublincore=False).as_html()
668 self.html_file.save('%s.html' % self.fileid(),
669 ContentFile(html_output.get_string()))
671 # get ancestor l-tags for adding to new fragments
675 ancestor_tags.append(p.book_tag())
678 # Delete old fragments and create them from scratch
679 self.fragments.all().delete()
681 closed_fragments, open_fragments = html.extract_fragments(self.html_file.path)
682 for fragment in closed_fragments.values():
684 theme_names = [s.strip() for s in fragment.themes.split(',')]
685 except AttributeError:
688 for theme_name in theme_names:
691 tag, created = Tag.objects.get_or_create(slug=slughifi(theme_name), category='theme')
693 tag.name = theme_name
694 tag.sort_key = theme_name.lower()
700 text = fragment.to_string()
702 if (len(MarkupString(text)) > 240):
703 short_text = unicode(MarkupString(text)[:160])
704 new_fragment = Fragment.objects.create(anchor=fragment.id, book=self,
705 text=text, short_text=short_text)
708 new_fragment.tags = set(meta_tags + themes + [book_tag] + ancestor_tags)
710 self.html_built.send(sender=self)
715 def zip_format(format_):
716 def pretty_file_name(book):
717 return "%s/%s.%s" % (
718 b.get_extra_info_value()['author'],
722 field_name = "%s_file" % format_
723 books = Book.objects.filter(parent=None).exclude(**{field_name: ""})
724 paths = [(pretty_file_name(b), getattr(b, field_name).path)
726 result = create_zip.delay(paths,
727 getattr(settings, "ALL_%s_ZIP" % format_.upper()))
730 def zip_audiobooks(self):
731 bm = BookMedia.objects.filter(book=self, type='mp3')
732 paths = map(lambda bm: (None, bm.file.path), bm)
733 result = create_zip.delay(paths, self.fileid())
737 def from_xml_file(cls, xml_file, **kwargs):
738 from django.core.files import File
739 from librarian import dcparser
741 # use librarian to parse meta-data
742 book_info = dcparser.parse(xml_file)
744 if not isinstance(xml_file, File):
745 xml_file = File(open(xml_file))
748 return cls.from_text_and_meta(xml_file, book_info, **kwargs)
753 def from_text_and_meta(cls, raw_file, book_info, overwrite=False,
754 build_epub=True, build_txt=True, build_pdf=True, build_mobi=True):
756 from sortify import sortify
758 # check for parts before we do anything
760 if hasattr(book_info, 'parts'):
761 for part_url in book_info.parts:
763 children.append(Book.objects.get(
764 slug=part_url.slug, language=part_url.language))
765 except Book.DoesNotExist, e:
766 raise Book.DoesNotExist(_('Book "%s/%s" does not exist.') %
767 (part_url.slug, part_url.language))
771 book_slug = book_info.url.slug
772 language = book_info.language
773 if re.search(r'[^a-zA-Z0-9-]', book_slug):
774 raise ValueError('Invalid characters in slug')
775 book, created = Book.objects.get_or_create(slug=book_slug, language=language)
781 raise Book.AlreadyExists(_('Book %s/%s already exists') % (
782 book_slug, language))
783 # Save shelves for this book
784 book_shelves = list(book.tags.filter(category='set'))
786 book.title = book_info.title
787 book.set_extra_info_value(book_info.to_dict())
790 meta_tags = Tag.tags_from_info(book_info)
792 book.tags = set(meta_tags + book_shelves)
794 book_tag = book.book_tag()
796 for n, child_book in enumerate(children):
797 child_book.parent = book
798 child_book.parent_number = n
801 # Save XML and HTML files
802 book.xml_file.save('%s.xml' % book.slug, raw_file, save=False)
804 # delete old fragments when overwriting
805 book.fragments.all().delete()
807 if book.build_html():
808 if not settings.NO_BUILD_TXT and build_txt:
811 book.build_cover(book_info)
813 if not settings.NO_BUILD_EPUB and build_epub:
816 if not settings.NO_BUILD_PDF and build_pdf:
819 if not settings.NO_BUILD_MOBI and build_mobi:
822 book_descendants = list(book.children.all())
823 descendants_tags = set()
824 # add l-tag to descendants and their fragments
825 while len(book_descendants) > 0:
826 child_book = book_descendants.pop(0)
827 descendants_tags.update(child_book.tags)
828 child_book.tags = list(child_book.tags) + [book_tag]
830 for fragment in child_book.fragments.all():
831 fragment.tags = set(list(fragment.tags) + [book_tag])
832 book_descendants += list(child_book.children.all())
834 for tag in descendants_tags:
840 book.reset_tag_counter()
841 book.reset_theme_counter()
843 cls.published.send(sender=book)
846 def reset_tag_counter(self):
850 cache_key = "Book.tag_counter/%d" % self.id
851 cache.delete(cache_key)
853 self.parent.reset_tag_counter()
856 def tag_counter(self):
858 cache_key = "Book.tag_counter/%d" % self.id
859 tags = cache.get(cache_key)
865 for child in self.children.all().order_by():
866 for tag_pk, value in child.tag_counter.iteritems():
867 tags[tag_pk] = tags.get(tag_pk, 0) + value
868 for tag in self.tags.exclude(category__in=('book', 'theme', 'set')).order_by():
872 cache.set(cache_key, tags, CACHE_FOREVER)
875 def reset_theme_counter(self):
879 cache_key = "Book.theme_counter/%d" % self.id
880 cache.delete(cache_key)
882 self.parent.reset_theme_counter()
885 def theme_counter(self):
887 cache_key = "Book.theme_counter/%d" % self.id
888 tags = cache.get(cache_key)
894 for fragment in Fragment.tagged.with_any([self.book_tag()]).order_by():
895 for tag in fragment.tags.filter(category='theme').order_by():
896 tags[tag.pk] = tags.get(tag.pk, 0) + 1
899 cache.set(cache_key, tags, CACHE_FOREVER)
902 def pretty_title(self, html_links=False):
904 names = list(book.tags.filter(category='author'))
910 names.extend(reversed(books))
913 names = ['<a href="%s">%s</a>' % (tag.get_absolute_url(), tag.name) for tag in names]
915 names = [tag.name for tag in names]
917 return ', '.join(names)
920 def tagged_top_level(cls, tags):
921 """ Returns top-level books tagged with `tags'.
923 It only returns those books which don't have ancestors which are
924 also tagged with those tags.
927 # get relevant books and their tags
928 objects = cls.tagged.with_all(tags)
929 # eliminate descendants
930 l_tags = Tag.objects.filter(category='book', slug__in=[book.book_tag_slug() for book in objects])
931 descendants_keys = [book.pk for book in cls.tagged.with_any(l_tags)]
933 objects = objects.exclude(pk__in=descendants_keys)
938 def book_list(cls, filter=None):
939 """Generates a hierarchical listing of all books.
941 Books are optionally filtered with a test function.
946 books = cls.objects.all().order_by('parent_number', 'sort_key').only(
947 'title', 'parent', 'slug', 'language')
949 books = books.filter(filter).distinct()
950 book_ids = set((book.pk for book in books))
952 parent = book.parent_id
953 if parent not in book_ids:
955 books_by_parent.setdefault(parent, []).append(book)
958 books_by_parent.setdefault(book.parent_id, []).append(book)
961 books_by_author = SortedDict()
962 for tag in Tag.objects.filter(category='author'):
963 books_by_author[tag] = []
965 for book in books_by_parent.get(None,()):
966 authors = list(book.tags.filter(category='author'))
968 for author in authors:
969 books_by_author[author].append(book)
973 return books_by_author, orphans, books_by_parent
976 "SP1": (1, u"szkoła podstawowa"),
977 "SP2": (1, u"szkoła podstawowa"),
978 "P": (1, u"szkoła podstawowa"),
979 "G": (2, u"gimnazjum"),
981 "LP": (3, u"liceum"),
983 def audiences_pl(self):
984 audiences = self.get_extra_info_value().get('audiences', [])
985 audiences = sorted(set([self._audiences_pl[a] for a in audiences]))
986 return [a[1] for a in audiences]
989 def _has_factory(ftype):
990 has = lambda self: bool(getattr(self, "%s_file" % ftype))
991 has.short_description = t.upper()
993 has.__name__ = "has_%s_file" % ftype
997 # add the file fields
998 for t in Book.formats:
999 field_name = "%s_file" % t
1000 models.FileField(_("%s file" % t.upper()),
1001 upload_to=book_upload_path(t),
1002 blank=True).contribute_to_class(Book, field_name)
1004 setattr(Book, "has_%s_file" % t, _has_factory(t))
1007 class Fragment(models.Model):
1008 text = models.TextField()
1009 short_text = models.TextField(editable=False)
1010 anchor = models.CharField(max_length=120)
1011 book = models.ForeignKey(Book, related_name='fragments')
1013 objects = models.Manager()
1014 tagged = managers.ModelTaggedItemManager(Tag)
1015 tags = managers.TagDescriptor(Tag)
1018 ordering = ('book', 'anchor',)
1019 verbose_name = _('fragment')
1020 verbose_name_plural = _('fragments')
1022 def get_absolute_url(self):
1023 return '%s#m%s' % (self.book.get_html_url(), self.anchor)
1025 def reset_short_html(self):
1029 cache_key = "Fragment.short_html/%d/%s"
1030 for lang, langname in settings.LANGUAGES:
1031 cache.delete(cache_key % (self.id, lang))
1033 def short_html(self):
1035 cache_key = "Fragment.short_html/%d/%s" % (self.id, get_language())
1036 short_html = cache.get(cache_key)
1040 if short_html is not None:
1041 return mark_safe(short_html)
1043 short_html = unicode(render_to_string('catalogue/fragment_short.html',
1044 {'fragment': self}))
1046 cache.set(cache_key, short_html, CACHE_FOREVER)
1047 return mark_safe(short_html)
1057 def _tags_updated_handler(sender, affected_tags, **kwargs):
1058 # reset tag global counter
1059 # we want Tag.changed_at updated for API to know the tag was touched
1060 for tag in affected_tags:
1061 touch_tag.delay(tag)
1063 # if book tags changed, reset book tag counter
1064 if isinstance(sender, Book) and \
1065 Tag.objects.filter(pk__in=(tag.pk for tag in affected_tags)).\
1066 exclude(category__in=('book', 'theme', 'set')).count():
1067 sender.reset_tag_counter()
1068 # if fragment theme changed, reset book theme counter
1069 elif isinstance(sender, Fragment) and \
1070 Tag.objects.filter(pk__in=(tag.pk for tag in affected_tags)).\
1071 filter(category='theme').count():
1072 sender.book.reset_theme_counter()
1073 tags_updated.connect(_tags_updated_handler)
1076 def _pre_delete_handler(sender, instance, **kwargs):
1077 """ refresh Book on BookMedia delete """
1078 if sender == BookMedia:
1079 instance.book.save()
1080 pre_delete.connect(_pre_delete_handler)
1082 def _post_save_handler(sender, instance, **kwargs):
1083 """ refresh all the short_html stuff on BookMedia update """
1084 if sender == BookMedia:
1085 instance.book.save()
1086 post_save.connect(_post_save_handler)