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