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