move a bunch of things to celery
[wolnelektury.git] / apps / catalogue / models.py
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.
4 #
5 from collections import namedtuple
6
7 from django.db import models
8 from django.db.models import permalink
9 import django.dispatch
10 from django.core.cache import get_cache
11 from django.utils.translation import ugettext_lazy as _
12 from django.contrib.auth.models import User
13 from django.template.loader import render_to_string
14 from django.utils.datastructures import SortedDict
15 from django.utils.safestring import mark_safe
16 from django.utils.translation import get_language
17 from django.core.urlresolvers import reverse
18 from django.db.models.signals import post_save, pre_delete, post_delete
19 import jsonfield
20
21 from django.conf import settings
22
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, split_tags, truncate_html_words
27 from catalogue import tasks
28 import re
29
30 import search
31
32 # Those are hard-coded here so that makemessages sees them.
33 TAG_CATEGORIES = (
34     ('author', _('author')),
35     ('epoch', _('epoch')),
36     ('kind', _('kind')),
37     ('genre', _('genre')),
38     ('theme', _('theme')),
39     ('set', _('set')),
40     ('book', _('book')),
41 )
42
43
44 permanent_cache = get_cache('permanent')
45
46
47 class TagSubcategoryManager(models.Manager):
48     def __init__(self, subcategory):
49         super(TagSubcategoryManager, self).__init__()
50         self.subcategory = subcategory
51
52     def get_query_set(self):
53         return super(TagSubcategoryManager, self).get_query_set().filter(category=self.subcategory)
54
55
56 class Tag(TagBase):
57     name = models.CharField(_('name'), max_length=50, db_index=True)
58     slug = models.SlugField(_('slug'), max_length=120, db_index=True)
59     sort_key = models.CharField(_('sort key'), max_length=120, db_index=True)
60     category = models.CharField(_('category'), max_length=50, blank=False, null=False,
61         db_index=True, choices=TAG_CATEGORIES)
62     description = models.TextField(_('description'), blank=True)
63
64     user = models.ForeignKey(User, blank=True, null=True)
65     book_count = models.IntegerField(_('book count'), blank=True, null=True)
66     gazeta_link = models.CharField(blank=True, max_length=240)
67     wiki_link = models.CharField(blank=True, max_length=240)
68
69     created_at    = models.DateTimeField(_('creation date'), auto_now_add=True, db_index=True)
70     changed_at    = models.DateTimeField(_('creation date'), auto_now=True, db_index=True)
71
72     class UrlDeprecationWarning(DeprecationWarning):
73         pass
74
75     categories_rev = {
76         'autor': 'author',
77         'epoka': 'epoch',
78         'rodzaj': 'kind',
79         'gatunek': 'genre',
80         'motyw': 'theme',
81         'polka': 'set',
82     }
83     categories_dict = dict((item[::-1] for item in categories_rev.iteritems()))
84
85     class Meta:
86         ordering = ('sort_key',)
87         verbose_name = _('tag')
88         verbose_name_plural = _('tags')
89         unique_together = (("slug", "category"),)
90
91     def __unicode__(self):
92         return self.name
93
94     def __repr__(self):
95         return "Tag(slug=%r)" % self.slug
96
97     @permalink
98     def get_absolute_url(self):
99         return ('catalogue.views.tagged_object_list', [self.url_chunk])
100
101     def has_description(self):
102         return len(self.description) > 0
103     has_description.short_description = _('description')
104     has_description.boolean = True
105
106     def get_count(self):
107         """Returns global book count for book tags, fragment count for themes."""
108
109         if self.category == 'book':
110             # never used
111             objects = Book.objects.none()
112         elif self.category == 'theme':
113             objects = Fragment.tagged.with_all((self,))
114         else:
115             objects = Book.tagged.with_all((self,)).order_by()
116             if self.category != 'set':
117                 # eliminate descendants
118                 l_tags = Tag.objects.filter(slug__in=[book.book_tag_slug() for book in objects])
119                 descendants_keys = [book.pk for book in Book.tagged.with_any(l_tags)]
120                 if descendants_keys:
121                     objects = objects.exclude(pk__in=descendants_keys)
122         return objects.count()
123
124     @staticmethod
125     def get_tag_list(tags):
126         if isinstance(tags, basestring):
127             real_tags = []
128             ambiguous_slugs = []
129             category = None
130             deprecated = False
131             tags_splitted = tags.split('/')
132             for name in tags_splitted:
133                 if category:
134                     real_tags.append(Tag.objects.get(slug=name, category=category))
135                     category = None
136                 elif name in Tag.categories_rev:
137                     category = Tag.categories_rev[name]
138                 else:
139                     try:
140                         real_tags.append(Tag.objects.exclude(category='book').get(slug=name))
141                         deprecated = True 
142                     except Tag.MultipleObjectsReturned, e:
143                         ambiguous_slugs.append(name)
144
145             if category:
146                 # something strange left off
147                 raise Tag.DoesNotExist()
148             if ambiguous_slugs:
149                 # some tags should be qualified
150                 e = Tag.MultipleObjectsReturned()
151                 e.tags = real_tags
152                 e.ambiguous_slugs = ambiguous_slugs
153                 raise e
154             if deprecated:
155                 e = Tag.UrlDeprecationWarning()
156                 e.tags = real_tags
157                 raise e
158             return real_tags
159         else:
160             return TagBase.get_tag_list(tags)
161
162     @property
163     def url_chunk(self):
164         return '/'.join((Tag.categories_dict[self.category], self.slug))
165
166     @staticmethod
167     def tags_from_info(info):
168         from slughifi import slughifi
169         from sortify import sortify
170         meta_tags = []
171         categories = (('kinds', 'kind'), ('genres', 'genre'), ('authors', 'author'), ('epochs', 'epoch'))
172         for field_name, category in categories:
173             try:
174                 tag_names = getattr(info, field_name)
175             except:
176                 try:
177                     tag_names = [getattr(info, category)]
178                 except:
179                     # For instance, Pictures do not have 'genre' field.
180                     continue
181             for tag_name in tag_names:
182                 tag_sort_key = tag_name
183                 if category == 'author':
184                     tag_sort_key = tag_name.last_name
185                     tag_name = tag_name.readable()
186                 tag, created = Tag.objects.get_or_create(slug=slughifi(tag_name), category=category)
187                 if created:
188                     tag.name = tag_name
189                     tag.sort_key = sortify(tag_sort_key.lower())
190                     tag.save()
191                 meta_tags.append(tag)
192         return meta_tags
193
194
195
196 def get_dynamic_path(media, filename, ext=None, maxlen=100):
197     from slughifi import slughifi
198
199     # how to put related book's slug here?
200     if not ext:
201         # BookMedia case
202         ext = media.formats[media.type].ext
203     if media is None or not media.name:
204         name = slughifi(filename.split(".")[0])
205     else:
206         name = slughifi(media.name)
207     return 'book/%s/%s.%s' % (ext, name[:maxlen-len('book/%s/.%s' % (ext, ext))-4], ext)
208
209
210 # TODO: why is this hard-coded ?
211 def book_upload_path(ext=None, maxlen=100):
212     return lambda *args: get_dynamic_path(*args, ext=ext, maxlen=maxlen)
213
214
215 class BookMedia(models.Model):
216     FileFormat = namedtuple("FileFormat", "name ext")
217     formats = SortedDict([
218         ('mp3', FileFormat(name='MP3', ext='mp3')),
219         ('ogg', FileFormat(name='Ogg Vorbis', ext='ogg')),
220         ('daisy', FileFormat(name='DAISY', ext='daisy.zip')),
221     ])
222     format_choices = [(k, _('%s file') % t.name)
223             for k, t in formats.items()]
224
225     type        = models.CharField(_('type'), choices=format_choices, max_length="100")
226     name        = models.CharField(_('name'), max_length="100")
227     file        = OverwritingFileField(_('file'), upload_to=book_upload_path())
228     uploaded_at = models.DateTimeField(_('creation date'), auto_now_add=True, editable=False)
229     extra_info  = JSONField(_('extra information'), default='{}', editable=False)
230     book = models.ForeignKey('Book', related_name='media')
231     source_sha1 = models.CharField(null=True, blank=True, max_length=40, editable=False)
232
233     def __unicode__(self):
234         return "%s (%s)" % (self.name, self.file.name.split("/")[-1])
235
236     class Meta:
237         ordering            = ('type', 'name')
238         verbose_name        = _('book media')
239         verbose_name_plural = _('book media')
240
241     def save(self, *args, **kwargs):
242         from slughifi import slughifi
243         from catalogue.utils import ExistingFile, remove_zip
244
245         try:
246             old = BookMedia.objects.get(pk=self.pk)
247         except BookMedia.DoesNotExist, e:
248             old = None
249         else:
250             # if name changed, change the file name, too
251             if slughifi(self.name) != slughifi(old.name):
252                 self.file.save(None, ExistingFile(self.file.path), save=False, leave=True)
253
254         super(BookMedia, self).save(*args, **kwargs)
255
256         # remove the zip package for book with modified media
257         if old:
258             remove_zip("%s_%s" % (old.book.slug, old.type))
259         remove_zip("%s_%s" % (self.book.slug, self.type))
260
261         extra_info = self.get_extra_info_value()
262         extra_info.update(self.read_meta())
263         self.set_extra_info_value(extra_info)
264         self.source_sha1 = self.read_source_sha1(self.file.path, self.type)
265         return super(BookMedia, self).save(*args, **kwargs)
266
267     def read_meta(self):
268         """
269             Reads some metadata from the audiobook.
270         """
271         import mutagen
272         from mutagen import id3
273
274         artist_name = director_name = project = funded_by = ''
275         if self.type == 'mp3':
276             try:
277                 audio = id3.ID3(self.file.path)
278                 artist_name = ', '.join(', '.join(tag.text) for tag in audio.getall('TPE1'))
279                 director_name = ', '.join(', '.join(tag.text) for tag in audio.getall('TPE3'))
280                 project = ", ".join([t.data for t in audio.getall('PRIV') 
281                         if t.owner=='wolnelektury.pl?project'])
282                 funded_by = ", ".join([t.data for t in audio.getall('PRIV') 
283                         if t.owner=='wolnelektury.pl?funded_by'])
284             except:
285                 pass
286         elif self.type == 'ogg':
287             try:
288                 audio = mutagen.File(self.file.path)
289                 artist_name = ', '.join(audio.get('artist', []))
290                 director_name = ', '.join(audio.get('conductor', []))
291                 project = ", ".join(audio.get('project', []))
292                 funded_by = ", ".join(audio.get('funded_by', []))
293             except:
294                 pass
295         else:
296             return {}
297         return {'artist_name': artist_name, 'director_name': director_name,
298                 'project': project, 'funded_by': funded_by}
299
300     @staticmethod
301     def read_source_sha1(filepath, filetype):
302         """
303             Reads source file SHA1 from audiobok metadata.
304         """
305         import mutagen
306         from mutagen import id3
307
308         if filetype == 'mp3':
309             try:
310                 audio = id3.ID3(filepath)
311                 return [t.data for t in audio.getall('PRIV') 
312                         if t.owner=='wolnelektury.pl?flac_sha1'][0]
313             except:
314                 return None
315         elif filetype == 'ogg':
316             try:
317                 audio = mutagen.File(filepath)
318                 return audio.get('flac_sha1', [None])[0] 
319             except:
320                 return None
321         else:
322             return None
323
324
325 class Book(models.Model):
326     title         = models.CharField(_('title'), max_length=120)
327     sort_key = models.CharField(_('sort key'), max_length=120, db_index=True, editable=False)
328     slug = models.SlugField(_('slug'), max_length=120, db_index=True,
329             unique=True)
330     common_slug = models.SlugField(_('slug'), max_length=120, db_index=True)
331     language = models.CharField(_('language code'), max_length=3, db_index=True,
332                     default=settings.CATALOGUE_DEFAULT_LANGUAGE)
333     description   = models.TextField(_('description'), blank=True)
334     created_at    = models.DateTimeField(_('creation date'), auto_now_add=True, db_index=True)
335     changed_at    = models.DateTimeField(_('creation date'), auto_now=True, db_index=True)
336     parent_number = models.IntegerField(_('parent number'), default=0)
337     extra_info    = JSONField(_('extra information'), default='{}')
338     gazeta_link   = models.CharField(blank=True, max_length=240)
339     wiki_link     = models.CharField(blank=True, max_length=240)
340     # files generated during publication
341
342     cover = models.FileField(_('cover'), upload_to=book_upload_path('png'),
343                 null=True, blank=True)
344     ebook_formats = ['pdf', 'epub', 'mobi', 'txt']
345     formats = ebook_formats + ['html', 'xml']
346
347     parent        = models.ForeignKey('self', blank=True, null=True, related_name='children')
348
349     _related_info = jsonfield.JSONField(blank=True, null=True, editable=False)
350
351     objects  = models.Manager()
352     tagged   = managers.ModelTaggedItemManager(Tag)
353     tags     = managers.TagDescriptor(Tag)
354
355     html_built = django.dispatch.Signal()
356     published = django.dispatch.Signal()
357
358     class AlreadyExists(Exception):
359         pass
360
361     class Meta:
362         ordering = ('sort_key',)
363         verbose_name = _('book')
364         verbose_name_plural = _('books')
365
366     def __unicode__(self):
367         return self.title
368
369     def save(self, force_insert=False, force_update=False, reset_short_html=True, **kwargs):
370         from sortify import sortify
371
372         self.sort_key = sortify(self.title)
373
374         ret = super(Book, self).save(force_insert, force_update)
375
376         if reset_short_html:
377             self.reset_short_html()
378
379         return ret
380
381     @permalink
382     def get_absolute_url(self):
383         return ('catalogue.views.book_detail', [self.slug])
384
385     @property
386     def name(self):
387         return self.title
388
389     def book_tag_slug(self):
390         return ('l-' + self.slug)[:120]
391
392     def book_tag(self):
393         slug = self.book_tag_slug()
394         book_tag, created = Tag.objects.get_or_create(slug=slug, category='book')
395         if created:
396             book_tag.name = self.title[:50]
397             book_tag.sort_key = self.title.lower()
398             book_tag.save()
399         return book_tag
400
401     def has_media(self, type):
402         if type in Book.formats:
403             return bool(getattr(self, "%s_file" % type))
404         else:
405             return self.media.filter(type=type).exists()
406
407     def get_media(self, type):
408         if self.has_media(type):
409             if type in Book.formats:
410                 return getattr(self, "%s_file" % type)
411             else:                                             
412                 return self.media.filter(type=type)
413         else:
414             return None
415
416     def get_mp3(self):
417         return self.get_media("mp3")
418     def get_odt(self):
419         return self.get_media("odt")
420     def get_ogg(self):
421         return self.get_media("ogg")
422     def get_daisy(self):
423         return self.get_media("daisy")                       
424
425     def reset_short_html(self):
426         if self.id is None:
427             return
428
429         type(self).objects.filter(pk=self.pk).update(_related_info=None)
430         # Fragment.short_html relies on book's tags, so reset it here too
431         for fragm in self.fragments.all():
432             fragm.reset_short_html()
433
434     def has_description(self):
435         return len(self.description) > 0
436     has_description.short_description = _('description')
437     has_description.boolean = True
438
439     # ugly ugly ugly
440     def has_mp3_file(self):
441         return bool(self.has_media("mp3"))
442     has_mp3_file.short_description = 'MP3'
443     has_mp3_file.boolean = True
444
445     def has_ogg_file(self):
446         return bool(self.has_media("ogg"))
447     has_ogg_file.short_description = 'OGG'
448     has_ogg_file.boolean = True
449
450     def has_daisy_file(self):
451         return bool(self.has_media("daisy"))
452     has_daisy_file.short_description = 'DAISY'
453     has_daisy_file.boolean = True
454
455     def wldocument(self, parse_dublincore=True):
456         from catalogue.import_utils import ORMDocProvider
457         from librarian.parser import WLDocument
458
459         return WLDocument.from_file(self.xml_file.path,
460                 provider=ORMDocProvider(self),
461                 parse_dublincore=parse_dublincore)
462
463     def build_cover(self, book_info=None):
464         """(Re)builds the cover image."""
465         from StringIO import StringIO
466         from django.core.files.base import ContentFile
467         from librarian.cover import WLCover
468
469         if book_info is None:
470             book_info = self.wldocument().book_info
471
472         cover = WLCover(book_info).image()
473         imgstr = StringIO()
474         cover.save(imgstr, 'png')
475         self.cover.save(None, ContentFile(imgstr.getvalue()))
476
477     def build_html(self):
478         from django.core.files.base import ContentFile
479         from slughifi import slughifi
480         from librarian import html
481
482         meta_tags = list(self.tags.filter(
483             category__in=('author', 'epoch', 'genre', 'kind')))
484         book_tag = self.book_tag()
485
486         html_output = self.wldocument(parse_dublincore=False).as_html()
487         if html_output:
488             self.html_file.save('%s.html' % self.slug,
489                     ContentFile(html_output.get_string()))
490
491             # get ancestor l-tags for adding to new fragments
492             ancestor_tags = []
493             p = self.parent
494             while p:
495                 ancestor_tags.append(p.book_tag())
496                 p = p.parent
497
498             # Delete old fragments and create them from scratch
499             self.fragments.all().delete()
500             # Extract fragments
501             closed_fragments, open_fragments = html.extract_fragments(self.html_file.path)
502             for fragment in closed_fragments.values():
503                 try:
504                     theme_names = [s.strip() for s in fragment.themes.split(',')]
505                 except AttributeError:
506                     continue
507                 themes = []
508                 for theme_name in theme_names:
509                     if not theme_name:
510                         continue
511                     tag, created = Tag.objects.get_or_create(slug=slughifi(theme_name), category='theme')
512                     if created:
513                         tag.name = theme_name
514                         tag.sort_key = theme_name.lower()
515                         tag.save()
516                     themes.append(tag)
517                 if not themes:
518                     continue
519
520                 text = fragment.to_string()
521                 short_text = truncate_html_words(text, 15)
522                 if text == short_text:
523                     short_text = ''
524                 new_fragment = Fragment.objects.create(anchor=fragment.id, book=self,
525                     text=text, short_text=short_text)
526
527                 new_fragment.save()
528                 new_fragment.tags = set(meta_tags + themes + [book_tag] + ancestor_tags)
529             self.save()
530             self.html_built.send(sender=self)
531             return True
532         return False
533
534     @staticmethod
535     def zip_format(format_):
536         def pretty_file_name(book):
537             return "%s/%s.%s" % (
538                 b.get_extra_info_value()['author'],
539                 b.slug,
540                 format_)
541
542         field_name = "%s_file" % format_
543         books = Book.objects.filter(parent=None).exclude(**{field_name: ""})
544         paths = [(pretty_file_name(b), getattr(b, field_name).path)
545                     for b in books]
546         return create_zip(paths,
547                     getattr(settings, "ALL_%s_ZIP" % format_.upper()))
548
549     def zip_audiobooks(self, format_):
550         bm = BookMedia.objects.filter(book=self, type=format_)
551         paths = map(lambda bm: (None, bm.file.path), bm)
552         return create_zip(paths, "%s_%s" % (self.slug, format_))
553
554     def search_index(self, book_info=None, reuse_index=False, index_tags=True):
555         if reuse_index:
556             idx = search.ReusableIndex()
557         else:
558             idx = search.Index()
559             
560         idx.open()
561         try:
562             idx.index_book(self, book_info)
563             if index_tags:
564                 idx.index_tags()
565         finally:
566             idx.close()
567
568     @classmethod
569     def from_xml_file(cls, xml_file, **kwargs):
570         from django.core.files import File
571         from librarian import dcparser
572
573         # use librarian to parse meta-data
574         book_info = dcparser.parse(xml_file)
575
576         if not isinstance(xml_file, File):
577             xml_file = File(open(xml_file))
578
579         try:
580             return cls.from_text_and_meta(xml_file, book_info, **kwargs)
581         finally:
582             xml_file.close()
583
584     @classmethod
585     def from_text_and_meta(cls, raw_file, book_info, overwrite=False,
586             build_epub=True, build_txt=True, build_pdf=True, build_mobi=True,
587             search_index=True, search_index_tags=True, search_index_reuse=False):
588
589         # check for parts before we do anything
590         children = []
591         if hasattr(book_info, 'parts'):
592             for part_url in book_info.parts:
593                 try:
594                     children.append(Book.objects.get(slug=part_url.slug))
595                 except Book.DoesNotExist, e:
596                     raise Book.DoesNotExist(_('Book "%s" does not exist.') %
597                             part_url.slug)
598
599
600         # Read book metadata
601         book_slug = book_info.url.slug
602         if re.search(r'[^a-z0-9-]', book_slug):
603             raise ValueError('Invalid characters in slug')
604         book, created = Book.objects.get_or_create(slug=book_slug)
605
606         if created:
607             book_shelves = []
608         else:
609             if not overwrite:
610                 raise Book.AlreadyExists(_('Book %s already exists') % (
611                         book_slug))
612             # Save shelves for this book
613             book_shelves = list(book.tags.filter(category='set'))
614
615         book.language = book_info.language
616         book.title = book_info.title
617         if book_info.variant_of:
618             book.common_slug = book_info.variant_of.slug
619         else:
620             book.common_slug = book.slug
621         book.set_extra_info_value(book_info.to_dict())
622         book.save()
623
624         meta_tags = Tag.tags_from_info(book_info)
625
626         book.tags = set(meta_tags + book_shelves)
627
628         book_tag = book.book_tag()
629
630         for n, child_book in enumerate(children):
631             child_book.parent = book
632             child_book.parent_number = n
633             child_book.save()
634
635         # Save XML and HTML files
636         book.xml_file.save('%s.xml' % book.slug, raw_file, save=False)
637
638         # delete old fragments when overwriting
639         book.fragments.all().delete()
640
641         if book.build_html():
642             if not settings.NO_BUILD_TXT and build_txt:
643                 tasks.build_txt.delay(book.pk)
644
645         book.build_cover(book_info)
646
647         if not settings.NO_BUILD_EPUB and build_epub:
648             tasks.build_epub.delay(book.pk)
649
650         if not settings.NO_BUILD_PDF and build_pdf:
651             tasks.build_pdf.delay(book.pk)
652
653         if not settings.NO_BUILD_MOBI and build_mobi:
654             tasks.build_mobi.delay(book.pk)
655
656         if not settings.NO_SEARCH_INDEX and search_index:
657             book.search_index(index_tags=search_index_tags, reuse_index=search_index_reuse)
658             #index_book.delay(book.id, book_info)
659
660         book_descendants = list(book.children.all())
661         descendants_tags = set()
662         # add l-tag to descendants and their fragments
663         while len(book_descendants) > 0:
664             child_book = book_descendants.pop(0)
665             descendants_tags.update(child_book.tags)
666             child_book.tags = list(child_book.tags) + [book_tag]
667             child_book.save()
668             for fragment in child_book.fragments.all():
669                 fragment.tags = set(list(fragment.tags) + [book_tag])
670             book_descendants += list(child_book.children.all())
671
672         for tag in descendants_tags:
673             tasks.touch_tag(tag)
674
675         book.save()
676
677         # refresh cache
678         book.reset_tag_counter()
679         book.reset_theme_counter()
680
681         cls.published.send(sender=book)
682         return book
683
684     def related_info(self):
685         """Keeps info about related objects (tags, media) in cache field."""
686         if self._related_info is not None:
687             return self._related_info
688         else:
689             rel = {'tags': {}, 'media': {}}
690
691             tags = self.tags.filter(category__in=(
692                     'author', 'kind', 'genre', 'epoch'))
693             tags = split_tags(tags)
694             for category in tags:
695                 rel['tags'][category] = [
696                         (t.name, t.slug) for t in tags[category]]
697
698             for media_format in BookMedia.formats:
699                 rel['media'][media_format] = self.has_media(media_format)
700
701             book = self
702             parents = []
703             while book.parent:
704                 parents.append((book.parent.title, book.parent.slug))
705                 book = book.parent
706             parents = parents[::-1]
707             if parents:
708                 rel['parents'] = parents
709
710             if self.pk:
711                 type(self).objects.filter(pk=self.pk).update(_related_info=rel)
712             return rel
713
714     def reset_tag_counter(self):
715         if self.id is None:
716             return
717
718         cache_key = "Book.tag_counter/%d" % self.id
719         permanent_cache.delete(cache_key)
720         if self.parent:
721             self.parent.reset_tag_counter()
722
723     @property
724     def tag_counter(self):
725         if self.id:
726             cache_key = "Book.tag_counter/%d" % self.id
727             tags = permanent_cache.get(cache_key)
728         else:
729             tags = None
730
731         if tags is None:
732             tags = {}
733             for child in self.children.all().order_by():
734                 for tag_pk, value in child.tag_counter.iteritems():
735                     tags[tag_pk] = tags.get(tag_pk, 0) + value
736             for tag in self.tags.exclude(category__in=('book', 'theme', 'set')).order_by():
737                 tags[tag.pk] = 1
738
739             if self.id:
740                 permanent_cache.set(cache_key, tags)
741         return tags
742
743     def reset_theme_counter(self):
744         if self.id is None:
745             return
746
747         cache_key = "Book.theme_counter/%d" % self.id
748         permanent_cache.delete(cache_key)
749         if self.parent:
750             self.parent.reset_theme_counter()
751
752     @property
753     def theme_counter(self):
754         if self.id:
755             cache_key = "Book.theme_counter/%d" % self.id
756             tags = permanent_cache.get(cache_key)
757         else:
758             tags = None
759
760         if tags is None:
761             tags = {}
762             for fragment in Fragment.tagged.with_any([self.book_tag()]).order_by():
763                 for tag in fragment.tags.filter(category='theme').order_by():
764                     tags[tag.pk] = tags.get(tag.pk, 0) + 1
765
766             if self.id:
767                 permanent_cache.set(cache_key, tags)
768         return tags
769
770     def pretty_title(self, html_links=False):
771         book = self
772         names = list(book.tags.filter(category='author'))
773
774         books = []
775         while book:
776             books.append(book)
777             book = book.parent
778         names.extend(reversed(books))
779
780         if html_links:
781             names = ['<a href="%s">%s</a>' % (tag.get_absolute_url(), tag.name) for tag in names]
782         else:
783             names = [tag.name for tag in names]
784
785         return ', '.join(names)
786
787     @classmethod
788     def tagged_top_level(cls, tags):
789         """ Returns top-level books tagged with `tags'.
790
791         It only returns those books which don't have ancestors which are
792         also tagged with those tags.
793
794         """
795         # get relevant books and their tags
796         objects = cls.tagged.with_all(tags)
797         # eliminate descendants
798         l_tags = Tag.objects.filter(category='book', slug__in=[book.book_tag_slug() for book in objects])
799         descendants_keys = [book.pk for book in cls.tagged.with_any(l_tags)]
800         if descendants_keys:
801             objects = objects.exclude(pk__in=descendants_keys)
802
803         return objects
804
805     @classmethod
806     def book_list(cls, filter=None):
807         """Generates a hierarchical listing of all books.
808
809         Books are optionally filtered with a test function.
810
811         """
812
813         books_by_parent = {}
814         books = cls.objects.all().order_by('parent_number', 'sort_key').only(
815                 'title', 'parent', 'slug')
816         if filter:
817             books = books.filter(filter).distinct()
818             book_ids = set((book.pk for book in books))
819             for book in books:
820                 parent = book.parent_id
821                 if parent not in book_ids:
822                     parent = None
823                 books_by_parent.setdefault(parent, []).append(book)
824         else:
825             for book in books:
826                 books_by_parent.setdefault(book.parent_id, []).append(book)
827
828         orphans = []
829         books_by_author = SortedDict()
830         for tag in Tag.objects.filter(category='author'):
831             books_by_author[tag] = []
832
833         for book in books_by_parent.get(None,()):
834             authors = list(book.tags.filter(category='author'))
835             if authors:
836                 for author in authors:
837                     books_by_author[author].append(book)
838             else:
839                 orphans.append(book)
840
841         return books_by_author, orphans, books_by_parent
842
843     _audiences_pl = {
844         "SP1": (1, u"szkoła podstawowa"),
845         "SP2": (1, u"szkoła podstawowa"),
846         "P": (1, u"szkoła podstawowa"),
847         "G": (2, u"gimnazjum"),
848         "L": (3, u"liceum"),
849         "LP": (3, u"liceum"),
850     }
851     def audiences_pl(self):
852         audiences = self.get_extra_info_value().get('audiences', [])
853         audiences = sorted(set([self._audiences_pl[a] for a in audiences]))
854         return [a[1] for a in audiences]
855
856     def choose_fragment(self):
857         tag = self.book_tag()
858         fragments = Fragment.tagged.with_any([tag])
859         if fragments.exists():
860             return fragments.order_by('?')[0]
861         elif self.parent:
862             return self.parent.choose_fragment()
863         else:
864             return None
865
866
867 def _has_factory(ftype):
868     has = lambda self: bool(getattr(self, "%s_file" % ftype))
869     has.short_description = t.upper()
870     has.boolean = True
871     has.__name__ = "has_%s_file" % ftype
872     return has
873
874     
875 # add the file fields
876 for t in Book.formats:
877     field_name = "%s_file" % t
878     models.FileField(_("%s file" % t.upper()),
879             upload_to=book_upload_path(t),
880             blank=True).contribute_to_class(Book, field_name)
881
882     setattr(Book, "has_%s_file" % t, _has_factory(t))
883
884
885 class Fragment(models.Model):
886     text = models.TextField()
887     short_text = models.TextField(editable=False)
888     anchor = models.CharField(max_length=120)
889     book = models.ForeignKey(Book, related_name='fragments')
890
891     objects = models.Manager()
892     tagged = managers.ModelTaggedItemManager(Tag)
893     tags = managers.TagDescriptor(Tag)
894
895     class Meta:
896         ordering = ('book', 'anchor',)
897         verbose_name = _('fragment')
898         verbose_name_plural = _('fragments')
899
900     def get_absolute_url(self):
901         return '%s#m%s' % (reverse('book_text', args=[self.book.slug]), self.anchor)
902
903     def reset_short_html(self):
904         if self.id is None:
905             return
906
907         cache_key = "Fragment.short_html/%d/%s"
908         for lang, langname in settings.LANGUAGES:
909             permanent_cache.delete(cache_key % (self.id, lang))
910
911     def get_short_text(self):
912         """Returns short version of the fragment."""
913         return self.short_text if self.short_text else self.text
914
915     def short_html(self):
916         if self.id:
917             cache_key = "Fragment.short_html/%d/%s" % (self.id, get_language())
918             short_html = permanent_cache.get(cache_key)
919         else:
920             short_html = None
921
922         if short_html is not None:
923             return mark_safe(short_html)
924         else:
925             short_html = unicode(render_to_string('catalogue/fragment_short.html',
926                 {'fragment': self}))
927             if self.id:
928                 permanent_cache.set(cache_key, short_html)
929             return mark_safe(short_html)
930
931
932 class Collection(models.Model):
933     """A collection of books, which might be defined before publishing them."""
934     title = models.CharField(_('title'), max_length=120, db_index=True)
935     slug = models.SlugField(_('slug'), max_length=120, primary_key=True)
936     description = models.TextField(_('description'), null=True, blank=True)
937
938     models.SlugField(_('slug'), max_length=120, unique=True, db_index=True)
939     book_slugs = models.TextField(_('book slugs'))
940
941     class Meta:
942         ordering = ('title',)
943         verbose_name = _('collection')
944         verbose_name_plural = _('collections')
945
946     def __unicode__(self):
947         return self.title
948
949
950 ###########
951 #
952 # SIGNALS
953 #
954 ###########
955
956
957 def _tags_updated_handler(sender, affected_tags, **kwargs):
958     # reset tag global counter
959     # we want Tag.changed_at updated for API to know the tag was touched
960     for tag in affected_tags:
961         tasks.touch_tag(tag)
962
963     # if book tags changed, reset book tag counter
964     if isinstance(sender, Book) and \
965                 Tag.objects.filter(pk__in=(tag.pk for tag in affected_tags)).\
966                     exclude(category__in=('book', 'theme', 'set')).count():
967         sender.reset_tag_counter()
968     # if fragment theme changed, reset book theme counter
969     elif isinstance(sender, Fragment) and \
970                 Tag.objects.filter(pk__in=(tag.pk for tag in affected_tags)).\
971                     filter(category='theme').count():
972         sender.book.reset_theme_counter()
973 tags_updated.connect(_tags_updated_handler)
974
975
976 def _pre_delete_handler(sender, instance, **kwargs):
977     """ refresh Book on BookMedia delete """
978     if sender == BookMedia:
979         instance.book.save()
980 pre_delete.connect(_pre_delete_handler)
981
982
983 def _post_save_handler(sender, instance, **kwargs):
984     """ refresh all the short_html stuff on BookMedia update """
985     if sender == BookMedia:
986         instance.book.save()
987 post_save.connect(_post_save_handler)
988
989
990 @django.dispatch.receiver(post_delete, sender=Book)
991 def _remove_book_from_index_handler(sender, instance, **kwargs):
992     """ remove the book from search index, when it is deleted."""
993     idx = search.Index()
994     idx.open(timeout=10000)  # 10 seconds timeout.
995     try:
996         idx.remove_book(instance)
997     finally:
998         idx.close()