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