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