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