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