8fb210935c20c5e4e0719a24e5faea96e98bc33c
[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 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.fileid(), 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.fileid(),)
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             pass
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         remove_zip(self.book.fileid())
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     language = models.CharField(_('language code'), max_length=3, db_index=True,
354                     default=settings.CATALOGUE_DEFAULT_LANGUAGE)
355     description   = models.TextField(_('description'), blank=True)
356     created_at    = models.DateTimeField(_('creation date'), auto_now_add=True, db_index=True)
357     changed_at    = models.DateTimeField(_('creation date'), auto_now=True, db_index=True)
358     parent_number = models.IntegerField(_('parent number'), default=0)
359     extra_info    = JSONField(_('extra information'), default='{}')
360     gazeta_link   = models.CharField(blank=True, max_length=240)
361     wiki_link     = models.CharField(blank=True, max_length=240)
362     # files generated during publication
363
364     cover = models.FileField(_('cover'), upload_to=book_upload_path('png'),
365                 null=True, blank=True)
366     ebook_formats = ['pdf', 'epub', 'mobi', 'txt']
367     formats = ebook_formats + ['html', 'xml']
368
369     parent        = models.ForeignKey('self', blank=True, null=True, related_name='children')
370     objects  = models.Manager()
371     tagged   = managers.ModelTaggedItemManager(Tag)
372     tags     = managers.TagDescriptor(Tag)
373
374     html_built = django.dispatch.Signal()
375     published = django.dispatch.Signal()
376
377     URLID_RE = r'[a-z0-9-]+(?:/[a-z]{3})?'
378     FILEID_RE = r'[a-z0-9-]+(?:_[a-z]{3})?'
379
380     class AlreadyExists(Exception):
381         pass
382
383     class Meta:
384         unique_together = [['slug', 'language']]
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 urlid(self, sep='/'):
393         stem = self.slug
394         if self.language != settings.CATALOGUE_DEFAULT_LANGUAGE:
395             stem += sep + self.language
396         return stem
397
398     def fileid(self):
399         return self.urlid('_')
400
401     @staticmethod
402     def split_urlid(urlid, sep='/', default_lang=settings.CATALOGUE_DEFAULT_LANGUAGE):
403         """Splits a URL book id into slug and language code.
404         
405         Returns a dictionary usable i.e. for object lookup, or None.
406
407         >>> Book.split_urlid("a-slug/pol", default_lang="eng")
408         {'slug': 'a-slug', 'language': 'pol'}
409         >>> Book.split_urlid("a-slug", default_lang="eng")
410         {'slug': 'a-slug', 'language': 'eng'}
411         >>> Book.split_urlid("a-slug_pol", "_", default_lang="eng")
412         {'slug': 'a-slug', 'language': 'pol'}
413         >>> Book.split_urlid("a-slug/eng", default_lang="eng")
414
415         """
416         parts = urlid.rsplit(sep, 1)
417         if len(parts) == 2:
418             if parts[1] == default_lang:
419                 return None
420             return {'slug': parts[0], 'language': parts[1]}
421         else:
422             return {'slug': urlid, 'language': default_lang}
423
424     @classmethod
425     def split_fileid(cls, fileid):
426         return cls.split_urlid(fileid, '_')
427
428     def save(self, force_insert=False, force_update=False, reset_short_html=True, **kwargs):
429         from sortify import sortify
430
431         self.sort_key = sortify(self.title)
432
433         ret = super(Book, self).save(force_insert, force_update)
434
435         if reset_short_html:
436             self.reset_short_html()
437
438         return ret
439
440     @permalink
441     def get_absolute_url(self):
442         return ('catalogue.views.book_detail', [self.urlid()])
443
444     @property
445     def name(self):
446         return self.title
447
448     def book_tag_slug(self):
449         stem = 'l-' + self.slug
450         if self.language != settings.CATALOGUE_DEFAULT_LANGUAGE:
451             return stem[:116] + ' ' + self.language
452         else:
453             return stem[:120]
454
455     def book_tag(self):
456         slug = self.book_tag_slug()
457         book_tag, created = Tag.objects.get_or_create(slug=slug, category='book')
458         if created:
459             book_tag.name = self.title[:50]
460             book_tag.sort_key = self.title.lower()
461             book_tag.save()
462         return book_tag
463
464     def has_media(self, type):
465         if type in Book.formats:
466             return bool(getattr(self, "%s_file" % type))
467         else:
468             return self.media.filter(type=type).exists()
469
470     def get_media(self, type):
471         if self.has_media(type):
472             if type in Book.formats:
473                 return getattr(self, "%s_file" % type)
474             else:                                             
475                 return self.media.filter(type=type)
476         else:
477             return None
478
479     def get_mp3(self):
480         return self.get_media("mp3")
481     def get_odt(self):
482         return self.get_media("odt")
483     def get_ogg(self):
484         return self.get_media("ogg")
485     def get_daisy(self):
486         return self.get_media("daisy")                       
487
488     def reset_short_html(self):
489         if self.id is None:
490             return
491
492         cache_key = "Book.short_html/%d/%s"
493         for lang, langname in settings.LANGUAGES:
494             cache.delete(cache_key % (self.id, lang))
495         cache.delete(cache_key = "Book.mini_box/%d" % (self.id, ))
496         # Fragment.short_html relies on book's tags, so reset it here too
497         for fragm in self.fragments.all():
498             fragm.reset_short_html()
499
500     def short_html(self):
501         if self.id:
502             cache_key = "Book.short_html/%d/%s" % (self.id, get_language())
503             short_html = cache.get(cache_key)
504         else:
505             short_html = None
506
507         if short_html is not None:
508             return mark_safe(short_html)
509         else:
510             tags = self.tags.filter(category__in=('author', 'kind', 'genre', 'epoch'))
511             tags = split_tags(tags)
512
513             formats = []
514             # files generated during publication
515             for ebook_format in self.ebook_formats:
516                 if self.has_media(ebook_format):
517                     formats.append(u'<a href="%s">%s</a>' % (
518                         "", #self.get_media(ebook_format).url,
519                         ebook_format.upper()
520                     ))
521
522             formats = [mark_safe(format) for format in formats]
523
524             short_html = unicode(render_to_string('catalogue/book_short.html',
525                 {'book': self, 'tags': tags, 'formats': formats}))
526
527             if self.id:
528                 cache.set(cache_key, short_html, CACHE_FOREVER)
529             return mark_safe(short_html)
530
531     def mini_box(self):
532         if self.id:
533             cache_key = "Book.mini_box/%d" % (self.id, )
534             short_html = cache.get(cache_key)
535         else:
536             short_html = None
537
538         if short_html is None:
539             authors = self.tags.filter(category='author')
540
541             short_html = unicode(render_to_string('catalogue/book_mini_box.html',
542                 {'book': self, 'authors': authors, 'STATIC_URL': settings.STATIC_URL}))
543
544             if self.id:
545                 cache.set(cache_key, short_html, CACHE_FOREVER)
546         return mark_safe(short_html)
547
548     def has_description(self):
549         return len(self.description) > 0
550     has_description.short_description = _('description')
551     has_description.boolean = True
552
553     # ugly ugly ugly
554     def has_mp3_file(self):
555         return bool(self.has_media("mp3"))
556     has_mp3_file.short_description = 'MP3'
557     has_mp3_file.boolean = True
558
559     def has_ogg_file(self):
560         return bool(self.has_media("ogg"))
561     has_ogg_file.short_description = 'OGG'
562     has_ogg_file.boolean = True
563
564     def has_daisy_file(self):
565         return bool(self.has_media("daisy"))
566     has_daisy_file.short_description = 'DAISY'
567     has_daisy_file.boolean = True
568
569     def wldocument(self, parse_dublincore=True):
570         from catalogue.utils import ORMDocProvider
571         from librarian.parser import WLDocument
572
573         return WLDocument.from_file(self.xml_file.path,
574                 provider=ORMDocProvider(self),
575                 parse_dublincore=parse_dublincore)
576
577     def build_cover(self, book_info=None):
578         """(Re)builds the cover image."""
579         from StringIO import StringIO
580         from django.core.files.base import ContentFile
581         from librarian.cover import WLCover
582
583         if book_info is None:
584             book_info = self.wldocument().book_info
585
586         cover = WLCover(book_info).image()
587         imgstr = StringIO()
588         cover.save(imgstr, 'png')
589         self.cover.save(None, ContentFile(imgstr.getvalue()))
590
591     def build_pdf(self, customizations=None, file_name=None):
592         """ (Re)builds the pdf file.
593         customizations - customizations which are passed to LaTeX class file.
594         file_name - save the pdf file under a different name and DO NOT save it in db.
595         """
596         from os import unlink
597         from django.core.files import File
598         from catalogue.utils import remove_zip
599
600         pdf = self.wldocument().as_pdf(customizations=customizations)
601
602         if file_name is None:
603             # we'd like to be sure not to overwrite changes happening while
604             # (timely) pdf generation is taking place (async celery scenario)
605             current_self = Book.objects.get(id=self.id)
606             current_self.pdf_file.save('%s.pdf' % self.fileid(),
607                     File(open(pdf.get_filename())))
608             self.pdf_file = current_self.pdf_file
609
610             # remove cached downloadables
611             remove_zip(settings.ALL_PDF_ZIP)
612
613             for customized_pdf in get_existing_customized_pdf(self):
614                 unlink(customized_pdf)
615         else:
616             print "saving %s" % file_name
617             print "to: %s" % DefaultStorage().path(file_name)
618             DefaultStorage().save(file_name, File(open(pdf.get_filename())))
619
620     def build_mobi(self):
621         """ (Re)builds the MOBI file.
622
623         """
624         from django.core.files import File
625         from catalogue.utils import remove_zip
626
627         mobi = self.wldocument().as_mobi()
628
629         self.mobi_file.save('%s.mobi' % self.fileid(), File(open(mobi.get_filename())))
630
631         # remove zip with all mobi files
632         remove_zip(settings.ALL_MOBI_ZIP)
633
634     def build_epub(self):
635         """(Re)builds the epub file."""
636         from django.core.files import File
637         from catalogue.utils import remove_zip
638
639         epub = self.wldocument().as_epub()
640
641         self.epub_file.save('%s.epub' % self.fileid(),
642                 File(open(epub.get_filename())))
643
644         # remove zip package with all epub files
645         remove_zip(settings.ALL_EPUB_ZIP)
646
647     def build_txt(self):
648         from django.core.files.base import ContentFile
649
650         text = self.wldocument().as_text()
651         self.txt_file.save('%s.txt' % self.fileid(), ContentFile(text.get_string()))
652
653
654     def build_html(self):
655         from markupstring import MarkupString
656         from django.core.files.base import ContentFile
657         from slughifi import slughifi
658         from librarian import html
659
660         meta_tags = list(self.tags.filter(
661             category__in=('author', 'epoch', 'genre', 'kind')))
662         book_tag = self.book_tag()
663
664         html_output = self.wldocument(parse_dublincore=False).as_html()
665         if html_output:
666             self.html_file.save('%s.html' % self.fileid(),
667                     ContentFile(html_output.get_string()))
668
669             # get ancestor l-tags for adding to new fragments
670             ancestor_tags = []
671             p = self.parent
672             while p:
673                 ancestor_tags.append(p.book_tag())
674                 p = p.parent
675
676             # Delete old fragments and create them from scratch
677             self.fragments.all().delete()
678             # Extract fragments
679             closed_fragments, open_fragments = html.extract_fragments(self.html_file.path)
680             for fragment in closed_fragments.values():
681                 try:
682                     theme_names = [s.strip() for s in fragment.themes.split(',')]
683                 except AttributeError:
684                     continue
685                 themes = []
686                 for theme_name in theme_names:
687                     if not theme_name:
688                         continue
689                     tag, created = Tag.objects.get_or_create(slug=slughifi(theme_name), category='theme')
690                     if created:
691                         tag.name = theme_name
692                         tag.sort_key = theme_name.lower()
693                         tag.save()
694                     themes.append(tag)
695                 if not themes:
696                     continue
697
698                 text = fragment.to_string()
699                 short_text = ''
700                 if (len(MarkupString(text)) > 240):
701                     short_text = unicode(MarkupString(text)[:160])
702                 new_fragment = Fragment.objects.create(anchor=fragment.id, book=self,
703                     text=text, short_text=short_text)
704
705                 new_fragment.save()
706                 new_fragment.tags = set(meta_tags + themes + [book_tag] + ancestor_tags)
707             self.save()
708             self.html_built.send(sender=self)
709             return True
710         return False
711
712     @staticmethod
713     def zip_format(format_):
714         def pretty_file_name(book):
715             return "%s/%s.%s" % (
716                 b.get_extra_info_value()['author'],
717                 b.fileid(),
718                 format_)
719
720         field_name = "%s_file" % format_
721         books = Book.objects.filter(parent=None).exclude(**{field_name: ""})
722         paths = [(pretty_file_name(b), getattr(b, field_name).path)
723                     for b in books]
724         result = create_zip.delay(paths,
725                     getattr(settings, "ALL_%s_ZIP" % format_.upper()))
726         return result.wait()
727
728     def zip_audiobooks(self):
729         bm = BookMedia.objects.filter(book=self, type='mp3')
730         paths = map(lambda bm: (None, bm.file.path), bm)
731         result = create_zip.delay(paths, self.fileid())
732         return result.wait()
733
734     def search_index(self):
735         if settings.SEARCH_INDEX_PARALLEL:
736             if instance(settings.SEARCH_INDEX_PARALLEL, int):
737                 idx = search.ReusableIndex(threads=4)
738             else:
739                 idx = search.ReusableIndex()
740         else:
741             idx = search.Index()
742             
743         idx.open()
744         try:
745             idx.index_book(self)
746         finally:
747             idx.close()
748
749     @classmethod
750     def from_xml_file(cls, xml_file, **kwargs):
751         from django.core.files import File
752         from librarian import dcparser
753
754         # use librarian to parse meta-data
755         book_info = dcparser.parse(xml_file)
756
757         if not isinstance(xml_file, File):
758             xml_file = File(open(xml_file))
759
760         try:
761             return cls.from_text_and_meta(xml_file, book_info, **kwargs)
762         finally:
763             xml_file.close()
764
765     @classmethod
766     def from_text_and_meta(cls, raw_file, book_info, overwrite=False,
767             build_epub=True, build_txt=True, build_pdf=True, build_mobi=True,
768             search_index=True):
769         import re
770         from sortify import sortify
771
772         # check for parts before we do anything
773         children = []
774         if hasattr(book_info, 'parts'):
775             for part_url in book_info.parts:
776                 try:
777                     children.append(Book.objects.get(
778                         slug=part_url.slug, language=part_url.language))
779                 except Book.DoesNotExist, e:
780                     raise Book.DoesNotExist(_('Book "%s/%s" does not exist.') %
781                             (part_url.slug, part_url.language))
782
783
784         # Read book metadata
785         book_slug = book_info.url.slug
786         language = book_info.language
787         if re.search(r'[^a-zA-Z0-9-]', book_slug):
788             raise ValueError('Invalid characters in slug')
789         book, created = Book.objects.get_or_create(slug=book_slug, language=language)
790
791         if created:
792             book_shelves = []
793         else:
794             if not overwrite:
795                 raise Book.AlreadyExists(_('Book %s/%s already exists') % (
796                         book_slug, language))
797             # Save shelves for this book
798             book_shelves = list(book.tags.filter(category='set'))
799
800         book.title = book_info.title
801         book.set_extra_info_value(book_info.to_dict())
802         book.save()
803
804         meta_tags = Tag.tags_from_info(book_info)
805
806         book.tags = set(meta_tags + book_shelves)
807
808         book_tag = book.book_tag()
809
810         for n, child_book in enumerate(children):
811             child_book.parent = book
812             child_book.parent_number = n
813             child_book.save()
814
815         # Save XML and HTML files
816         book.xml_file.save('%s.xml' % book.slug, raw_file, save=False)
817
818         # delete old fragments when overwriting
819         book.fragments.all().delete()
820
821         if book.build_html():
822             if not settings.NO_BUILD_TXT and build_txt:
823                 book.build_txt()
824
825         book.build_cover(book_info)
826
827         if not settings.NO_BUILD_EPUB and build_epub:
828             book.build_epub()
829
830         if not settings.NO_BUILD_PDF and build_pdf:
831             book.build_pdf()
832
833         if not settings.NO_BUILD_MOBI and build_mobi:
834             book.build_mobi()
835
836         if not settings.NO_SEARCH_INDEX and search_index:
837             book.search_index()
838
839         book_descendants = list(book.children.all())
840         descendants_tags = set()
841         # add l-tag to descendants and their fragments
842         while len(book_descendants) > 0:
843             child_book = book_descendants.pop(0)
844             descendants_tags.update(child_book.tags)
845             child_book.tags = list(child_book.tags) + [book_tag]
846             child_book.save()
847             for fragment in child_book.fragments.all():
848                 fragment.tags = set(list(fragment.tags) + [book_tag])
849             book_descendants += list(child_book.children.all())
850
851         for tag in descendants_tags:
852             touch_tag.delay(tag)
853
854         book.save()
855
856         # refresh cache
857         book.reset_tag_counter()
858         book.reset_theme_counter()
859
860         cls.published.send(sender=book)
861         return book
862
863     def reset_tag_counter(self):
864         if self.id is None:
865             return
866
867         cache_key = "Book.tag_counter/%d" % self.id
868         cache.delete(cache_key)
869         if self.parent:
870             self.parent.reset_tag_counter()
871
872     @property
873     def tag_counter(self):
874         if self.id:
875             cache_key = "Book.tag_counter/%d" % self.id
876             tags = cache.get(cache_key)
877         else:
878             tags = None
879
880         if tags is None:
881             tags = {}
882             for child in self.children.all().order_by():
883                 for tag_pk, value in child.tag_counter.iteritems():
884                     tags[tag_pk] = tags.get(tag_pk, 0) + value
885             for tag in self.tags.exclude(category__in=('book', 'theme', 'set')).order_by():
886                 tags[tag.pk] = 1
887
888             if self.id:
889                 cache.set(cache_key, tags, CACHE_FOREVER)
890         return tags
891
892     def reset_theme_counter(self):
893         if self.id is None:
894             return
895
896         cache_key = "Book.theme_counter/%d" % self.id
897         cache.delete(cache_key)
898         if self.parent:
899             self.parent.reset_theme_counter()
900
901     @property
902     def theme_counter(self):
903         if self.id:
904             cache_key = "Book.theme_counter/%d" % self.id
905             tags = cache.get(cache_key)
906         else:
907             tags = None
908
909         if tags is None:
910             tags = {}
911             for fragment in Fragment.tagged.with_any([self.book_tag()]).order_by():
912                 for tag in fragment.tags.filter(category='theme').order_by():
913                     tags[tag.pk] = tags.get(tag.pk, 0) + 1
914
915             if self.id:
916                 cache.set(cache_key, tags, CACHE_FOREVER)
917         return tags
918
919     def pretty_title(self, html_links=False):
920         book = self
921         names = list(book.tags.filter(category='author'))
922
923         books = []
924         while book:
925             books.append(book)
926             book = book.parent
927         names.extend(reversed(books))
928
929         if html_links:
930             names = ['<a href="%s">%s</a>' % (tag.get_absolute_url(), tag.name) for tag in names]
931         else:
932             names = [tag.name for tag in names]
933
934         return ', '.join(names)
935
936     @classmethod
937     def tagged_top_level(cls, tags):
938         """ Returns top-level books tagged with `tags'.
939
940         It only returns those books which don't have ancestors which are
941         also tagged with those tags.
942
943         """
944         # get relevant books and their tags
945         objects = cls.tagged.with_all(tags)
946         # eliminate descendants
947         l_tags = Tag.objects.filter(category='book', slug__in=[book.book_tag_slug() for book in objects])
948         descendants_keys = [book.pk for book in cls.tagged.with_any(l_tags)]
949         if descendants_keys:
950             objects = objects.exclude(pk__in=descendants_keys)
951
952         return objects
953
954     @classmethod
955     def book_list(cls, filter=None):
956         """Generates a hierarchical listing of all books.
957
958         Books are optionally filtered with a test function.
959
960         """
961
962         books_by_parent = {}
963         books = cls.objects.all().order_by('parent_number', 'sort_key').only(
964                 'title', 'parent', 'slug', 'language')
965         if filter:
966             books = books.filter(filter).distinct()
967             book_ids = set((book.pk for book in books))
968             for book in books:
969                 parent = book.parent_id
970                 if parent not in book_ids:
971                     parent = None
972                 books_by_parent.setdefault(parent, []).append(book)
973         else:
974             for book in books:
975                 books_by_parent.setdefault(book.parent_id, []).append(book)
976
977         orphans = []
978         books_by_author = SortedDict()
979         for tag in Tag.objects.filter(category='author'):
980             books_by_author[tag] = []
981
982         for book in books_by_parent.get(None,()):
983             authors = list(book.tags.filter(category='author'))
984             if authors:
985                 for author in authors:
986                     books_by_author[author].append(book)
987             else:
988                 orphans.append(book)
989
990         return books_by_author, orphans, books_by_parent
991
992     _audiences_pl = {
993         "SP1": (1, u"szkoła podstawowa"),
994         "SP2": (1, u"szkoła podstawowa"),
995         "P": (1, u"szkoła podstawowa"),
996         "G": (2, u"gimnazjum"),
997         "L": (3, u"liceum"),
998         "LP": (3, u"liceum"),
999     }
1000     def audiences_pl(self):
1001         audiences = self.get_extra_info_value().get('audiences', [])
1002         audiences = sorted(set([self._audiences_pl[a] for a in audiences]))
1003         return [a[1] for a in audiences]
1004
1005
1006 def _has_factory(ftype):
1007     has = lambda self: bool(getattr(self, "%s_file" % ftype))
1008     has.short_description = t.upper()
1009     has.boolean = True
1010     has.__name__ = "has_%s_file" % ftype
1011     return has
1012
1013     
1014 # add the file fields
1015 for t in Book.formats:
1016     field_name = "%s_file" % t
1017     models.FileField(_("%s file" % t.upper()),
1018             upload_to=book_upload_path(t),
1019             blank=True).contribute_to_class(Book, field_name)
1020
1021     setattr(Book, "has_%s_file" % t, _has_factory(t))
1022
1023
1024 class Fragment(models.Model):
1025     text = models.TextField()
1026     short_text = models.TextField(editable=False)
1027     anchor = models.CharField(max_length=120)
1028     book = models.ForeignKey(Book, related_name='fragments')
1029
1030     objects = models.Manager()
1031     tagged = managers.ModelTaggedItemManager(Tag)
1032     tags = managers.TagDescriptor(Tag)
1033
1034     class Meta:
1035         ordering = ('book', 'anchor',)
1036         verbose_name = _('fragment')
1037         verbose_name_plural = _('fragments')
1038
1039     def get_absolute_url(self):
1040         return '%s#m%s' % (self.book.get_html_url(), self.anchor)
1041
1042     def reset_short_html(self):
1043         if self.id is None:
1044             return
1045
1046         cache_key = "Fragment.short_html/%d/%s"
1047         for lang, langname in settings.LANGUAGES:
1048             cache.delete(cache_key % (self.id, lang))
1049
1050     def short_html(self):
1051         if self.id:
1052             cache_key = "Fragment.short_html/%d/%s" % (self.id, get_language())
1053             short_html = cache.get(cache_key)
1054         else:
1055             short_html = None
1056
1057         if short_html is not None:
1058             return mark_safe(short_html)
1059         else:
1060             short_html = unicode(render_to_string('catalogue/fragment_short.html',
1061                 {'fragment': self}))
1062             if self.id:
1063                 cache.set(cache_key, short_html, CACHE_FOREVER)
1064             return mark_safe(short_html)
1065
1066
1067 ###########
1068 #
1069 # SIGNALS
1070 #
1071 ###########
1072
1073
1074 def _tags_updated_handler(sender, affected_tags, **kwargs):
1075     # reset tag global counter
1076     # we want Tag.changed_at updated for API to know the tag was touched
1077     for tag in affected_tags:
1078         touch_tag.delay(tag)
1079
1080     # if book tags changed, reset book tag counter
1081     if isinstance(sender, Book) and \
1082                 Tag.objects.filter(pk__in=(tag.pk for tag in affected_tags)).\
1083                     exclude(category__in=('book', 'theme', 'set')).count():
1084         sender.reset_tag_counter()
1085     # if fragment theme changed, reset book theme counter
1086     elif isinstance(sender, Fragment) and \
1087                 Tag.objects.filter(pk__in=(tag.pk for tag in affected_tags)).\
1088                     filter(category='theme').count():
1089         sender.book.reset_theme_counter()
1090 tags_updated.connect(_tags_updated_handler)
1091
1092
1093 def _pre_delete_handler(sender, instance, **kwargs):
1094     """ refresh Book on BookMedia delete """
1095     if sender == BookMedia:
1096         instance.book.save()
1097 pre_delete.connect(_pre_delete_handler)
1098
1099 def _post_save_handler(sender, instance, **kwargs):
1100     """ refresh all the short_html stuff on BookMedia update """
1101     if sender == BookMedia:
1102         instance.book.save()
1103 post_save.connect(_post_save_handler)