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