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