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