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