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