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