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 datetime import datetime
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 shutil import copy
34 ('author', _('author')),
35 ('epoch', _('epoch')),
37 ('genre', _('genre')),
38 ('theme', _('theme')),
44 ('odt', _('ODT file')),
45 ('mp3', _('MP3 file')),
46 ('ogg', _('OGG file')),
47 ('daisy', _('DAISY file')),
50 # not quite, but Django wants you to set a timeout
51 CACHE_FOREVER = 2419200 # 28 days
54 class TagSubcategoryManager(models.Manager):
55 def __init__(self, subcategory):
56 super(TagSubcategoryManager, self).__init__()
57 self.subcategory = subcategory
59 def get_query_set(self):
60 return super(TagSubcategoryManager, self).get_query_set().filter(category=self.subcategory)
64 name = models.CharField(_('name'), max_length=50, db_index=True)
65 slug = models.SlugField(_('slug'), max_length=120, db_index=True)
66 sort_key = models.CharField(_('sort key'), max_length=120, db_index=True)
67 category = models.CharField(_('category'), max_length=50, blank=False, null=False,
68 db_index=True, choices=TAG_CATEGORIES)
69 description = models.TextField(_('description'), blank=True)
70 main_page = models.BooleanField(_('main page'), default=False, db_index=True, help_text=_('Show tag on main page'))
72 user = models.ForeignKey(User, blank=True, null=True)
73 book_count = models.IntegerField(_('book count'), blank=True, null=True)
74 gazeta_link = models.CharField(blank=True, max_length=240)
75 wiki_link = models.CharField(blank=True, max_length=240)
77 created_at = models.DateTimeField(_('creation date'), auto_now_add=True, db_index=True)
78 changed_at = models.DateTimeField(_('creation date'), auto_now=True, db_index=True)
80 class UrlDeprecationWarning(DeprecationWarning):
91 categories_dict = dict((item[::-1] for item in categories_rev.iteritems()))
94 ordering = ('sort_key',)
95 verbose_name = _('tag')
96 verbose_name_plural = _('tags')
97 unique_together = (("slug", "category"),)
99 def __unicode__(self):
103 return "Tag(slug=%r)" % self.slug
106 def get_absolute_url(self):
107 return ('catalogue.views.tagged_object_list', [self.url_chunk])
109 def has_description(self):
110 return len(self.description) > 0
111 has_description.short_description = _('description')
112 has_description.boolean = True
115 """ returns global book count for book tags, fragment count for themes """
117 if self.book_count is None:
118 if self.category == 'book':
120 objects = Book.objects.none()
121 elif self.category == 'theme':
122 objects = Fragment.tagged.with_all((self,))
124 objects = Book.tagged.with_all((self,)).order_by()
125 if self.category != 'set':
126 # eliminate descendants
127 l_tags = Tag.objects.filter(slug__in=[book.book_tag_slug() for book in objects])
128 descendants_keys = [book.pk for book in Book.tagged.with_any(l_tags)]
130 objects = objects.exclude(pk__in=descendants_keys)
131 self.book_count = objects.count()
133 return self.book_count
136 def get_tag_list(tags):
137 if isinstance(tags, basestring):
142 tags_splitted = tags.split('/')
143 for name in tags_splitted:
145 real_tags.append(Tag.objects.get(slug=name, category=category))
147 elif name in Tag.categories_rev:
148 category = Tag.categories_rev[name]
151 real_tags.append(Tag.objects.exclude(category='book').get(slug=name))
153 except Tag.MultipleObjectsReturned, e:
154 ambiguous_slugs.append(name)
157 # something strange left off
158 raise Tag.DoesNotExist()
160 # some tags should be qualified
161 e = Tag.MultipleObjectsReturned()
163 e.ambiguous_slugs = ambiguous_slugs
166 e = Tag.UrlDeprecationWarning()
171 return TagBase.get_tag_list(tags)
175 return '/'.join((Tag.categories_dict[self.category], self.slug))
178 def get_dynamic_path(media, filename, ext=None, maxlen=100):
179 from slughifi import slughifi
181 # how to put related book's slug here?
183 if media.type == 'daisy':
187 if media is None or not media.name:
188 name = slughifi(filename.split(".")[0])
190 name = slughifi(media.name)
191 return 'book/%s/%s.%s' % (ext, name[:maxlen-len('book/%s/.%s' % (ext, ext))-4], ext)
194 # TODO: why is this hard-coded ?
195 def book_upload_path(ext=None, maxlen=100):
196 return lambda *args: get_dynamic_path(*args, ext=ext, maxlen=maxlen)
199 def get_customized_pdf_path(book, customizations):
201 Returns a MEDIA_ROOT relative path for a customized pdf. The name will contain a hash of customization options.
203 customizations.sort()
204 h = hash(tuple(customizations))
206 pdf_name = '%s-custom-%s' % (book.fileid(), h)
207 pdf_file = get_dynamic_path(None, pdf_name, ext='pdf')
212 def get_existing_customized_pdf(book):
214 Returns a list of paths to generated customized pdf of a book
216 pdf_glob = '%s-custom-' % (book.fileid(),)
217 pdf_glob = get_dynamic_path(None, pdf_glob, ext='pdf')
218 pdf_glob = re.sub(r"[.]([a-z0-9]+)$", "*.\\1", pdf_glob)
219 return glob(path.join(settings.MEDIA_ROOT, pdf_glob))
222 class BookMedia(models.Model):
223 type = models.CharField(_('type'), choices=MEDIA_FORMATS, max_length="100")
224 name = models.CharField(_('name'), max_length="100")
225 file = OverwritingFileField(_('file'), upload_to=book_upload_path())
226 uploaded_at = models.DateTimeField(_('creation date'), auto_now_add=True, editable=False)
227 extra_info = JSONField(_('extra information'), default='{}', editable=False)
228 book = models.ForeignKey('Book', related_name='media')
229 source_sha1 = models.CharField(null=True, blank=True, max_length=40, editable=False)
231 def __unicode__(self):
232 return "%s (%s)" % (self.name, self.file.name.split("/")[-1])
235 ordering = ('type', 'name')
236 verbose_name = _('book media')
237 verbose_name_plural = _('book media')
239 def save(self, *args, **kwargs):
240 from slughifi import slughifi
241 from catalogue.utils import ExistingFile, remove_zip
244 old = BookMedia.objects.get(pk=self.pk)
245 except BookMedia.DoesNotExist, e:
248 # if name changed, change the file name, too
249 if slughifi(self.name) != slughifi(old.name):
250 self.file.save(None, ExistingFile(self.file.path), save=False, leave=True)
252 super(BookMedia, self).save(*args, **kwargs)
254 # remove the zip package for book with modified media
255 remove_zip(self.book.fileid())
257 extra_info = self.get_extra_info_value()
258 extra_info.update(self.read_meta())
259 self.set_extra_info_value(extra_info)
260 self.source_sha1 = self.read_source_sha1(self.file.path, self.type)
261 return super(BookMedia, self).save(*args, **kwargs)
265 Reads some metadata from the audiobook.
268 from mutagen import id3
270 artist_name = director_name = project = funded_by = ''
271 if self.type == 'mp3':
273 audio = id3.ID3(self.file.path)
274 artist_name = ', '.join(', '.join(tag.text) for tag in audio.getall('TPE1'))
275 director_name = ', '.join(', '.join(tag.text) for tag in audio.getall('TPE3'))
276 project = ", ".join([t.data for t in audio.getall('PRIV')
277 if t.owner=='wolnelektury.pl?project'])
278 funded_by = ", ".join([t.data for t in audio.getall('PRIV')
279 if t.owner=='wolnelektury.pl?funded_by'])
282 elif self.type == 'ogg':
284 audio = mutagen.File(self.file.path)
285 artist_name = ', '.join(audio.get('artist', []))
286 director_name = ', '.join(audio.get('conductor', []))
287 project = ", ".join(audio.get('project', []))
288 funded_by = ", ".join(audio.get('funded_by', []))
293 return {'artist_name': artist_name, 'director_name': director_name,
294 'project': project, 'funded_by': funded_by}
297 def read_source_sha1(filepath, filetype):
299 Reads source file SHA1 from audiobok metadata.
302 from mutagen import id3
304 if filetype == 'mp3':
306 audio = id3.ID3(filepath)
307 return [t.data for t in audio.getall('PRIV')
308 if t.owner=='wolnelektury.pl?flac_sha1'][0]
311 elif filetype == 'ogg':
313 audio = mutagen.File(filepath)
314 return audio.get('flac_sha1', [None])[0]
321 class Book(models.Model):
322 title = models.CharField(_('title'), max_length=120)
323 sort_key = models.CharField(_('sort key'), max_length=120, db_index=True, editable=False)
324 slug = models.SlugField(_('slug'), max_length=120, db_index=True)
325 language = models.CharField(_('language code'), max_length=3, db_index=True,
326 default=settings.CATALOGUE_DEFAULT_LANGUAGE)
327 description = models.TextField(_('description'), blank=True)
328 created_at = models.DateTimeField(_('creation date'), auto_now_add=True, db_index=True)
329 changed_at = models.DateTimeField(_('creation date'), auto_now=True, db_index=True)
330 parent_number = models.IntegerField(_('parent number'), default=0)
331 extra_info = JSONField(_('extra information'), default='{}')
332 gazeta_link = models.CharField(blank=True, max_length=240)
333 wiki_link = models.CharField(blank=True, max_length=240)
334 # files generated during publication
336 file_types = ['epub', 'html', 'mobi', 'pdf', 'txt', 'xml']
338 parent = models.ForeignKey('self', blank=True, null=True, related_name='children')
339 objects = models.Manager()
340 tagged = managers.ModelTaggedItemManager(Tag)
341 tags = managers.TagDescriptor(Tag)
343 html_built = django.dispatch.Signal()
344 published = django.dispatch.Signal()
346 URLID_RE = r'[a-z0-9-]+(?:/[a-z]{3})?'
347 FILEID_RE = r'[a-z0-9-]+(?:_[a-z]{3})?'
349 class AlreadyExists(Exception):
353 unique_together = [['slug', 'language']]
354 ordering = ('sort_key',)
355 verbose_name = _('book')
356 verbose_name_plural = _('books')
358 def __unicode__(self):
361 def urlid(self, sep='/'):
363 if self.language != settings.CATALOGUE_DEFAULT_LANGUAGE:
364 stem += sep + self.language
368 return self.urlid('_')
371 def split_urlid(urlid, sep='/', default_lang=settings.CATALOGUE_DEFAULT_LANGUAGE):
372 """Splits a URL book id into slug and language code.
374 Returns a dictionary usable i.e. for object lookup, or None.
376 >>> Book.split_urlid("a-slug/pol", default_lang="eng")
377 {'slug': 'a-slug', 'language': 'pol'}
378 >>> Book.split_urlid("a-slug", default_lang="eng")
379 {'slug': 'a-slug', 'language': 'eng'}
380 >>> Book.split_urlid("a-slug_pol", "_", default_lang="eng")
381 {'slug': 'a-slug', 'language': 'pol'}
382 >>> Book.split_urlid("a-slug/eng", default_lang="eng")
385 parts = urlid.rsplit(sep, 1)
387 if parts[1] == default_lang:
389 return {'slug': parts[0], 'language': parts[1]}
391 return {'slug': urlid, 'language': default_lang}
394 def split_fileid(cls, fileid):
395 return cls.split_urlid(fileid, '_')
397 def save(self, force_insert=False, force_update=False, reset_short_html=True, **kwargs):
398 from sortify import sortify
400 self.sort_key = sortify(self.title)
402 ret = super(Book, self).save(force_insert, force_update)
405 self.reset_short_html()
410 def get_absolute_url(self):
411 return ('catalogue.views.book_detail', [self.urlid()])
417 def book_tag_slug(self):
418 stem = 'l-' + self.slug
419 if self.language != settings.CATALOGUE_DEFAULT_LANGUAGE:
420 return stem[:116] + ' ' + self.language
425 slug = self.book_tag_slug()
426 book_tag, created = Tag.objects.get_or_create(slug=slug, category='book')
428 book_tag.name = self.title[:50]
429 book_tag.sort_key = self.title.lower()
433 def has_media(self, type):
434 if type in Book.file_types:
435 return bool(getattr(self, "%s_file" % type))
437 return self.media.filter(type=type).exists()
439 def get_media(self, type):
440 if self.has_media(type):
441 if type in Book.file_types:
442 return getattr(self, "%s_file" % type)
444 return self.media.filter(type=type)
449 return self.get_media("mp3")
451 return self.get_media("odt")
453 return self.get_media("ogg")
455 return self.get_media("daisy")
457 def reset_short_html(self):
461 cache_key = "Book.short_html/%d/%s"
462 for lang, langname in settings.LANGUAGES:
463 cache.delete(cache_key % (self.id, lang))
464 # Fragment.short_html relies on book's tags, so reset it here too
465 for fragm in self.fragments.all():
466 fragm.reset_short_html()
468 def short_html(self):
470 cache_key = "Book.short_html/%d/%s" % (self.id, get_language())
471 short_html = cache.get(cache_key)
475 if short_html is not None:
476 return mark_safe(short_html)
478 tags = self.tags.filter(~Q(category__in=('set', 'theme', 'book')))
479 tags = [mark_safe(u'<a href="%s">%s</a>' % (tag.get_absolute_url(), tag.name)) for tag in tags]
482 # files generated during publication
483 if self.has_media("html"):
484 formats.append(u'<a href="%s">%s</a>' % (reverse('book_text', [self.fileid()]), _('Read online')))
485 if self.has_media("pdf"):
486 formats.append(u'<a href="%s">PDF</a>' % self.get_media('pdf').url)
487 if self.has_media("mobi"):
488 formats.append(u'<a href="%s">MOBI</a>' % self.get_media('mobi').url)
489 if self.root_ancestor.has_media("epub"):
490 formats.append(u'<a href="%s">EPUB</a>' % self.root_ancestor.get_media('epub').url)
491 if self.has_media("txt"):
492 formats.append(u'<a href="%s">TXT</a>' % self.get_media('txt').url)
494 for m in self.media.order_by('type'):
495 formats.append(u'<a href="%s">%s</a>' % (m.file.url, m.type.upper()))
497 formats = [mark_safe(format) for format in formats]
499 short_html = unicode(render_to_string('catalogue/book_short.html',
500 {'book': self, 'tags': tags, 'formats': formats}))
503 cache.set(cache_key, short_html, CACHE_FOREVER)
504 return mark_safe(short_html)
507 def root_ancestor(self):
508 """ returns the oldest ancestor """
510 if not hasattr(self, '_root_ancestor'):
514 self._root_ancestor = book
515 return self._root_ancestor
518 def has_description(self):
519 return len(self.description) > 0
520 has_description.short_description = _('description')
521 has_description.boolean = True
524 def has_odt_file(self):
525 return bool(self.has_media("odt"))
526 has_odt_file.short_description = 'ODT'
527 has_odt_file.boolean = True
529 def has_mp3_file(self):
530 return bool(self.has_media("mp3"))
531 has_mp3_file.short_description = 'MP3'
532 has_mp3_file.boolean = True
534 def has_ogg_file(self):
535 return bool(self.has_media("ogg"))
536 has_ogg_file.short_description = 'OGG'
537 has_ogg_file.boolean = True
539 def has_daisy_file(self):
540 return bool(self.has_media("daisy"))
541 has_daisy_file.short_description = 'DAISY'
542 has_daisy_file.boolean = True
544 def wldocument(self, parse_dublincore=True):
545 from catalogue.utils import ORMDocProvider
546 from librarian.parser import WLDocument
548 return WLDocument.from_file(self.xml_file.path,
549 provider=ORMDocProvider(self),
550 parse_dublincore=parse_dublincore)
552 def build_pdf(self, customizations=None, file_name=None):
553 """ (Re)builds the pdf file.
554 customizations - customizations which are passed to LaTeX class file.
555 file_name - save the pdf file under a different name and DO NOT save it in db.
557 from os import unlink
558 from django.core.files import File
559 from catalogue.utils import remove_zip
561 pdf = self.wldocument().as_pdf(customizations=customizations)
563 if file_name is None:
564 # we'd like to be sure not to overwrite changes happening while
565 # (timely) pdf generation is taking place (async celery scenario)
566 current_self = Book.objects.get(id=self.id)
567 current_self.pdf_file.save('%s.pdf' % self.fileid(),
568 File(open(pdf.get_filename())))
569 self.pdf_file = current_self.pdf_file
571 # remove cached downloadables
572 remove_zip(settings.ALL_PDF_ZIP)
574 for customized_pdf in get_existing_customized_pdf(self):
575 unlink(customized_pdf)
577 print "saving %s" % file_name
578 print "to: %s" % DefaultStorage().path(file_name)
579 DefaultStorage().save(file_name, File(open(pdf.get_filename())))
581 def build_mobi(self):
582 """ (Re)builds the MOBI file.
585 from django.core.files import File
586 from catalogue.utils import remove_zip
588 mobi = self.wldocument().as_mobi()
590 self.mobi_file.save('%s.mobi' % self.fileid(), File(open(mobi.get_filename())))
592 # remove zip with all mobi files
593 remove_zip(settings.ALL_MOBI_ZIP)
595 def build_epub(self, remove_descendants=True):
596 """ (Re)builds the epub file.
597 If book has a parent, does nothing.
598 Unless remove_descendants is False, descendants' epubs are removed.
600 from django.core.files import File
601 from catalogue.utils import remove_zip
607 epub = self.wldocument().as_epub()
610 epub.transform(ORMDocProvider(self), self.fileid(), output_file=epub_file)
611 self.epub_file.save('%s.epub' % self.fileid(), File(open(epub.get_filename())))
615 book_descendants = list(self.children.all())
616 while len(book_descendants) > 0:
617 child_book = book_descendants.pop(0)
618 if remove_descendants and child_book.has_epub_file():
619 child_book.epub_file.delete()
620 # save anyway, to refresh short_html
622 book_descendants += list(child_book.children.all())
624 # remove zip package with all epub files
625 remove_zip(settings.ALL_EPUB_ZIP)
628 from django.core.files.base import ContentFile
630 text = self.wldocument().as_text()
631 self.txt_file.save('%s.txt' % self.fileid(), ContentFile(text.get_string()))
634 def build_html(self):
635 from markupstring import MarkupString
636 from django.core.files.base import ContentFile
637 from slughifi import slughifi
638 from librarian import html
640 meta_tags = list(self.tags.filter(
641 category__in=('author', 'epoch', 'genre', 'kind')))
642 book_tag = self.book_tag()
644 html_output = self.wldocument(parse_dublincore=False).as_html()
646 self.html_file.save('%s.html' % self.fileid(),
647 ContentFile(html_output.get_string()))
649 # get ancestor l-tags for adding to new fragments
653 ancestor_tags.append(p.book_tag())
656 # Delete old fragments and create them from scratch
657 self.fragments.all().delete()
659 closed_fragments, open_fragments = html.extract_fragments(self.html_file.path)
660 for fragment in closed_fragments.values():
662 theme_names = [s.strip() for s in fragment.themes.split(',')]
663 except AttributeError:
666 for theme_name in theme_names:
669 tag, created = Tag.objects.get_or_create(slug=slughifi(theme_name), category='theme')
671 tag.name = theme_name
672 tag.sort_key = theme_name.lower()
678 text = fragment.to_string()
680 if (len(MarkupString(text)) > 240):
681 short_text = unicode(MarkupString(text)[:160])
682 new_fragment = Fragment.objects.create(anchor=fragment.id, book=self,
683 text=text, short_text=short_text)
686 new_fragment.tags = set(meta_tags + themes + [book_tag] + ancestor_tags)
688 self.html_built.send(sender=self)
693 def zip_format(format_):
694 def pretty_file_name(book):
695 return "%s/%s.%s" % (
696 b.get_extra_info_value()['author'],
700 field_name = "%s_file" % format_
701 books = Book.objects.filter(parent=None).exclude(**{field_name: ""})
702 paths = [(pretty_file_name(b), getattr(b, field_name).path)
704 result = create_zip.delay(paths,
705 getattr(settings, "ALL_%s_ZIP" % format_.upper()))
708 def zip_audiobooks(self):
709 bm = BookMedia.objects.filter(book=self, type='mp3')
710 paths = map(lambda bm: (None, bm.file.path), bm)
711 result = create_zip.delay(paths, self.fileid())
715 def from_xml_file(cls, xml_file, **kwargs):
716 from django.core.files import File
717 from librarian import dcparser
719 # use librarian to parse meta-data
720 book_info = dcparser.parse(xml_file)
722 if not isinstance(xml_file, File):
723 xml_file = File(open(xml_file))
726 return cls.from_text_and_meta(xml_file, book_info, **kwargs)
731 def from_text_and_meta(cls, raw_file, book_info, overwrite=False,
732 build_epub=True, build_txt=True, build_pdf=True, build_mobi=True):
734 from slughifi import slughifi
735 from sortify import sortify
737 # check for parts before we do anything
739 if hasattr(book_info, 'parts'):
740 for part_url in book_info.parts:
742 children.append(Book.objects.get(
743 slug=part_url.slug, language=part_url.language))
744 except Book.DoesNotExist, e:
745 raise Book.DoesNotExist(_('Book "%s/%s" does not exist.') %
746 (part_url.slug, part_url.language))
750 book_slug = book_info.url.slug
751 language = book_info.language
752 if re.search(r'[^a-zA-Z0-9-]', book_slug):
753 raise ValueError('Invalid characters in slug')
754 book, created = Book.objects.get_or_create(slug=book_slug, language=language)
760 raise Book.AlreadyExists(_('Book %s/%s already exists') % (
761 book_slug, language))
762 # Save shelves for this book
763 book_shelves = list(book.tags.filter(category='set'))
765 book.title = book_info.title
766 book.set_extra_info_value(book_info.to_dict())
770 categories = (('kinds', 'kind'), ('genres', 'genre'), ('authors', 'author'), ('epochs', 'epoch'))
771 for field_name, category in categories:
773 tag_names = getattr(book_info, field_name)
775 tag_names = [getattr(book_info, category)]
776 for tag_name in tag_names:
777 tag_sort_key = tag_name
778 if category == 'author':
779 tag_sort_key = tag_name.last_name
780 tag_name = ' '.join(tag_name.first_names) + ' ' + tag_name.last_name
781 tag, created = Tag.objects.get_or_create(slug=slughifi(tag_name), category=category)
784 tag.sort_key = sortify(tag_sort_key.lower())
786 meta_tags.append(tag)
788 book.tags = set(meta_tags + book_shelves)
790 book_tag = book.book_tag()
792 for n, child_book in enumerate(children):
793 child_book.parent = book
794 child_book.parent_number = n
797 # Save XML and HTML files
798 book.xml_file.save('%s.xml' % book.slug, raw_file, save=False)
800 # delete old fragments when overwriting
801 book.fragments.all().delete()
803 if book.build_html():
804 if not settings.NO_BUILD_TXT and build_txt:
807 if not settings.NO_BUILD_EPUB and build_epub:
808 book.root_ancestor.build_epub()
810 if not settings.NO_BUILD_PDF and build_pdf:
811 book.root_ancestor.build_pdf()
813 if not settings.NO_BUILD_MOBI and build_mobi:
816 book_descendants = list(book.children.all())
817 # add l-tag to descendants and their fragments
818 # delete unnecessary EPUB files
819 while len(book_descendants) > 0:
820 child_book = book_descendants.pop(0)
821 child_book.tags = list(child_book.tags) + [book_tag]
823 for fragment in child_book.fragments.all():
824 fragment.tags = set(list(fragment.tags) + [book_tag])
825 book_descendants += list(child_book.children.all())
830 book.reset_tag_counter()
831 book.reset_theme_counter()
833 cls.published.send(sender=book)
836 def reset_tag_counter(self):
840 cache_key = "Book.tag_counter/%d" % self.id
841 cache.delete(cache_key)
843 self.parent.reset_tag_counter()
846 def tag_counter(self):
848 cache_key = "Book.tag_counter/%d" % self.id
849 tags = cache.get(cache_key)
855 for child in self.children.all().order_by():
856 for tag_pk, value in child.tag_counter.iteritems():
857 tags[tag_pk] = tags.get(tag_pk, 0) + value
858 for tag in self.tags.exclude(category__in=('book', 'theme', 'set')).order_by():
862 cache.set(cache_key, tags, CACHE_FOREVER)
865 def reset_theme_counter(self):
869 cache_key = "Book.theme_counter/%d" % self.id
870 cache.delete(cache_key)
872 self.parent.reset_theme_counter()
875 def theme_counter(self):
877 cache_key = "Book.theme_counter/%d" % self.id
878 tags = cache.get(cache_key)
884 for fragment in Fragment.tagged.with_any([self.book_tag()]).order_by():
885 for tag in fragment.tags.filter(category='theme').order_by():
886 tags[tag.pk] = tags.get(tag.pk, 0) + 1
889 cache.set(cache_key, tags, CACHE_FOREVER)
892 def pretty_title(self, html_links=False):
894 names = list(book.tags.filter(category='author'))
900 names.extend(reversed(books))
903 names = ['<a href="%s">%s</a>' % (tag.get_absolute_url(), tag.name) for tag in names]
905 names = [tag.name for tag in names]
907 return ', '.join(names)
910 def tagged_top_level(cls, tags):
911 """ Returns top-level books tagged with `tags'.
913 It only returns those books which don't have ancestors which are
914 also tagged with those tags.
917 # get relevant books and their tags
918 objects = cls.tagged.with_all(tags)
919 # eliminate descendants
920 l_tags = Tag.objects.filter(category='book', slug__in=[book.book_tag_slug() for book in objects])
921 descendants_keys = [book.pk for book in cls.tagged.with_any(l_tags)]
923 objects = objects.exclude(pk__in=descendants_keys)
928 def book_list(cls, filter=None):
929 """Generates a hierarchical listing of all books.
931 Books are optionally filtered with a test function.
936 books = cls.objects.all().order_by('parent_number', 'sort_key').only(
937 'title', 'parent', 'slug', 'language')
939 books = books.filter(filter).distinct()
940 book_ids = set((book.pk for book in books))
942 parent = book.parent_id
943 if parent not in book_ids:
945 books_by_parent.setdefault(parent, []).append(book)
948 books_by_parent.setdefault(book.parent_id, []).append(book)
951 books_by_author = SortedDict()
952 for tag in Tag.objects.filter(category='author'):
953 books_by_author[tag] = []
955 for book in books_by_parent.get(None,()):
956 authors = list(book.tags.filter(category='author'))
958 for author in authors:
959 books_by_author[author].append(book)
963 return books_by_author, orphans, books_by_parent
966 "SP1": (1, u"szkoła podstawowa"),
967 "SP2": (1, u"szkoła podstawowa"),
968 "P": (1, u"szkoła podstawowa"),
969 "G": (2, u"gimnazjum"),
971 "LP": (3, u"liceum"),
973 def audiences_pl(self):
974 audiences = self.get_extra_info_value().get('audiences', [])
975 audiences = sorted(set([self._audiences_pl[a] for a in audiences]))
976 return [a[1] for a in audiences]
979 def _has_factory(ftype):
980 has = lambda self: bool(getattr(self, "%s_file" % ftype))
981 has.short_description = t.upper()
983 has.__name__ = "has_%s_file" % ftype
987 # add the file fields
988 for t in Book.file_types:
989 field_name = "%s_file" % t
990 models.FileField(_("%s file" % t.upper()),
991 upload_to=book_upload_path(t),
992 blank=True).contribute_to_class(Book, field_name)
994 setattr(Book, "has_%s_file" % t, _has_factory(t))
997 class Fragment(models.Model):
998 text = models.TextField()
999 short_text = models.TextField(editable=False)
1000 anchor = models.CharField(max_length=120)
1001 book = models.ForeignKey(Book, related_name='fragments')
1003 objects = models.Manager()
1004 tagged = managers.ModelTaggedItemManager(Tag)
1005 tags = managers.TagDescriptor(Tag)
1008 ordering = ('book', 'anchor',)
1009 verbose_name = _('fragment')
1010 verbose_name_plural = _('fragments')
1012 def get_absolute_url(self):
1013 return '%s#m%s' % (self.book.get_html_url(), self.anchor)
1015 def reset_short_html(self):
1019 cache_key = "Fragment.short_html/%d/%s"
1020 for lang, langname in settings.LANGUAGES:
1021 cache.delete(cache_key % (self.id, lang))
1023 def short_html(self):
1025 cache_key = "Fragment.short_html/%d/%s" % (self.id, get_language())
1026 short_html = cache.get(cache_key)
1030 if short_html is not None:
1031 return mark_safe(short_html)
1033 short_html = unicode(render_to_string('catalogue/fragment_short.html',
1034 {'fragment': self}))
1036 cache.set(cache_key, short_html, CACHE_FOREVER)
1037 return mark_safe(short_html)
1047 def _tags_updated_handler(sender, affected_tags, **kwargs):
1048 # reset tag global counter
1049 # we want Tag.changed_at updated for API to know the tag was touched
1050 Tag.objects.filter(pk__in=[tag.pk for tag in affected_tags]).update(book_count=None, changed_at=datetime.now())
1052 # if book tags changed, reset book tag counter
1053 if isinstance(sender, Book) and \
1054 Tag.objects.filter(pk__in=(tag.pk for tag in affected_tags)).\
1055 exclude(category__in=('book', 'theme', 'set')).count():
1056 sender.reset_tag_counter()
1057 # if fragment theme changed, reset book theme counter
1058 elif isinstance(sender, Fragment) and \
1059 Tag.objects.filter(pk__in=(tag.pk for tag in affected_tags)).\
1060 filter(category='theme').count():
1061 sender.book.reset_theme_counter()
1062 tags_updated.connect(_tags_updated_handler)
1065 def _pre_delete_handler(sender, instance, **kwargs):
1066 """ refresh Book on BookMedia delete """
1067 if sender == BookMedia:
1068 instance.book.save()
1069 pre_delete.connect(_pre_delete_handler)
1071 def _post_save_handler(sender, instance, **kwargs):
1072 """ refresh all the short_html stuff on BookMedia update """
1073 if sender == BookMedia:
1074 instance.book.save()
1075 post_save.connect(_post_save_handler)