- inheriting covers after parents,
[wolnelektury.git] / apps / catalogue / models / book.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 import re
6 from django.conf import settings as settings
7 from django.core.cache import get_cache
8 from django.db import models
9 from django.db.models import permalink
10 import django.dispatch
11 from django.utils.datastructures import SortedDict
12 from django.utils.translation import ugettext_lazy as _
13 import jsonfield
14 from catalogue import constants
15 from catalogue.fields import EbookField
16 from catalogue.models import Tag, Fragment, BookMedia
17 from catalogue.utils import create_zip, split_tags, book_upload_path
18 from catalogue import app_settings
19 from catalogue import tasks
20 from newtagging import managers
21
22
23 permanent_cache = get_cache('permanent')
24
25
26 class Book(models.Model):
27     """Represents a book imported from WL-XML."""
28     title         = models.CharField(_('title'), max_length=120)
29     sort_key = models.CharField(_('sort key'), max_length=120, db_index=True, editable=False)
30     slug = models.SlugField(_('slug'), max_length=120, db_index=True,
31             unique=True)
32     common_slug = models.SlugField(_('slug'), max_length=120, db_index=True)
33     language = models.CharField(_('language code'), max_length=3, db_index=True,
34                     default=app_settings.DEFAULT_LANGUAGE)
35     description   = models.TextField(_('description'), blank=True)
36     created_at    = models.DateTimeField(_('creation date'), auto_now_add=True, db_index=True)
37     changed_at    = models.DateTimeField(_('creation date'), auto_now=True, db_index=True)
38     parent_number = models.IntegerField(_('parent number'), default=0)
39     extra_info    = jsonfield.JSONField(_('extra information'), default='{}')
40     gazeta_link   = models.CharField(blank=True, max_length=240)
41     wiki_link     = models.CharField(blank=True, max_length=240)
42     # files generated during publication
43
44     cover = EbookField('cover', _('cover'),
45                 upload_to=book_upload_path('jpg'), null=True, blank=True)
46     ebook_formats = constants.EBOOK_FORMATS
47     formats = ebook_formats + ['html', 'xml']
48
49     parent = models.ForeignKey('self', blank=True, null=True,
50         related_name='children')
51
52     _related_info = jsonfield.JSONField(blank=True, null=True, editable=False)
53
54     objects  = models.Manager()
55     tagged   = managers.ModelTaggedItemManager(Tag)
56     tags     = managers.TagDescriptor(Tag)
57
58     html_built = django.dispatch.Signal()
59     published = django.dispatch.Signal()
60
61     class AlreadyExists(Exception):
62         pass
63
64     class Meta:
65         ordering = ('sort_key',)
66         verbose_name = _('book')
67         verbose_name_plural = _('books')
68         app_label = 'catalogue'
69
70     def __unicode__(self):
71         return self.title
72
73     def save(self, force_insert=False, force_update=False, reset_short_html=True, **kwargs):
74         from sortify import sortify
75
76         self.sort_key = sortify(self.title)
77
78         ret = super(Book, self).save(force_insert, force_update)
79
80         if reset_short_html:
81             self.reset_short_html()
82
83         return ret
84
85     @permalink
86     def get_absolute_url(self):
87         return ('catalogue.views.book_detail', [self.slug])
88
89     @property
90     def name(self):
91         return self.title
92
93     def book_tag_slug(self):
94         return ('l-' + self.slug)[:120]
95
96     def book_tag(self):
97         slug = self.book_tag_slug()
98         book_tag, created = Tag.objects.get_or_create(slug=slug, category='book')
99         if created:
100             book_tag.name = self.title[:50]
101             book_tag.sort_key = self.title.lower()
102             book_tag.save()
103         return book_tag
104
105     def has_media(self, type_):
106         if type_ in Book.formats:
107             return bool(getattr(self, "%s_file" % type_))
108         else:
109             return self.media.filter(type=type_).exists()
110
111     def get_media(self, type_):
112         if self.has_media(type_):
113             if type_ in Book.formats:
114                 return getattr(self, "%s_file" % type_)
115             else:                                             
116                 return self.media.filter(type=type_)
117         else:
118             return None
119
120     def get_mp3(self):
121         return self.get_media("mp3")
122     def get_odt(self):
123         return self.get_media("odt")
124     def get_ogg(self):
125         return self.get_media("ogg")
126     def get_daisy(self):
127         return self.get_media("daisy")                       
128
129     def reset_short_html(self):
130         if self.id is None:
131             return
132
133         type(self).objects.filter(pk=self.pk).update(_related_info=None)
134         # Fragment.short_html relies on book's tags, so reset it here too
135         for fragm in self.fragments.all().iterator():
136             fragm.reset_short_html()
137
138     def has_description(self):
139         return len(self.description) > 0
140     has_description.short_description = _('description')
141     has_description.boolean = True
142
143     # ugly ugly ugly
144     def has_mp3_file(self):
145         return bool(self.has_media("mp3"))
146     has_mp3_file.short_description = 'MP3'
147     has_mp3_file.boolean = True
148
149     def has_ogg_file(self):
150         return bool(self.has_media("ogg"))
151     has_ogg_file.short_description = 'OGG'
152     has_ogg_file.boolean = True
153
154     def has_daisy_file(self):
155         return bool(self.has_media("daisy"))
156     has_daisy_file.short_description = 'DAISY'
157     has_daisy_file.boolean = True
158
159     def wldocument(self, parse_dublincore=True, inherit=True):
160         from catalogue.import_utils import ORMDocProvider
161         from librarian.parser import WLDocument
162
163         if inherit and self.parent:
164             meta_fallbacks = self.parent.cover_info()
165         else:
166             meta_fallbacks = None
167
168         return WLDocument.from_file(self.xml_file.path,
169                 provider=ORMDocProvider(self),
170                 parse_dublincore=parse_dublincore,
171                 meta_fallbacks=meta_fallbacks)
172
173     @staticmethod
174     def zip_format(format_):
175         def pretty_file_name(book):
176             return "%s/%s.%s" % (
177                 book.extra_info['author'],
178                 book.slug,
179                 format_)
180
181         field_name = "%s_file" % format_
182         books = Book.objects.filter(parent=None).exclude(**{field_name: ""})
183         paths = [(pretty_file_name(b), getattr(b, field_name).path)
184                     for b in books.iterator()]
185         return create_zip(paths, app_settings.FORMAT_ZIPS[format_])
186
187     def zip_audiobooks(self, format_):
188         bm = BookMedia.objects.filter(book=self, type=format_)
189         paths = map(lambda bm: (None, bm.file.path), bm)
190         return create_zip(paths, "%s_%s" % (self.slug, format_))
191
192     def search_index(self, book_info=None, reuse_index=False, index_tags=True):
193         import search
194         if reuse_index:
195             idx = search.ReusableIndex()
196         else:
197             idx = search.Index()
198             
199         idx.open()
200         try:
201             idx.index_book(self, book_info)
202             if index_tags:
203                 idx.index_tags()
204         finally:
205             idx.close()
206
207     @classmethod
208     def from_xml_file(cls, xml_file, **kwargs):
209         from django.core.files import File
210         from librarian import dcparser
211
212         # use librarian to parse meta-data
213         book_info = dcparser.parse(xml_file)
214
215         if not isinstance(xml_file, File):
216             xml_file = File(open(xml_file))
217
218         try:
219             return cls.from_text_and_meta(xml_file, book_info, **kwargs)
220         finally:
221             xml_file.close()
222
223     @classmethod
224     def from_text_and_meta(cls, raw_file, book_info, overwrite=False,
225             dont_build=None, search_index=True,
226             search_index_tags=True, search_index_reuse=False):
227         if dont_build is None:
228             dont_build = set()
229         dont_build = set.union(set(dont_build), set(app_settings.DONT_BUILD))
230
231         # check for parts before we do anything
232         children = []
233         if hasattr(book_info, 'parts'):
234             for part_url in book_info.parts:
235                 try:
236                     children.append(Book.objects.get(slug=part_url.slug))
237                 except Book.DoesNotExist:
238                     raise Book.DoesNotExist(_('Book "%s" does not exist.') %
239                             part_url.slug)
240
241         # Read book metadata
242         book_slug = book_info.url.slug
243         if re.search(r'[^a-z0-9-]', book_slug):
244             raise ValueError('Invalid characters in slug')
245         book, created = Book.objects.get_or_create(slug=book_slug)
246
247         if created:
248             book_shelves = []
249             old_cover = None
250         else:
251             if not overwrite:
252                 raise Book.AlreadyExists(_('Book %s already exists') % (
253                         book_slug))
254             # Save shelves for this book
255             book_shelves = list(book.tags.filter(category='set'))
256             old_cover = book.cover_info()
257
258         # Save XML file
259         book.xml_file.save('%s.xml' % book.slug, raw_file, save=False)
260
261         book.language = book_info.language
262         book.title = book_info.title
263         if book_info.variant_of:
264             book.common_slug = book_info.variant_of.slug
265         else:
266             book.common_slug = book.slug
267         book.extra_info = book_info.to_dict()
268         book.save()
269
270         meta_tags = Tag.tags_from_info(book_info)
271
272         book.tags = set(meta_tags + book_shelves)
273
274         cover_changed = old_cover != book.cover_info()
275         obsolete_children = set(b for b in book.children.all()
276                                 if b not in children)
277         for n, child_book in enumerate(children):
278             child_book.parent = book
279             child_book.parent_number = n
280             child_book.save()
281             if cover_changed:
282                 child_book.parent_cover_changed()
283         # Disown unfaithful children and let them cope on their own.
284         for child in obsolete_children:
285             child.parent = None
286             child.parent_number = 0
287             child.save()
288             tasks.fix_tree_tags.delay(child)
289             if old_cover:
290                 child.parent_cover_changed()
291
292         # delete old fragments when overwriting
293         book.fragments.all().delete()
294         # Build HTML, fix the tree tags, build cover.
295         has_own_text = bool(book.html_file.build())
296         tasks.fix_tree_tags.delay(book)
297         if 'cover' not in dont_build:
298             book.cover.build_delay()
299         
300         # No saves behind this point.
301
302         if has_own_text:
303             for format_ in constants.EBOOK_FORMATS_WITHOUT_CHILDREN:
304                 if format_ not in dont_build:
305                     getattr(book, '%s_file' % format_).build_delay()
306         for format_ in constants.EBOOK_FORMATS_WITH_CHILDREN:
307             if format_ not in dont_build:
308                 getattr(book, '%s_file' % format_).build_delay()
309
310         if not settings.NO_SEARCH_INDEX and search_index:
311             book.search_index(index_tags=search_index_tags, reuse_index=search_index_reuse)
312             #index_book.delay(book.id, book_info)
313
314         cls.published.send(sender=book)
315         return book
316
317     def fix_tree_tags(self):
318         """Fixes the l-tags on the book's subtree.
319
320         Makes sure that:
321         * the book has its parents book-tags,
322         * its fragments have the book's and its parents book-tags,
323         * runs those for every child book too,
324         * touches all relevant tags,
325         * resets tag and theme counter on the book and its ancestry.
326         """
327         def fix_subtree(book, parent_tags):
328             affected_tags = set(book.tags)
329             book.tags = list(book.tags.exclude(category='book')) + parent_tags
330             sub_parent_tags = parent_tags + [book.book_tag()]
331             for frag in book.fragments.all():
332                 affected_tags.update(frag.tags)
333                 frag.tags = list(frag.tags.exclude(category='book')
334                                     ) + sub_parent_tags
335             for child in book.children.all():
336                 affected_tags.update(fix_subtree(child, sub_parent_tags))
337             return affected_tags
338
339         parent_tags = []
340         parent = self.parent
341         while parent is not None:
342             parent_tags.append(parent.book_tag())
343             parent = parent.parent
344
345         affected_tags = fix_subtree(self, parent_tags)
346         for tag in affected_tags:
347             tasks.touch_tag(tag)
348
349         book = self
350         while book is not None:
351             book.reset_tag_counter()
352             book.reset_theme_counter()
353             book = book.parent
354
355     def cover_info(self, inherit=True):
356         """Returns a dictionary to serve as fallback for BookInfo.
357
358         For now, the only thing inherited is the cover image.
359         """
360         need = False
361         info = {}
362         for field in ('cover_url', 'cover_by', 'cover_source'):
363             val = self.extra_info.get(field)
364             if val:
365                 info[field] = val
366             else:
367                 need = True
368         if inherit and need and self.parent is not None:
369             parent_info = self.parent.cover_info()
370             parent_info.update(info)
371             info = parent_info
372         return info
373
374     def parent_cover_changed(self):
375         """Called when parent book's cover image is changed."""
376         if not self.cover_info(inherit=False):
377             if 'cover' not in app_settings.DONT_BUILD:
378                 self.cover.build_delay()
379             for format_ in constants.EBOOK_FORMATS_WITH_COVERS:
380                 if format_ not in app_settings.DONT_BUILD:
381                     getattr(self, '%s_file' % format_).build_delay()
382             for child in self.children.all():
383                 child.parent_cover_changed()
384
385     def related_info(self):
386         """Keeps info about related objects (tags, media) in cache field."""
387         if self._related_info is not None:
388             return self._related_info
389         else:
390             rel = {'tags': {}, 'media': {}}
391
392             tags = self.tags.filter(category__in=(
393                     'author', 'kind', 'genre', 'epoch'))
394             tags = split_tags(tags)
395             for category in tags:
396                 rel['tags'][category] = [
397                         (t.name, t.slug) for t in tags[category]]
398
399             for media_format in BookMedia.formats:
400                 rel['media'][media_format] = self.has_media(media_format)
401
402             book = self
403             parents = []
404             while book.parent:
405                 parents.append((book.parent.title, book.parent.slug))
406                 book = book.parent
407             parents = parents[::-1]
408             if parents:
409                 rel['parents'] = parents
410
411             if self.pk:
412                 type(self).objects.filter(pk=self.pk).update(_related_info=rel)
413             return rel
414
415     def related_themes(self):
416         theme_counter = self.theme_counter
417         book_themes = list(Tag.objects.filter(pk__in=theme_counter.keys()))
418         for tag in book_themes:
419             tag.count = theme_counter[tag.pk]
420         return book_themes
421
422     def reset_tag_counter(self):
423         if self.id is None:
424             return
425
426         cache_key = "Book.tag_counter/%d" % self.id
427         permanent_cache.delete(cache_key)
428         if self.parent:
429             self.parent.reset_tag_counter()
430
431     @property
432     def tag_counter(self):
433         if self.id:
434             cache_key = "Book.tag_counter/%d" % self.id
435             tags = permanent_cache.get(cache_key)
436         else:
437             tags = None
438
439         if tags is None:
440             tags = {}
441             for child in self.children.all().order_by().iterator():
442                 for tag_pk, value in child.tag_counter.iteritems():
443                     tags[tag_pk] = tags.get(tag_pk, 0) + value
444             for tag in self.tags.exclude(category__in=('book', 'theme', 'set')).order_by().iterator():
445                 tags[tag.pk] = 1
446
447             if self.id:
448                 permanent_cache.set(cache_key, tags)
449         return tags
450
451     def reset_theme_counter(self):
452         if self.id is None:
453             return
454
455         cache_key = "Book.theme_counter/%d" % self.id
456         permanent_cache.delete(cache_key)
457         if self.parent:
458             self.parent.reset_theme_counter()
459
460     @property
461     def theme_counter(self):
462         if self.id:
463             cache_key = "Book.theme_counter/%d" % self.id
464             tags = permanent_cache.get(cache_key)
465         else:
466             tags = None
467
468         if tags is None:
469             tags = {}
470             for fragment in Fragment.tagged.with_any([self.book_tag()]).order_by().iterator():
471                 for tag in fragment.tags.filter(category='theme').order_by().iterator():
472                     tags[tag.pk] = tags.get(tag.pk, 0) + 1
473
474             if self.id:
475                 permanent_cache.set(cache_key, tags)
476         return tags
477
478     def pretty_title(self, html_links=False):
479         book = self
480         names = list(book.tags.filter(category='author'))
481
482         books = []
483         while book:
484             books.append(book)
485             book = book.parent
486         names.extend(reversed(books))
487
488         if html_links:
489             names = ['<a href="%s">%s</a>' % (tag.get_absolute_url(), tag.name) for tag in names]
490         else:
491             names = [tag.name for tag in names]
492
493         return ', '.join(names)
494
495     @classmethod
496     def tagged_top_level(cls, tags):
497         """ Returns top-level books tagged with `tags`.
498
499         It only returns those books which don't have ancestors which are
500         also tagged with those tags.
501
502         """
503         # get relevant books and their tags
504         objects = cls.tagged.with_all(tags)
505         # eliminate descendants
506         l_tags = Tag.objects.filter(category='book',
507             slug__in=[book.book_tag_slug() for book in objects.iterator()])
508         descendants_keys = [book.pk for book in cls.tagged.with_any(l_tags).iterator()]
509         if descendants_keys:
510             objects = objects.exclude(pk__in=descendants_keys)
511
512         return objects
513
514     @classmethod
515     def book_list(cls, filter=None):
516         """Generates a hierarchical listing of all books.
517
518         Books are optionally filtered with a test function.
519
520         """
521
522         books_by_parent = {}
523         books = cls.objects.all().order_by('parent_number', 'sort_key').only(
524                 'title', 'parent', 'slug')
525         if filter:
526             books = books.filter(filter).distinct()
527             
528             book_ids = set(b['pk'] for b in books.values("pk").iterator())
529             for book in books.iterator():
530                 parent = book.parent_id
531                 if parent not in book_ids:
532                     parent = None
533                 books_by_parent.setdefault(parent, []).append(book)
534         else:
535             for book in books.iterator():
536                 books_by_parent.setdefault(book.parent_id, []).append(book)
537
538         orphans = []
539         books_by_author = SortedDict()
540         for tag in Tag.objects.filter(category='author').iterator():
541             books_by_author[tag] = []
542
543         for book in books_by_parent.get(None,()):
544             authors = list(book.tags.filter(category='author'))
545             if authors:
546                 for author in authors:
547                     books_by_author[author].append(book)
548             else:
549                 orphans.append(book)
550
551         return books_by_author, orphans, books_by_parent
552
553     _audiences_pl = {
554         "SP1": (1, u"szkoła podstawowa"),
555         "SP2": (1, u"szkoła podstawowa"),
556         "P": (1, u"szkoła podstawowa"),
557         "G": (2, u"gimnazjum"),
558         "L": (3, u"liceum"),
559         "LP": (3, u"liceum"),
560     }
561     def audiences_pl(self):
562         audiences = self.extra_info.get('audiences', [])
563         audiences = sorted(set([self._audiences_pl[a] for a in audiences]))
564         return [a[1] for a in audiences]
565
566     def choose_fragment(self):
567         tag = self.book_tag()
568         fragments = Fragment.tagged.with_any([tag])
569         if fragments.exists():
570             return fragments.order_by('?')[0]
571         elif self.parent:
572             return self.parent.choose_fragment()
573         else:
574             return None
575
576
577 # add the file fields
578 for format_ in Book.formats:
579     field_name = "%s_file" % format_
580     EbookField(format_, _("%s file" % format_.upper()),
581             upload_to=book_upload_path(format_),
582             blank=True, default='').contribute_to_class(Book, field_name)