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