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