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)
64 main_page = models.BooleanField(_('main page'), default=False, db_index=True, help_text=_('Show tag on main page'))
66 user = models.ForeignKey(User, blank=True, null=True)
67 book_count = models.IntegerField(_('book count'), blank=True, null=True)
68 gazeta_link = models.CharField(blank=True, max_length=240)
69 wiki_link = models.CharField(blank=True, max_length=240)
71 created_at = models.DateTimeField(_('creation date'), auto_now_add=True, db_index=True)
72 changed_at = models.DateTimeField(_('creation date'), auto_now=True, db_index=True)
74 class UrlDeprecationWarning(DeprecationWarning):
85 categories_dict = dict((item[::-1] for item in categories_rev.iteritems()))
88 ordering = ('sort_key',)
89 verbose_name = _('tag')
90 verbose_name_plural = _('tags')
91 unique_together = (("slug", "category"),)
93 def __unicode__(self):
97 return "Tag(slug=%r)" % self.slug
100 def get_absolute_url(self):
101 return ('catalogue.views.tagged_object_list', [self.url_chunk])
103 def has_description(self):
104 return len(self.description) > 0
105 has_description.short_description = _('description')
106 has_description.boolean = True
109 """Returns global book count for book tags, fragment count for themes."""
111 if self.category == 'book':
113 objects = Book.objects.none()
114 elif self.category == 'theme':
115 objects = Fragment.tagged.with_all((self,))
117 objects = Book.tagged.with_all((self,)).order_by()
118 if self.category != 'set':
119 # eliminate descendants
120 l_tags = Tag.objects.filter(slug__in=[book.book_tag_slug() for book in objects])
121 descendants_keys = [book.pk for book in Book.tagged.with_any(l_tags)]
123 objects = objects.exclude(pk__in=descendants_keys)
124 return objects.count()
127 def get_tag_list(tags):
128 if isinstance(tags, basestring):
133 tags_splitted = tags.split('/')
134 for name in tags_splitted:
136 real_tags.append(Tag.objects.get(slug=name, category=category))
138 elif name in Tag.categories_rev:
139 category = Tag.categories_rev[name]
142 real_tags.append(Tag.objects.exclude(category='book').get(slug=name))
144 except Tag.MultipleObjectsReturned, e:
145 ambiguous_slugs.append(name)
148 # something strange left off
149 raise Tag.DoesNotExist()
151 # some tags should be qualified
152 e = Tag.MultipleObjectsReturned()
154 e.ambiguous_slugs = ambiguous_slugs
157 e = Tag.UrlDeprecationWarning()
162 return TagBase.get_tag_list(tags)
166 return '/'.join((Tag.categories_dict[self.category], self.slug))
169 def tags_from_info(info):
170 from slughifi import slughifi
171 from sortify import sortify
173 categories = (('kinds', 'kind'), ('genres', 'genre'), ('authors', 'author'), ('epochs', 'epoch'))
174 for field_name, category in categories:
176 tag_names = getattr(info, field_name)
178 tag_names = [getattr(info, category)]
179 for tag_name in tag_names:
180 tag_sort_key = tag_name
181 if category == 'author':
182 tag_sort_key = tag_name.last_name
183 tag_name = tag_name.readable()
184 tag, created = Tag.objects.get_or_create(slug=slughifi(tag_name), category=category)
187 tag.sort_key = sortify(tag_sort_key.lower())
189 meta_tags.append(tag)
194 def get_dynamic_path(media, filename, ext=None, maxlen=100):
195 from slughifi import slughifi
197 # how to put related book's slug here?
200 ext = media.formats[media.type].ext
201 if media is None or not media.name:
202 name = slughifi(filename.split(".")[0])
204 name = slughifi(media.name)
205 return 'book/%s/%s.%s' % (ext, name[:maxlen-len('book/%s/.%s' % (ext, ext))-4], ext)
208 # TODO: why is this hard-coded ?
209 def book_upload_path(ext=None, maxlen=100):
210 return lambda *args: get_dynamic_path(*args, ext=ext, maxlen=maxlen)
213 def get_customized_pdf_path(book, customizations):
215 Returns a MEDIA_ROOT relative path for a customized pdf. The name will contain a hash of customization options.
217 customizations.sort()
218 h = hash(tuple(customizations))
220 pdf_name = '%s-custom-%s' % (book.fileid(), h)
221 pdf_file = get_dynamic_path(None, pdf_name, ext='pdf')
226 def get_existing_customized_pdf(book):
228 Returns a list of paths to generated customized pdf of a book
230 pdf_glob = '%s-custom-' % (book.fileid(),)
231 pdf_glob = get_dynamic_path(None, pdf_glob, ext='pdf')
232 pdf_glob = re.sub(r"[.]([a-z0-9]+)$", "*.\\1", pdf_glob)
233 return glob(path.join(settings.MEDIA_ROOT, pdf_glob))
236 class BookMedia(models.Model):
237 FileFormat = namedtuple("FileFormat", "name ext")
238 formats = SortedDict([
239 ('mp3', FileFormat(name='MP3', ext='mp3')),
240 ('ogg', FileFormat(name='Ogg Vorbis', ext='ogg')),
241 ('daisy', FileFormat(name='DAISY', ext='daisy.zip')),
243 format_choices = [(k, _('%s file') % t.name)
244 for k, t in formats.items()]
246 type = models.CharField(_('type'), choices=format_choices, max_length="100")
247 name = models.CharField(_('name'), max_length="100")
248 file = OverwritingFileField(_('file'), upload_to=book_upload_path())
249 uploaded_at = models.DateTimeField(_('creation date'), auto_now_add=True, editable=False)
250 extra_info = JSONField(_('extra information'), default='{}', editable=False)
251 book = models.ForeignKey('Book', related_name='media')
252 source_sha1 = models.CharField(null=True, blank=True, max_length=40, editable=False)
254 def __unicode__(self):
255 return "%s (%s)" % (self.name, self.file.name.split("/")[-1])
258 ordering = ('type', 'name')
259 verbose_name = _('book media')
260 verbose_name_plural = _('book media')
262 def save(self, *args, **kwargs):
263 from slughifi import slughifi
264 from catalogue.utils import ExistingFile, remove_zip
267 old = BookMedia.objects.get(pk=self.pk)
268 except BookMedia.DoesNotExist, e:
271 # if name changed, change the file name, too
272 if slughifi(self.name) != slughifi(old.name):
273 self.file.save(None, ExistingFile(self.file.path), save=False, leave=True)
275 super(BookMedia, self).save(*args, **kwargs)
277 # remove the zip package for book with modified media
278 remove_zip(self.book.fileid())
280 extra_info = self.get_extra_info_value()
281 extra_info.update(self.read_meta())
282 self.set_extra_info_value(extra_info)
283 self.source_sha1 = self.read_source_sha1(self.file.path, self.type)
284 return super(BookMedia, self).save(*args, **kwargs)
288 Reads some metadata from the audiobook.
291 from mutagen import id3
293 artist_name = director_name = project = funded_by = ''
294 if self.type == 'mp3':
296 audio = id3.ID3(self.file.path)
297 artist_name = ', '.join(', '.join(tag.text) for tag in audio.getall('TPE1'))
298 director_name = ', '.join(', '.join(tag.text) for tag in audio.getall('TPE3'))
299 project = ", ".join([t.data for t in audio.getall('PRIV')
300 if t.owner=='wolnelektury.pl?project'])
301 funded_by = ", ".join([t.data for t in audio.getall('PRIV')
302 if t.owner=='wolnelektury.pl?funded_by'])
305 elif self.type == 'ogg':
307 audio = mutagen.File(self.file.path)
308 artist_name = ', '.join(audio.get('artist', []))
309 director_name = ', '.join(audio.get('conductor', []))
310 project = ", ".join(audio.get('project', []))
311 funded_by = ", ".join(audio.get('funded_by', []))
316 return {'artist_name': artist_name, 'director_name': director_name,
317 'project': project, 'funded_by': funded_by}
320 def read_source_sha1(filepath, filetype):
322 Reads source file SHA1 from audiobok metadata.
325 from mutagen import id3
327 if filetype == 'mp3':
329 audio = id3.ID3(filepath)
330 return [t.data for t in audio.getall('PRIV')
331 if t.owner=='wolnelektury.pl?flac_sha1'][0]
334 elif filetype == 'ogg':
336 audio = mutagen.File(filepath)
337 return audio.get('flac_sha1', [None])[0]
344 class Book(models.Model):
345 title = models.CharField(_('title'), max_length=120)
346 sort_key = models.CharField(_('sort key'), max_length=120, db_index=True, editable=False)
347 slug = models.SlugField(_('slug'), max_length=120, db_index=True)
348 language = models.CharField(_('language code'), max_length=3, db_index=True,
349 default=settings.CATALOGUE_DEFAULT_LANGUAGE)
350 description = models.TextField(_('description'), blank=True)
351 created_at = models.DateTimeField(_('creation date'), auto_now_add=True, db_index=True)
352 changed_at = models.DateTimeField(_('creation date'), auto_now=True, db_index=True)
353 parent_number = models.IntegerField(_('parent number'), default=0)
354 extra_info = JSONField(_('extra information'), default='{}')
355 gazeta_link = models.CharField(blank=True, max_length=240)
356 wiki_link = models.CharField(blank=True, max_length=240)
357 # files generated during publication
359 cover = models.FileField(_('cover'), upload_to=book_upload_path('png'),
360 null=True, blank=True)
361 ebook_formats = ['pdf', 'epub', 'mobi', 'txt']
362 formats = ebook_formats + ['html', 'xml']
364 parent = models.ForeignKey('self', blank=True, null=True, related_name='children')
365 objects = models.Manager()
366 tagged = managers.ModelTaggedItemManager(Tag)
367 tags = managers.TagDescriptor(Tag)
369 html_built = django.dispatch.Signal()
370 published = django.dispatch.Signal()
372 URLID_RE = r'[a-z0-9-]+(?:/[a-z]{3})?'
373 FILEID_RE = r'[a-z0-9-]+(?:_[a-z]{3})?'
375 class AlreadyExists(Exception):
379 unique_together = [['slug', 'language']]
380 ordering = ('sort_key',)
381 verbose_name = _('book')
382 verbose_name_plural = _('books')
384 def __unicode__(self):
387 def urlid(self, sep='/'):
389 if self.language != settings.CATALOGUE_DEFAULT_LANGUAGE:
390 stem += sep + self.language
394 return self.urlid('_')
397 def split_urlid(urlid, sep='/', default_lang=settings.CATALOGUE_DEFAULT_LANGUAGE):
398 """Splits a URL book id into slug and language code.
400 Returns a dictionary usable i.e. for object lookup, or None.
402 >>> Book.split_urlid("a-slug/pol", default_lang="eng")
403 {'slug': 'a-slug', 'language': 'pol'}
404 >>> Book.split_urlid("a-slug", default_lang="eng")
405 {'slug': 'a-slug', 'language': 'eng'}
406 >>> Book.split_urlid("a-slug_pol", "_", default_lang="eng")
407 {'slug': 'a-slug', 'language': 'pol'}
408 >>> Book.split_urlid("a-slug/eng", default_lang="eng")
411 parts = urlid.rsplit(sep, 1)
413 if parts[1] == default_lang:
415 return {'slug': parts[0], 'language': parts[1]}
417 return {'slug': urlid, 'language': default_lang}
420 def split_fileid(cls, fileid):
421 return cls.split_urlid(fileid, '_')
423 def save(self, force_insert=False, force_update=False, reset_short_html=True, **kwargs):
424 from sortify import sortify
426 self.sort_key = sortify(self.title)
428 ret = super(Book, self).save(force_insert, force_update)
431 self.reset_short_html()
436 def get_absolute_url(self):
437 return ('catalogue.views.book_detail', [self.urlid()])
443 def book_tag_slug(self):
444 stem = 'l-' + self.slug
445 if self.language != settings.CATALOGUE_DEFAULT_LANGUAGE:
446 return stem[:116] + ' ' + self.language
451 slug = self.book_tag_slug()
452 book_tag, created = Tag.objects.get_or_create(slug=slug, category='book')
454 book_tag.name = self.title[:50]
455 book_tag.sort_key = self.title.lower()
459 def has_media(self, type):
460 if type in Book.formats:
461 return bool(getattr(self, "%s_file" % type))
463 return self.media.filter(type=type).exists()
465 def get_media(self, type):
466 if self.has_media(type):
467 if type in Book.formats:
468 return getattr(self, "%s_file" % type)
470 return self.media.filter(type=type)
475 return self.get_media("mp3")
477 return self.get_media("odt")
479 return self.get_media("ogg")
481 return self.get_media("daisy")
483 def reset_short_html(self):
487 cache_key = "Book.short_html/%d/%s"
488 for lang, langname in settings.LANGUAGES:
489 cache.delete(cache_key % (self.id, lang))
490 # Fragment.short_html relies on book's tags, so reset it here too
491 for fragm in self.fragments.all():
492 fragm.reset_short_html()
494 def short_html(self):
496 cache_key = "Book.short_html/%d/%s" % (self.id, get_language())
497 short_html = cache.get(cache_key)
501 if short_html is not None:
502 return mark_safe(short_html)
504 tags = self.tags.filter(~Q(category__in=('set', 'theme', 'book')))
505 tags = [mark_safe(u'<a href="%s">%s</a>' % (tag.get_absolute_url(), tag.name)) for tag in tags]
508 # files generated during publication
509 if self.has_media("html"):
510 formats.append(u'<a href="%s">%s</a>' % (reverse('book_text', args=[self.fileid()]), _('Read online')))
511 for ebook_format in self.ebook_formats:
512 if self.has_media(ebook_format):
513 formats.append(u'<a href="%s">%s</a>' % (
514 self.get_media(ebook_format).url,
518 for m in self.media.order_by('type'):
519 formats.append(u'<a href="%s">%s</a>' % (m.file.url, m.type.upper()))
521 formats = [mark_safe(format) for format in formats]
523 short_html = unicode(render_to_string('catalogue/book_short.html',
524 {'book': self, 'tags': tags, 'formats': formats}))
527 cache.set(cache_key, short_html, CACHE_FOREVER)
528 return mark_safe(short_html)
532 cache_key = "Book.mini_boxs/%d" % (self.id, )
533 short_html = cache.get(cache_key)
537 if short_html is None:
538 authors = self.tags.filter(category='author')
540 short_html = unicode(render_to_string('catalogue/book_mini_box.html',
541 {'book': self, 'authors': authors, 'STATIC_URL': settings.STATIC_URL}))
544 cache.set(cache_key, short_html, CACHE_FOREVER)
545 return mark_safe(short_html)
547 def has_description(self):
548 return len(self.description) > 0
549 has_description.short_description = _('description')
550 has_description.boolean = True
553 def has_mp3_file(self):
554 return bool(self.has_media("mp3"))
555 has_mp3_file.short_description = 'MP3'
556 has_mp3_file.boolean = True
558 def has_ogg_file(self):
559 return bool(self.has_media("ogg"))
560 has_ogg_file.short_description = 'OGG'
561 has_ogg_file.boolean = True
563 def has_daisy_file(self):
564 return bool(self.has_media("daisy"))
565 has_daisy_file.short_description = 'DAISY'
566 has_daisy_file.boolean = True
568 def wldocument(self, parse_dublincore=True):
569 from catalogue.utils import ORMDocProvider
570 from librarian.parser import WLDocument
572 return WLDocument.from_file(self.xml_file.path,
573 provider=ORMDocProvider(self),
574 parse_dublincore=parse_dublincore)
576 def build_cover(self, book_info=None):
577 """(Re)builds the cover image."""
578 from StringIO import StringIO
579 from django.core.files.base import ContentFile
580 from librarian.cover import WLCover
582 if book_info is None:
583 book_info = self.wldocument().book_info
585 cover = WLCover(book_info).image()
587 cover.save(imgstr, 'png')
588 self.cover.save(None, ContentFile(imgstr.getvalue()))
590 def build_pdf(self, customizations=None, file_name=None):
591 """ (Re)builds the pdf file.
592 customizations - customizations which are passed to LaTeX class file.
593 file_name - save the pdf file under a different name and DO NOT save it in db.
595 from os import unlink
596 from django.core.files import File
597 from catalogue.utils import remove_zip
599 pdf = self.wldocument().as_pdf(customizations=customizations)
601 if file_name is None:
602 # we'd like to be sure not to overwrite changes happening while
603 # (timely) pdf generation is taking place (async celery scenario)
604 current_self = Book.objects.get(id=self.id)
605 current_self.pdf_file.save('%s.pdf' % self.fileid(),
606 File(open(pdf.get_filename())))
607 self.pdf_file = current_self.pdf_file
609 # remove cached downloadables
610 remove_zip(settings.ALL_PDF_ZIP)
612 for customized_pdf in get_existing_customized_pdf(self):
613 unlink(customized_pdf)
615 print "saving %s" % file_name
616 print "to: %s" % DefaultStorage().path(file_name)
617 DefaultStorage().save(file_name, File(open(pdf.get_filename())))
619 def build_mobi(self):
620 """ (Re)builds the MOBI file.
623 from django.core.files import File
624 from catalogue.utils import remove_zip
626 mobi = self.wldocument().as_mobi()
628 self.mobi_file.save('%s.mobi' % self.fileid(), File(open(mobi.get_filename())))
630 # remove zip with all mobi files
631 remove_zip(settings.ALL_MOBI_ZIP)
633 def build_epub(self):
634 """(Re)builds the epub file."""
635 from django.core.files import File
636 from catalogue.utils import remove_zip
638 epub = self.wldocument().as_epub()
640 self.epub_file.save('%s.epub' % self.fileid(),
641 File(open(epub.get_filename())))
643 # remove zip package with all epub files
644 remove_zip(settings.ALL_EPUB_ZIP)
647 from django.core.files.base import ContentFile
649 text = self.wldocument().as_text()
650 self.txt_file.save('%s.txt' % self.fileid(), ContentFile(text.get_string()))
653 def build_html(self):
654 from markupstring import MarkupString
655 from django.core.files.base import ContentFile
656 from slughifi import slughifi
657 from librarian import html
659 meta_tags = list(self.tags.filter(
660 category__in=('author', 'epoch', 'genre', 'kind')))
661 book_tag = self.book_tag()
663 html_output = self.wldocument(parse_dublincore=False).as_html()
665 self.html_file.save('%s.html' % self.fileid(),
666 ContentFile(html_output.get_string()))
668 # get ancestor l-tags for adding to new fragments
672 ancestor_tags.append(p.book_tag())
675 # Delete old fragments and create them from scratch
676 self.fragments.all().delete()
678 closed_fragments, open_fragments = html.extract_fragments(self.html_file.path)
679 for fragment in closed_fragments.values():
681 theme_names = [s.strip() for s in fragment.themes.split(',')]
682 except AttributeError:
685 for theme_name in theme_names:
688 tag, created = Tag.objects.get_or_create(slug=slughifi(theme_name), category='theme')
690 tag.name = theme_name
691 tag.sort_key = theme_name.lower()
697 text = fragment.to_string()
699 if (len(MarkupString(text)) > 240):
700 short_text = unicode(MarkupString(text)[:160])
701 new_fragment = Fragment.objects.create(anchor=fragment.id, book=self,
702 text=text, short_text=short_text)
705 new_fragment.tags = set(meta_tags + themes + [book_tag] + ancestor_tags)
707 self.html_built.send(sender=self)
712 def zip_format(format_):
713 def pretty_file_name(book):
714 return "%s/%s.%s" % (
715 b.get_extra_info_value()['author'],
719 field_name = "%s_file" % format_
720 books = Book.objects.filter(parent=None).exclude(**{field_name: ""})
721 paths = [(pretty_file_name(b), getattr(b, field_name).path)
723 result = create_zip.delay(paths,
724 getattr(settings, "ALL_%s_ZIP" % format_.upper()))
727 def zip_audiobooks(self):
728 bm = BookMedia.objects.filter(book=self, type='mp3')
729 paths = map(lambda bm: (None, bm.file.path), bm)
730 result = create_zip.delay(paths, self.fileid())
734 def from_xml_file(cls, xml_file, **kwargs):
735 from django.core.files import File
736 from librarian import dcparser
738 # use librarian to parse meta-data
739 book_info = dcparser.parse(xml_file)
741 if not isinstance(xml_file, File):
742 xml_file = File(open(xml_file))
745 return cls.from_text_and_meta(xml_file, book_info, **kwargs)
750 def from_text_and_meta(cls, raw_file, book_info, overwrite=False,
751 build_epub=True, build_txt=True, build_pdf=True, build_mobi=True):
753 from sortify import sortify
755 # check for parts before we do anything
757 if hasattr(book_info, 'parts'):
758 for part_url in book_info.parts:
760 children.append(Book.objects.get(
761 slug=part_url.slug, language=part_url.language))
762 except Book.DoesNotExist, e:
763 raise Book.DoesNotExist(_('Book "%s/%s" does not exist.') %
764 (part_url.slug, part_url.language))
768 book_slug = book_info.url.slug
769 language = book_info.language
770 if re.search(r'[^a-zA-Z0-9-]', book_slug):
771 raise ValueError('Invalid characters in slug')
772 book, created = Book.objects.get_or_create(slug=book_slug, language=language)
778 raise Book.AlreadyExists(_('Book %s/%s already exists') % (
779 book_slug, language))
780 # Save shelves for this book
781 book_shelves = list(book.tags.filter(category='set'))
783 book.title = book_info.title
784 book.set_extra_info_value(book_info.to_dict())
787 meta_tags = Tag.tags_from_info(book_info)
789 book.tags = set(meta_tags + book_shelves)
791 book_tag = book.book_tag()
793 for n, child_book in enumerate(children):
794 child_book.parent = book
795 child_book.parent_number = n
798 # Save XML and HTML files
799 book.xml_file.save('%s.xml' % book.slug, raw_file, save=False)
801 # delete old fragments when overwriting
802 book.fragments.all().delete()
804 if book.build_html():
805 if not settings.NO_BUILD_TXT and build_txt:
808 book.build_cover(book_info)
810 if not settings.NO_BUILD_EPUB and build_epub:
813 if not settings.NO_BUILD_PDF and build_pdf:
816 if not settings.NO_BUILD_MOBI and build_mobi:
819 book_descendants = list(book.children.all())
820 descendants_tags = set()
821 # add l-tag to descendants and their fragments
822 while len(book_descendants) > 0:
823 child_book = book_descendants.pop(0)
824 descendants_tags.update(child_book.tags)
825 child_book.tags = list(child_book.tags) + [book_tag]
827 for fragment in child_book.fragments.all():
828 fragment.tags = set(list(fragment.tags) + [book_tag])
829 book_descendants += list(child_book.children.all())
831 for tag in descendants_tags:
837 book.reset_tag_counter()
838 book.reset_theme_counter()
840 cls.published.send(sender=book)
843 def reset_tag_counter(self):
847 cache_key = "Book.tag_counter/%d" % self.id
848 cache.delete(cache_key)
850 self.parent.reset_tag_counter()
853 def tag_counter(self):
855 cache_key = "Book.tag_counter/%d" % self.id
856 tags = cache.get(cache_key)
862 for child in self.children.all().order_by():
863 for tag_pk, value in child.tag_counter.iteritems():
864 tags[tag_pk] = tags.get(tag_pk, 0) + value
865 for tag in self.tags.exclude(category__in=('book', 'theme', 'set')).order_by():
869 cache.set(cache_key, tags, CACHE_FOREVER)
872 def reset_theme_counter(self):
876 cache_key = "Book.theme_counter/%d" % self.id
877 cache.delete(cache_key)
879 self.parent.reset_theme_counter()
882 def theme_counter(self):
884 cache_key = "Book.theme_counter/%d" % self.id
885 tags = cache.get(cache_key)
891 for fragment in Fragment.tagged.with_any([self.book_tag()]).order_by():
892 for tag in fragment.tags.filter(category='theme').order_by():
893 tags[tag.pk] = tags.get(tag.pk, 0) + 1
896 cache.set(cache_key, tags, CACHE_FOREVER)
899 def pretty_title(self, html_links=False):
901 names = list(book.tags.filter(category='author'))
907 names.extend(reversed(books))
910 names = ['<a href="%s">%s</a>' % (tag.get_absolute_url(), tag.name) for tag in names]
912 names = [tag.name for tag in names]
914 return ', '.join(names)
917 def tagged_top_level(cls, tags):
918 """ Returns top-level books tagged with `tags'.
920 It only returns those books which don't have ancestors which are
921 also tagged with those tags.
924 # get relevant books and their tags
925 objects = cls.tagged.with_all(tags)
926 # eliminate descendants
927 l_tags = Tag.objects.filter(category='book', slug__in=[book.book_tag_slug() for book in objects])
928 descendants_keys = [book.pk for book in cls.tagged.with_any(l_tags)]
930 objects = objects.exclude(pk__in=descendants_keys)
935 def book_list(cls, filter=None):
936 """Generates a hierarchical listing of all books.
938 Books are optionally filtered with a test function.
943 books = cls.objects.all().order_by('parent_number', 'sort_key').only(
944 'title', 'parent', 'slug', 'language')
946 books = books.filter(filter).distinct()
947 book_ids = set((book.pk for book in books))
949 parent = book.parent_id
950 if parent not in book_ids:
952 books_by_parent.setdefault(parent, []).append(book)
955 books_by_parent.setdefault(book.parent_id, []).append(book)
958 books_by_author = SortedDict()
959 for tag in Tag.objects.filter(category='author'):
960 books_by_author[tag] = []
962 for book in books_by_parent.get(None,()):
963 authors = list(book.tags.filter(category='author'))
965 for author in authors:
966 books_by_author[author].append(book)
970 return books_by_author, orphans, books_by_parent
973 "SP1": (1, u"szkoła podstawowa"),
974 "SP2": (1, u"szkoła podstawowa"),
975 "P": (1, u"szkoła podstawowa"),
976 "G": (2, u"gimnazjum"),
978 "LP": (3, u"liceum"),
980 def audiences_pl(self):
981 audiences = self.get_extra_info_value().get('audiences', [])
982 audiences = sorted(set([self._audiences_pl[a] for a in audiences]))
983 return [a[1] for a in audiences]
986 def _has_factory(ftype):
987 has = lambda self: bool(getattr(self, "%s_file" % ftype))
988 has.short_description = t.upper()
990 has.__name__ = "has_%s_file" % ftype
994 # add the file fields
995 for t in Book.formats:
996 field_name = "%s_file" % t
997 models.FileField(_("%s file" % t.upper()),
998 upload_to=book_upload_path(t),
999 blank=True).contribute_to_class(Book, field_name)
1001 setattr(Book, "has_%s_file" % t, _has_factory(t))
1004 class Fragment(models.Model):
1005 text = models.TextField()
1006 short_text = models.TextField(editable=False)
1007 anchor = models.CharField(max_length=120)
1008 book = models.ForeignKey(Book, related_name='fragments')
1010 objects = models.Manager()
1011 tagged = managers.ModelTaggedItemManager(Tag)
1012 tags = managers.TagDescriptor(Tag)
1015 ordering = ('book', 'anchor',)
1016 verbose_name = _('fragment')
1017 verbose_name_plural = _('fragments')
1019 def get_absolute_url(self):
1020 return '%s#m%s' % (self.book.get_html_url(), self.anchor)
1022 def reset_short_html(self):
1026 cache_key = "Fragment.short_html/%d/%s"
1027 for lang, langname in settings.LANGUAGES:
1028 cache.delete(cache_key % (self.id, lang))
1030 def short_html(self):
1032 cache_key = "Fragment.short_html/%d/%s" % (self.id, get_language())
1033 short_html = cache.get(cache_key)
1037 if short_html is not None:
1038 return mark_safe(short_html)
1040 short_html = unicode(render_to_string('catalogue/fragment_short.html',
1041 {'fragment': self}))
1043 cache.set(cache_key, short_html, CACHE_FOREVER)
1044 return mark_safe(short_html)
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:
1058 touch_tag.delay(tag)
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)
1079 def _post_save_handler(sender, instance, **kwargs):
1080 """ refresh all the short_html stuff on BookMedia update """
1081 if sender == BookMedia:
1082 instance.book.save()
1083 post_save.connect(_post_save_handler)